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-knowledge

Create 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)DefaultMeaning
base_url / baseUrlthe service host and its /knowledge path
api_key / apiKeythe project key. Needs Knowledge enabled on the project
user_id / userIdsent as X-User-Id. Required by the service
user_role / userRolenonesent as X-User-Role
user_scopes / userScopesnonesent as X-User-Scopes; narrows what this user can find. See What a user can see
timeout30.0 s / 30000 msper-request timeout
max_retries / maxRetries3retries 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 status is pending, processing, succeeded or failed. It becomes searchable at succeeded.
  • 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 failed with an error_code and error_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:

FieldMeaning
idthe document's ID
file_name, mime_type, size_byteswhat was uploaded
statuspending, processing, succeeded or failed
num_chunkspassages produced, once processed
attempts, error_code, error_detailprocessing attempts, and why it failed
embedding_modelthe model that embedded it
source_uriprovenance, if you gave one
created_at, ingested_attimestamps (ISO 8601)
accessowner, or shared when it was shared with you
duplicatetrue 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 document

documents.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.

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:

FieldMeaning
querythe question or phrase, 1–2,000 characters
top_khow many passages to return. Leave it out for the service's default (5); the maximum is 20
scope_idssearch only these scopes (and the scopes beneath them). A scope ID that doesn't exist is a 400
explainadd a diagnostics object explaining how the results were chosen

The response:

FieldMeaning
resultsthe passages, best first
abstainedtrue when the service judged nothing relevant and returned no results. Show your own empty state, and don't fall back to guessing
top_khow many were asked for after limits
diagnosticsonly 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:

FieldMeaning
document_id, file_namewhere the passage came from
chunk_index, pagewhere in the document: together, a citation
contentthe passage text
distancecosine distance; lower is closer
metadataextra detail about the passage
context_before, context_afterneighbouring 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:

  1. A scope type is a kind of grouping, like "Department".
  2. Scopes are its values, like "Finance" or "Engineering". They form a tree: "Accounts Payable" can sit under "Finance".
  3. 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 a 409 while scopes still use that type.
  • Scopes and tags are batch-only. One item is a one-item list. Every batch answers 207 with a per-outcome count and a results array, so check each result rather than the HTTP status.
  • A child's parent_scope_id must 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.
CallBodyOutcomes 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.listquery document_ids (repeat it per document){documents: [{..., scopes: [...]}]}; unknown or invisible documents are left out
scope_types.list, scopes.listquery 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 / userScopesSearches and lists
not setevery 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 ID

share_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

PythonTypeScriptEndpoint
documents.uploaddocuments.uploadPOST /documents
documents.upload_batchdocuments.uploadBatchPOST /documents/batch
documents.listdocuments.listGET /documents
documents.getdocuments.getGET /documents/{id}
documents.retrydocuments.retryPOST /documents/{id}/retry
documents.deletedocuments.deleteDELETE /documents/{id}
documents.share_create / share_list / share_deleteshareCreate / shareList / shareDelete/documents/{id}/share
searchsearchPOST /search
scope_types.create / list / deletescopeTypes.*/scope-types
scopes.create / list / deletescopes.*/scopes
document_scopes.link / list / deletedocumentScopes.*/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.

On this page