Knowledge
Upload documents, organise them into scopes, and search them by meaning.
The Knowledge service turns documents (PDF, DOCX, spreadsheets, slides, web pages and scans through OCR) into searchable passages. You upload a file, the service parses it, splits it into chunks, embeds each chunk, and from then on you can search by meaning. Scopes tag documents so each user only searches what they're allowed to see.
pip install aice-knowledgeCreate a client
import os
from aice_knowledge import KnowledgeClient
client = KnowledgeClient(
base_url=os.environ["AICE_KNOWLEDGE_URL"], # http://localhost:6100/knowledge
api_key=os.environ["AICE_API_KEY"],
user_id=current_user.id,
user_scopes=["finance"], # optional; see below
)| Argument (Python / TypeScript) | Default | Meaning |
|---|---|---|
base_url / baseUrl | the service host and its /knowledge path | |
api_key / apiKey | the project key. Needs Knowledge enabled on the project | |
user_id / userId | sent as X-User-Id. Required by the service | |
user_role / userRole | none | sent as X-User-Role |
user_scopes / userScopes | none | sent as X-User-Scopes; narrows what this user can find. See What a user can see |
timeout | 30.0 s / 30000 ms | per-request timeout |
max_retries / maxRetries | 3 | retries on network errors, 5xx and 429 |
Python also has AsyncKnowledgeClient with the same resources (await every call, close with await client.aclose()).
How a document is processed
upload ─▶ stored, hashed ─▶ pending ─▶ processing ─▶ succeeded
│ │
└─ same bytes seen before └─▶ failed ─▶ retry
▶ returned as a duplicate- A document's
statusispending,processing,succeededorfailed. It becomes searchable atsucceeded. - Identical bytes are never processed twice. Two uploads of the same file in one project return the same document with
duplicate: true. Another project uploading the same file gets its own independent document. - Processing is retried automatically with backoff. A permanent failure (an unsupported or corrupt file) skips the retries and lands in
failedwith anerror_codeanderror_detail. - Accepted types:
.pdf,.docx,.pptx,.xlsx,.csv,.html,.md,.adoc, and the images.png,.jpg,.jpeg,.tiff,.bmp,.webp(read with OCR). The default limits are 50 MB per file; a batch takes up to 20 files and 200 MB in total. Your deployment may differ.
Upload
with open("contract.pdf", "rb") as f:
doc = client.documents.upload(
file=f.read(),
filename="contract.pdf",
metadata={"source_uri": "https://intranet.example.com/contracts/42"},
)
print(doc["id"], doc["status"], doc["duplicate"])Of metadata, the service reads only source_uri: where the document came from, so a citation can show its URL instead of its file name.
The response is the document:
| Field | Meaning |
|---|---|
id | the document's ID |
file_name, mime_type, size_bytes | what was uploaded |
status | pending, processing, succeeded or failed |
num_chunks | passages produced, once processed |
attempts, error_code, error_detail | processing attempts, and why it failed |
embedding_model | the model that embedded it |
source_uri | provenance, if you gave one |
created_at, ingested_at | timestamps (ISO 8601) |
access | owner, or shared when it was shared with you |
duplicate | true when these exact bytes were already uploaded |
Status codes tell you what happened: 202 queued, 200 this exact file was already ingested (nothing to do), and 409 when the same file previously failed. A 409 is not retried automatically so a loop can't hide a permanent failure: call documents.retry(id) once you've looked at error_code.
Failures raise the usual errors: 400 for an empty or invalid file name, 413 too large, 415 unsupported type (the message lists the allowed ones).
Wait for processing
import time
while (doc := client.documents.get(doc["id"]))["status"] in ("pending", "processing"):
time.sleep(2)
if doc["status"] == "failed":
print(doc["error_code"], doc["error_detail"])Retry, list and delete
client.documents.retry(doc["id"]) # only for a "failed" document; 409 otherwise
page = client.documents.list(params={"status": "failed", "limit": 50, "offset": 0})
for d in page["documents"]:
print(d["id"], d["file_name"], d["error_code"])
client.documents.delete(doc["id"]) # deletes the documentdocuments.list returns {"documents": [...], "limit", "offset"}. Filters: status, batch_id (the progress view of one batch upload), limit (1–200, default 50) and offset. Documents outside the acting user's scopes are left out.
Batch upload
result = client.documents.upload_batch(
[("a.pdf", open("a.pdf", "rb").read(), "application/pdf"),
("b.pdf", open("b.pdf", "rb").read(), "application/pdf")],
sources=[{"uri": "https://example.com/a"}, {"uri": "https://example.com/b"}], # optional
)
for r in result["results"]:
print(r["outcome"], r.get("error_code"))A batch takes up to 20 files and 200 MB, and always answers 207 with {batch_id, total, accepted, duplicates, rejected, errors, results}. Each result says accepted, duplicate, rejected (with an error_code) or error, so one bad file never blocks the rest. Check each result rather than the HTTP status. The optional sources give each file its provenance, matched to the files by position; a length mismatch is refused before anything is sent. Use the batch_id with documents.list(params={"batch_id": ...}) to follow progress.
Search
result = client.search("payment terms", top_k=5)
if result["abstained"]:
print("nothing relevant")
for hit in result["results"]:
print(hit["file_name"], hit["page"], hit["distance"])
print(hit["content"])The request takes:
| Field | Meaning |
|---|---|
query | the question or phrase, 1–2,000 characters |
top_k | how many passages to return. Leave it out for the service's default (5); the maximum is 20 |
scope_ids | search only these scopes (and the scopes beneath them). A scope ID that doesn't exist is a 400 |
explain | add a diagnostics object explaining how the results were chosen |
The response:
| Field | Meaning |
|---|---|
results | the passages, best first |
abstained | true when the service judged nothing relevant and returned no results. Show your own empty state, and don't fall back to guessing |
top_k | how many were asked for after limits |
diagnostics | only with explain: the relevance band, whether the relevance gate was applied (gate_applied), how many results were dropped, and the distances behind the decision |
Each result:
| Field | Meaning |
|---|---|
document_id, file_name | where the passage came from |
chunk_index, page | where in the document: together, a citation |
content | the passage text |
distance | cosine distance; lower is closer |
metadata | extra detail about the passage |
context_before, context_after | neighbouring passages (each {chunk_index, page, content}), empty unless the deployment enables them |
The client's options are top_k, scope_ids and explain, named the same in both languages. Before 0.2.0 the result count was called limit; it is still accepted and sent as top_k.
Read gate_applied before trusting abstained
The relevance gate that sets abstained ships switched off in many deployments. Until it is on, abstained stays false however poor the best match is. Ask for explain: true and read diagnostics.gate_applied to see whether the gate ran, and use distance to judge relevance yourself if it didn't.
The service puts no rate limit on search, and each call costs an embedding pass. Rate-limit it in your own backend before you expose it to a browser.
Scopes
Scopes are how you control visibility inside a project. There are three pieces:
- A scope type is a kind of grouping, like "Department".
- Scopes are its values, like "Finance" or "Engineering". They form a tree: "Accounts Payable" can sit under "Finance".
- Tags link documents to scopes. A document can carry several.
A document with no tags is visible to everyone in the project. Only tagged documents are restricted, so you can adopt scopes gradually.
Build the tree
dept = client.scope_types.create({"name": "Department"})
type_id = dept["scope_type_id"]
top = client.scopes.create({
"scope_type_id": type_id,
"scopes": [{"name": "Finance"}, {"name": "Engineering"}],
})
finance_id = top["results"][0]["scope"]["scope_id"]
client.scopes.create({
"scope_type_id": type_id,
"scopes": [{"name": "Accounts Payable", "parent_scope_id": finance_id}],
})
client.document_scopes.link({"tags": [{"document_id": doc["id"], "scope_id": finance_id}]})- Scope types are created one at a time. A duplicate name is a
409.scope_types.delete(id)is a409while scopes still use that type. - Scopes and tags are batch-only. One item is a one-item list. Every batch answers
207with a per-outcome count and aresultsarray, so check each result rather than the HTTP status. - A child's
parent_scope_idmust already exist, so create a tree one level per call, parents first. - A batch holds at most 200 items; more is a
413. - A name must be unique among siblings. Cycles are rejected by the database.
| Call | Body | Outcomes in results |
|---|---|---|
scope_types.create | {name} | returns {scope_type_id, name, created_at} |
scopes.create | {scope_type_id, scopes: [{name, parent_scope_id?}]} | created (with the scope), rejected (invalid_name, invalid_parent, duplicate_name) |
scopes.delete | {scope_ids: [...]} | deleted, blocked (still in use), not_found |
document_scopes.link | {tags: [{document_id, scope_id}]} | tagged, already_tagged, not_found, rejected |
document_scopes.delete | {tags: [{document_id, scope_id}]} | untagged, not_found |
document_scopes.list | query document_ids (repeat it per document) | {documents: [{..., scopes: [...]}]}; unknown or invisible documents are left out |
scope_types.list, scopes.list | query limit, offset (and scope_type_id on scopes.list) | {scope_types: [...]} / {scopes: [...]} |
Pass several documents as a list: params={"document_ids": [id1, id2]} in Python, { document_ids: [id1, id2] } in TypeScript. Each is sent as its own document_ids query parameter.
What a user can see
The acting user's X-User-Scopes decides what they find:
user_scopes / userScopes | Searches and lists |
|---|---|
| not set | every document in the project |
["finance"] | untagged documents, and documents tagged with those scopes or any scope beneath them |
[] | untagged documents only |
Pass the scope IDs (the UUIDs from the tree). A unrestricted user and a restricted user with no scopes are different cases: None/omitted means no restriction, and an empty list means restricted to nothing. Set it from your own permissions for the user; the service trusts it because only your backend holds the key.
A request's scope_ids can narrow a search further, for example a department filter in a UI. It can only narrow: the effective filter is the overlap of what the user may see and what the request asked for, never more.
Sharing
documents.share_create(id, {"tenant_id": other_project_id}) gives another project read access to one document (the field is still called tenant_id). It then appears in that project's searches and listings with access: "shared", and the other project can tag it into its own scope tree. It can't retry or delete it, and can't re-share it.
client.documents.share_create(doc["id"], {"tenant_id": other_project_id})
print(client.documents.share_list(doc["id"])["shares"])
client.documents.share_delete(doc["id"], other_project_id) # takes the other project's IDshare_list returns {document_id, shares: [{tenant_id, permission, created_at}]}. Only the owning project can manage shares.
Use it from an agent
An agent searches Knowledge through a tool the Agent Platform provides: add Knowledge to the agent in Agent Studio (tool_bindings: ["knowledge"] in code). The agent can search, and can list the scopes it is allowed to use so it can narrow its own search. It never receives a project ID, and what it can reach is limited to the acting user's scopes. Documents the Crawler publishes land here too, with the page's URL as their source_uri.
Reference
| Python | TypeScript | Endpoint |
|---|---|---|
documents.upload | documents.upload | POST /documents |
documents.upload_batch | documents.uploadBatch | POST /documents/batch |
documents.list | documents.list | GET /documents |
documents.get | documents.get | GET /documents/{id} |
documents.retry | documents.retry | POST /documents/{id}/retry |
documents.delete | documents.delete | DELETE /documents/{id} |
documents.share_create / share_list / share_delete | shareCreate / shareList / shareDelete | /documents/{id}/share |
search | search | POST /search |
scope_types.create / list / delete | scopeTypes.* | /scope-types |
scopes.create / list / delete | scopes.* | /scopes |
document_scopes.link / list / delete | documentScopes.* | /document-scopes |
Uploads and sharing calls that create something carry an automatic Idempotency-Key and are retried on transient failures; deletes and reads always are. See Errors and retries.