Docs
Contents

Knowledge Base API

Before running the examples, replace <APPBASE_ENDPOINT_WITH_V1> with the intended environment API endpoint and verify that the project and credentials belong to that environment.

Full-chain API for rich-document RAG knowledge bases: knowledge base CRUD, document ingestion (Storage file registration + parse/chunk/Embedding pipeline), chunk-level maintenance, data source connections and synchronization, single-library/cross-library semantic retrieval, index rebuilding, and management observability.

Service and resource boundaries

The KnowledgeBases and Lexicons modules form the core engine of Agentbase platform's enterprise-grade multi-source RAG and query rewriting:

Among document location parameters, only creation supports sectionCode; retrieval and listing filter via documentTag and subProductId, and do not accept a standalone sectionCode filter parameter.

Resources and Base Paths

Authentication and Permissions

For authentication and request header conventions, see General Conventions. Scopes in this domain: knowledgebases.read (query, retrieval, management summary), knowledgebases.write (all write operations). Embedding / Rerank are executed via the LLM Gateway (provider reference format project:<providerId> or trial:<bindingId>, see llm-gateway).

Endpoint overview

This page covers two core path prefixes: /v1/knowledgebases (knowledge bases, documents, chunks, ingestion, data sources, and retrieval) and /v1/lexicons (project lexicons, lexicon entries, import/export, rewrite preview, and resource references).

Endpoint List

Method + pathPurpose
GET /knowledgebasesList knowledge bases
POST /knowledgebasesCreate knowledge base
GET /knowledgebases/{knowledgeBaseId}Get knowledge base
PATCH /knowledgebases/{knowledgeBaseId}Update knowledge base
DELETE /knowledgebases/{knowledgeBaseId}Delete knowledge base
POST /knowledgebases/searchCross-library retrieval (1–10 libraries)
POST /knowledgebases/{knowledgeBaseId}/searchSingle-library retrieval
GET /knowledgebases/{knowledgeBaseId}/managementManagement summary (recent ingestion/trace/scores)
POST /knowledgebases/{knowledgeBaseId}/reindexBounded batch index rebuild
GET /knowledgebases/{knowledgeBaseId}/documentsList documents
POST /knowledgebases/{knowledgeBaseId}/documentsRegister document; start ingestion separately
POST /knowledgebases/{knowledgeBaseId}/documents/batchBatch registration (up to 50 files)
DELETE /knowledgebases/{knowledgeBaseId}/documentsBatch delete documents (up to 50, atomic precheck)
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}Get document
PATCH /knowledgebases/{knowledgeBaseId}/documents/{documentId}Update document
DELETE /knowledgebases/{knowledgeBaseId}/documents/{documentId}Delete document
POST /knowledgebases/{knowledgeBaseId}/documents/{documentId}/processTrigger (re)processing
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/sourceDownload original source file
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/contentRead document content and truncation status
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/parse-artifactGet current parse artifact status
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/parse-artifact/contentRead parsed Markdown
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/chunksList chunks
POST /knowledgebases/{knowledgeBaseId}/documents/{documentId}/chunksManually create chunk
GET|PATCH|DELETE .../chunks/{chunkId}Chunk read/update/delete
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/ingestionsIngestion task list
POST /knowledgebases/{knowledgeBaseId}/documents/{documentId}/ingestionsStart ingestion
GET|DELETE .../ingestions/{ingestionId}Ingestion details/cancel
GET /knowledgebases/{knowledgeBaseId}/datasourcesList data sources
POST /knowledgebases/{knowledgeBaseId}/datasourcesCreate external data source (Yuque team space)
GET|PATCH|DELETE .../datasources/{dataSourceId}Data source read/update/delete
POST .../datasources/yuque/repos, POST .../datasources/yuque/docsEnumerate Yuque team repositories and document inventory
POST .../datasources/{dataSourceId}/documentsImport single document from data source URL
POST .../datasources/{dataSourceId}/documents/batchBatch import (up to 20 URLs)
GET|POST .../datasources/{dataSourceId}/syncs, GET .../syncs/{syncId}Data source synchronization and status polling
GET /knowledgebases/{knowledgeBaseId}/version-adoptionsList adoption operations (see version management)
POST /knowledgebases/{knowledgeBaseId}/version-adoptionsStart version adoption (async) (see version management)
GET /knowledgebases/{knowledgeBaseId}/version-adoptions/{adoptionId}Get adoption operation (see version management)
POST /knowledgebases/{knowledgeBaseId}/version-adoptions/{adoptionId}/cancelRequest adoption cancellation (async) (see version management)
GET /knowledgebases/{knowledgeBaseId}/version-delete-operations/{operationId}Query version deletion operation (see version management)
GET /knowledgebases/{knowledgeBaseId}/versionsList versions (see version management)
POST /knowledgebases/{knowledgeBaseId}/versionsCreate working copy (async) (see version management)
GET /knowledgebases/{knowledgeBaseId}/versions/{versionId}Get version (see version management)
DELETE /knowledgebases/{knowledgeBaseId}/versions/{versionId}Request irreversible version deletion (async) (see version management)
POST /knowledgebases/{knowledgeBaseId}/versions/{versionId}/publishPublish READY version as current version (see version management)
GET /knowledgebases/{knowledgeBaseId}/versions/{versionId}/readinessVersion readiness summary (see version management)
POST /knowledgebases/{knowledgeBaseId}/versions/{versionId}/rollbackRoll back to the retained rollback target (see version management)
POST /knowledgebases/{knowledgeBaseId}/versions/{versionId}/sealSeal DRAFT as READY (see version management)
GET /knowledgebases/{knowledgeBaseId}/working-copy-operationsList working copy operations (see version management)
GET /knowledgebases/{knowledgeBaseId}/working-copy-operations/{operationId}Get working copy operation (see version management)
POST /knowledgebases/{knowledgeBaseId}/working-copy-operations/{operationId}/cancelRequest cancellation of working copy operation (see version management)
GET /lexiconsList project lexicons
POST /lexiconsCreate project lexicon
GET /lexicons/{lexiconId}Get lexicon details
PATCH /lexicons/{lexiconId}Update lexicon metadata and permissions
DELETE /lexicons/{lexiconId}Delete an unbound lexicon
GET /lexicons/{lexiconId}/entriesList lexicon entries (supports filtering by entryType)
POST /lexicons/{lexiconId}/entriesCreate entry (synonym / expansion / stop)
GET|PATCH|DELETE /lexicons/{lexiconId}/entries/{entryId}Entry details/update/delete
POST /lexicons/{lexiconId}/previewPreview query rewrite and stopword hit effects
POST /lexicons/{lexiconId}/importBatch import entries (JSON / CSV / XLSX, supports dryRun)
GET /lexicons/{lexiconId}/exportExport lexicon entry file (JSON / CSV / XLSX)
GET /lexicons/{lexiconId}/referencesQuery the list of knowledge bases and agents bound to this lexicon
GET|PUT /knowledgebases/{knowledgeBaseId}/lexiconsQuery/wholesale replace the lexicon list bound to a knowledge base
GET|PUT /agent-runtime/project/lexiconsQuery/wholesale replace the lexicon list bound to the current project's agent workspace
GET|PATCH /knowledgebases/{knowledgeBaseId}/index-capabilities*, POST|GET .../index-operations*GraphRAG / RAPTOR / LLM Wiki index capability governance and build tasks (see Wiki and Index Governance)
GET /knowledgebases/{knowledgeBaseId}/graph*, GET|POST .../wiki/*Knowledge graph, entity neighbors, community reports, and LLM Wiki governance (see Wiki and Index Governance)

Endpoint details

Requests and Responses

The following sections provide, endpoint by endpoint across resource domains, inputs, outputs, and copyable call/response examples. General conventions:

Knowledge Base Management

GET /v1/knowledgebases

SDK:KnowledgeBases.list · scope:knowledgebases.read

List all knowledge bases in the current project, searchable by ID/name.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
searchquerystringNoDefault ""Filter by knowledge base ID or name, maximum 256 characters.

Output:

200, returns model Models.KnowledgeBaseList.

FieldTypeDescription
total*integerTotal number of knowledge bases matching the query.
knowledgeBases*object[]List of knowledge bases.
$id*stringKnowledge base ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
name*stringKnowledge base name.
description*stringKnowledge base description.
embeddingModel*stringEmbedding model ID pinned at creation time.
embeddingProviderRef*stringPinned Embedding provider source (project:<providerId> / trial:<bindingId>); empty means automatic routing.
embeddingDimension*integerEmbedding vector dimension, matching the model output; immutable after creation.
parserId*stringDefault chunk strategy: general / title / smart / regex / faq.
parserConfig*objectDefault parsing/chunk configuration (dynamic object; fields are described in the creation endpoint).
retrievalDefaults*objectRetrieval defaults (e.g., similarityThreshold, vectorWeight, rate limits).
vectorsdbDatabaseId*stringBacking VectorsDB database ID; null before provisioning completes.
vectorsdbCollectionId*stringBacking VectorsDB collection ID; null before provisioning completes.
bucketId*stringDefault Storage bucket ID (where source documents are stored); null before provisioning completes.
iconFileId*stringAvatar/icon file ID; null when not set.
ingestRoutes*objectDeprecated MIME→Function mapping, kept only for compatibility.
documentCount*integerTotal number of documents in the knowledge base.

Call example:

curl -X GET "https://<your-endpoint>/v1/knowledgebases?search=产品手册" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "total": 2,
  "knowledgeBases": [
    {
      "$id": "kb_product_docs",
      "$createdAt": "2026-08-30T09:00:00.000+00:00",
      "$updatedAt": "2026-09-14T02:01:12.000+00:00",
      "name": "产品文档库",
      "description": "产品手册与 FAQ 的检索库",
      "embeddingModel": "text-embedding-v3",
      "embeddingProviderRef": "",
      "embeddingDimension": 1024,
      "parserId": "smart",
      "parserConfig": {
        "chunkTokenNum": 512
      },
      "retrievalDefaults": {
        "similarityThreshold": 0.5,
        "vectorWeight": 0.7
      },
      "vectorsdbDatabaseId": "vdb_kb_docs",
      "vectorsdbCollectionId": "col_kb_docs",
      "bucketId": "bkt_kb_docs",
      "iconFileId": "",
      "ingestRoutes": {},
      "documentCount": 2
    }
  ]
}

POST /v1/knowledgebases

SDK:KnowledgeBases.create · scope:knowledgebases.write

Create a knowledge base: pin the Embedding model and automatically provision a dedicated VectorsDB database/collection and Storage bucket.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdbodystringYesKnowledge base ID: custom or generated as ID.unique().
namebodystringYesKnowledge base name.
descriptionbodystringNoKnowledge base description.
embeddingModelbodystringYesEmbedding model ID; the vector dimension is probed once against the LLM Gateway at creation time, and the model and dimension are immutable after creation.
embeddingProviderRefbodystringNoPin the Embedding provider (project:<providerId> / trial:<bindingId>); omit to use automatic routing.
embeddingDimensionbodyintegerNo1–65535Explicit vector dimension (2.9.0): validated by probing the selected model; creation fails if it does not match the model output dimension (400).
tracingEnabledbodybooleanNoDefault falseIngestion tracing switch (2.9.0): records parsing/chunk intermediate artifacts for use by knowledge base parsing evaluation; depends on a platform administrator global switch, and once enabled, re-ingestion is required for complete evidence.
parserId (or chunkingStrategy)bodystringNoEnum: general / title / smart / regex / faq / sheetKnowledge-base-level default chunking strategy; documents that do not override it are chunked according to this setting.
parserbodystringNoEnum: text / mineru / vlm / officeKnowledge-base-level default document parser shorthand (equivalent to parserConfig.documentParser).
parserConfigbodyobjectNoKnowledge-base-level default parsing/chunking and multimodal configuration (subfields below).
parserConfig.chunkTokenNumbodyintegerNoToken budget per chunk: general/smart defaults to 512, title/regex defaults to 256; range 64–4096.
parserConfig.overlapPercentbodyintegerNoDefault 10Token overlap percentage between adjacent chunks for the general/smart chunker; defaults to 10 (0–50).
parserConfig.delimiterbodystringNoFallback splitting delimiter for oversized title/regex chunks; defaults to \n。;!? for title and \n。.;;!!?? for regex.
parserConfig.titleLevelbodyintegerNoDefault 3Maximum Markdown heading level split by the title chunker (1–6, default 3, i.e., split down to ###).
parserConfig.minChunkTokensbodyintegerNoDefault 128Minimum chunk size for the smart chunker; defaults to 128 and must not exceed chunkTokenNum.
parserConfig.regexPatternbodystringNoDefault "[.!?]+\\s*"PCRE regular expression used by the regex chunker; defaults to [.!?]+\s*.
parserConfig.documentParserbodystringNoEnum: text / mineru / vlm / officeDocument parsing engine: text (plain text/source code parsing), mineru (structured parsing of complex-layout PDFs, tables, and formulas), vlm (full-page parsing by a vision LLM), office (native styles and header extraction for Word/Excel/PPT).
parserConfig.visionModelbodystringNoVision LLM used when documentParser=vlm (e.g., qwen-vl-max).
parserConfig.visionProviderRefbodystringNoPinned provider reference for the vision model (e.g., project:dashscope-prod).
parserConfig.imageUnderstanding (or top-level imageUnderstanding)bodyobjectNoMultimodal image understanding configuration: enabled (boolean, whether to enable illustration extraction and semantic transcription), providerRef (string, required, e.g., "project:dashscope-prod"), model (string, required, e.g., "qwen-vl-max"), maxConcurrency (integer, concurrency 1–8, default 4), prompt (string, custom vision understanding prompt), maxImagesPerDocument (integer, image limit per document, default 20), maxDescriptionChars (integer, description character limit per image, default 800).
retrievalDefaultsbodyobjectNoRetrieval defaults (e.g., similarityThreshold, vectorWeight).
ingestRoutesbodyobjectNoDeprecated MIME→Function mapping, kept only for compatibility.

Provisioning is asynchronous: vectorsdbDatabaseId / vectorsdbCollectionId / bucketId may briefly be null in the response; re-check with GET shortly after.

Output:

201, returns model Models.KnowledgeBase.

FieldTypeDescription
$id*stringKnowledge base ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
name*stringKnowledge base name.
description*stringKnowledge base description.
embeddingModel*stringEmbedding model ID pinned at creation time.
embeddingProviderRef*stringPinned Embedding provider source (project:<providerId> / trial:<bindingId>); empty means automatic routing.
embeddingDimension*integerEmbedding vector dimension, matching the model output; immutable after creation.
parserId*stringDefault chunk strategy: general / title / smart / regex / faq.
parserConfig*objectDefault parsing/chunk configuration (dynamic object; fields are described in the creation endpoint).
retrievalDefaults*objectRetrieval defaults (e.g., similarityThreshold, vectorWeight, rate limits).
vectorsdbDatabaseId*stringBacking VectorsDB database ID; null before provisioning completes.
vectorsdbCollectionId*stringBacking VectorsDB collection ID; null before provisioning completes.
bucketId*stringDefault Storage bucket ID (where source documents are stored); null before provisioning completes.
iconFileId*stringAvatar/icon file ID; null when not set.
ingestRoutes*objectDeprecated MIME→Function mapping, kept only for compatibility.
documentCount*integerTotal number of documents in the knowledge base.

Call example:

curl -X POST "https://<your-endpoint>/v1/knowledgebases" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "knowledgeBaseId": "kb_product_docs",
    "name": "产品文档库",
    "description": "产品手册与 FAQ 的检索库",
    "embeddingModel": "text-embedding-v3",
    "parserId": "smart",
    "parserConfig": {
      "chunkTokenNum": 512
    },
    "retrievalDefaults": {
      "similarityThreshold": 0.5,
      "vectorWeight": 0.7
    },
    "ingestRoutes": {}
  }'

Response example:

{
  "$id": "kb_product_docs",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "name": "产品文档库",
  "description": "产品手册与 FAQ 的检索库",
  "embeddingModel": "text-embedding-v3",
  "embeddingProviderRef": "",
  "embeddingDimension": 1024,
  "parserId": "smart",
  "parserConfig": {
    "chunkTokenNum": 512
  },
  "retrievalDefaults": {
    "similarityThreshold": 0.5,
    "vectorWeight": 0.7
  },
  "vectorsdbDatabaseId": "vdb_kb_docs",
  "vectorsdbCollectionId": "col_kb_docs",
  "bucketId": "bkt_kb_docs",
  "iconFileId": "",
  "ingestRoutes": {},
  "documentCount": 12
}

GET /v1/knowledgebases/{knowledgeBaseId}

SDK:KnowledgeBases.get · scope:knowledgebases.read

Get a knowledge base by ID (including provisioning status and document count).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.

Output:

200, returns model Models.KnowledgeBase.

FieldTypeDescription
$id*stringKnowledge base ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
name*stringKnowledge base name.
description*stringKnowledge base description.
embeddingModel*stringEmbedding model ID pinned at creation time.
embeddingProviderRef*stringPinned Embedding provider source (project:<providerId> / trial:<bindingId>); empty means automatic routing.
embeddingDimension*integerEmbedding vector dimension, matching the model output; immutable after creation.
parserId*stringDefault chunk strategy: general / title / smart / regex / faq.
parserConfig*objectDefault parsing/chunk configuration (dynamic object; fields are described in the creation endpoint).
retrievalDefaults*objectRetrieval defaults (e.g., similarityThreshold, vectorWeight, rate limits).
vectorsdbDatabaseId*stringBacking VectorsDB database ID; null before provisioning completes.
vectorsdbCollectionId*stringBacking VectorsDB collection ID; null before provisioning completes.
bucketId*stringDefault Storage bucket ID (where source documents are stored); null before provisioning completes.
iconFileId*stringAvatar/icon file ID; null when not set.
ingestRoutes*objectDeprecated MIME→Function mapping, kept only for compatibility.
documentCount*integerTotal number of documents in the knowledge base.

Call example:

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "$id": "kb_product_docs",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "name": "产品文档库",
  "description": "产品手册与 FAQ 的检索库",
  "embeddingModel": "text-embedding-v3",
  "embeddingProviderRef": "",
  "embeddingDimension": 1024,
  "parserId": "smart",
  "parserConfig": {
    "chunkTokenNum": 512
  },
  "retrievalDefaults": {
    "similarityThreshold": 0.5,
    "vectorWeight": 0.7
  },
  "vectorsdbDatabaseId": "vdb_kb_docs",
  "vectorsdbCollectionId": "col_kb_docs",
  "bucketId": "bkt_kb_docs",
  "iconFileId": "",
  "ingestRoutes": {},
  "documentCount": 12
}

PATCH /v1/knowledgebases/{knowledgeBaseId}

SDK:KnowledgeBases.update · scope:knowledgebases.write

Update the knowledge base name, default parsing configuration, or retrieval defaults (only the fields provided are changed).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
namebodystringNoNew name.
descriptionbodystringNoNew description.
embeddingProviderRefbodystringNoPin the Embedding provider; for existing knowledge bases this can be set only once.
parserIdbodystringNoEnum: general / title / smart / regex / faqKnowledge-base-level default chunk strategy.
parserConfigbodyobjectNoLibrary-level default parsing/chunking configuration (see sub-fields below).
parserConfig.chunkTokenNumbodyintegerNoToken budget per chunk: general/smart defaults to 512, title/regex defaults to 256.
parserConfig.overlapPercentbodyintegerNoDefault 10general Token overlap percentage for the chunker, default 10.
parserConfig.delimiterbodystringNoDelimiter for over-long title/regex chunks; default is \n。;!? for title and \n。.;;!!?? for regex.
parserConfig.titleLevelbodyintegerNoDefault 3title Markdown heading levels used by the chunker, default 3.
parserConfig.minChunkTokensbodyintegerNoDefault 128Minimum chunk size for the smart chunker; defaults to 128 and must not exceed chunkTokenNum.
parserConfig.regexPatternbodystringNoDefault "[.!?]+\\s*"regex PCRE expression used by the chunker, default [.!?]+\s*.
parserConfig.documentParserbodystringNoEnum: text / vlm / mineruDocument parser: text (plain text) / vlm (vision model) / mineru; MinerU deployment and credentials are outside the scope of this API.
parserConfig.visionModelbodystringNodocumentParser=vlm The vision model used at that time.
parserConfig.visionProviderRefbodystringNoPinned provider reference for the vision model.
parserConfig.imageUnderstandingbodyobjectNoImage interpretation configuration (dynamic object): when enabled=true, model and providerRef are required; also includes prompt, maxImagesPerDocument (default 20), maxDescriptionChars (default 800), maxConcurrency (default 4).
retrievalDefaultsbodyobjectNoRetrieval defaults.
ingestRoutesbodyobjectNoDeprecated field, kept only for compatibility.
iconFileIdbodystringNoFile ID of the avatar image (must already be uploaded to this library's default bucket); pass an empty string to clear the avatar.

Output:

200, returns model Models.KnowledgeBase. embeddingModel and embeddingDimension are fixed after library creation and cannot be modified through this endpoint.

FieldTypeDescription
$id*stringKnowledge base ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
name*stringKnowledge base name.
description*stringKnowledge base description.
embeddingModel*stringEmbedding model ID pinned at creation time.
embeddingProviderRef*stringPinned Embedding provider source (project:<providerId> / trial:<bindingId>); empty means automatic routing.
embeddingDimension*integerEmbedding vector dimension, matching the model output; immutable after creation.
parserId*stringDefault chunk strategy: general / title / smart / regex / faq.
parserConfig*objectDefault parsing/chunk configuration (dynamic object; fields are described in the creation endpoint).
retrievalDefaults*objectRetrieval defaults (e.g., similarityThreshold, vectorWeight, rate limits).
vectorsdbDatabaseId*stringBacking VectorsDB database ID; null before provisioning completes.
vectorsdbCollectionId*stringBacking VectorsDB collection ID; null before provisioning completes.
bucketId*stringDefault Storage bucket ID (where source documents are stored); null before provisioning completes.
iconFileId*stringAvatar/icon file ID; null when not set.
ingestRoutes*objectDeprecated MIME→Function mapping, kept only for compatibility.
documentCount*integerTotal number of documents in the knowledge base.

Call example:

curl -X PATCH "https://<your-endpoint>/v1/knowledgebases/kb_product_docs" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "产品文档库",
    "description": "产品手册与 FAQ 的检索库",
    "parserId": "smart",
    "parserConfig": {},
    "retrievalDefaults": {},
    "ingestRoutes": {}
  }'

Response example:

{
  "$id": "kb_product_docs",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "name": "产品文档库",
  "description": "产品手册与 FAQ 的检索库",
  "embeddingModel": "text-embedding-v3",
  "embeddingProviderRef": "",
  "embeddingDimension": 1024,
  "parserId": "smart",
  "parserConfig": {
    "chunkTokenNum": 512
  },
  "retrievalDefaults": {
    "similarityThreshold": 0.5,
    "vectorWeight": 0.7
  },
  "vectorsdbDatabaseId": "vdb_kb_docs",
  "vectorsdbCollectionId": "col_kb_docs",
  "bucketId": "bkt_kb_docs",
  "iconFileId": "",
  "ingestRoutes": {},
  "documentCount": 12
}

DELETE /v1/knowledgebases/{knowledgeBaseId}

SDK:KnowledgeBases.delete · scope:knowledgebases.write

Deletes the knowledge base, cascading deletion of data sources (including sync history), documents, and ingestion records, and asynchronously reclaims VectorsDB resources.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
deleteBucketbodybooleanNoWhen true, the default Storage bucket and all files in it are deleted as well; by default the bucket and files are retained.

Output:

204, no response body.

Call example:

curl -X DELETE "https://<your-endpoint>/v1/knowledgebases/kb_product_docs" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "deleteBucket": true
  }'

GET /v1/knowledgebases/{knowledgeBaseId}/management

SDK:KnowledgeBases.getManagement · scope:knowledgebases.read

Reads a knowledge base's content-agnostic processing and observability summary (recent ingestion, traces, evaluations).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
limitqueryintegerNoDefault 10Maximum number of entries each of recent ingestion/trace/evaluation includes, default 10.
fromquerystringNoDefault ""Start of the observability time window (ISO 8601).
toquerystringNoDefault ""End of the observability time window (ISO 8601).

Output:

200, returns a wide-type JSON object (spec does not fix the schema). Typically includes: recent ingestion task summaries (status/phase/duration), retrieval trace summaries, and evaluation records; fields depend on the actual deployment, and an illustrative skeleton is given here.

Call example:

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/management?limit=10&from=2026-09-01T00:00:00Z&to=2026-09-14T00:00:00Z" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "recentIngestions": [
    {
      "$id": "ing_3301",
      "documentId": "doc_manual_v2",
      "status": "ready",
      "stage": "embedding"
    }
  ],
  "recentTraces": [
    {
      "traceId": "4c9f2ab1",
      "operation": "search",
      "durationMs": 210
    }
  ],
  "recentScores": [
    {
      "documentId": "doc_manual_v2",
      "score": 0.91,
      "ratedAt": "2026-09-14T08:00:00.000+00:00"
    }
  ]
}

POST /v1/knowledgebases/{knowledgeBaseId}/reindex

SDK:KnowledgeBases.createReindex · scope:knowledgebases.write

Re-enqueues ready documents for ingestion in bounded batches (used to apply changes after updating library-level parsing configuration).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
limitbodyintegerNoMaximum number of ready documents to enqueue in this batch.
cursorbodystringNoDocument cursor returned by the previous batch's response.
idempotencyKeybodystringNoBatch idempotency key to prevent duplicate enqueueing.

Output:

202, returns model Models.KnowledgeBaseReindex; when nextCursor is not null, carry it to call the next batch.

FieldTypeDescription
queued*integerNumber of ready documents successfully enqueued for re-ingestion in this batch.
skipped*integerNumber of documents skipped because an active ingestion already exists.
failed*integerNumber of documents that failed to be enqueued in this batch.
nextCursor*stringCursor for the next batch; null indicates all complete.

Call example:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/reindex" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "limit": 50,
    "cursor": "cur_doc_0086",
    "idempotencyKey": "idem-reindex-01"
  }'

Response example:

{
  "queued": 12,
  "skipped": 0,
  "failed": 0,
  "nextCursor": null
}

Semantic Retrieval

POST /v1/knowledgebases/{knowledgeBaseId}/search

SDK:KnowledgeBases.createSearch · scope:knowledgebases.read

Single-library vector / full-text / hybrid retrieval, optionally reranked via the LLM Gateway, returning chunks with scores and sources.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
querybodystringYesQuery text.
limitbodyintegerNoDefault 10Number of results finally returned, range 1–100.
searchModebodystringNoDefault hybrid; enum: vector / fulltext / hybridRetrieval mode.
rerankbodybooleanNoDefault falseWhen true, retrieval is first widened, candidates are reranked via the LLM Gateway, and finally truncated to limit.
recallLimitbodyintegerNoWhen rerank is enabled, defaults to min(100, max(limit×4, 20)) if omitted; explicit values 1–100 and must not be less than limitRetrieval width when rerank is enabled; unused when rerank is off.
rerankModelbodystringNoExplicit rerank model ID; overrides automatic selection when rerank is enabled.
rerankProviderRefbodystringNoPinned rerank provider: project:<providerId> or trial:<bindingId>; do not use the providerType:providerId form.
similarityThresholdbodynumberNoMinimum vector similarity threshold (applies to the vector branch of vector and hybrid); omit to use the library's retrievalDefaults.similarityThreshold.
vectorWeightbodynumberNoWeight of the vector branch in hybrid mode (full-text gets 1 - vectorWeight); omit to use the library's retrievalDefaults.vectorWeight.
useKnowledgeGraphbodybooleanNoDefault falseWhen true, currently available GraphRAG retrieval results are included.
useWikibodybooleanNoDefault falseWhen true, currently available Wiki retrieval results are included.
graphOptionsbodyobjectNoDefault {}Bounded GraphRAG retrieval options; used only when useKnowledgeGraph=true.
wikiOptionsbodyobjectNoDefault {}Wiki retrieval options, including routing mode, topK, minK, and vector and bounded link expansion; used only when useWiki=true.
allowDegradedbodybooleanNoDefault trueWhether, when enhanced retrieval encounters a degradable error, to return ordinary retrieval results and list degradedCapabilities; when set to false, the error is propagated upward.
answerbodybooleanNoDefault falseAnswer synthesis (2.9.0): when true, the chat model from the knowledge base's indexingDefaults performs grounded synthesis of merged evidence (up to 12 lines of evidence, answer ≤1024 tokens), and the response carries a answer object.
documentTagbodystringNoDocument tags: server 2.12.0 supports multiple non-empty comma-separated tags and segment-aligned matching for chunk, GraphRAG, and Wiki retrieval.
subProductIdbodystringNoSub-product code filter (2.10.0): narrows retrieval by metadata.subProductId first; if absent, falls back to the sub-product segment of the first parseable structured tag with a non-empty sub-product segment; has AND semantics with documentTag.
metadataFilterbodyobjectNoDocument metadata filter (2.10.0): documents are filtered first, then chunks are retrieved; chunks of non-matching documents are excluded.
versionIdbodystringNoWhen omitted, versioned knowledge bases default to the current READY versionOptional version ID; retrieval is executed against the selected version.

Output:

200, returns model Models.KnowledgeBaseSearchResultList: results[] contains matched chunks, score (rerank score or retrieval score), and optional imageContexts; reranked indicates whether reranking succeeded. This endpoint is subject to both library-level retrievalDefaults.rateLimit/rateLimitPeriod and project rate limits.

FieldTypeDescription
total*integerNumber of results returned.
results*object[]List of retrieval results.
$id*stringDocument ID of the matched chunk.
content*stringBody text of the matched chunk.
sourceId*stringKnowledge base document ID the chunk belongs to.
source*objectDescription of the source document and protected source URI (dynamic object).
locator*objectSection/original-text locator of the chunk (dynamic object).
metadata*objectChunk metadata (internal provenance fields removed).
imageContexts*object[]Association projections of interpreted images within the chunk (response only, does not modify the chunk).
score*numberFinal ranking score: uses the reranker score if reranking succeeded, otherwise the initial retrieval score.
indexSource*stringResult source: rag, raptor, graphrag, or wiki.
resultType*stringResult type: chunk, raptor_summary, graph_context, or wiki_page.
resultGenerationstring / nullDerived index result generation; ordinary RAG chunks are null.
reranked*booleanWhether reranking via the LLM Gateway succeeded; false when automatic rerank failed and degraded.
resolvedVersionIdstring / nullThe version actually used for this search; null when versioned reads are not enabled.
capabilities*objectStatus, elapsed time, result generation, results, and redacted errors for RAPTOR, GraphRAG, and Wiki.
degradedCapabilities*object[]Enhanced capabilities that explicitly degraded; an empty array when no degradation occurred.
answerobject / nullAnswer synthesis result (2.9.0): status / text / model / latency; null when answer synthesis was not requested.

Call example:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/search" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "早餐机首次使用要注意什么",
    "limit": 5,
    "searchMode": "hybrid",
    "rerank": false,
    "similarityThreshold": 0.5,
    "vectorWeight": 0.7
  }'

Response example:

{
  "total": 2,
  "results": [
    {
      "$id": "chk_0042",
      "content": "早餐机首次使用前请用温水清洗内胆,并空烧一次完成除味。",
      "sourceId": "doc_manual_v2",
      "source": {
        "documentId": "doc_manual_v2",
        "uri": "/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/source"
      },
      "locator": {
        "generation": "gen_3",
        "chapter": 4,
        "order": 12
      },
      "metadata": {
        "page": 17
      },
      "imageContexts": [],
      "score": 0.91
    },
    {
      "$id": "chk_0043",
      "content": "清洗后首次空烧时若有轻微气味属正常现象,通风放置即可。",
      "sourceId": "doc_manual_v2",
      "source": {
        "documentId": "doc_manual_v2",
        "uri": "/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/source"
      },
      "locator": {
        "generation": "gen_3",
        "chapter": 4,
        "order": 13
      },
      "metadata": {
        "page": 17
      },
      "imageContexts": [
        {
          "chunkReferenceIndex": 0,
          "url": "/v1/storage/bkt_kb_docs/files/file_img_01/view",
          "description": "早餐机正面部件示意图:内胆、蒸汽阀与控制面板位置标注。"
        }
      ],
      "score": 0.86
    }
  ],
  "reranked": false
}

POST /v1/knowledgebases/search

SDK:KnowledgeBases.createMultiSearch · scope:knowledgebases.read

Cross-library retrieval (1–10 libraries): independent retrieval per library → RRF merge → a single unified rerank, returned in global ranking order.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdsbodystring[]YesArray of knowledge base IDs, 1–10 items with no duplicates.
querybodystringYesQuery text.
limitbodyintegerNoGlobal TopK (the final number of items after merging all libraries).
searchModebodystringNoEnum: vector / fulltext / hybridRetrieval mode: vector / fulltext / hybrid.
rerankbodybooleanNoWhen true, each library retrieves candidates independently; the server first merges them cross-library via RRF, then performs a single rerank on the merged candidate pool.
recallLimitbodyintegerNoGlobal retrieval width, capped at 100, and must be ≥ limit and ≥ the number of selected knowledge bases.
rerankModelbodystringNoExplicit rerank model ID.
rerankProviderRefbodystringNoPin the rerank provider (project: / trial: prefix).
similarityThresholdbodynumberNoMinimum similarity applied to each library; omit to use each library's default.
vectorWeightbodynumberNoHybrid vector weight applied to each library; omit to use each library's default.
documentTagbodystringNoDocument tags: server 2.12.0 supports multiple tags and segment-aligned matching, applied per knowledge base to chunk retrieval.
subProductIdbodystringNoSub-product code filter (2.10.0): narrows the retrieval scope per library.
metadataFilterbodyobjectNoDocument metadata filter (2.10.0): keyed by knowledge base ID, with an optional "*" key as a fallback applied to libraries not individually configured; documents are filtered before retrieval.
offsetbodyintegerNo0Number of results to skip after fusion ranking (2.10.0), combined with limit for pagination.

Output:

200, returns model Models.KnowledgeBaseMultiSearchResultList, with each result additionally carrying knowledgeBaseId. Strict failure semantics: if any library does not exist / is not provisioned / is rate-limited / fails retrieval, the entire request fails; on automatic rerank failure, it degrades to RRF order and sets reranked=false. Preflight, retrieval, global rerank, and serialization share a request-level total time limit of 30 seconds; on timeout 408 is returned. Response headers X-RateLimit-Limit/Remaining take the minimum across libraries, X-RateLimit-Reset takes the latest value, and X-AppBase-Trace-Id is the unified correlation ID for this cross-library request.

FieldTypeDescription
total*integerNumber of results returned.
results*object[]List of results in global ranking order.
$id*stringDocument ID of the matched chunk.
knowledgeBaseId*stringThe knowledge base ID containing the chunk; use (knowledgeBaseId, $id) for a cross-library stable identifier.
content*stringBody text of the matched chunk.
sourceId*stringKnowledge base document ID the chunk belongs to.
source*objectDescription of the source document and protected source URI (dynamic object).
locator*objectSection/original-text locator of the chunk (dynamic object).
metadata*objectChunk metadata (internal provenance fields removed).
imageContexts*object[]Association projections of interpreted images within the chunk (response only, does not modify the chunk).
score*numberFinal score: the reranker score if global reranking succeeded, otherwise the cross-library RRF score.
reranked*booleanWhether the merged results were successfully reranked once via the LLM Gateway.

Call example:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/search" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "knowledgeBaseIds": [
      "kb_product_docs",
      "kb_faq"
    ],
    "query": "早餐机保修多久",
    "limit": 8,
    "searchMode": "hybrid",
    "rerank": true,
    "similarityThreshold": 0,
    "vectorWeight": 0
  }'

Response example:

{
  "total": 2,
  "results": [
    {
      "$id": "chk_0042",
      "knowledgeBaseId": "kb_product_docs",
      "content": "早餐机首次使用前请用温水清洗内胆,并空烧一次完成除味。",
      "sourceId": "doc_manual_v2",
      "source": {
        "documentId": "doc_manual_v2",
        "uri": "/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/source"
      },
      "locator": {
        "generation": "gen_3",
        "chapter": 4,
        "order": 12
      },
      "metadata": {
        "page": 17
      },
      "imageContexts": [],
      "score": 0.91
    },
    {
      "$id": "chk_faq_007",
      "knowledgeBaseId": "kb_faq",
      "content": "早餐机整机保修 12 个月,加热元件保修 24 个月。",
      "sourceId": "doc_faq_v1",
      "source": {
        "documentId": "doc_faq_v1",
        "uri": "/v1/knowledgebases/kb_faq/documents/doc_faq_v1/source"
      },
      "locator": {
        "generation": "gen_1",
        "chapter": 2,
        "order": 3
      },
      "metadata": {},
      "imageContexts": [],
      "score": 0.84
    }
  ],
  "reranked": false
}

Document Management

GET /v1/knowledgebases/{knowledgeBaseId}/documents

SDK:KnowledgeBases.listDocuments · scope:knowledgebases.read

Lists documents in a knowledge base; filter by status/stage/enabled or use queries for advanced queries.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
versionIdquerystringNoVersion ID; when versioning is active, omission selects the current version.
statusquerystringNoDefault ""Filter by processing status: uploaded / processing / ready / failed.
stagequerystringNoDefault ""Filter by processing stage.
enabledquerybooleanNoFilter by enabled state.
documentTagquerystringNoFilter by document tags; server 2.12.0 supports multiple tags and segment-aligned matching.
subProductIdquerystringNoExact filter by sub-product code (2.10.0).
directoryPathquerystringNoFilters by a normalized directory and descendants; a non-empty value cannot be combined with documentTag or subProductId filters.
directoryUnclassifiedquerybooleanNoDefault falseLists only documents without a directory; true cannot be combined with documentTag or subProductId filters.
queriesquerystring[]NoDefault []Array of Appbase Query advanced query strings, at most 100 items with 4096 characters each. When documentTag or subProductId is non-empty, the server ignores queries, including filtering, sorting, and pagination; status, stage, and enabled still apply.

Directory filter boundaries: A non-empty directoryPath and directoryUnclassified=true are mutually exclusive; directory filters cannot be combined with non-empty documentTag or subProductId. Directory pagination allows Query.limit up to 100; larger values return general_query_invalid.

Output:

200, returns model Models.KnowledgeBaseDocumentList.

FieldTypeDescription
total*integerTotal number of documents matching the query.
documents*object[]List of documents.
$id*stringDocument ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringOwning knowledge base ID.
name*stringDocument display name.
bucketId*stringStorage bucket ID where the source file resides.
fileId*stringStorage file ID of the source file.
mimeType*stringMIME type of the source file.
source*stringSource: manual manual upload, datasource:{id} data source sync, yuque:personal personal Yuque import.
externalItemId*stringExternal system entry ID, used by data source sync for deduplicated updates.
parserId*stringDocument-level chunk strategy override; empty means inheriting the library default.
parserConfig*objectDocument-level parsing/chunking configuration override.
metadata*objectBusiness metadata.
status*stringProcessing status: uploaded registered / processing processing / ready ready / failed failed.
enabled*booleanWhether the document participates in retrieval; when false, chunks are retained but excluded from retrieval results.
stage*stringMirror of the pipeline stage of the current/most recent ingestion.
activeIngestionId*stringID of the current or most recent ingestion task.
activeGeneration*stringRetrieval-visible generation; valid only when status=ready.
processingStartedAt*stringTime of the most recent processing trigger.
chunksTotal*integerExpected total number of chunks (populated once known).
chunkCount*integerNumber of chunks in the active generation.
error*stringMost recent processing error message; normally an empty string.
lastExecutionId*stringDeprecated legacy Function execution ID.

Call example:

The example omits versionId; include the draft version ID as a query parameter when reading a draft.

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents?status=ready&stage=embedding&enabled=true" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "total": 2,
  "documents": [
    {
      "$id": "doc_manual_v2",
      "$createdAt": "2026-09-01T08:00:00.000+00:00",
      "$updatedAt": "2026-09-01T08:00:31.000+00:00",
      "kbId": "kb_product_docs",
      "name": "产品使用手册 v2.pdf",
      "bucketId": "bkt_kb_docs",
      "fileId": "file_9a11cc",
      "mimeType": "application/pdf",
      "source": "manual",
      "externalItemId": "",
      "parserId": "",
      "parserConfig": {},
      "metadata": {
        "edition": "v2"
      },
      "status": "ready",
      "enabled": true,
      "stage": "",
      "activeIngestionId": "ing_3301",
      "activeGeneration": "gen_3",
      "processingStartedAt": "2026-09-01T08:00:01.000+00:00",
      "chunksTotal": 86,
      "chunkCount": 86,
      "error": "",
      "lastExecutionId": ""
    },
    {
      "$id": "doc_faq_v1",
      "$createdAt": "2026-09-02T09:00:00.000+00:00",
      "$updatedAt": "2026-09-02T09:00:40.000+00:00",
      "kbId": "kb_product_docs",
      "name": "售后 FAQ.docx",
      "bucketId": "bkt_kb_docs",
      "fileId": "file_9b22aa",
      "mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "source": "manual",
      "externalItemId": "",
      "parserId": "faq",
      "parserConfig": {},
      "metadata": {},
      "status": "ready",
      "enabled": true,
      "stage": "",
      "activeIngestionId": "ing_3312",
      "activeGeneration": "gen_1",
      "processingStartedAt": "2026-09-02T09:00:05.000+00:00",
      "chunksTotal": 21,
      "chunkCount": 21,
      "error": "",
      "lastExecutionId": ""
    }
  ]
}

POST /v1/knowledgebases/{knowledgeBaseId}/documents

SDK:KnowledgeBases.createDocument · scope:knowledgebases.write

Registers a file already uploaded to Storage as a document (registration itself does not trigger ingestion; call the ingestion endpoint separately).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
versionIdbodystringNoRequired for writes when versioning is enabled; specify a DRAFT version ID.
bucketIdbodystringNoBucket ID where the source file resides; defaults to the library's default bucket if omitted.
fileIdbodystringYesStorage file ID of the uploaded source file (required).
namebodystringNoDocument display name; defaults to the source file name if omitted.
sourcebodystringNoDocument source marker, default manual.
externalItemIdbodystringNoEntry ID when originating from an external data source (used for sync deduplication).
documentTagbodystringNoDocument tags: server 2.12.0 accepts free-form values and multiple non-empty comma-separated tags. A structured locator may omit its final segment, which the server generates on write; read the stored value for subsequent filtering.
subProductIdbodystringNoSub-product code (2.10.0, 1–64 letters/digits), stored in metadata.subProductId; when a non-empty documentTag is also submitted and this field is omitted or emptied, it is derived only if the first tag is a valid structured locator with a non-empty sub-product segment. A free-form first tag does not guarantee derivation, even when a later tag is structured. Retrieval prefers the standalone field and otherwise falls back to the sub-product segment of the first parseable structured tag with a non-empty sub-product segment.
sectionCodebodystringNoSection code (2.10.0, 1–64 digits); when documentTag is omitted, it is embedded in the automatically generated locator identifier.
parserId (or chunkingStrategy)bodystringNoEnum: general / title / smart / regex / faq / sheetDocument-level chunk strategy override (inherits the knowledge base default strategy when omitted).
parserbodystringNoEnum: text / mineru / vlm / officeDocument-level parsing engine shorthand override (equivalent to parserConfig.documentParser).
parserConfigbodyobjectNoDocument-level parsing/chunking and multimodal configuration override (see sub-fields below).
parserConfig.chunkTokenNumbodyintegerNoToken budget per chunk: general/smart defaults to 512, title/regex defaults to 256.
parserConfig.overlapPercentbodyintegerNoDefault 10general/smart Token overlap percentage for the chunker, default 10.
parserConfig.delimiterbodystringNoDelimiter for over-long title/regex chunks; default is \n。;!? for title and \n。.;;!!?? for regex.
parserConfig.titleLevelbodyintegerNoDefault 3title Markdown heading levels used by the chunker, default 3.
parserConfig.minChunkTokensbodyintegerNoDefault 128Minimum chunk size for the smart chunker; defaults to 128 and must not exceed chunkTokenNum.
parserConfig.regexPatternbodystringNoDefault "[.!?]+\\s*"regex PCRE expression used by the chunker, default [.!?]+\s*.
parserConfig.documentParserbodystringNoEnum: text / mineru / vlm / officeDocument parsing engine: text (plain text) / mineru (MinerU complex layout and table parsing) / vlm (vision large model full-page parsing) / office (Office structured extraction).
parserConfig.visionModelbodystringNodocumentParser=vlm the vision model used at that time (e.g., qwen-vl-max).
parserConfig.visionProviderRefbodystringNoPinned provider reference for the vision model (e.g., project:dashscope-prod).
parserConfig.imageUnderstanding (or top-level imageUnderstanding)bodyobjectNoMultimodal image understanding configuration: enabled (boolean), providerRef (string, e.g. "project:dashscope-prod"), model (string, e.g. "qwen-vl-max"), maxConcurrency (integer, default 4), prompt (string), maxImagesPerDocument (default 20), maxDescriptionChars (default 800).
metadatabodyobjectNoBusiness metadata.

After registration, call POST .../ingestions (or POST .../process) to trigger the parsing → chunk → Embedding pipeline.

Output:

201, returns model Models.KnowledgeBaseDocument (initial status=uploaded).

FieldTypeDescription
$id*stringDocument ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringOwning knowledge base ID.
name*stringDocument display name.
bucketId*stringStorage bucket ID where the source file resides.
fileId*stringStorage file ID of the source file.
mimeType*stringMIME type of the source file.
source*stringSource: manual manual upload, datasource:{id} data source sync, yuque:personal personal Yuque import.
externalItemId*stringExternal system entry ID; data source sync uses it for deduplication and updates.
parserId*stringDocument-level chunk strategy override; empty inherits the knowledge base default.
parserConfig*objectDocument-level parsing/chunk configuration override.
metadata*objectBusiness metadata.
status*stringProcessing status: uploaded registered / processing processing / ready ready / failed failed.
enabled*booleanWhether it participates in retrieval; when false, chunks are retained but excluded from retrieval results.
stage*stringMirror of the pipeline stage for the current/most recent ingestion.
activeIngestionId*stringID of the current or most recent ingestion task.
activeGeneration*stringRetrieval-visible generation; only valid when status=ready.
processingStartedAt*stringTime of the most recent processing trigger.
chunksTotal*integerExpected total number of chunks (filled once known).
chunkCount*integerNumber of chunks in the active generation.
error*stringMost recent processing error message; normally an empty string.
lastExecutionId*stringDeprecated legacy Function execution ID.

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "fileId": "file_9a11cc",
    "name": "产品使用手册 v2.pdf",
    "source": "ops-console",
    "parserId": "smart",
    "parserConfig": {},
    "metadata": {
      "edition": "v2"
    }
  }'

Advanced example of multi-parser and chunk/multimodal image understanding invocation (SIT baseline environment kb_enterprise_support):

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
: "${APPBASE_PROJECT_ID:?Set APPBASE_PROJECT_ID for the target environment}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X POST "${APPBASE_ENDPOINT}/knowledgebases/kb_enterprise_support/documents" \
  -H "X-Appwrite-Project: ${APPBASE_PROJECT_ID}" \
  --header @- \
  -H "Content-Type: application/json" \
  -d '{
    "bucketId": "kb_enterprise_docs",
    "fileId": "file_ob_arch_v43",
    "name": "OceanBase-V4.3-高可用架构白皮书.pdf",
    "source": "manual",
    "documentTag": "oceanbase_4301_8f9a2b3c4d5e6f708192a3b4c5d6e7f8",
    "subProductId": "oceanbase",
    "sectionCode": "4301",
    "parser": "mineru",
    "chunkingStrategy": "smart",
    "parserId": "smart",
    "parserConfig": {
      "documentParser": "mineru",
      "chunkTokenNum": 600,
      "minChunkTokens": 150,
      "overlapPercent": 15,
      "imageUnderstanding": {
        "enabled": true,
        "providerRef": "project:dashscope-prod",
        "model": "qwen-vl-max",
        "maxConcurrency": 4,
        "maxImagesPerDocument": 20,
        "maxDescriptionChars": 800,
        "prompt": "请提取架构图与故障排查流程图中的核心组件、数据流向与告警阈值,输出结构化文字说明。"
      }
    },
    "imageUnderstanding": {
      "enabled": true,
      "providerRef": "project:dashscope-prod",
      "model": "qwen-vl-max",
      "maxConcurrency": 4,
      "prompt": "请提取架构图与故障排查流程图中的核心组件、数据流向与告警阈值,输出结构化文字说明。"
    },
    "metadata": {
      "department": "DBA支持中心",
      "version": "4.3"
    }
  }'

)

Response example:

{
  "$id": "doc_manual_v2",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "name": "产品使用手册 v2.pdf",
  "bucketId": "bkt_kb_docs",
  "fileId": "file_9a11cc",
  "mimeType": "application/pdf",
  "source": "manual",
  "externalItemId": "",
  "parserId": "",
  "parserConfig": {},
  "metadata": {
    "edition": "v2"
  },
  "status": "ready",
  "enabled": true,
  "stage": "",
  "activeIngestionId": "ing_3301",
  "activeGeneration": "gen_3",
  "processingStartedAt": "2026-09-01T08:00:01.000+00:00",
  "chunksTotal": 86,
  "chunkCount": 86,
  "error": "",
  "lastExecutionId": ""
}

DELETE /v1/knowledgebases/{knowledgeBaseId}/documents

SDK: KnowledgeBases.deleteDocuments · scope: knowledgebases.write

ParameterLocationTypeRequiredDescription
knowledgeBaseIdpathstringYesKnowledge base ID.
documentIdsbodystring[]YesIDs of 1–50 documents to delete.
versionIdbodystringWhen versioning is enabledSelects a DRAFT version.

Deletion follows preflight checks and returns 204 on success. Verify the target first; an active versioned knowledge base requires the draft version ID.

POST /v1/knowledgebases/{knowledgeBaseId}/documents/batch

SDK:KnowledgeBases.createDocumentsBatch · scope:knowledgebases.write

Batch-register documents (1–50 files; validate all first, then create).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
versionIdbodystringNoRequired for writes when versioning is enabled; specify a DRAFT version ID.
fileIdsbodystring[]YesArray of Storage file IDs, 1–50 items with no duplicates.
bucketIdbodystringNoBucket containing the files; defaults to the knowledge base default bucket; all files must be in the same bucket.
sourcebodystringNoSource marker for all documents, default manual.
parserIdbodystringNoEnum: general / title / smart / regex / faqDocument-level chunk strategy override (applies to this batch).
parserConfigbodyobjectNoDocument-level parsing/chunk configuration override (applies to this batch; see sub-fields below).
parserConfig.chunkTokenNumbodyintegerNoToken budget per chunk: general/smart defaults to 512, title/regex defaults to 256.
parserConfig.overlapPercentbodyintegerNoDefault 10general Token overlap percentage for the chunker, default 10.
parserConfig.delimiterbodystringNoDelimiter for over-long title/regex chunks; default is \n。;!? for title and \n。.;;!!?? for regex.
parserConfig.titleLevelbodyintegerNoDefault 3title Markdown heading levels used by the chunker, default 3.
parserConfig.minChunkTokensbodyintegerNoDefault 128Minimum chunk size for the smart chunker; defaults to 128 and must not exceed chunkTokenNum.
parserConfig.regexPatternbodystringNoDefault "[.!?]+\\s*"regex PCRE expression used by the chunker, default [.!?]+\s*.
parserConfig.documentParserbodystringNoEnum: text / vlm / mineruDocument parser: text (plain text) / vlm (vision model) / mineru; MinerU deployment and credentials are outside the scope of this API.
parserConfig.visionModelbodystringNodocumentParser=vlm The vision model used at that time.
parserConfig.visionProviderRefbodystringNoPinned provider reference for the vision model.
parserConfig.imageUnderstandingbodyobjectNoImage interpretation configuration (dynamic object): when enabled=true, model and providerRef are required; also includes prompt, maxImagesPerDocument (default 20), maxDescriptionChars (default 800), maxConcurrency (default 4).
metadatabodyobjectNoBusiness metadata shared by documents in this batch.

Output:

201, returns model Models.KnowledgeBaseDocumentList; afterwards ingestion must be initiated per document.

FieldTypeDescription
total*integerTotal number of documents matching the query.
documents*object[]List of documents.
$id*stringDocument ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringOwning knowledge base ID.
name*stringDocument display name.
bucketId*stringStorage bucket ID where the source file resides.
fileId*stringStorage file ID of the source file.
mimeType*stringMIME type of the source file.
source*stringSource: manual manual upload, datasource:{id} data source sync, yuque:personal personal Yuque import.
externalItemId*stringExternal system entry ID, used by data source sync for deduplicated updates.
parserId*stringDocument-level chunk strategy override; empty means inheriting the library default.
parserConfig*objectDocument-level parsing/chunking configuration override.
metadata*objectBusiness metadata.
status*stringProcessing status: uploaded registered / processing processing / ready ready / failed failed.
enabled*booleanWhether the document participates in retrieval; when false, chunks are retained but excluded from retrieval results.
stage*stringMirror of the pipeline stage of the current/most recent ingestion.
activeIngestionId*stringID of the current or most recent ingestion task.
activeGeneration*stringRetrieval-visible generation; valid only when status=ready.
processingStartedAt*stringTime of the most recent processing trigger.
chunksTotal*integerExpected total number of chunks (populated once known).
chunkCount*integerNumber of chunks in the active generation.
error*stringMost recent processing error message; normally an empty string.
lastExecutionId*stringDeprecated legacy Function execution ID.

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/batch" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "fileIds": [
      "file_9a11cc",
      "file_9a12dd"
    ],
    "source": "manual",
    "parserId": "smart",
    "parserConfig": {},
    "metadata": {
      "topic": "早餐店经营"
    }
  }'

Response example:

{
  "total": 2,
  "documents": [
    {
      "$id": "doc_manual_v2",
      "$createdAt": "2026-09-01T08:00:00.000+00:00",
      "$updatedAt": "2026-09-01T08:00:31.000+00:00",
      "kbId": "kb_product_docs",
      "name": "产品使用手册 v2.pdf",
      "bucketId": "bkt_kb_docs",
      "fileId": "file_9a11cc",
      "mimeType": "application/pdf",
      "source": "manual",
      "externalItemId": "",
      "parserId": "",
      "parserConfig": {},
      "metadata": {
        "edition": "v2"
      },
      "status": "ready",
      "enabled": true,
      "stage": "",
      "activeIngestionId": "ing_3301",
      "activeGeneration": "gen_3",
      "processingStartedAt": "2026-09-01T08:00:01.000+00:00",
      "chunksTotal": 86,
      "chunkCount": 86,
      "error": "",
      "lastExecutionId": ""
    },
    {
      "$id": "doc_faq_v1",
      "$createdAt": "2026-09-02T09:00:00.000+00:00",
      "$updatedAt": "2026-09-02T09:00:40.000+00:00",
      "kbId": "kb_product_docs",
      "name": "售后 FAQ.docx",
      "bucketId": "bkt_kb_docs",
      "fileId": "file_9b22aa",
      "mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "source": "manual",
      "externalItemId": "",
      "parserId": "faq",
      "parserConfig": {},
      "metadata": {},
      "status": "ready",
      "enabled": true,
      "stage": "",
      "activeIngestionId": "ing_3312",
      "activeGeneration": "gen_1",
      "processingStartedAt": "2026-09-02T09:00:05.000+00:00",
      "chunksTotal": 21,
      "chunkCount": 21,
      "error": "",
      "lastExecutionId": ""
    }
  ]
}

GET /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/content

Scope: knowledgebases.read. SDK method availability depends on the published version.

ParameterLocationTypeRequiredDescription
knowledgeBaseIdpathstringYesKnowledge base ID.
documentIdpathstringYesDocument ID.
versionIdquerystringNoKnowledge base version ID; the current version is used when omitted for an active versioned knowledge base.

A successful response returns 200 and a document-content object including content, chunksTotal, truncated, and generation. When truncated is true, the returned content is incomplete. This is distinct from the parse-artifact endpoints.

GET /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}

SDK:KnowledgeBases.getDocument · scope:knowledgebases.read

Get a document by ID (including processing status, generation, and chunk count).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdquerystringNoOptional; with versioning enabled, omission reads the current version. Specify the draft ID to read a draft.
documentIdpathstringYesTarget document ID.

Output:

200, returns model Models.KnowledgeBaseDocument.

FieldTypeDescription
$id*stringDocument ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringOwning knowledge base ID.
name*stringDocument display name.
bucketId*stringStorage bucket ID where the source file resides.
fileId*stringStorage file ID of the source file.
mimeType*stringMIME type of the source file.
source*stringSource: manual manual upload, datasource:{id} data source sync, yuque:personal personal Yuque import.
externalItemId*stringExternal system entry ID; data source sync uses it for deduplication and updates.
parserId*stringDocument-level chunk strategy override; empty inherits the knowledge base default.
parserConfig*objectDocument-level parsing/chunk configuration override.
metadata*objectBusiness metadata.
status*stringProcessing status: uploaded registered / processing processing / ready ready / failed failed.
enabled*booleanWhether it participates in retrieval; when false, chunks are retained but excluded from retrieval results.
stage*stringMirror of the pipeline stage for the current/most recent ingestion.
activeIngestionId*stringID of the current or most recent ingestion task.
activeGeneration*stringRetrieval-visible generation; only valid when status=ready.
processingStartedAt*stringTime of the most recent processing trigger.
chunksTotal*integerExpected total number of chunks (filled once known).
chunkCount*integerNumber of chunks in the active generation.
error*stringMost recent processing error message; normally an empty string.
lastExecutionId*stringDeprecated legacy Function execution ID.

Call example:

The example omits versionId; include the draft version ID as a query parameter when reading a draft.

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "$id": "doc_manual_v2",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "name": "产品使用手册 v2.pdf",
  "bucketId": "bkt_kb_docs",
  "fileId": "file_9a11cc",
  "mimeType": "application/pdf",
  "source": "manual",
  "externalItemId": "",
  "parserId": "",
  "parserConfig": {},
  "metadata": {
    "edition": "v2"
  },
  "status": "ready",
  "enabled": true,
  "stage": "",
  "activeIngestionId": "ing_3301",
  "activeGeneration": "gen_3",
  "processingStartedAt": "2026-09-01T08:00:01.000+00:00",
  "chunksTotal": 86,
  "chunkCount": 86,
  "error": "",
  "lastExecutionId": ""
}

PATCH /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}

SDK:KnowledgeBases.updateDocument · scope:knowledgebases.write

Update the document name, chunk override configuration, metadata, or enabled status (only fields provided are changed).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired for writes when versioning is enabled; specify a DRAFT version ID.
documentIdpathstringYesTarget document ID.
namebodystringNoDocument display name.
parserIdbodystringNoEnum: general / title / smart / regex / faq / (empty, meaning no restriction)Document-level chunk strategy override; passing an empty string clears the override and falls back to the knowledge base default.
parserConfigbodyobjectNoDocument-level parsing/chunk configuration override (see sub-fields below).
parserConfig.chunkTokenNumbodyintegerNoToken budget per chunk: general/smart defaults to 512, title/regex defaults to 256.
parserConfig.overlapPercentbodyintegerNoDefault 10general Token overlap percentage for the chunker, default 10.
parserConfig.delimiterbodystringNoDelimiter for over-long title/regex chunks; default is \n。;!? for title and \n。.;;!!?? for regex.
parserConfig.titleLevelbodyintegerNoDefault 3title Markdown heading levels used by the chunker, default 3.
parserConfig.minChunkTokensbodyintegerNoDefault 128Minimum chunk size for the smart chunker; defaults to 128 and must not exceed chunkTokenNum.
parserConfig.regexPatternbodystringNoDefault "[.!?]+\\s*"regex PCRE expression used by the chunker, default [.!?]+\s*.
parserConfig.documentParserbodystringNoEnum: text / vlm / mineruDocument parser: text (plain text) / vlm (vision model) / mineru; MinerU deployment and credentials are outside the scope of this API.
parserConfig.visionModelbodystringNodocumentParser=vlm The vision model used at that time.
parserConfig.visionProviderRefbodystringNoPinned provider reference for the vision model.
parserConfig.imageUnderstandingbodyobjectNoImage interpretation configuration (dynamic object): when enabled=true, model and providerRef are required; also includes prompt, maxImagesPerDocument (default 20), maxDescriptionChars (default 800), maxConcurrency (default 4).
metadatabodyobjectNoBusiness metadata.
documentTagbodystringNoUpdate the document locator identifier (2.10.0, same format as creation); empty string clears it.
subProductIdbodystringNoUpdate the sub-product code (2.10.0); when a non-empty documentTag is also submitted and this field is omitted or cleared, it is derived only if the first tag is a valid structured locator with a non-empty sub-product segment. A free-form first tag does not guarantee derivation, even when a later tag is structured. When no non-empty label is submitted together with it, an empty string deletes the standalone field, but effective filter values can still fall back to the sub-product segment of the first parseable structured tag with a non-empty sub-product segment; to remove both, clear both fields at the same time.
enabledbodybooleanNoWhen set to false, the document's chunks are retained but excluded from retrieval results.
statusbodystringNoProcessing status (legacy correction field, modifiable only via API Key).
stagebodystringNoProcessing stage (legacy correction field, modifiable only via API Key).
chunksTotalbodyintegerNoTotal chunk count (legacy correction field, modifiable only via API Key).
chunkCountbodyintegerNoChunk count (legacy correction field, modifiable only via API Key).
errorbodystringNoError message (legacy correction field, modifiable only via API Key).

Output:

200, returns model Models.KnowledgeBaseDocument. parserId/parserConfig cannot be changed while an ingestion is queued/running/cancelling.

FieldTypeDescription
$id*stringDocument ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringOwning knowledge base ID.
name*stringDocument display name.
bucketId*stringStorage bucket ID where the source file resides.
fileId*stringStorage file ID of the source file.
mimeType*stringMIME type of the source file.
source*stringSource: manual manual upload, datasource:{id} data source sync, yuque:personal personal Yuque import.
externalItemId*stringExternal system entry ID; data source sync uses it for deduplication and updates.
parserId*stringDocument-level chunk strategy override; empty inherits the knowledge base default.
parserConfig*objectDocument-level parsing/chunk configuration override.
metadata*objectBusiness metadata.
status*stringProcessing status: uploaded registered / processing processing / ready ready / failed failed.
enabled*booleanWhether it participates in retrieval; when false, chunks are retained but excluded from retrieval results.
stage*stringMirror of the pipeline stage for the current/most recent ingestion.
activeIngestionId*stringID of the current or most recent ingestion task.
activeGeneration*stringRetrieval-visible generation; only valid when status=ready.
processingStartedAt*stringTime of the most recent processing trigger.
chunksTotal*integerExpected total number of chunks (filled once known).
chunkCount*integerNumber of chunks in the active generation.
error*stringMost recent processing error message; normally an empty string.
lastExecutionId*stringDeprecated legacy Function execution ID.

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

curl -X PATCH "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "产品使用手册 v2.pdf",
    "parserId": "general",
    "parserConfig": {},
    "metadata": {
      "topic": "早餐店经营"
    },
    "enabled": true,
    "chunksTotal": 0,
    "chunkCount": 0
  }'

Response example:

{
  "$id": "doc_manual_v2",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "name": "产品使用手册 v2.pdf",
  "bucketId": "bkt_kb_docs",
  "fileId": "file_9a11cc",
  "mimeType": "application/pdf",
  "source": "manual",
  "externalItemId": "",
  "parserId": "",
  "parserConfig": {},
  "metadata": {
    "edition": "v2"
  },
  "status": "ready",
  "enabled": true,
  "stage": "",
  "activeIngestionId": "ing_3301",
  "activeGeneration": "gen_3",
  "processingStartedAt": "2026-09-01T08:00:01.000+00:00",
  "chunksTotal": 86,
  "chunkCount": 86,
  "error": "",
  "lastExecutionId": ""
}

DELETE /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}

SDK:KnowledgeBases.deleteDocument · scope:knowledgebases.write

Delete the document: cascades deletion of all its chunks (VectorsDB), ingestion records, and decrements the knowledge base document count.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired for writes when versioning is enabled; specify a DRAFT version ID.
documentIdpathstringYesTarget document ID.

Output:

204, no response body.

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

curl -X DELETE "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

POST /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/process

SDK:KnowledgeBases.createDocumentProcess · scope:knowledgebases.write

Trigger one (re)processing run of an existing document with its current configuration, equivalent to creating an ingestion with default parameters.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired for writes when versioning is enabled; specify a DRAFT version ID.
documentIdpathstringYesTarget document ID.

Output:

202, returns model Models.KnowledgeBaseIngestion. Asynchronous task: poll GET .../ingestions/{ingestionId} until a terminal state (ready / failed / cancelled), or subscribe to the Realtime channel in trackingChannels of the response.

FieldTypeDescription
$id*stringIngestion task ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringKnowledge base ID.
documentId*stringDocument ID.
status*stringTask status: queued / running / ready / failed / cancelling / cancelled.
stage*stringCurrent pipeline stage (parsing → chunk → Embedding).
generation*stringGeneration written by this ingestion.
progress*objectProgress object: completed / total / unit.
effectiveConfig*objectSnapshot of the configuration frozen in effect for this ingestion.
configHash*stringeffectiveConfig hash, used to compare whether the configuration has changed.
retryOf*stringPrevious ingestion ID pointed to on retry.
attemptId*stringFencing token for this attempt.
idempotencyKey*stringRequester's idempotency key.
error*stringError message when failed.
startedAt*stringTime the worker started processing.
finishedAt*stringIngestion end time.
trackingChannels*objectRealtime subscription channels: ingestion (this task) and document (parent document).

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/process" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "$id": "ing_3301",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "documentId": "doc_manual_v2",
  "status": "running",
  "stage": "embedding",
  "generation": "gen_3",
  "progress": {
    "completed": 60,
    "total": 86,
    "unit": "chunks"
  },
  "effectiveConfig": {
    "parserId": "smart",
    "parserConfig": {
      "chunkTokenNum": 512
    }
  },
  "configHash": "blake3:9f2ca7",
  "retryOf": "",
  "attemptId": "att_b7d2",
  "idempotencyKey": "idem-20260914-0001",
  "error": "",
  "startedAt": "2026-09-01T08:00:01.000+00:00",
  "finishedAt": "",
  "trackingChannels": {
    "ingestion": "ingestion:ing_3301",
    "document": "document:doc_manual_v2"
  }
}

GET /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/source

SDK:KnowledgeBases.getDocumentSource · scope:knowledgebases.read

Download the original source file of the document (binary stream, not JSON).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdquerystringNoOptional; with versioning enabled, omission reads the current version. Specify the draft ID to read a draft.
documentIdpathstringYesTarget document ID.

Save the file with -o; do not parse it as JSON.

Output:

200, File binary content (Content-Type is the source file's MIME type), for archiving or manual verification.

Call example:

The example omits versionId; include the draft version ID as a query parameter when reading a draft.

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/source" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Chunks

Tag matching boundaries: 2.12.0 uses underscore-delimited segment prefixes for both structured and free-form tags: finance can match finance_confidential_notes. Removing trailing empty segments from ___ can match documents with tags; avoid all-underscore filters. This filter is not an authorization boundary. Effective subProductId resolution skips free-form tags and structured tags with an empty sub-product segment; for example, _12_<fileKey> followed by ob_12_<fileKey> can resolve to ob. An explicit field takes precedence.

Read a document parse artifact

Both REST endpoints require knowledgebases.read; availability of SDK methods depends on the published artifact. A parse artifact is Markdown produced before chunking, not a chunk list.

Get artifact status

GET /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/parse-artifact

ParameterLocationTypeRequiredDescription
knowledgeBaseIdpathstringYesKnowledge base ID.
documentIdpathstringYesDocument ID.
versionIdquerystringNoSelects a knowledge base version; when version management is active, omission uses the current version.
(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
  builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- -sS "${APPBASE_ENDPOINT:?Set endpoint including /v1}/knowledgebases/${KB_ID:?Set KB_ID}/documents/${DOCUMENT_ID:?Set DOCUMENT_ID}/parse-artifact" \
    -H "X-Appwrite-Project: ${APPBASE_PROJECT_ID:?Set project ID}"
)

A successful request returns 200; byteSize and sha256 below are illustrative:

{
  "knowledgeBaseId": "kb_example",
  "documentId": "doc_example",
  "status": "ready",
  "supported": true,
  "generation": "gen_1",
  "byteSize": 36,
  "sha256": "81968d11f4746b211ad5eed0cb1a6e732a2da734b2ff2a6754ce52c31149d45e"
}

status can be not_generated, ready, or too_large; an artifact from a non-active generation is reported as not_generated. For a successfully loaded document, this version always returns supported: true; it does not establish whether the document or parser has produced an artifact. Use status, the active generation, and the content endpoint to determine availability. generation, byteSize, and sha256 can be null when unavailable.

Read artifact content

GET /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/parse-artifact/content accepts the same path parameters and optional versionId query parameter.

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
  builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- -sS "${APPBASE_ENDPOINT:?Set endpoint including /v1}/knowledgebases/${KB_ID:?Set KB_ID}/documents/${DOCUMENT_ID:?Set DOCUMENT_ID}/parse-artifact/content" \
    -H "X-Appwrite-Project: ${APPBASE_PROJECT_ID:?Set project ID}"
)

200 returns text/markdown; charset=utf-8. Check status before calling the content endpoint:

HTTP statusError typeMeaning
400general_argument_invalidThe artifact was too large to store.
404storage_file_not_foundThe artifact was not generated or no longer belongs to the active generation; re-ingest if needed and check again.

Missing knowledge bases, documents, or versions and insufficient permissions can return their respective errors; inspect the actual error type.

GET /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/chunks

SDK:KnowledgeBases.listChunks · scope:knowledgebases.read

List chunks of the document's currently active generation, supporting keyword search and advanced queries over content.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdquerystringNoOptional; with versioning enabled, omission reads the current version. Specify the draft ID to read a draft.
documentIdpathstringYesTarget document ID.
searchquerystringNoDefault ""Keyword search within chunk body text.
queriesquerystring[]NoDefault []Array of Appbase Query advanced query strings, up to 100 items.

Output:

200, returns model Models.KnowledgeBaseChunkList.

FieldTypeDescription
total*integerTotal number of chunks matching the query.
chunks*object[]List of chunks.
$id*stringChunk ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
documentId*stringOwning document ID.
content*stringChunk body text.
ingestVersion*stringIngestion generation the chunk belongs to.
source*objectAuthoritative source document description and protected source URI (dynamic object).
locator*objectVersioned section and source text locators (dynamic object).
metadata*objectChunk metadata, with internal provenance fields stripped.

Call example:

The example omits versionId; include the draft version ID as a query parameter when reading a draft.

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/chunks?search=首次使用" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "total": 2,
  "chunks": [
    {
      "$id": "chk_0042",
      "$createdAt": "2026-09-01T08:00:31.000+00:00",
      "$updatedAt": "2026-09-01T08:00:31.000+00:00",
      "documentId": "doc_manual_v2",
      "content": "早餐机首次使用前请用温水清洗内胆,并空烧一次完成除味。",
      "ingestVersion": "gen_3",
      "source": {
        "documentId": "doc_manual_v2",
        "uri": "/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/source"
      },
      "locator": {
        "generation": "gen_3",
        "chapter": 4,
        "order": 12
      },
      "metadata": {
        "page": 17
      }
    },
    {
      "$id": "chk_0043",
      "$createdAt": "2026-09-01T08:00:31.000+00:00",
      "$updatedAt": "2026-09-01T08:00:31.000+00:00",
      "documentId": "doc_manual_v2",
      "content": "清洗后首次空烧时若有轻微气味属正常现象,通风放置即可。",
      "ingestVersion": "gen_3",
      "source": {
        "documentId": "doc_manual_v2",
        "uri": "/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/source"
      },
      "locator": {
        "generation": "gen_3",
        "chapter": 4,
        "order": 13
      },
      "metadata": {
        "page": 17
      }
    }
  ]
}

POST /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/chunks

SDK:KnowledgeBases.createChunk · scope:knowledgebases.write

Manually create chunks for a document directly, bypassing the parsing pipeline (embeddings are computed by the LLM Gateway).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired for writes when versioning is enabled; specify a DRAFT version ID.
documentIdpathstringYesTarget document ID.
contentbodystringYesChunk body text (required).
metadatabodyobjectNoArbitrary chunk metadata.

Output:

201, returning model Models.KnowledgeBaseChunk; the document's chunkCount/chunksTotal increment accordingly. The document must already have an active generation (i.e., ingestion has been completed at least once).

FieldTypeDescription
$id*stringChunk ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
documentId*stringOwning document ID.
content*stringChunk body text.
ingestVersion*stringIngestion generation the chunk belongs to.
source*objectAuthoritative source document description and protected source URI (dynamic object).
locator*objectVersioned section and source text locators (dynamic object).
metadata*objectChunk metadata, with internal provenance fields stripped.

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/chunks" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "保修政策:自购买之日起整机保修 12 个月。",
    "metadata": {
      "section": "售后"
    }
  }'

Response example:

{
  "$id": "chk_0042",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "documentId": "doc_manual_v2",
  "content": "早餐机首次使用前请用温水清洗内胆,并空烧一次完成除味。",
  "ingestVersion": "gen_3",
  "source": {
    "documentId": "doc_manual_v2",
    "uri": "/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/source"
  },
  "locator": {
    "generation": "gen_3",
    "chapter": 4,
    "order": 12
  },
  "metadata": {
    "page": 17
  }
}

GET /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/chunks/{chunkId}

SDK:KnowledgeBases.getChunk · scope:knowledgebases.read

Get a single chunk by ID.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdquerystringNoOptional; with versioning enabled, omission reads the current version. Specify the draft ID to read a draft.
documentIdpathstringYesTarget document ID.
chunkIdpathstringYesTarget chunk ID.

Output:

200, returns model Models.KnowledgeBaseChunk.

FieldTypeDescription
$id*stringChunk ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
documentId*stringOwning document ID.
content*stringChunk body text.
ingestVersion*stringIngestion generation the chunk belongs to.
source*objectAuthoritative source document description and protected source URI (dynamic object).
locator*objectVersioned section and source text locators (dynamic object).
metadata*objectChunk metadata, with internal provenance fields stripped.

Call example:

The example omits versionId; include the draft version ID as a query parameter when reading a draft.

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/chunks/chk_0042" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "$id": "chk_0042",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "documentId": "doc_manual_v2",
  "content": "早餐机首次使用前请用温水清洗内胆,并空烧一次完成除味。",
  "ingestVersion": "gen_3",
  "source": {
    "documentId": "doc_manual_v2",
    "uri": "/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/source"
  },
  "locator": {
    "generation": "gen_3",
    "chapter": 4,
    "order": 12
  },
  "metadata": {
    "page": 17
  }
}

PATCH /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/chunks/{chunkId}

SDK:KnowledgeBases.updateChunk · scope:knowledgebases.write

Update a chunk's content, metadata, or retrieval enablement. Changing content (or image description metadata) recomputes the vector. A disabled chunk is excluded from knowledge base search and remains disabled across document publications. Re-enabling it permits retrieval only when the document, ingestion generation, and version publication state allow it. This describes the REST API; enabled support in an SDK depends on the SDK version.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
documentIdpathstringYesTarget document ID.
chunkIdpathstringYesTarget chunk ID.
contentbodystringNoNew body text; providing it triggers vector recomputation (along with persisted image descriptions).
metadatabodyobjectNoChunk metadata; vectors are recomputed only when image descriptions change.
enabledbodybooleanNoWhether the chunk may participate in retrieval; omit to leave unchanged.
versionIdbodystringNoDRAFT version ID is required for writes when versioning is active.

Output:

200, returns model Models.KnowledgeBaseChunk.

FieldTypeDescription
$id*stringChunk ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
documentId*stringOwning document ID.
content*stringChunk body text.
ingestVersion*stringIngestion generation the chunk belongs to.
enabledbooleanWhether the chunk may participate in retrieval.
source*objectAuthoritative source document description and protected source URI (dynamic object).
locator*objectVersioned section and source text locators (dynamic object).
metadata*objectChunk metadata, with internal provenance fields stripped.

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X PATCH "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/chunks/chk_0042" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  --header @- \
  -H "Content-Type: application/json" \
  -d '{
    "content": "Warranty lasts 24 months from purchase.",
    "enabled": false,
    "metadata": {
      "topic": "warranty"
    }
  }'
)

Response example:

{
  "$id": "chk_0042",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "documentId": "doc_manual_v2",
  "content": "Warranty lasts 24 months from purchase.",
  "enabled": false,
  "ingestVersion": "gen_3",
  "source": {
    "documentId": "doc_manual_v2",
    "uri": "/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/source"
  },
  "locator": {
    "generation": "gen_3",
    "chapter": 4,
    "order": 12
  },
  "metadata": {
    "topic": "warranty"
  }
}

DELETE /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/chunks/{chunkId}

SDK:KnowledgeBases.deleteChunk · scope:knowledgebases.write

Delete a single chunk; the parent document's chunkCount/chunksTotal decrease accordingly.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired for writes when versioning is enabled; specify a DRAFT version ID.
documentIdpathstringYesTarget document ID.
chunkIdpathstringYesTarget chunk ID.

Output:

204, no response body.

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

curl -X DELETE "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/chunks/chk_0042" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Ingestion

GET /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/ingestions

SDK:KnowledgeBases.listIngestions · scope:knowledgebases.read

List the ingestion task history of a document; filter and sort with queries.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdquerystringNoOptional; with versioning enabled, omission reads the current version. Specify the draft ID to read a draft.
documentIdpathstringYesTarget document ID.
queriesquerystring[]NoDefault []Array of Appbase Query advanced query strings, up to 100 items.

Output:

200, returns model Models.KnowledgeBaseIngestionList.

FieldTypeDescription
total*integerTotal number of ingestion tasks matching the query.
ingestions*object[]List of ingestion tasks.
$id*stringIngestion task ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringKnowledge base ID.
documentId*stringDocument ID.
status*stringTask status: queued / running / ready / failed / cancelling / cancelled.
stage*stringCurrent pipeline stage (parse → chunk → Embedding).
generation*stringGeneration written by this ingestion.
progress*objectProgress object: completed / total / unit.
effectiveConfig*objectSnapshot of configuration frozen and applied for this ingestion.
configHash*stringHash of effectiveConfig, used to detect configuration changes.
retryOf*stringPrevious ingestion ID referenced when retrying.
attemptId*stringFencing token for this attempt.
idempotencyKey*stringRequester's idempotency key.
error*stringError message when failed.
startedAt*stringTime the worker started processing.
finishedAt*stringIngestion end time.
trackingChannels*objectRealtime subscription channels: ingestion (this task) and document (parent document).

Call example:

The example omits versionId; include the draft version ID as a query parameter when reading a draft.

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/ingestions" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "total": 2,
  "ingestions": [
    {
      "$id": "ing_3301",
      "$createdAt": "2026-09-01T08:00:00.000+00:00",
      "$updatedAt": "2026-09-01T08:00:31.000+00:00",
      "kbId": "kb_product_docs",
      "documentId": "doc_manual_v2",
      "status": "ready",
      "stage": "embedding",
      "generation": "gen_3",
      "progress": {
        "completed": 86,
        "total": 86,
        "unit": "chunks"
      },
      "effectiveConfig": {
        "parserId": "smart",
        "parserConfig": {
          "chunkTokenNum": 512
        }
      },
      "configHash": "blake3:9f2ca7",
      "retryOf": "",
      "attemptId": "att_b7d2",
      "idempotencyKey": "idem-20260914-0001",
      "error": "",
      "startedAt": "2026-09-01T08:00:01.000+00:00",
      "finishedAt": "2026-09-01T08:00:31.000+00:00",
      "trackingChannels": {
        "ingestion": "ingestion:ing_3301",
        "document": "document:doc_manual_v2"
      }
    }
  ]
}

POST /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/ingestions

SDK:KnowledgeBases.createIngestion · scope:knowledgebases.write

Trigger an ingestion for a document (parse → chunk → Embedding); 202 executes asynchronously.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired for writes when versioning is enabled; specify a DRAFT version ID.
documentIdpathstringYesTarget document ID.
idempotencyKeybodystringNoIdempotency key: retrying with the same key returns the existing ingestion instead of enqueueing a duplicate.
retryOfbodystringNoID of a previous failed ingestion to retry.
persistToDocumentbodybooleanNoWhen true, the overrides for this ingestion are promoted to document-level configuration after ingestion completes.
overridesbodyobjectNoParsing overrides effective only for this ingestion; embedding-related fields are rejected (see subfields below).
overrides.parserIdbodystringNoEnum: general / title / smart / regex / faqChunking strategy override for this ingestion.
overrides.parserConfigbodyobjectNoParse/chunk configuration overrides effective only for this ingestion; subfields are the same as parserConfig (see the knowledge base creation endpoint); embedding fields are rejected.

Output:

202, returning model Models.KnowledgeBaseIngestion (initial status=queued). Polling approach : GET .../ingestions/{ingestionId} every 2–3 seconds, status until a terminal state of ready/failed/cancelled is reached; alternatively, subscribe to the trackingChannels channel for real-time progress.

FieldTypeDescription
$id*stringIngestion task ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringKnowledge base ID.
documentId*stringDocument ID.
status*stringTask status: queued / running / ready / failed / cancelling / cancelled.
stage*stringCurrent pipeline stage (parsing → chunk → Embedding).
generation*stringGeneration written by this ingestion.
progress*objectProgress object: completed / total / unit.
effectiveConfig*objectSnapshot of the configuration frozen in effect for this ingestion.
configHash*stringeffectiveConfig hash, used to compare whether the configuration has changed.
retryOf*stringPrevious ingestion ID pointed to on retry.
attemptId*stringFencing token for this attempt.
idempotencyKey*stringRequester's idempotency key.
error*stringError message when failed.
startedAt*stringTime the worker started processing.
finishedAt*stringIngestion end time.
trackingChannels*objectRealtime subscription channels: ingestion (this task) and document (parent document).

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/ingestions" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "idempotencyKey": "idem-ingest-01",
    "retryOf": "ing_3298",
    "persistToDocument": false,
    "overrides": {
      "parserId": "smart",
      "parserConfig": {
        "chunkTokenNum": 384
      }
    }
  }'

Response example:

{
  "$id": "ing_3301",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "documentId": "doc_manual_v2",
  "status": "running",
  "stage": "embedding",
  "generation": "gen_3",
  "progress": {
    "completed": 60,
    "total": 86,
    "unit": "chunks"
  },
  "effectiveConfig": {
    "parserId": "smart",
    "parserConfig": {
      "chunkTokenNum": 512
    }
  },
  "configHash": "blake3:9f2ca7",
  "retryOf": "",
  "attemptId": "att_b7d2",
  "idempotencyKey": "idem-20260914-0001",
  "error": "",
  "startedAt": "2026-09-01T08:00:01.000+00:00",
  "finishedAt": "",
  "trackingChannels": {
    "ingestion": "ingestion:ing_3301",
    "document": "document:doc_manual_v2"
  }
}

GET /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/ingestions/{ingestionId}

SDK:KnowledgeBases.getIngestion · scope:knowledgebases.read

Query the status, stage, progress, and errors of a single ingestion task.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdquerystringNoOptional; with versioning enabled, omission reads the current version. Specify the draft ID to read a draft.
documentIdpathstringYesTarget document ID.
ingestionIdpathstringYesTarget ingestion task ID.

Output:

200, returning model Models.KnowledgeBaseIngestion (the polling entry point for async tasks, including Realtime trackingChannels).

FieldTypeDescription
$id*stringIngestion task ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringKnowledge base ID.
documentId*stringDocument ID.
status*stringTask status: queued / running / ready / failed / cancelling / cancelled.
stage*stringCurrent pipeline stage (parsing → chunk → Embedding).
generation*stringGeneration written by this ingestion.
progress*objectProgress object: completed / total / unit.
effectiveConfig*objectSnapshot of the configuration frozen in effect for this ingestion.
configHash*stringeffectiveConfig hash, used to compare whether the configuration has changed.
retryOf*stringPrevious ingestion ID pointed to on retry.
attemptId*stringFencing token for this attempt.
idempotencyKey*stringRequester's idempotency key.
error*stringError message when failed.
startedAt*stringTime the worker started processing.
finishedAt*stringIngestion end time.
trackingChannels*objectRealtime subscription channels: ingestion (this task) and document (parent document).

Call example:

The example omits versionId; include the draft version ID as a query parameter when reading a draft.

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/ingestions/ing_3301" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "$id": "ing_3301",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "documentId": "doc_manual_v2",
  "status": "running",
  "stage": "embedding",
  "generation": "gen_3",
  "progress": {
    "completed": 60,
    "total": 86,
    "unit": "chunks"
  },
  "effectiveConfig": {
    "parserId": "smart",
    "parserConfig": {
      "chunkTokenNum": 512
    }
  },
  "configHash": "blake3:9f2ca7",
  "retryOf": "",
  "attemptId": "att_b7d2",
  "idempotencyKey": "idem-20260914-0001",
  "error": "",
  "startedAt": "2026-09-01T08:00:01.000+00:00",
  "finishedAt": "",
  "trackingChannels": {
    "ingestion": "ingestion:ing_3301",
    "document": "document:doc_manual_v2"
  }
}

DELETE /v1/knowledgebases/{knowledgeBaseId}/documents/{documentId}/ingestions/{ingestionId}

SDK:KnowledgeBases.deleteIngestion · scope:knowledgebases.write

Cancel an ingestion: queued/running tasks transition to cancelling; tasks in a terminal state remain unchanged (idempotent).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired for writes when versioning is enabled; specify a DRAFT version ID.
documentIdpathstringYesTarget document ID.
ingestionIdpathstringYesTarget ingestion task ID.

Output:

202, returning model Models.KnowledgeBaseIngestion (current status); this operation does not delete the record.

FieldTypeDescription
$id*stringIngestion task ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringKnowledge base ID.
documentId*stringDocument ID.
status*stringTask status: queued / running / ready / failed / cancelling / cancelled.
stage*stringCurrent pipeline stage (parsing → chunk → Embedding).
generation*stringGeneration written by this ingestion.
progress*objectProgress object: completed / total / unit.
effectiveConfig*objectSnapshot of the configuration frozen in effect for this ingestion.
configHash*stringeffectiveConfig hash, used to compare whether the configuration has changed.
retryOf*stringPrevious ingestion ID pointed to on retry.
attemptId*stringFencing token for this attempt.
idempotencyKey*stringRequester's idempotency key.
error*stringError message when failed.
startedAt*stringTime the worker started processing.
finishedAt*stringIngestion end time.
trackingChannels*objectRealtime subscription channels: ingestion (this task) and document (parent document).

Call example:

The example omits versionId and applies when versioning is disabled; when enabled, include a DRAFT version ID in the request body.

curl -X DELETE "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/documents/doc_manual_v2/ingestions/ing_3301" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "$id": "ing_3301",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "documentId": "doc_manual_v2",
  "status": "cancelling",
  "stage": "embedding",
  "generation": "gen_3",
  "progress": {
    "completed": 60,
    "total": 86,
    "unit": "chunks"
  },
  "effectiveConfig": {
    "parserId": "smart",
    "parserConfig": {
      "chunkTokenNum": 512
    }
  },
  "configHash": "blake3:9f2ca7",
  "retryOf": "",
  "attemptId": "att_b7d2",
  "idempotencyKey": "idem-20260914-0001",
  "error": "",
  "startedAt": "2026-09-01T08:00:01.000+00:00",
  "finishedAt": "",
  "trackingChannels": {
    "ingestion": "ingestion:ing_3301",
    "document": "document:doc_manual_v2"
  }
}

Data Sources and Sync

GET /v1/knowledgebases/{knowledgeBaseId}/datasources

SDK:KnowledgeBases.listDataSources · scope:knowledgebases.read

List the data sources connected to a knowledge base; filter by type/status.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
versionIdquerystringNoOptional; defaults to the current ready version when versioning is enabled.
typequerystringNoDefault ""Filter by data source type (currently yuque).
statusquerystringNoDefault ""Filter by status: active / disabled / error.

Output:

200, returns model Models.KnowledgeBaseDataSourceList.

FieldTypeDescription
total*integerTotal number of data sources matching the query.
dataSources*object[]List of data sources.
$id*stringData source ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringBound knowledge base ID.
type*stringData source type (current enum: yuque).
name*stringData source name.
config*objectNon-sensitive configuration (e.g., repoNamespaces, syncSchedule).
credentials*objectCredential metadata; secrets are never echoed back.
status*stringStatus: active / disabled / error.
lastSyncAt*stringTime the most recent sync completed.
lastSyncStatus*stringStatus of the most recent sync.
lastCursor*stringIncremental sync cursor.
error*stringMost recent data source error message.

Call example:

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources?type=yuque&status=active" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "total": 2,
  "dataSources": [
    {
      "$id": "ds_yuque_team",
      "$createdAt": "2026-08-30T10:00:00.000+00:00",
      "$updatedAt": "2026-09-14T02:01:12.000+00:00",
      "kbId": "kb_product_docs",
      "type": "yuque",
      "name": "team-docs",
      "config": {
        "teamId": "acme",
        "repoNamespaces": [
          "acme/manuals"
        ],
        "syncSchedule": "0 2 * * *"
      },
      "credentials": {"teamToken": "********"},
      "status": "active",
      "lastSyncAt": "2026-09-14T02:01:12.000+00:00",
      "lastSyncStatus": "ready",
      "lastCursor": "yq-2026-09-14T02:00:00Z",
      "error": ""
    }
  ]
}

POST /v1/knowledgebases/{knowledgeBaseId}/datasources

SDK:KnowledgeBases.createDataSource · scope:knowledgebases.write

Connect an external data source to a knowledge base (currently supports Yuque team spaces), with optional registration of periodic sync.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
versionIdbodystringNoRequired for versioned knowledge bases; use a draft version ID. Scheduled sync is unavailable for versioned data sources.
namebodystringYesData source name.
typebodystringNoEnum: yuqueData source type; currently only yuque is supported.
configbodyobjectNoYuque requires a nonempty teamId; repoNamespaces and a syncSchedule cron expression are optional. Versioned data sources cannot set a sync schedule.
credentialsbodyobjectNoYuque requires a nonempty teamToken; stored credentials are encrypted and ciphertext is not returned.
statusbodystringNoEnum: active / disabledactive / disabled; periodic sync is automatically registered when active and config.syncSchedule are configured.
triggerSyncbodybooleanNoWhen true (default) and status=active, a full sync is queued immediately after creation.

Output:

201, returns model Models.KnowledgeBaseDataSource.

FieldTypeDescription
$id*stringData source ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringBound knowledge base ID.
type*stringData source type (current enum: yuque).
name*stringData source name.
config*objectNon-sensitive configuration (such as repoNamespaces, syncSchedule).
credentials*objectCredential metadata; secrets are never echoed back.
status*stringStatus: active / disabled / error.
lastSyncAt*stringTime the most recent sync completed.
lastSyncStatus*stringStatus of the most recent sync.
lastCursor*stringIncremental sync cursor.
error*stringMost recent data source error message.

Call example:

Set APPBASE_API_KEY and YUQUE_TEAM_TOKEN securely in Bash first; this example requires Python 3. Replace the endpoint, project ID, and team details for your environment.

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" "${YUQUE_TEAM_TOKEN:?Set YUQUE_TEAM_TOKEN}"
  export YUQUE_TEAM_TOKEN
  python3 -c "import json, os, sys; json.dump({'name':'team-docs','type':'yuque','config':{'teamId':'acme','repoNamespaces':['acme/manuals'],'syncSchedule':'0 2 * * *'},'credentials':{'teamToken':os.environ['YUQUE_TEAM_TOKEN']},'status':'active','triggerSync':True}, sys.stdout)" |
    curl --disable --fail --silent --show-error -i -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources" \
      -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
      --header @/dev/fd/3 \
      -H "Content-Type: application/json" --data-binary @- \
      3< <(builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY")
)

The create response does not wait for sync completion. If sync is triggered, check its record and document ingestion status.

Response example:

{
  "$id": "ds_yuque_team",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-01T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "type": "yuque",
  "name": "team-docs",
  "config": {
    "teamId": "acme",
    "repoNamespaces": [
      "acme/manuals"
    ],
    "syncSchedule": "0 2 * * *"
  },
  "credentials": {"teamToken": "********"},
  "status": "active",
  "lastSyncAt": null,
  "lastSyncStatus": null,
  "lastCursor": null,
  "error": null
}

GET /v1/knowledgebases/{knowledgeBaseId}/datasources/{dataSourceId}

SDK:KnowledgeBases.getDataSource · scope:knowledgebases.read

Get a data source by ID (credentials are not echoed back).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdquerystringNoOptional; defaults to the current ready version when versioning is enabled.
dataSourceIdpathstringYesTarget data source ID.

Output:

200, returns model Models.KnowledgeBaseDataSource.

FieldTypeDescription
$id*stringData source ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringBound knowledge base ID.
type*stringData source type (current enum: yuque).
name*stringData source name.
config*objectNon-sensitive configuration (such as repoNamespaces, syncSchedule).
credentials*objectCredential metadata; secrets are never echoed back.
status*stringStatus: active / disabled / error.
lastSyncAt*stringTime the most recent sync completed.
lastSyncStatus*stringStatus of the most recent sync.
lastCursor*stringIncremental sync cursor.
error*stringMost recent data source error message.

Call example:

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/ds_yuque_team" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "$id": "ds_yuque_team",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "type": "yuque",
  "name": "team-docs",
  "config": {
    "teamId": "acme",
    "repoNamespaces": [
      "acme/manuals"
    ],
    "syncSchedule": "0 2 * * *"
  },
  "credentials": {"teamToken": "********"},
  "status": "active",
  "lastSyncAt": "2026-09-14T02:00:00.000+00:00",
  "lastSyncStatus": "ready",
  "lastCursor": "yq-2026-09-14T02:00:00Z",
  "error": ""
}

PATCH /v1/knowledgebases/{knowledgeBaseId}/datasources/{dataSourceId}

SDK:KnowledgeBases.updateDataSource · scope:knowledgebases.write

Update the data source name, configuration, credentials, or status; credentials are merged key by key rather than replaced wholesale.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
dataSourceIdpathstringYesTarget data source ID.
versionIdbodystringNoRequired for versioned knowledge bases; use a draft version ID. Scheduled sync is unavailable for versioned data sources.
namebodystringNoData source name.
configbodyobjectNoWhen provided, validated and replaced as a complete configuration; Yuque requires a nonempty teamId.
credentialsbodyobjectNoWhen provided, a nonempty teamToken is required; omit the field to keep existing credentials.
statusbodystringNoEnum: active / disabled / error / (empty, meaning unrestricted)active / disabled / error; changing status or config.syncSchedule recalculates the periodic sync schedule.

Output:

200, returns model Models.KnowledgeBaseDataSource.

FieldTypeDescription
$id*stringData source ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringBound knowledge base ID.
type*stringData source type (current enum: yuque).
name*stringData source name.
config*objectNon-sensitive configuration (such as repoNamespaces, syncSchedule).
credentials*objectCredential metadata; secrets are never echoed back.
status*stringStatus: active / disabled / error.
lastSyncAt*stringTime the most recent sync completed.
lastSyncStatus*stringStatus of the most recent sync.
lastCursor*stringIncremental sync cursor.
error*stringMost recent data source error message.

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X PATCH "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/ds_yuque_team" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  --header @- \
  -H "Content-Type: application/json" \
  -d '{
    "config": {
      "teamId": "acme",
      "repoNamespaces": [
        "acme/manuals",
        "acme/faq"
      ],
      "syncSchedule": "0 */6 * * *"
    },
    "status": "active"
  }'
)

Response example:

{
  "$id": "ds_yuque_team",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "type": "yuque",
  "name": "team-docs",
  "config": {
    "teamId": "acme",
    "repoNamespaces": [
      "acme/manuals",
      "acme/faq"
    ],
    "syncSchedule": "0 */6 * * *"
  },
  "credentials": {"teamToken": "********"},
  "status": "active",
  "lastSyncAt": "2026-09-14T02:00:00.000+00:00",
  "lastSyncStatus": "ready",
  "lastCursor": "yq-2026-09-14T02:00:00Z",
  "error": ""
}

DELETE /v1/knowledgebases/{knowledgeBaseId}/datasources/{dataSourceId}

SDK:KnowledgeBases.deleteDataSource · scope:knowledgebases.write

Delete the data source along with its sync history and periodic schedule; knowledge base documents already generated are unaffected.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired when versioning is enabled; use the draft version ID to write.
dataSourceIdpathstringYesTarget data source ID.

Output:

204, no response body.

Call example:

curl -X DELETE "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/ds_yuque_team" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

POST /v1/knowledgebases/{knowledgeBaseId}/datasources/yuque/repos

SDK:KnowledgeBases.listYuqueRepos · scope:knowledgebases.write

Enumerate repositories reachable by the Yuque team using a team token, for choosing repoNamespaces before creating a data source (the token is used once and discarded, never persisted).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
teamIdbodystringYesYuque team ID.
teamTokenbodystringYesYuque Open API team token; used only for this query and never stored.

Output:

200, returns a wide-type JSON object: a list of Yuque team repositories (namespace, name, etc.) for populating the data source config.repoNamespaces.

Call example:

Set APPBASE_API_KEY and YUQUE_TEAM_TOKEN securely in Bash first; this example requires Python 3. Replace the endpoint, project ID, and team details for your environment.

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" "${YUQUE_TEAM_TOKEN:?Set YUQUE_TEAM_TOKEN}"
  export YUQUE_TEAM_TOKEN
  python3 -c "import json, os, sys; json.dump({'teamId':'acme','teamToken':os.environ['YUQUE_TEAM_TOKEN']}, sys.stdout)" |
    curl --disable --fail --silent --show-error -i -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/yuque/repos" \
      -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
      --header @/dev/fd/3 \
      -H "Content-Type: application/json" --data-binary @- \
      3< <(builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY")
)

Response example:

{
  "repos": [
    {
      "namespace": "acme/manuals",
      "name": "产品手册"
    },
    {
      "namespace": "acme/faq",
      "name": "常见问题"
    }
  ]
}

POST /v1/knowledgebases/{knowledgeBaseId}/datasources/yuque/docs

SDK:KnowledgeBases.listYuqueDocs · scope:knowledgebases.write

Enumerate importable Yuque documents in selected repositories. The request passes a temporary team token that is not stored.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesTarget knowledge base ID.
teamIdbodystringYesYuque team ID.
teamTokenbodystringYesYuque Open API team token (not stored).
repoNamespacesbodystring[]NoArray of repository namespaces; an empty array lists documents across all team repositories.

Output:

200, returns a wide-type JSON object: a list of importable documents per repository (URL/title, etc.) for batch import selection.

Call example:

Set APPBASE_API_KEY and YUQUE_TEAM_TOKEN securely in Bash first; this example requires Python 3. Replace the endpoint, project ID, and team details for your environment.

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" "${YUQUE_TEAM_TOKEN:?Set YUQUE_TEAM_TOKEN}"
  export YUQUE_TEAM_TOKEN
  python3 -c "import json, os, sys; json.dump({'teamId':'acme','teamToken':os.environ['YUQUE_TEAM_TOKEN'],'repoNamespaces':['acme/manuals']}, sys.stdout)" |
    curl --disable --fail --silent --show-error -i -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/yuque/docs" \
      -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
      --header @/dev/fd/3 \
      -H "Content-Type: application/json" --data-binary @- \
      3< <(builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY")
)

Response example:

{
  "docs": [
    {
      "namespace": "acme/manuals",
      "title": "早餐机快速上手",
      "url": "<YUQUE_DOCUMENT_URL_1>"
    }
  ]
}

POST /v1/knowledgebases/{knowledgeBaseId}/datasources/{dataSourceId}/documents

SDK:KnowledgeBases.createDataSourceDocument · scope:knowledgebases.write

Import a single document from a data source by URL: the URL is only used for locating the document; the server does not fetch the URL directly.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired when versioning is enabled; use the draft version ID to write.
dataSourceIdpathstringYesTarget data source ID.
urlbodystringYesYuque document URL; only supported Yuque HTTPS domains and the exact {group}/{book}/{slug} path are accepted.
idempotencyKeybodystringNoIdempotency key.

Output:

202 newly created or has updates (ingestion enqueued), or 200 content unchanged (document already processing/ready); returns model Models.KnowledgeBaseDocument.409 conflicts with an active ingestion; 503 Yuque is temporarily unavailable.

FieldTypeDescription
$id*stringDocument ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
kbId*stringOwning knowledge base ID.
name*stringDocument display name.
bucketId*stringStorage bucket ID where the source file resides.
fileId*stringStorage file ID of the source file.
mimeType*stringMIME type of the source file.
source*stringSource: manual manual upload, datasource:{id} data source sync, yuque:personal personal Yuque import.
externalItemId*stringExternal system entry ID; data source sync uses it for deduplication and updates.
parserId*stringDocument-level chunk strategy override; empty inherits the knowledge base default.
parserConfig*objectDocument-level parsing/chunk configuration override.
metadata*objectBusiness metadata.
status*stringProcessing status: uploaded registered / processing processing / ready ready / failed failed.
enabled*booleanWhether it participates in retrieval; when false, chunks are retained but excluded from retrieval results.
stage*stringMirror of the pipeline stage for the current/most recent ingestion.
activeIngestionId*stringID of the current or most recent ingestion task.
activeGeneration*stringRetrieval-visible generation; only valid when status=ready.
processingStartedAt*stringTime of the most recent processing trigger.
chunksTotal*integerExpected total number of chunks (filled once known).
chunkCount*integerNumber of chunks in the active generation.
error*stringMost recent processing error message; normally an empty string.
lastExecutionId*stringDeprecated legacy Function execution ID.

Call example:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/ds_yuque_team/documents" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "<YUQUE_DOCUMENT_URL_1>",
    "idempotencyKey": "idem-ds-01"
  }'

Response example:

{
  "$id": "doc_manual_v2",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "kbId": "kb_product_docs",
  "name": "产品使用手册 v2.pdf",
  "bucketId": "bkt_kb_docs",
  "fileId": "file_9a11cc",
  "mimeType": "application/pdf",
  "source": "datasource:ds_yuque_team",
  "externalItemId": "acme/manuals/breakfast-quickstart",
  "parserId": "",
  "parserConfig": {},
  "metadata": {
    "edition": "v2"
  },
  "status": "processing",
  "enabled": true,
  "stage": "",
  "activeIngestionId": "ing_3301",
  "activeGeneration": "gen_3",
  "processingStartedAt": "2026-09-01T08:00:01.000+00:00",
  "chunksTotal": 86,
  "chunkCount": 86,
  "error": "",
  "lastExecutionId": ""
}

POST /v1/knowledgebases/{knowledgeBaseId}/datasources/{dataSourceId}/documents/batch

SDK:KnowledgeBases.createDataSourceDocumentsBatch · scope:knowledgebases.write

Batch import documents from a data source by URL (up to 20 items, with per-item results returned).

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdbodystringNoRequired when versioning is enabled; use the draft version ID to write.
dataSourceIdpathstringYesTarget data source ID.
urlsbodystring[]YesArray of Yuque document URLs, up to 20 items, no duplicates.
idempotencyKeybodystringNoBatch idempotency key prefix.

Output:

200 all accepted/unchanged, 207 when any failed exists; returns model Models.KnowledgeBaseDataSourceDocumentImportBatch (results[] matches the request order and must be checked item by item). Empty list / more than 20 items / duplicate URLs / data source not active return 400.

FieldTypeDescription
total*integerNumber of URLs processed this time.
accepted*integerNumber of URLs whose documents were created/updated and ingestion enqueued.
unchanged*integerNumber of URLs left untouched because remote content was already processing/ready.
failed*integerNumber of URLs that failed validation or import.
results*object[]Per-URL results arranged in request order.
url*stringRequested Yuque document URL.
status*stringPer-URL import outcome: accepted, unchanged, or failed.
documentobjectImported knowledge base document when status is accepted or unchanged.
errorstringHuman-readable failure detail when status is failed.
errorTypestringMachine-readable AppBase exception type when status is failed.

Call example:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/ds_yuque_team/documents/batch" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "urls": [
      "<YUQUE_DOCUMENT_URL_1>",
      "<YUQUE_DOCUMENT_URL_2>"
    ],
    "idempotencyKey": "idem-ds-batch-01"
  }'

Response example:

{
  "total": 2,
  "accepted": 0,
  "unchanged": 0,
  "failed": 0,
  "results": [
    {
      "url": "",
      "status": "available",
      "document": {},
      "error": "",
      "errorType": ""
    },
    {
      "url": "",
      "status": "available",
      "document": {},
      "error": "",
      "errorType": ""
    }
  ]
}

GET /v1/knowledgebases/{knowledgeBaseId}/datasources/{dataSourceId}/syncs

SDK:KnowledgeBases.listDataSourceSyncs · scope:knowledgebases.read

List data source sync records (in reverse order of creation time), filterable by status.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdquerystringNoOptional; defaults to the current ready version when versioning is enabled.
dataSourceIdpathstringYesTarget data source ID.
statusquerystringNoDefault ""Filter by sync status: queued / running / ready / failed.

Output:

200, returns model Models.KnowledgeBaseDataSourceSyncList.

FieldTypeDescription
total*integerTotal number of sync records matching the query.
syncs*object[]List of sync records (in reverse order of creation time).
$id*stringSync record ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
datasourceId*stringData source ID.
kbId*stringKnowledge base ID.
status*stringSync status: queued / running / ready / failed.
cursorStart*stringCursor at the start of the sync.
cursorEnd*stringNew cursor produced by the sync.
stats*objectSync counts: created, updated, skipped, disabled, and failed.
error*stringError message when failed.
startedAt*stringTime the worker started processing.
finishedAt*stringSync end time.

Call example:

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/ds_yuque_team/syncs?status=ready" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "total": 1,
  "syncs": [
    {
      "$id": "sync_771f",
      "$createdAt": "2026-09-14T02:00:00.000+00:00",
      "$updatedAt": "2026-09-14T02:01:12.000+00:00",
      "datasourceId": "ds_yuque_team",
      "kbId": "kb_product_docs",
      "status": "ready",
      "cursorStart": "yq-2026-09-13T02:00:00Z",
      "cursorEnd": "yq-2026-09-14T02:00:00Z",
      "stats": {
        "created": 1,
        "updated": 2,
        "skipped": 36,
        "disabled": 0,
        "failed": 0
      },
      "error": "",
      "startedAt": "2026-09-14T02:00:01.000+00:00",
      "finishedAt": "2026-09-14T02:01:12.000+00:00"
    }
  ]
}

POST /v1/knowledgebases/{knowledgeBaseId}/datasources/{dataSourceId}/syncs

SDK:KnowledgeBases.createDataSourceSync · scope:knowledgebases.write

Trigger a data source sync; if a queued/running sync already exists, the existing record is returned without enqueueing again.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
dataSourceIdpathstringYesTarget data source ID.
versionIdbodystringNoRequired when versioning is enabled; use the target draft version ID.

Output:

202, returns model Models.KnowledgeBaseDataSourceSync.Asynchronous task: poll GET .../syncs/{syncId} until ready/failed.

FieldTypeDescription
$id*stringSync record ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
datasourceId*stringData source ID.
kbId*stringKnowledge base ID.
status*stringSync status: queued / running / ready / failed.
cursorStart*stringCursor at the start of the sync.
cursorEnd*stringNew cursor produced by the sync.
stats*objectSync counts: created, updated, skipped, disabled, and failed.
error*stringError message when failed.
startedAt*stringTime the worker started processing.
finishedAt*stringSync end time.

Call example:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/ds_yuque_team/syncs" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

When versioning is enabled, send the actual draft ID in the request body:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/ds_yuque_team/syncs" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" -d '{"versionId":"<DRAFT_VERSION_ID>"}'

Response example:

{
  "$id": "sync_771f",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "datasourceId": "ds_yuque_team",
  "kbId": "kb_product_docs",
  "status": "queued",
  "cursorStart": "yq-2026-09-13T02:00:00Z",
  "cursorEnd": null,
  "stats": {
    "created": 0,
    "updated": 0,
    "skipped": 0,
    "disabled": 0,
    "failed": 0
  },
  "error": null,
  "startedAt": null,
  "finishedAt": null
}

GET /v1/knowledgebases/{knowledgeBaseId}/datasources/{dataSourceId}/syncs/{syncId}

SDK:KnowledgeBases.getDataSourceSync · scope:knowledgebases.read

Query the status, cursor advancement, and statistics of a single sync.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringYesOwning knowledge base ID.
versionIdquerystringNoOptional; defaults to the current ready version when versioning is enabled.
dataSourceIdpathstringYesTarget data source ID.
syncIdpathstringYesTarget sync record ID.

Output:

200, returns model Models.KnowledgeBaseDataSourceSync.

FieldTypeDescription
$id*stringSync record ID.
$createdAt*stringCreation time (ISO 8601).
$updatedAt*stringLast update time (ISO 8601).
datasourceId*stringData source ID.
kbId*stringKnowledge base ID.
status*stringSync status: queued / running / ready / failed.
cursorStart*stringCursor at the start of the sync.
cursorEnd*stringNew cursor produced by the sync.
stats*objectSync counts: created, updated, skipped, disabled, and failed.
error*stringError message when failed.
startedAt*stringTime the worker started processing.
finishedAt*stringSync end time.

Call example:

curl -X GET "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/ds_yuque_team/syncs/sync_771f" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>"

Response example:

{
  "$id": "sync_771f",
  "$createdAt": "2026-09-01T08:00:00.000+00:00",
  "$updatedAt": "2026-09-14T08:00:00.000+00:00",
  "datasourceId": "ds_yuque_team",
  "kbId": "kb_product_docs",
  "status": "ready",
  "cursorStart": "yq-2026-09-13T02:00:00Z",
  "cursorEnd": "yq-2026-09-14T02:00:00Z",
  "stats": {
    "created": 1,
    "updated": 2,
    "skipped": 36,
    "disabled": 0,
    "failed": 0
  },
  "error": "",
  "startedAt": "2026-09-14T02:00:01.000+00:00",
  "finishedAt": "2026-09-14T02:01:12.000+00:00"
}

Lexicons and binding management

GET /v1/lexicons

SDK:Lexicons.list · scope:lexicons.read

List in pages all lexicons visible in the current project.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
limitqueryintegerNoDefault 25Number of items returned per page, range 1–100.
offsetqueryintegerNoDefault 0Pagination offset, range 0–1000000.

output: 200 OK, returns lexiconList models (total + lexicons[]).

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X GET "<APPBASE_ENDPOINT_WITH_V1>/lexicons?limit=25&offset=0" \
  -H "X-Appwrite-Project: <APPBASE_PROJECT_ID>" \
  --header @-
)

Response example:

{
  "total": 2,
  "lexicons": [
    {
      "$id": "lex_enterprise_synonyms",
      "$createdAt": "2026-10-21T08:00:00.000+00:00",
      "$updatedAt": "2026-10-22T03:15:00.000+00:00",
      "$permissions": [
        "read(\"any\")"
      ],
      "name": "企业智能客服同义词与扩展词典",
      "description": "统一 OceanBase、AI 网关与智能客服业务术语标准表达",
      "tokenizerProfile": "unicode-v1",
      "revision": 4
    },
    {
      "$id": "lex_support_stopwords",
      "$createdAt": "2026-10-21T08:10:00.000+00:00",
      "$updatedAt": "2026-10-21T09:00:00.000+00:00",
      "$permissions": [
        "read(\"any\")"
      ],
      "name": "客服检索与对话停用词词典",
      "description": "过滤口语冗余词与违规阻断词",
      "tokenizerProfile": "unicode-v1",
      "revision": 2
    }
  ]
}

POST /v1/lexicons

SDK:Lexicons.create · scope:lexicons.write

Create a new lexicon in the project.

Input:

ParameterLocationTypeRequiredDefault/enumDescription
lexiconIdbodystringNoDefault "unique()"Custom lexicon ID (e.g. lex_enterprise_synonyms), or pass "unique()".
namebodystringYes—Lexicon name, 1–128 characters long.
descriptionbodystringNoDefault ""Lexicon purpose description, up to 4096 characters.
permissionsbodystring[]NoDefault nullArray of resource-level permissions (only read, update, delete actions allowed).

Output : 201 Created, returns a lexicon model.

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
: "${APPBASE_PROJECT_ID:?Set APPBASE_PROJECT_ID for the target environment}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X POST "${APPBASE_ENDPOINT}/lexicons" \
  -H "X-Appwrite-Project: ${APPBASE_PROJECT_ID}" \
  --header @- \
  -H "Content-Type: application/json" \
  -d '{
    "lexiconId": "lex_enterprise_synonyms",
    "name": "企业智能客服同义词与扩展词典",
    "description": "统一 OceanBase、AI 网关与智能客服业务术语标准表达"
  }'
)

GET /v1/lexicons/{lexiconId}、PATCH /v1/lexicons/{lexiconId}、DELETE /v1/lexicons/{lexiconId}

SDK:Lexicons.get / Lexicons.update / Lexicons.delete · scope:lexicons.read / lexicons.write

Method + pathParameterLocationTypeRequiredDescription
GET /v1/lexicons/{lexiconId}lexiconIdpathstringYesGet lexicon details by ID (including the current revision and tokenizerProfile).
PATCH /v1/lexicons/{lexiconId}lexiconIdpathstringYesTarget lexicon ID.
PATCH /v1/lexicons/{lexiconId}namebodystringNoUpdated lexicon name (1–128 characters).
PATCH /v1/lexicons/{lexiconId}descriptionbodystringNoUpdated lexicon description (up to 4096 characters).
PATCH /v1/lexicons/{lexiconId}permissionsbodystring[]NoArray of resource-level permissions (revision is atomically incremented after the update).
DELETE /v1/lexicons/{lexiconId}lexiconIdpathstringYesDelete the lexicon and all of its entries (returns 204); if it is still bound to any knowledge base or agent, returns 409 general_conflict.

Call example:

Set APPBASE_ENDPOINT to the target environment API endpoint (including /v1), and confirm the project and credentials belong to that environment.

  1. Get lexicon details

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X GET "${APPBASE_ENDPOINT}/lexicons/lex_enterprise_synonyms" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  --header @-
)
  1. Update the lexicon name and description

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X PATCH "${APPBASE_ENDPOINT}/lexicons/lex_enterprise_synonyms" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  --header @- \
  -H "Content-Type: application/json" \
  -d '{
    "name": "企业智能客服同义词与扩展词典(v2)",
    "description": "覆盖 OceanBase V4.3、LLM Gateway 与智能体专有术语"
  }'
)
  1. Delete an unbound lexicon. Run separately only after confirming the target and consequences.

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X DELETE "${APPBASE_ENDPOINT}/lexicons/lex_temp_test" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  --header @-
)

GET /v1/lexicons/{lexiconId}/entries and POST /v1/lexicons/{lexiconId}/entries

SDK:Lexicons.listEntries / Lexicons.createEntry · scope:lexicons.read / lexicons.write

Manage structured lexicon entry rules within a lexicon.

Create lexicon entry (POST /v1/lexicons/{lexiconId}/entries) input parameters:

ParameterLocationTypeRequiredDefault/enumDescription
lexiconIdpathstringYes—Target lexicon ID.
entryIdbodystringNoDefault "unique()"Lexicon entry ID.
entryTypebodystringYesEnum synonym, expansion, stopRule type: synonym (bidirectional equivalent synonym), expansion (one-way hyponym expansion term), stop (stopword/blocklist word).
termsbodystring[]yes—Trigger term array (1–100 items, each 1–256 characters); when synonym, the first item is the Canonical Term.
expansionsbodystring[]nodefault []Required only when entryType="expansion"; fill in the array of expanded target terms.
positionbodyintegernodefault 0Rule matching sort priority (0–2147483647, lower takes precedence).

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
: "${APPBASE_PROJECT_ID:?Set APPBASE_PROJECT_ID for the target environment}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X POST "${APPBASE_ENDPOINT}/lexicons/lex_enterprise_synonyms/entries" \
  -H "X-Appwrite-Project: ${APPBASE_PROJECT_ID}" \
  --header @- \
  -H "Content-Type: application/json" \
  -d '{
    "entryId": "unique()",
    "entryType": "synonym",
    "terms": ["OceanBase", "OB数据库", "蚂蚁分布式数据库"],
    "expansions": [],
    "position": 10
  }'
)

Response example (201 Created):

{
  "$id": "ent_ob_syn_01",
  "$createdAt": "2026-10-22T03:15:00.000+00:00",
  "$updatedAt": "2026-10-22T03:15:00.000+00:00",
  "lexiconId": "lex_enterprise_synonyms",
  "entryType": "synonym",
  "terms": ["OceanBase", "OB数据库", "蚂蚁分布式数据库"],
  "expansions": [],
  "position": 10
}

POST /v1/lexicons/{lexiconId}/preview、POST /v1/lexicons/{lexiconId}/import、GET /v1/lexicons/{lexiconId}/export、GET /v1/lexicons/{lexiconId}/references

SDK:Lexicons.preview / Lexicons.import / Lexicons.export / Lexicons.listReferences · scope:lexicons.read / lexicons.write

endpointcore parametersreturn model / formatdescription
POST /v1/lexicons/{lexiconId}/previewquery (body, string, required)Models.LexiconRewritePreview the normalized text after lexicon rewriting for a single query sentence, including synonym replacement, expansion term expansion, and stopword hit details.
POST /v1/lexicons/{lexiconId}/importformat (json/csv/xlsx), mode (merge/overwrite), dryRun (boolean, default true), content / entriesModels.LexiconImportResultBatch import lexicon entries (first use dryRun: true to validate deduplication and the 1,000 entry quota, then call dryRun: false to persist officially and increment revision).
GET /v1/lexicons/{lexiconId}/exportformat (query: json/csv/xlsx)file stream / JSONExport all lexicon entry rules of the specified lexicon.
GET /v1/lexicons/{lexiconId}/referenceslexiconId (path, string, required)Models.LexiconReferenceListQuery the list of knowledgebases and agents resource references currently bound to this lexicon.

call example (rewrite preview POST /v1/lexicons/{lexiconId}/preview):

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
: "${APPBASE_PROJECT_ID:?Set APPBASE_PROJECT_ID for the target environment}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X POST "${APPBASE_ENDPOINT}/lexicons/lex_enterprise_synonyms/preview" \
  -H "X-Appwrite-Project: ${APPBASE_PROJECT_ID}" \
  --header @- \
  -H "Content-Type: application/json" \
  -d '{
    "query": "请问OB数据库向量索引报错怎么排查"
  }'

)

Response example (200 OK):

{
  "originalQuery": "请问OB数据库向量索引报错怎么排查",
  "rewrittenQuery": "OceanBase 向量索引报错怎么排查",
  "expandedTerms": [
    "OceanBase",
    "OB数据库",
    "HNSW索引",
    "IVF索引"
  ],
  "removedStopwords": [
    "请问"
  ],
  "matchedEntries": [
    {
      "entryId": "ent_ob_syn_01",
      "entryType": "synonym",
      "matchedTerm": "OB数据库",
      "canonicalTerm": "OceanBase"
    }
  ]
}

GET /v1/knowledgebases/{knowledgeBaseId}/lexicons and PUT /v1/knowledgebases/{knowledgeBaseId}/lexicons

SDK:Lexicons.getKnowledgeBaseBindings / Lexicons.updateKnowledgeBaseBindings · scope:lexicons.read / lexicons.write

Query or wholesale replace the lexicon list and enablement status bound to the specified knowledge base (e.g., kb_enterprise_support).

PUT /v1/knowledgebases/{knowledgeBaseId}/lexicons input parameters:

ParameterLocationTypeRequiredDefault/enumDescription
knowledgeBaseIdpathstringyes—Target knowledge base ID.
enabledbodybooleannodefault falseWhether to enable lexicon rewriting for retrieval and preprocessing of this knowledge base.
bindingsbodyobject[]yes—Ordered binding array (up to 100 items), each in the format {"lexiconId": "<id>", "priority": <int>}.

Call example:

(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
: "${APPBASE_ENDPOINT:?Set APPBASE_ENDPOINT to the target API endpoint including /v1}"
APPBASE_ENDPOINT="${APPBASE_ENDPOINT%/}"
: "${APPBASE_PROJECT_ID:?Set APPBASE_PROJECT_ID for the target environment}"
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X PUT "${APPBASE_ENDPOINT}/knowledgebases/kb_enterprise_support/lexicons" \
  -H "X-Appwrite-Project: ${APPBASE_PROJECT_ID}" \
  --header @- \
  -H "Content-Type: application/json" \
  -d '{
    "enabled": true,
    "bindings": [
      {"lexiconId": "lex_enterprise_synonyms", "priority": 1},
      {"lexiconId": "lex_support_stopwords", "priority": 2}
    ]
  }'
)
(
  set +x
  set -o pipefail
  : "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
# Query the list of lexicons currently bound to the knowledge base (GET /v1/knowledgebases/{kbId}/lexicons)
builtin printf 'X-Appwrite-Key: %s\n' "$APPBASE_API_KEY" | curl --disable -X GET "<APPBASE_ENDPOINT_WITH_V1>/knowledgebases/kb_enterprise_support/lexicons" \
  -H "X-Appwrite-Project: <APPBASE_PROJECT_ID>" \
  --header @-

)

Response example (200 OK):

{
  "enabled": true,
  "stopIntercept": false,
  "stopReply": "",
  "bindings": [
    {
      "lexiconId": "lex_enterprise_synonyms",
      "priority": 1
    },
    {
      "lexiconId": "lex_support_stopwords",
      "priority": 2
    }
  ]
}

Note: The current project agent workbench (Agent Runtime Workbench) supports binding the same project lexicon via the isomorphic endpoints GET /v1/agent-runtime/project/lexicons and PUT /v1/agent-runtime/project/lexicons (additionally supporting stopIntercept: true and stopReply blocked-phrase configuration); see Agent Runtime API.

Errors and boundaries

Correspondence with the Server SDK

service.methodEndpoint
KnowledgeBases.list / create / get / update / delete/knowledgebases CRUD
KnowledgeBases.createSearch / createMultiSearchPOST .../{id}/search、POST /knowledgebases/search
KnowledgeBases.getManagement / createReindexGET .../management、POST .../reindex
KnowledgeBases.listDocuments / createDocument / createDocumentsBatch / getDocument / updateDocument / deleteDocument/knowledgebases/{id}/documents*
KnowledgeBases.createDocumentProcess / getDocumentSourcePOST .../process、GET .../source
KnowledgeBases.listChunks / createChunk / getChunk / updateChunk / deleteChunk.../chunks*
KnowledgeBases.listIngestions / createIngestion / getIngestion / deleteIngestion.../ingestions*
KnowledgeBases.listDataSources / createDataSource / getDataSource / updateDataSource / deleteDataSource.../datasources*
KnowledgeBases.listYuqueRepos / listYuqueDocsPOST .../datasources/yuque/repos|docs
KnowledgeBases.createDataSourceDocument / createDataSourceDocumentsBatch / listDataSourceSyncs / createDataSourceSync / getDataSourceSync.../datasources/{dataSourceId}/documents*、syncs*
Lexicons.list / create / get / update / delete/v1/lexicons CRUD
Lexicons.listEntries / createEntry / getEntry / updateEntry / deleteEntry/v1/lexicons/{lexiconId}/entries*
Lexicons.preview / import / export / listReferences/v1/lexicons/{lexiconId}/preview|import|export|references
Lexicons.getKnowledgeBaseBindings / updateKnowledgeBaseBindingsGET|PUT /v1/knowledgebases/{knowledgeBaseId}/lexicons

2.12.0 endpoints and compatibility

Paths below are relative to /v1. Server requests carry X-Appwrite-Project and X-Appwrite-Key; keep the key on the server. Scopes below are necessary; dataset access, ownership and resource state may add checks. HTTP 202 means accepted; use the returned operation identifier to read its terminal result.

HTTPScopeSDK
POST /knowledgebases/project-scopesknowledgebases.writeknowledgeBases.createProjectScope
GET /knowledgebases/project-scopes/{projectId}knowledgebases.readknowledgeBases.getProjectScope
PATCH /knowledgebases/project-scopes/{projectId}knowledgebases.writeknowledgeBases.updateProjectScope
POST /knowledgebases/searchknowledgebases.readknowledgeBases.createMultiSearch
GET /knowledgebases/{knowledgeBaseId}/document-directoriesknowledgebases.readknowledgeBases.listDocumentDirectories
POST /knowledgebases/{knowledgeBaseId}/document-directories/countknowledgebases.readknowledgeBases.countDocumentDirectories
GET /knowledgebases/{knowledgeBaseId}/documentsknowledgebases.readknowledgeBases.listDocuments
POST /knowledgebases/{knowledgeBaseId}/documentsknowledgebases.writeknowledgeBases.createDocument
POST /knowledgebases/{knowledgeBaseId}/documents/batchknowledgebases.writeknowledgeBases.createDocumentsBatch
PATCH /knowledgebases/{knowledgeBaseId}/documents/{documentId}knowledgebases.writeknowledgeBases.updateDocument
PATCH /knowledgebases/{knowledgeBaseId}/documents/{documentId}/chunks/{chunkId}knowledgebases.writeknowledgeBases.updateChunk
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/contentknowledgebases.readknowledgeBases.getDocumentContent
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/parse-artifactknowledgebases.readknowledgeBases.getDocumentParseArtifact
GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/parse-artifact/contentknowledgebases.readknowledgeBases.getDocumentParseArtifactContent
GET /knowledgebases/{knowledgeBaseId}/enhancement-operationsknowledgebases.readknowledgeBases.listEnhancementOperations
POST /knowledgebases/{knowledgeBaseId}/enhancement-operationsknowledgebases.writeknowledgeBases.createEnhancementOperation
GET /knowledgebases/{knowledgeBaseId}/enhancement-operations/{operationId}knowledgebases.readknowledgeBases.getEnhancementOperation
POST /knowledgebases/{knowledgeBaseId}/enhancement-operations/{operationId}/cancelknowledgebases.writeknowledgeBases.cancelEnhancementOperation
GET /knowledgebases/{knowledgeBaseId}/graphknowledgebases.readknowledgeBases.getGraph
POST /knowledgebases/{knowledgeBaseId}/graph/searchknowledgebases.readknowledgeBases.createGraphSearch
GET /knowledgebases/{knowledgeBaseId}/lexiconslexicons.readlexicons.getKnowledgeBaseBindings
PUT /knowledgebases/{knowledgeBaseId}/lexiconslexicons.writelexicons.updateKnowledgeBaseBindings
POST /knowledgebases/{knowledgeBaseId}/searchknowledgebases.readknowledgeBases.createSearch
GET /knowledgebases/{knowledgeBaseId}/wiki/graphknowledgebases.readknowledgeBases.getWikiGraph
GET /knowledgebases/{knowledgeBaseId}/wiki/pagesknowledgebases.readknowledgeBases.listWikiPages
POST /knowledgebases/{knowledgeBaseId}/wiki/searchknowledgebases.readknowledgeBases.createWikiSearch
GET /lexiconslexicons.readlexicons.list
POST /lexiconslexicons.writelexicons.create
GET /lexicons/{lexiconId}lexicons.readlexicons.get
PATCH /lexicons/{lexiconId}lexicons.writelexicons.update
DELETE /lexicons/{lexiconId}lexicons.writelexicons.delete
GET /lexicons/{lexiconId}/entrieslexicons.readlexicons.listEntries
POST /lexicons/{lexiconId}/entrieslexicons.writelexicons.createEntry
GET /lexicons/{lexiconId}/entries/{entryId}lexicons.readlexicons.getEntry
PATCH /lexicons/{lexiconId}/entries/{entryId}lexicons.writelexicons.updateEntry
DELETE /lexicons/{lexiconId}/entries/{entryId}lexicons.writelexicons.deleteEntry
GET /lexicons/{lexiconId}/exportlexicons.readlexicons.export
POST /lexicons/{lexiconId}/importlexicons.writelexicons.import
POST /lexicons/{lexiconId}/previewlexicons.readlexicons.preview
GET /lexicons/{lexiconId}/referenceslexicons.readlexicons.listReferences

POST /knowledgebases/project-scopes

Register a project scope

ParameterLocationRequiredTypeConstraints / defaultMeaning
projectIdbodyyesstring—Customer-facing project identifier. 1-64 letters/digits.
namebodynostringdefault=""Optional display name used for team naming.
subProductIdbodynostringdefault=""Bound sub-product code. Optional, can be bound later.
knowledgeBaseIdbodynostringdefault=""Existing knowledge base to bind as the project asset store. Optional; bind later via update.

Success response: HTTP 201 — knowledgeBaseProjectScope.

Response fields: $id (string), $createdAt (string), $updatedAt (string), projectId (string), name (string), knowledgeBaseId (string), teamId (string), subProductId (string).

GET /knowledgebases/project-scopes/{projectId}

Get a project scope

ParameterLocationRequiredTypeConstraints / defaultMeaning
projectIdpathyesstring—Customer-facing project identifier.

Success response: HTTP 200 — knowledgeBaseProjectScope.

Response fields: $id (string), $createdAt (string), $updatedAt (string), projectId (string), name (string), knowledgeBaseId (string), teamId (string), subProductId (string).

PATCH /knowledgebases/project-scopes/{projectId}

Update a project scope

ParameterLocationRequiredTypeConstraints / defaultMeaning
projectIdpathyesstring—Customer-facing project identifier.
namebodynostringdefault=""Display name. Empty keeps the current value.
subProductIdbodynostringdefault=""Bound sub-product code. Empty keeps the current binding; pass a new code to rebind. There is no clear sentinel — clearing requires rebinding or platform assistance.
knowledgeBaseIdbodynostringdefault=""Knowledge base to bind as the project asset store. Empty keeps the current binding; "none" clears it.

Success response: HTTP 200 — knowledgeBaseProjectScope.

Response fields: $id (string), $createdAt (string), $updatedAt (string), projectId (string), name (string), knowledgeBaseId (string), teamId (string), subProductId (string).

POST /knowledgebases/search

Search multiple knowledge bases

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdsbodynoarray[string]default=[]Knowledge base IDs. Between 1 and 10 unique IDs are required when projectId is omitted. Omit when projectId is set so the server expands the three-layer search range.
querybodyyesstring—Search query text.
limitbodynointegerformat=int32; default=10Final number of results to return across all knowledge bases.
searchModebodynostringenum=vector, fulltext, hybrid; default="hybrid"Search mode: vector, fulltext, or hybrid.
rerankbodynobooleandefault=falseWhether to rerank the merged recall results once via LLM Gateway.
recallLimitbodynointegerformat=int32Global recall width when rerank is enabled. Defaults to max(limit×4, 20).
rerankModelbodynostringdefault=""Optional explicit rerank model ID. Overrides automatic provider selection when rerank is enabled.
rerankProviderRefbodynostring—Pinned rerank provider source as project:<providerId> or trial:<bindingId>. Omit to use automatic routing. Do not use providerType:providerId.
similarityThresholdbodynonumberformat=floatMinimum vector similarity applied to every knowledge base. Each knowledge base default is used when omitted.
vectorWeightbodynonumberformat=floatHybrid vector branch weight applied to every knowledge base. Each knowledge base default is used when omitted.
projectIdbodynostring—Optional customer project identifier. When set, knowledgeBaseIds must be omitted: the server expands the project layer (whole project knowledge base), the bound sub-product layer (narrowed by the bound subProductId) and the common layer, after a fail-closed project membership check.
documentTagbodynostring—Optional tag {subProductId}_{sectionCode}_{fileKey} or multiple comma-separated tags (any-match); free-form values are also accepted., applied per knowledge base chunk recall.
subProductIdbodynostring—Optional sub-product code applied per knowledge base. Restricts chunk recall to documents of this sub-product.
offsetbodynointegerformat=int32; default=0Number of ranked results to skip across the fused ranking. Combine with limit for pagination.
metadataFilterbodynoobjectdefault={}Optional document metadata filter keyed by knowledge base ID, with an optional "*" entry applied to every knowledge base without its own key. Matching documents are selected before that knowledge base's chunk recall.

Success response: HTTP 200 — knowledgeBaseMultiSearchResultList.

Response fields: stopped (boolean), effectiveQuery (string), stopReply (string), total (integer), results (array), reranked (boolean).

GET /knowledgebases/{knowledgeBaseId}/document-directories

List document directories

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
parentPathquerynostringdefault=""Parent directory path; empty means root.
limitquerynointegerformat=int32; default=100Maximum number of directories.
offsetquerynointegerformat=int32; default=0Directory page offset.
versionIdquerynostring—Optional Knowledge Base Version ID.

Success response: HTTP 200 — any.

POST /knowledgebases/{knowledgeBaseId}/document-directories/count

Count documents in directory union

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
pathsbodynoarray[string]default=[]Directory paths; counts the document union.
versionIdbodynostring—Optional Knowledge Base Version ID.
groupsbodynoarray[string]—Optional batch of directory unions, at most 100 groups per request. Mutually exclusive with nonempty paths.

Success response: HTTP 200 — any.

GET /knowledgebases/{knowledgeBaseId}/documents

List knowledge base documents

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
statusquerynostringdefault=""Filter documents by status.
stagequerynostringdefault=""Filter documents by stage.
enabledquerynoboolean—Filter documents by enabled status.
documentTagquerynostring—Optional tag {subProductId}_{sectionCode}_{fileKey} exact match on metadata.documentTag; free-form values are also accepted.
subProductIdquerynostring—Optional sub-product code. Returns only documents whose metadata.subProductId (or documentTag subProductId segment) equals this value. Combine with documentTag to require both.
queriesquerynoarray[string]default=[]Array of query strings generated using the Query class provided by the SDK. Learn more about queries. Maximum of 100 queries are allowed, each 4096 characters long. Ignored when documentTag or subProductId is set.
versionIdquerynostring—Optional Knowledge Base Version ID. Defaults to the current Version for ACTIVE Knowledge Bases.
directoryPathquerynostring—Normalized directory path, including descendants.
directoryUnclassifiedquerynobooleandefault=falseOnly documents without a directory.

Success response: HTTP 200 — knowledgeBaseDocumentList.

Response fields: total (integer), documents (array).

POST /knowledgebases/{knowledgeBaseId}/documents

Create knowledge base document

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
bucketIdbodynostringdefault=""Optional Storage bucket ID of the already-uploaded source file. Defaults to the knowledge base bucket.
fileIdbodyyesstring—Storage file ID of the already-uploaded source file.
namebodynostringdefault=""Optional document display name. Defaults to the storage file name.
documentTagbodynostringdefault=""Optional tag {subProductId}_{sectionCode}_{fileKey}; fileKey may be omitted ({subProductId}_{sectionCode}) and is generated server-side. Multiple tags comma-separated in one value (tag1,tag2); free-form values are also accepted. Stored as a list in metadata.documentTag.
subProductIdbodynostringdefault=""Optional sub-product code (1–64 letters or digits), saved in the independent metadata.subProductId field. When a nonempty documentTag is submitted and this field is omitted or cleared, derivation occurs only if the first tag is a valid structured identifier with a nonempty sub-product segment.
projectIdbodynostringdefault=""Optional customer project identifier (1-64 letters/digits) stored in metadata.projectId. Marks this document as project-owned; the shared-library layout (6.2 option B) filters recall by it.
sectionCodebodynostringdefault=""Optional section code (1-64 digits) embedded as the sectionCode segment of the auto-generated documentTag when documentTag is omitted.
sourcebodynostringdefault="manual"Document source. Default: manual.
externalItemIdbodynostringdefault=""External item ID when the document originates from an external data source.
parserIdbodynostringenum=general, title, smart, regex, faq, sheetOptional document-level chunking strategy override. An omitted value inherits the Knowledge Base default and is checked against the concrete file. Excel .xls/.xlsx documents directly support faq or sheet; smart automatically resolves to sheet. Sheet is unavailable for other formats.
parserConfigbodynoobject—Optional document-level parser configuration override.
metadatabodynoobjectdefault=[]Optional business metadata.
versionIdbodynostring—Optional DRAFT knowledge-base version ID. Required for writes when Versioning is ACTIVE.

Success response: HTTP 201 — knowledgeBaseDocument.

Response fields: $id (string), $createdAt (string), $updatedAt (string), kbId (string), versionId (string), name (string), bucketId (string), fileId (string), mimeType (string), source (string), externalItemId (string), parserId (string), parserConfig (object), metadata (object), status (string), enabled (boolean), stage (string), activeIngestionId (string), activeGeneration (string), processingStartedAt (string), chunksTotal (integer), chunkCount (integer), error (string), lastExecutionId (string).

POST /knowledgebases/{knowledgeBaseId}/documents/batch

Create knowledge base documents in a batch

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
fileIdsbodyyesarray[string]—Storage file IDs to register as documents. Maximum 50 files.
bucketIdbodynostringdefault=""Optional Storage bucket ID. Defaults to the knowledge base bucket.
sourcebodynostringdefault="manual"Document source. Default: manual.
parserIdbodynostringenum=general, title, smart, regex, faq, sheetOptional document-level chunking strategy override. An omitted value inherits the Knowledge Base default and is checked against every concrete file. Excel .xls/.xlsx documents directly support faq or sheet; smart automatically resolves to sheet. Sheet is unavailable for other formats.
parserConfigbodynoobject—Optional document-level parser configuration override.
metadatabodynoobjectdefault=[]Optional business metadata shared by all documents.
documentTagbodynostringdefault=""Optional tag {subProductId}_{sectionCode}_{fileKey}; fileKey may be omitted ({subProductId}_{sectionCode}) and is generated server-side per document. Multiple tags comma-separated in one value (tag1,tag2); free-form values are also accepted. Applied to every document in the batch. Stored as a list in metadata.documentTag.
subProductIdbodynostringdefault=""Optional sub-product code (1–64 letters or digits) applied to every document and saved in the independent metadata.subProductId field. When a nonempty documentTag is submitted and this field is omitted or cleared, derivation occurs only if the first tag is a valid structured identifier with a nonempty sub-product segment.
projectIdbodynostringdefault=""Optional customer project identifier (1-64 letters/digits) stored in every document metadata.projectId. Marks documents as project-owned; the shared-library layout (6.2 option B) filters recall by it.
sectionCodebodynostringdefault=""Optional section code (1-64 digits) embedded as the sectionCode segment of each auto-generated documentTag when documentTag is omitted.
versionIdbodynostring—Optional DRAFT knowledge-base version ID. Required for writes when Versioning is ACTIVE.

Success response: HTTP 201 — knowledgeBaseDocumentList.

Response fields: total (integer), documents (array).

PATCH /knowledgebases/{knowledgeBaseId}/documents/{documentId}

Update knowledge base document

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
documentIdpathyesstring—Knowledge base document ID.
namebodynostring—Document display name.
documentTagbodynostring—Optional tag {subProductId}_{sectionCode}_{fileKey}; fileKey may be omitted ({subProductId}_{sectionCode}) and is generated server-side, or multiple tags comma-separated in one value (tag1,tag2). Free-form values are also accepted. Pass an empty string to clear metadata.documentTag.
subProductIdbodynostring—Optional sub-product code saved in the independent metadata.subProductId field. Clearing this field alone can leave the effective filter falling back to an existing structured tag; clear documentTag as well to remove both associations. When a nonempty documentTag is submitted and this field is omitted or cleared, derivation occurs only if the first tag is a valid structured identifier with a nonempty sub-product segment.
projectIdbodynostring—Optional customer project identifier stored in metadata.projectId. Pass an empty string to clear. Marks the document as project-owned for shared-library recall filtering.
parserIdbodynostringenum=general, title, smart, regex, faq, sheetDocument-level chunking strategy override. Excel .xls/.xlsx documents directly support faq or sheet; smart automatically resolves to sheet. Sheet is unavailable for other formats. Pass an empty string to clear the override and validate the inherited Knowledge Base default against the concrete file.
parserConfigbodynoobject—Document-level parser configuration override.
metadatabodynoobjectdefault={}Optional business metadata. Replaces existing business metadata while preserving metadata.documentTag unless documentTag is explicitly provided.
enabledbodynoboolean—Whether the document is enabled and eligible for search retrieval. Disabled documents are excluded from knowledge base search results.
statusbodynostring—Processing status (API key only, legacy).
stagebodynostring—Processing stage (API key only, legacy).
chunksTotalbodynointegerformat=int32Total chunks (API key only, legacy).
chunkCountbodynointegerformat=int32Chunk count (API key only, legacy).
errorbodynostring—Error message (API key only, legacy).
versionIdbodynostring—Optional DRAFT knowledge-base version ID. Required for writes when Versioning is ACTIVE.

Success response: HTTP 200 — knowledgeBaseDocument.

Response fields: $id (string), $createdAt (string), $updatedAt (string), kbId (string), versionId (string), name (string), bucketId (string), fileId (string), mimeType (string), source (string), externalItemId (string), parserId (string), parserConfig (object), metadata (object), status (string), enabled (boolean), stage (string), activeIngestionId (string), activeGeneration (string), processingStartedAt (string), chunksTotal (integer), chunkCount (integer), error (string), lastExecutionId (string).

PATCH /knowledgebases/{knowledgeBaseId}/documents/{documentId}/chunks/{chunkId}

Update knowledge base document chunk

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
documentIdpathyesstring—Knowledge base document ID.
chunkIdpathyesstring—Chunk ID.
contentbodynostring—Chunk text content. Recomputes the embedding vector together with persisted image descriptions.
metadatabodynoobjectdefault={}Optional arbitrary chunk metadata. Recomputes the embedding vector when image descriptions change.
enabledbodynoboolean—Whether the chunk is enabled for retrieval. Disabled chunks are excluded from knowledge base search results and stay disabled across document publish cycles.
versionIdbodynostring—Optional DRAFT knowledge-base version ID. Required for writes when Versioning is ACTIVE.

Success response: HTTP 200 — knowledgeBaseChunk.

Response fields: $id (string), $createdAt (string), $updatedAt (string), documentId (string), versionId (string), content (string), ingestVersion (string), enabled (boolean), source (object), locator (object), metadata (object).

GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/content

Get knowledge base document content

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
documentIdpathyesstring—Knowledge base document ID.
versionIdquerynostring—Optional Knowledge Base Version ID. Defaults to the current Version for ACTIVE Knowledge Bases.

Success response: HTTP 200 — knowledgeBaseDocumentContent.

Response fields: knowledgeBaseId (string), documentId (string), name (string), mimeType (string), status (string), generation (string), chunksTotal (integer), truncated (boolean), content (string).

GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/parse-artifact

Get knowledge base document parse artifact status

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
documentIdpathyesstring—Knowledge base document ID.
versionIdquerynostring—Optional Knowledge Base Version ID. Defaults to the current Version for ACTIVE Knowledge Bases.

Success response: HTTP 200 — knowledgeBaseDocumentParseArtifact.

Response fields: knowledgeBaseId (string), documentId (string), status (string), supported (boolean), generation (string), byteSize (integer), sha256 (string).

GET /knowledgebases/{knowledgeBaseId}/documents/{documentId}/parse-artifact/content

Get knowledge base document parse artifact content

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
documentIdpathyesstring—Knowledge base document ID.
versionIdquerynostring—Optional Knowledge Base Version ID. Defaults to the current Version for ACTIVE Knowledge Bases.

Success response: HTTP 200 — File.

GET /knowledgebases/{knowledgeBaseId}/enhancement-operations

List Knowledge Base content enhancement operations

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
kindquerynostringenum=enhance, clear; default=""Optional operation kind filter.
statusquerynostringenum=queued, running, cancelling, done, failed, cancelled; default=""Optional operation status filter.
limitquerynointegerformat=int32; default=25Maximum operations to return.
offsetquerynointegerformat=int32; default=0Number of operations to skip.

Success response: HTTP 200 — knowledgeBaseEnhancementOperationList.

Response fields: total (integer), operations (array).

POST /knowledgebases/{knowledgeBaseId}/enhancement-operations

Queue a content enhancement operation for stored documents

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
kindbodynostringenum=enhance, clear; default="enhance"Operation kind. enhance re-runs keyword, question, and metadata extraction on stored chunks; clear removes existing enhancement results.
scopebodynostringenum=knowledgebase, document; default="knowledgeBase"Operation scope.
documentIdsbodynoarray[string]default=[]Document IDs for document-scoped operations.
configbodynoobjectdefault=[]One-shot configuration overrides merged over the inherited keyword/question/metadata settings. Never persisted back to the knowledge base.
forcebodynobooleandefault=falseCancel a different active enhancement operation before queuing this one.
onlyMissingbodynobooleandefault=falseWith kind=enhance, skip documents that already have results for every enabled extractor instead of re-running them.
idempotencyKeybodyyesstring—Stable key used to deduplicate retries.
retryOfbodynostring—Previous failed or cancelled enhancement operation to retry.
versionIdbodynostring—Optional Knowledge Base DRAFT knowledge-base version ID for an ACTIVE Knowledge Base.

Success response: HTTP 202 — knowledgeBaseEnhancementOperation.

Response fields: $id (string), $createdAt (string), $updatedAt (string), knowledgeBaseId (string), versionId (string), kind (string), scope (string), documentIds (array), criteria (object), status (string), stage (string), message (string), effectiveConfig (object), configHash (string), retryOf (string), stats (object), error (object), logTail (string), startedAt (string), heartbeatAt (string), finishedAt (string).

GET /knowledgebases/{knowledgeBaseId}/enhancement-operations/{operationId}

Get a Knowledge Base content enhancement operation

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
operationIdpathyesstring—Enhancement operation ID.

Success response: HTTP 200 — knowledgeBaseEnhancementOperation.

Response fields: $id (string), $createdAt (string), $updatedAt (string), knowledgeBaseId (string), versionId (string), kind (string), scope (string), documentIds (array), criteria (object), status (string), stage (string), message (string), effectiveConfig (object), configHash (string), retryOf (string), stats (object), error (object), logTail (string), startedAt (string), heartbeatAt (string), finishedAt (string).

POST /knowledgebases/{knowledgeBaseId}/enhancement-operations/{operationId}/cancel

Request cancellation of a Knowledge Base content enhancement operation

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
operationIdpathyesstring—Enhancement operation ID.

Success response: HTTP 202 — knowledgeBaseEnhancementOperation.

Response fields: $id (string), $createdAt (string), $updatedAt (string), knowledgeBaseId (string), versionId (string), kind (string), scope (string), documentIds (array), criteria (object), status (string), stage (string), message (string), effectiveConfig (object), configHash (string), retryOf (string), stats (object), error (object), logTail (string), startedAt (string), heartbeatAt (string), finishedAt (string).

GET /knowledgebases/{knowledgeBaseId}/graph

Browse the active GraphRAG node-link graph

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
queryquerynostringdefault=""Optional entity text filter.
typequerynostringdefault=""Optional entity type filter.
communityquerynostringdefault=""Optional community filter.
seedquerynostringdefault=""Optional entity seed for bounded N-hop expansion.
hopsquerynointegerformat=int32; default=1Number of neighbor hops when seed is present.
limitquerynointegerformat=int32; default=100Maximum nodes to return.
cursorquerynostringdefault=""Opaque cursor returned by the previous graph page.
entityScopequerynostringenum=core, all; default="core"Entity scope: "core" shows entities appearing across multiple documents (subsystem-level view), "all" shows every indexed entity.
documentIdquerynostring—Optional Knowledge Base document ID. When set, returns only entities attributed to this document (reverse lookup from the document detail page).
documentTagquerynostring—Optional tag {subProductId}_{sectionCode}_{fileKey} or multiple comma-separated tags (any-match); free-form values are also accepted.. Combine with documentId to require both.
subProductIdquerynostring—Optional sub-product code. Returns only entities attributed to documents of this sub-product. Combine with documentTag to require both.
versionIdquerynostring—Optional Knowledge Base Version ID. Defaults to the current Version for ACTIVE Knowledge Bases.
viewquerynostringenum=entities, communities, community; default="entities"Graph view. Communities returns the lightweight overview; community pages its members and incident edges. Community views require entityScope=all and do not accept entity or document filters.
communityIdsquerynoarray[string]—Optional batch of 1-8 unique visualization community IDs for view=community and entityScope=all. Mutually exclusive with community; cursor is not supported. All members must fit in min(limit,100) nodes or the request returns 400. Discover support through visualization.member_batch_version=1.

Success response: HTTP 200 — knowledgeBaseGraph.

Response fields: resultGeneration (string), versionId (string), graph (object), totalNodes (integer), hasMore (boolean), nextCursor (string), truncated (boolean).

POST /knowledgebases/{knowledgeBaseId}/graph/search

Retrieve GraphRAG context for a question in one Knowledge Base

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
querybodyyesstring—Question to retrieve GraphRAG context for.
maxTokenbodynointegerformat=int32; default=8196Maximum graph context tokens.
entityTopNbodynointegerformat=int32; default=6Maximum matching entities.
relationTopNbodynointegerformat=int32; default=6Maximum matching relations.
communityTopNbodynointegerformat=int32; default=1Maximum community reports.
entitySimilarityThresholdbodynonumberformat=float; default=0.3Minimum entity similarity.
relationSimilarityThresholdbodynonumberformat=float; default=0.3Minimum relation similarity.
versionIdbodynostring—Optional Knowledge Base Version ID. Defaults to the current Version.

Success response: HTTP 200 — knowledgeBaseGraphSearch.

Response fields: resultGeneration (string), versionId (string), content (string), graphContext (object).

GET /knowledgebases/{knowledgeBaseId}/lexicons

getKnowledgeBaseBindings

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—knowledgeBaseId

Success response: HTTP 200 — lexiconBindings.

Response fields: enabled (boolean), stopIntercept (boolean), stopReply (string), bindings (object).

PUT /knowledgebases/{knowledgeBaseId}/lexicons

updateKnowledgeBaseBindings

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—knowledgeBaseId
bindingsbodyyesarray[array]—bindings
enabledbodynobooleandefault=falseenabled

Success response: HTTP 200 — lexiconBindings.

Response fields: enabled (boolean), stopIntercept (boolean), stopReply (string), bindings (object).

POST /knowledgebases/{knowledgeBaseId}/search

Search knowledge base

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
querybodyyesstring—Search query text.
limitbodynointegerformat=int32; default=10Final number of results to return.
searchModebodynostringenum=vector, fulltext, hybrid; default="hybrid"Search mode: vector, fulltext, or hybrid.
rerankbodynobooleandefault=falseWhether to rerank recall results via LLM Gateway.
recallLimitbodynointegerformat=int32Recall width when rerank is enabled. Defaults to max(limit×4, 20).
rerankModelbodynostringdefault=""Optional explicit rerank model ID. Overrides automatic provider selection when rerank is enabled.
rerankProviderRefbodynostring—Pinned rerank provider source as project:<providerId> or trial:<bindingId>. Omit to use automatic routing. Do not use providerType:providerId.
similarityThresholdbodynonumberformat=floatMinimum vector similarity. Supported by vector search and the vector recall branch of hybrid search.
vectorWeightbodynonumberformat=floatHybrid vector branch weight (fulltext uses 1 - vectorWeight). Defaults to knowledge base retrievalDefaults.vectorWeight.
useKnowledgeGraphbodynobooleandefault=falseWhether to add active GraphRAG retrieval.
useWikibodynobooleandefault=falseWhether to add active Wiki retrieval.
graphOptionsbodynoobjectdefault=[]Bounded GraphRAG retrieval options.
wikiOptionsbodynoobjectdefault=[]Wiki mode, topK, minK, vector, and bounded link expansion options.
allowDegradedbodynobooleandefault=trueWhether enhanced capability failures may return ordinary results with explicit degradation metadata.
answerbodynobooleandefault=falseWhether to synthesize a grounded answer from merged retrieval evidence. Uses the knowledge base indexingDefaults chat model.
documentTagbodynostring—Optional tag {subProductId}_{sectionCode}_{fileKey} or multiple comma-separated tags (any-match); free-form values are also accepted.. Restricts chunk, GraphRAG, and Wiki recall.
subProductIdbodynostring—Optional sub-product code. Restricts chunk, GraphRAG, and Wiki recall to documents of this sub-product (metadata.subProductId or the documentTag segment).
projectIdbodynostring—Optional customer project identifier. Restricts recall to documents carrying metadata.projectId of this project (shared-library layout 6.2 option B).
metadataFilterbodynoobjectdefault={}Optional document metadata filter. Matching documents are selected before chunk recall, so other documents' chunks are excluded.
applyLexiconbodynoboolean—Override lexicon rewriting for this search only. Omit to use knowledge base settings.
documentIdsbodynoarray[string]—Optional list of 1 to 100 unique document IDs. Restricts base RAG recall to those documents; cannot be combined with GraphRAG or Wiki retrieval.
versionIdbodynostring—Optional Version ID. Defaults to the current READY Version when Versioning is active.

Success response: HTTP 200 — knowledgeBaseSearchResultList.

Response fields: stopped (boolean), effectiveQuery (string), stopReply (string), total (integer), results (array), reranked (boolean), resolvedVersionId (string), capabilities (object), degradedCapabilities (array), answer (object), elapsedMs (integer), timingMs (object).

GET /knowledgebases/{knowledgeBaseId}/wiki/graph

Get the canonical Wiki page-link graph including red links

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
versionIdquerynostring—Optional Knowledge Base Version ID. Defaults to the current Version for ACTIVE Knowledge Bases.
documentTagquerynostring—Optional tag {subProductId}_{sectionCode}_{fileKey} or multiple comma-separated tags (any-match); free-form values are also accepted. Returns only Wiki pages whose sourceChunks provenance cites a matching document; links become the induced subgraph on the retained pages.
subProductIdquerynostring—Optional sub-product code. Returns only Wiki pages whose provenance cites documents of this sub-product. Combine with documentTag to require both.

Success response: HTTP 200 — knowledgeBaseWikiGraph.

Response fields: versionId (string), pages (array), links (object).

GET /knowledgebases/{knowledgeBaseId}/wiki/pages

List canonical Knowledge Wiki pages

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
pageTypequerynostringenum=entity, topic, survey, agent_practice, category_index; default=""Optional Wiki page type.
statusquerynostringenum=draft, published, conflict, archived; default=""Optional Wiki page status.
limitquerynointegerformat=int32; default=50Maximum pages to return.
offsetquerynointegerformat=int32; default=0Number of pages to skip.
versionIdquerynostring—Optional Knowledge Base Version ID. Defaults to the current Version for ACTIVE Knowledge Bases.
documentTagquerynostring—Optional tag {subProductId}_{sectionCode}_{fileKey} or multiple comma-separated tags (any-match); free-form values are also accepted. Returns only Wiki pages whose sourceChunks provenance cites a matching document.
subProductIdquerynostring—Optional sub-product code. Returns only Wiki pages whose provenance cites documents of this sub-product. Combine with documentTag to require both.

Success response: HTTP 200 — knowledgeBaseWikiPageList.

Response fields: total (integer), pages (array).

POST /knowledgebases/{knowledgeBaseId}/wiki/search

Search Wiki pages in one Knowledge Base

ParameterLocationRequiredTypeConstraints / defaultMeaning
knowledgeBaseIdpathyesstring—Knowledge base ID.
querybodyyesstring—Wiki query text.
searchModebodynostringenum=auto, wiki_direct, wiki_retrieved, rag_first; default="auto"Wiki router tier override.
topKbodynointegerformat=int32; default=8Maximum Wiki pages to return.
useVectorbodynobooleandefault=trueWhether to include vector recall.
vectorWeightbodynonumberformat=float; default=0.4Vector contribution before RRF.
linkOptionsbodynoobjectdefault=[]Bounded Wiki link expansion options.
versionIdbodynostring—Optional Knowledge Base Version ID. Defaults to the current Version.

Success response: HTTP 200 — knowledgeBaseWikiSearch.

Response fields: resultGeneration (string), contentStale (boolean), tier (string), results (array), toc (object), categoryIndex (object), latencyMs (integer).

GET /lexicons

list

ParameterLocationRequiredTypeConstraints / defaultMeaning
limitquerynointegerformat=int32; default=25limit
offsetquerynointegerformat=int32; default=0offset

Success response: HTTP 200 — lexiconList.

Response fields: total (integer), lexicons (array).

POST /lexicons

create

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdbodynostringdefault="unique()"lexiconId
namebodyyesstring—name
descriptionbodynostringdefault=""description
permissionsbodynoarray[string]—permissions
synonymRewriteModebodynostringenum=matched, primary, primary_expansion; default="matched"Synonym rewriting: matched, primary, or primary_expansion.

Success response: HTTP 201 — lexicon.

Response fields: $id (string), $createdAt (string), $updatedAt (string), $permissions (array), name (string), description (string), tokenizerProfile (string), synonymRewriteMode (string), revision (integer).

GET /lexicons/{lexiconId}

get

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId

Success response: HTTP 200 — lexicon.

Response fields: $id (string), $createdAt (string), $updatedAt (string), $permissions (array), name (string), description (string), tokenizerProfile (string), synonymRewriteMode (string), revision (integer).

PATCH /lexicons/{lexiconId}

update

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId
namebodynostring—name
descriptionbodynostring—description
permissionsbodynoarray[string]—permissions
synonymRewriteModebodynostringenum=matched, primary, primary_expansionSynonym rewriting: matched, primary, or primary_expansion.

Success response: HTTP 200 — lexicon.

Response fields: $id (string), $createdAt (string), $updatedAt (string), $permissions (array), name (string), description (string), tokenizerProfile (string), synonymRewriteMode (string), revision (integer).

DELETE /lexicons/{lexiconId}

delete

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId

Success response: HTTP 204 — No content.

GET /lexicons/{lexiconId}/entries

listEntries

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId
limitquerynointegerformat=int32; default=25Page size.
offsetquerynointegerformat=int32; default=0Page offset.
entryTypequerynostringenum=synonym, expansion, stopFilter entries by rule type. Omit to list all types.

Success response: HTTP 200 — lexiconEntryList.

Response fields: total (integer), entries (array).

POST /lexicons/{lexiconId}/entries

createEntry

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId
entryIdbodynostringdefault="unique()"entryId
entryTypebodyyesstringenum=synonym, expansion, stopentryType
termsbodyyesarray[string]—terms
expansionsbodynoarray[string]default=[]expansions
positionbodynointegerformat=int32; default=0position

Success response: HTTP 201 — lexiconEntry.

Response fields: $id (string), $createdAt (string), $updatedAt (string), lexiconId (string), entryType (string), terms (array), expansions (array), position (integer).

GET /lexicons/{lexiconId}/entries/{entryId}

getEntry

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId
entryIdpathyesstring—entryId

Success response: HTTP 200 — lexiconEntry.

Response fields: $id (string), $createdAt (string), $updatedAt (string), lexiconId (string), entryType (string), terms (array), expansions (array), position (integer).

PATCH /lexicons/{lexiconId}/entries/{entryId}

updateEntry

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId
entryIdpathyesstring—entryId
entryTypebodynostringenum=synonym, expansion, stopentryType
termsbodynoarray[string]—terms
expansionsbodynoarray[string]—expansions
positionbodynointegerformat=int32position

Success response: HTTP 200 — lexiconEntry.

Response fields: $id (string), $createdAt (string), $updatedAt (string), lexiconId (string), entryType (string), terms (array), expansions (array), position (integer).

DELETE /lexicons/{lexiconId}/entries/{entryId}

deleteEntry

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId
entryIdpathyesstring—entryId

Success response: HTTP 204 — No content.

GET /lexicons/{lexiconId}/export

export

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—Lexicon ID.
formatquerynostringenum=json, csv, xlsx; default="json"Export format.

Success response: HTTP 200 — File.

POST /lexicons/{lexiconId}/import

import

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId
entriesbodynoarray[array]default=[]entries
modebodynostringenum=merge, overwrite; default="merge"mode
dryRunbodynobooleandefault=truedryRun
formatbodynostringenum=json, csv, xlsx; default="json"File format.
contentbodynostringdefault=""Base64 file content for CSV/XLSX.

Success response: HTTP 200 — lexiconImport.

Response fields: total (integer), inserted (integer), skipped (integer), errors (object), rows (object), applied (boolean), tokenizerProfile (string), tokenizationChanged (boolean).

POST /lexicons/{lexiconId}/preview

preview

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId
querybodyyesstring—query

Success response: HTTP 200 — lexiconRewrite.

Response fields: original (string), rewritten (string), stopped (boolean), stopMatched (array), mappings (object), tokenizerProfile (string), queryTokens (array).

GET /lexicons/{lexiconId}/references

listReferences

ParameterLocationRequiredTypeConstraints / defaultMeaning
lexiconIdpathyesstring—lexiconId

Success response: HTTP 200 — lexiconReferences.

Response fields: total (integer), references (object).

Errors and retries

400/422: check types, enumerations and rules. 401/403: verify identity and scopes; dataset analyses additionally require trace and dataset read access. 404: check that the resource exists in the current project. 409: read current state before deciding to retry. 429: honor Retry-After. After 5xx or network loss, inspect operation state first. Preserve an idempotency key across retries; change it only for a deliberate new operation. Confirm deletion and clearing targets before writing.