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:
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:
| Parameter | Type | Description |
|---|---|---|
name | string | optional — up to 200 characters. |
Response (201 Created):
{
"id": "6a51b4e5c0d24f0e9b1a7c3d2e8f4a10",
"name": "HR policies",
"document_count": 0,
"created_at": "2026-10-03T10:00:00Z"
}
Code Examples:
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:
| Parameter | Type | Description |
|---|---|---|
limit | integer | optional — 1 to 500, default 100. |
offset | integer | optional — 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}
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:
| Parameter | Type | Description |
|---|---|---|
file | file | PDF, DOCX, PPTX, TXT or MD, up to 100 MB. |
url | string | Instead of file: a public HTTPS link alAPI downloads the document from (optional filename). |
title | string | optional — defaults to the file name without its extension. |
pages | object[] | 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
}
Code Examples:
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"
}
| status | Description |
|---|---|
processing | Processing is running; ingest.stage names the step. |
ready | Searchable. |
failed | Processing stopped; ingest.error says why. Call retry. |
| deep_tree.status | Description |
|---|---|
not_supported | Text documents: always searched page by page. |
waiting / queued / processing | The section tree is on its way. |
ready | Searches use whole sections. degraded: true means no usable table of contents was found. |
skipped / failed | No 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:
| Parameter | Type | Description |
|---|---|---|
limit | integer | optional — 1 to 500, default 500. |
offset | integer | optional — 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"
}
| field | Description |
|---|---|
view_url | API-key-protected link to the original file, available while processing and until deletion. null for JSON pages or when no original file was retained. |
source | pdf or text. |
page_count | Pages found; 0 until processing finishes. |
status / ingest / deep_tree / pipeline | As 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
| File | Content-Type | Content-Disposition |
|---|---|---|
application/pdf | inline | |
| TXT | text/plain; charset=utf-8 | inline |
| MD | text/markdown; charset=utf-8 | inline |
| DOCX | application/vnd.openxmlformats-officedocument.wordprocessingml.document | attachment |
| PPTX | application/vnd.openxmlformats-officedocument.presentationml.presentation | attachment |
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)
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:
| Parameter | Type | Description |
|---|---|---|
start | integer | optional — first page, from 1. |
end | integer | optional — last page, inclusive. Default: the last page. |
Response (200 OK):
{ "document_id": "3146366e04ff", "pages": [ { "page_num": 1, "text": "..." } ] }
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": ["...", "..."] }
}
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
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:
| Parameter | Type | Description |
|---|---|---|
query | string | required — 1 to 4,000 characters, Arabic or English. |
document_ids | string[] | optional — search only these documents; omit to search every ready document. |
top_k | integer | optional — 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.
document_ids is not ready.
document_ids.
Code Examples:
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:
| Parameter | Type | Description |
|---|---|---|
query | string | required — 1 to 4,000 characters. |
document_ids | string[] | optional — as in retrieve. |
history | object[] | optional — earlier turns, oldest first: {"role": "user" | "assistant", "content"}. |
stream | boolean | optional — 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"}
document_ids.
Code Examples:
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:
| Parameter | Type | Description |
|---|---|---|
count | integer | optional — 1 to 12, default 6. The body may be omitted. |
Response (200 OK):
{
"questions": ["ما هي مدة الإجازة السنوية للعامل؟", "..."],
"document_ids": ["3146366e04ff"],
"generated_at": "2026-11-05T07:35:41Z"
}
POST first.
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 / code | Description |
|---|---|
400 invalid_json / missing_file | Fix the request. |
402 insufficient_balance | This month's requests or OCR pages are used up; upgrade at /pricing. |
404 collection_not_found / document_not_found | The id does not exist in your account. |
409 document_not_ready / no_ready_documents / nothing_to_retry / document_limit_reached | See the endpoint. |
413 / 415 | File too large or unsupported type. |
422 invalid_request | See details; includes unknown fields and out-of-range values. |
502 / 504 | A temporary upstream failure or timeout; retry. |
Ready to Get Started?
Generate an API key from your dashboard and start building