BETA

alRetrieval

Ingest documents and query them with natural-language semantic retrieval. Supports PDF, DOCX, PPTX, TXT, and Markdown files.

Path
/v1/alRetrieval
Key scope
alretrieval

Supported file formats

PDF, DOCX, PPTX, TXT, MD

PDFs are processed via OCR; DOCX, PPTX, TXT, and MD have text extracted directly — no OCR cost

Scope Required: All alRetrieval endpoints require an API key with the alretrieval scope. Pass it as a Bearer token in the Authorization header.

How it works

Every request works inside a collection that belongs to your account: create a collection, upload documents, wait until they are ready, then retrieve passages or generate an answer that cites them. Lists are paged with limit, offset, total and has_more. Every response carries an X-Request-Id header; quote it when you contact support.

Code Examples:

retrieval_quickstart.py
import time, requests

BASE = "https://alapi.deep.sa/v1/alRetrieval"
headers = {"Authorization": "Bearer YOUR_API_KEY"}

# 1. Create a collection
cid = requests.post(f"{BASE}/collections", json={"name": "HR policies"}, headers=headers).json()["id"]

# 2. Upload a PDF
with open("leave-policy.pdf", "rb") as f:
    doc = requests.post(f"{BASE}/collections/{cid}/documents",
                        files={"file": f}, data={"title": "Leave policy"}, headers=headers).json()

# 3. Wait until it is searchable and its section tree is settled
while True:
    s = requests.get(f"{BASE}/collections/{cid}/documents/{doc['id']}/status", headers=headers).json()
    if s["status"] == "failed":
        raise RuntimeError(s["ingest"]["error"])
    if s["status"] == "ready" and s["deep_tree"]["status"] not in ("waiting", "queued", "processing"):
        break
    time.sleep(3)

# 4. Ask a question
answer = requests.post(f"{BASE}/collections/{cid}/answer",
                       json={"query": "كم مدة الإجازة السنوية؟"}, headers=headers).json()
print(answer["answer"])

POSTCreate a collection

Returns 201 with the new collection and a Location header. The body is optional.

POST /v1/alRetrieval/collections

Parameters:

ParameterTypeDescription
namestringoptional — up to 200 characters.

Response (201 Created):

{
  "id": "6a51b4e5c0d24f0e9b1a7c3d2e8f4a10",
  "name": "HR policies",
  "document_count": 0,
  "created_at": "2026-10-03T10:00:00Z"
}

Code Examples:

retrieval_create.py
import requests

headers = {"Authorization": "Bearer YOUR_API_KEY"}
collection = requests.post("https://alapi.deep.sa/v1/alRetrieval/collections",
                           json={"name": "HR policies"}, headers=headers).json()
print(collection["id"])

GETList collections

Your collections, newest first.

GET /v1/alRetrieval/collections?limit=100&offset=0

Parameters:

ParameterTypeDescription
limitintegeroptional — 1 to 500, default 100.
offsetintegeroptional — collections to skip, default 0.

Response (200 OK):

{
  "collections": [
    { "id": "6a51b4e5c0d24f0e9b1a7c3d2e8f4a10", "name": "HR policies", "document_count": 3, "created_at": "..." }
  ],
  "limit": 100,
  "offset": 0,
  "total": 1,
  "has_more": false
}

GETGet a collection

Returns the collection object.

GET /v1/alRetrieval/collections/{collection_id}
404 collection_not_found The collection does not exist in your account.

DELETEDelete a collection

Deletes the collection and every document in it.

DELETE /v1/alRetrieval/collections/{collection_id}

This cannot be undone.

Response (200 OK):

{ "id": "6a51b4e5c0d24f0e9b1a7c3d2e8f4a10", "deleted": true, "deleted_documents": 3 }

POSTUpload a document

Send a file or a URL as multipart/form-data, or text you have already extracted as JSON pages. Returns 202 with the document in status: "processing" and a Location header pointing at its status endpoint. A collection holds up to 500 documents.

POST /v1/alRetrieval/collections/{collection_id}/documents

Parameters:

ParameterTypeDescription
filefilePDF, DOCX, PPTX, TXT or MD, up to 100 MB.
urlstringInstead of file: a public HTTPS link alAPI downloads the document from (optional filename).
titlestringoptional — defaults to the file name without its extension.
pagesobject[]JSON body instead of a file: 1 to 5,000 entries of {"page_num", "text"}, with optional title and filename.

The document includes a view_url for the original file as soon as the upload is accepted, including while processing. Get and list responses include the same link; JSON pages have view_url: null. Request the link from your server with the same API key; keep the key out of the URL.

PDFs are OCR'd and charged per page from your OCR balance; the upload is refused with 402 when the file has more pages than you have available. Once processed, PDFs also get section-aware retrieval.

Response (202 Accepted):

{
  "id": "3146366e04ff",
  "collection_id": "6a51b4e5c0d24f0e9b1a7c3d2e8f4a10",
  "title": "Leave policy",
  "filename": "leave-policy.pdf",
  "view_url": "https://alapi.deep.sa/v1/alRetrieval/collections/6a51b4e5c0d24f0e9b1a7c3d2e8f4a10/documents/3146366e04ff/file",
  "source": "pdf",
  "page_count": 0,
  "created_at": "2026-10-03T10:01:12Z",
  "status": "processing",
  "ingest": { "stage": "queued", "error": null },
  "deep_tree": { "status": "waiting", "degraded": false, "error": null },
  "pipeline": null
}
400 missing_file The upload had no file, url or pages.
402 insufficient_balance Not enough OCR pages for this PDF.
409 document_limit_reached The collection already holds 500 documents.
413 file_too_large Files are limited to 100 MB.
415 unsupported_file_type Send PDF, DOCX, PPTX, TXT or MD.

Code Examples:

retrieval_upload.py
import requests

headers = {"Authorization": "Bearer YOUR_API_KEY"}
url = "https://alapi.deep.sa/v1/alRetrieval/collections/COLLECTION_ID/documents"

# A file
with open("leave-policy.pdf", "rb") as f:
    doc = requests.post(url, files={"file": f}, data={"title": "Leave policy"}, headers=headers).json()

# A public URL
doc = requests.post(url, data={"url": "https://example.com/handbook.pdf"}, headers=headers).json()

# Text you already extracted
doc = requests.post(url, json={
    "title": "دليل الموظف",
    "pages": [{"page_num": 1, "text": "سياسة الإجازات: ..."}],
}, headers=headers).json()
print(doc["id"], doc["status"])

GETGet document status

Poll every 2 to 5 seconds after an upload. A PDF first becomes searchable (status: ready), then its section tree is built in the background, usually within a few minutes. You can search as soon as status is ready; waiting for deep_tree as well makes results whole sections instead of pages.

GET /v1/alRetrieval/collections/{collection_id}/documents/{document_id}/status

Response (200 OK):

{
  "id": "3146366e04ff",
  "status": "ready",
  "ingest": { "stage": "ready", "error": null },
  "deep_tree": { "status": "ready", "degraded": false, "error": null },
  "pipeline": "deep_tree"
}
statusDescription
processingProcessing is running; ingest.stage names the step.
readySearchable.
failedProcessing stopped; ingest.error says why. Call retry.
deep_tree.statusDescription
not_supportedText documents: always searched page by page.
waiting / queued / processingThe section tree is on its way.
readySearches use whole sections. degraded: true means no usable table of contents was found.
skipped / failedNo tree; the document still works page by page. Retry rebuilds a failed tree.

pipeline is what a search of this document alone would use: deep_tree (sections) or basic (pages), or null while it is not ready. A search uses deep_tree only when every document in its scope has a ready tree.

GETList documents

Every document in the collection with its current status, newest first.

GET /v1/alRetrieval/collections/{collection_id}/documents?limit=500&offset=0

Parameters:

ParameterTypeDescription
limitintegeroptional — 1 to 500, default 500.
offsetintegeroptional — documents to skip, default 0.

Response (200 OK):

{
  "collection_id": "6a51b4e5c0d24f0e9b1a7c3d2e8f4a10",
  "documents": [ { "id": "3146366e04ff", "title": "Leave policy", "status": "ready", "pipeline": "deep_tree", ... } ],
  "limit": 500,
  "offset": 0,
  "total": 1,
  "has_more": false
}

GETGet a document

Returns the full document object.

GET /v1/alRetrieval/collections/{collection_id}/documents/{document_id}

Response (200 OK):

{
  "id": "3146366e04ff",
  "collection_id": "6a51b4e5c0d24f0e9b1a7c3d2e8f4a10",
  "title": "Leave policy",
  "filename": "leave-policy.pdf",
  "view_url": "https://alapi.deep.sa/v1/alRetrieval/collections/6a51b4e5c0d24f0e9b1a7c3d2e8f4a10/documents/3146366e04ff/file",
  "source": "pdf",
  "page_count": 10,
  "created_at": "2026-10-03T10:01:12Z",
  "status": "ready",
  "ingest": { "stage": "ready", "error": null },
  "deep_tree": { "status": "ready", "degraded": false, "error": null },
  "pipeline": "deep_tree"
}
fieldDescription
view_urlAPI-key-protected link to the original file, available while processing and until deletion. null for JSON pages or when no original file was retained.
sourcepdf or text.
page_countPages found; 0 until processing finishes.
status / ingest / deep_tree / pipelineAs in the status endpoint.

GET / HEADGet the original file

Returns the original uploaded file, or the file downloaded from url, unchanged. Send the same API key in the Authorization header. You can open it before the document is ready; the link stays valid until deletion. HEAD returns the status and headers without a body.

GET /v1/alRetrieval/collections/{collection_id}/documents/{document_id}/file
HEAD /v1/alRetrieval/collections/{collection_id}/documents/{document_id}/file
FileContent-TypeContent-Disposition
PDFapplication/pdfinline
TXTtext/plain; charset=utf-8inline
MDtext/markdown; charset=utf-8inline
DOCXapplication/vnd.openxmlformats-officedocument.wordprocessingml.documentattachment
PPTXapplication/vnd.openxmlformats-officedocument.presentationml.presentationattachment

The response includes Content-Length and both filename and UTF-8 filename* for Arabic names. A single byte range is supported per request; multiple ranges return 416 invalid_range. In your app, fetch the file from your server and serve it to the signed-in user.

Code Examples:

import requests

headers = {"Authorization": "Bearer YOUR_API_KEY"}
# doc is the document object from an upload, get or list response.
with requests.get(doc["view_url"], headers=headers, stream=True) as r:
    r.raise_for_status()
    with open("original.pdf", "wb") as f:
        for chunk in r.iter_content(65536):
            f.write(chunk)
404 document_not_foundThe document does not exist in this collection, or was deleted.
404 file_not_availableThe document was uploaded as JSON pages, or its original bytes were not retained.
416 invalid_rangeSend one byte range in a single Range header.

GETGet page text

The text extracted from each page, once the document is ready.

GET /v1/alRetrieval/collections/{collection_id}/documents/{document_id}/pages?start=1&end=3

Parameters:

ParameterTypeDescription
startintegeroptional — first page, from 1.
endintegeroptional — last page, inclusive. Default: the last page.

Response (200 OK):

{ "document_id": "3146366e04ff", "pages": [ { "page_num": 1, "text": "..." } ] }
409 document_not_ready Wait until the document is ready.

GETGet a document summary

A summary of the document and questions a reader could ask it: basic from its pages, deep_tree from its section tree. Values are null until that pipeline has produced them, such as deep_tree while the tree is still building. Free.

GET /v1/alRetrieval/collections/{collection_id}/documents/{document_id}/summary

Response (200 OK):

{
  "id": "3146366e04ff",
  "basic": { "summary": null, "suggested_questions": null },
  "deep_tree": { "summary": "...", "suggested_questions": ["...", "..."] }
}
409 document_not_ready Wait until the document is ready.

POSTRetry a failed document

If processing failed, runs it again; otherwise, if the section tree failed, builds the tree again. Returns 202 with the document. If OCR itself failed on the file, upload it again instead.

POST /v1/alRetrieval/collections/{collection_id}/documents/{document_id}/retry
409 nothing_to_retry Nothing failed; no action needed.

DELETEDelete a document

Deletes the document, its text and its index.

DELETE /v1/alRetrieval/collections/{collection_id}/documents/{document_id}

This cannot be undone.

Response (200 OK):

{ "id": "3146366e04ff", "deleted": true }

POSTRetrieve passages

Returns the passages most relevant to a query, without generating an answer. Use it to build your own prompt or show search results. Costs 1 request.

POST /v1/alRetrieval/collections/{collection_id}/retrieve

Parameters:

ParameterTypeDescription
querystringrequired — 1 to 4,000 characters, Arabic or English.
document_idsstring[]optional — search only these documents; omit to search every ready document.
top_kintegeroptional — 1 to 20, default 10.

Response (200 OK):

{
  "pipeline": "deep_tree",
  "document_ids": ["3146366e04ff"],
  "results": [
    {
      "document_id": "3146366e04ff",
      "document_title": "Leave policy",
      "text": "Document: Leave policy\nContext path: Chapter 2 / Article 5\n...",
      "score": 0.5773,
      "page_start": 4,
      "page_end": 5,
      "pages": [4, 5],
      "section": "Chapter 2: Leave / Article 5",
      "section_paths": ["Chapter 2: Leave / Article 5"],
      "is_direct_hit": true
    }
  ]
}

section is the heading path for citations (null for page results). pages lists the pages whose text is in text; page_start/page_end are its first and last, and a deep_tree result can skip pages in between. Compare score only within one response.

409 no_ready_documents No document in scope is ready yet.
409 document_not_ready A document in document_ids is not ready.
504 retrieval_timeout Retry, or narrow document_ids.

Code Examples:

retrieval_retrieve.py
import requests

headers = {"Authorization": "Bearer YOUR_API_KEY"}
r = requests.post("https://alapi.deep.sa/v1/alRetrieval/collections/COLLECTION_ID/retrieve",
                  json={"query": "كم مدة الإجازة السنوية؟", "top_k": 5}, headers=headers).json()
for p in r["results"]:
    print(p["document_title"], p["section"] or f"page {p['page_start']}", p["score"])

POSTSearch pages

Same parameters, response and errors as retrieve passages, but always searches pages, even when every document has a ready section tree, so pipeline is always basic. Costs 1 request.

POST /v1/alRetrieval/collections/{collection_id}/retrieve/basic

POSTGenerate an answer

Retrieves passages the same way as retrieve, then writes an answer grounded in them, in the language of the question, with inline citations: ((مسار: …)) for sections, ((صفحة N)) for pages. Use the structured sources array in your interface. Costs 2 requests (retrieval + generation). The API keeps no conversation state: send earlier turns in history.

POST /v1/alRetrieval/collections/{collection_id}/answer

Parameters:

ParameterTypeDescription
querystringrequired — 1 to 4,000 characters.
document_idsstring[]optional — as in retrieve.
historyobject[]optional — earlier turns, oldest first: {"role": "user" | "assistant", "content"}.
streambooleanoptional — stream the answer as server-sent events.

Response (200 OK):

{
  "answer": "الإجازة السنوية مدتها ثلاثون يوماً ((صفحة 1)).",
  "pipeline": "basic",
  "document_ids": ["3146366e04ff"],
  "sources": [ { "document_id": "3146366e04ff", "document_title": "Leave policy", "text": "...", "score": 1.0,
                 "page_start": 1, "page_end": 1, "pages": [1], "section": null, "section_paths": [], "is_direct_hit": true } ],
  "rephrased_query": null,
  "search_terms": null,
  "strategy": "fast"
}

rephrased_query and search_terms are set only when the first attempt found strong passages but no answer, so the question was retried once, rephrased; otherwise both are null. The stream's sources event carries them too.

strategy is "fast" or "agent". When the research agent answered (a structural question such as the last article of a law), steps lists what it read: {"index", "tool", "input", "result", "message", "elapsed_ms"}.

Streaming:

With "stream": true the response is text/event-stream: one sources event, many delta events, then done. An error event replaces done if generation fails mid-stream. Lines starting with : are keep-alive comments; ignore them. When the research agent answers, status events ({"message": "…"}, in the language of the question, ready to show while it works) and step events (the steps entries) come before sources.

event: sources
data: {"pipeline": "deep_tree", "document_ids": ["3146366e04ff"], "sources": [ ... ]}

event: delta
data: {"text": "الإجازة السنوية مدتها "}

event: delta
data: {"text": "ثلاثون يوماً ..."}

event: done
data: {"finish_reason": "stop"}
502 generation_failed A temporary failure; retry after a few seconds.
504 generation_timeout Retry, or narrow document_ids.

Code Examples:

retrieval_answer.py
import json, requests

headers = {"Authorization": "Bearer YOUR_API_KEY"}
url = "https://alapi.deep.sa/v1/alRetrieval/collections/COLLECTION_ID/answer"

answer = requests.post(url, json={"query": "كم مدة الإجازة السنوية؟"}, headers=headers).json()
print(answer["answer"])

# Streaming
with requests.post(url, json={"query": "وماذا بعد عشر سنوات؟", "stream": True,
                               "history": [{"role": "user", "content": "كم مدة الإجازة السنوية؟"},
                                           {"role": "assistant", "content": answer["answer"]}]},
                   headers=headers, stream=True) as res:
    event = None
    for line in res.iter_lines(decode_unicode=True):
        if line.startswith("event: "):
            event = line[7:]
        elif line.startswith("data: ") and event == "delta":
            print(json.loads(line[6:])["text"], end="", flush=True)

POSTSuggested questions

Writes starter questions a reader would ask about the collection, drawn from every ready document, keeps only those the documents can answer, and stores them in place of the previous list. Costs 1 request. GET on the same path returns the stored list without generating, and is free.

POST /v1/alRetrieval/collections/{collection_id}/suggested-questions
GET  /v1/alRetrieval/collections/{collection_id}/suggested-questions

Parameters:

ParameterTypeDescription
countintegeroptional — 1 to 12, default 6. The body may be omitted.

Response (200 OK):

{
  "questions": ["ما هي مدة الإجازة السنوية للعامل؟", "..."],
  "document_ids": ["3146366e04ff"],
  "generated_at": "2026-11-05T07:35:41Z"
}
404 suggested_questions_not_found None generated yet; send a POST first.
409 no_ready_documents Wait until at least one document is ready.
502 generation_failed A temporary failure; retry after a few seconds.
504 generation_timeout Retry.

Errors

Errors use standard HTTP status codes and one JSON shape. Branch on error.code, which is stable; message is for people and may change. Some errors also carry document_ids, statuses or details.

{
  "error": {
    "code": "document_not_ready",
    "message": "Documents not ready: '3146366e04ff' is processing.",
    "request_id": "7f3c1a9d0b2e4c6f8a1b3d5e7f9a0b2c",
    "document_ids": ["3146366e04ff"],
    "statuses": { "3146366e04ff": "processing" }
  }
}
HTTP / codeDescription
400 invalid_json / missing_fileFix the request.
402 insufficient_balanceThis month's requests or OCR pages are used up; upgrade at /pricing.
404 collection_not_found / document_not_foundThe id does not exist in your account.
409 document_not_ready / no_ready_documents / nothing_to_retry / document_limit_reachedSee the endpoint.
413 / 415File too large or unsupported type.
422 invalid_requestSee details; includes unknown fields and out-of-range values.
502 / 504A temporary upstream failure or timeout; retry.

Ready to Get Started?

Generate an API key from your dashboard and start building

Activate account?

Activate this account?