Docs
Contents

Knowledge Base API

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}/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 locator exact match (2.10.0): {subProductId}_{sectionCode}_{fileKey}; narrows the scope of chunk, GraphRAG, and Wiki retrieval.
subProductIdbodystringNoSub-product code filter (2.10.0): narrows retrieval by metadata.subProductId (or the first segment of documentTag); 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.
documentTagbodystringNoExact match on document locator identifier (2.10.0): applied per library 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.
statusquerystringNoDefault ""Filter by processing status: uploaded / processing / ready / failed.
stagequerystringNoDefault ""Filter by processing stage.
enabledquerybooleanNoFilter by enabled state.
documentTagquerystringNoExact filter by document locator identifier (2.10.0).
subProductIdquerystringNoExact filter by sub-product code (2.10.0).
queriesquerystring[]NoDefault []Array of Appbase Query advanced query strings, at most 100 items with 4096 characters each.

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:

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.
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 locator identifier (2.10.0): {subProductId}_{sectionCode}_{fileKey} (subProductId letters/digits, sectionCode digits, fileKey requires 32 hex digits without hyphens), stored in metadata.documentTag.
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 still derived from the first segment of the locator identifier. Retrieval endpoints use a separate field or the first segment of the locator identifier for filtering.
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:

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):

curl -X POST "https://appbuild-sit.oceanbase.com/v1/knowledgebases/kb_enterprise_support/documents" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>" \
  -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": ""
}

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

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}

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

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.
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, the first segment is still derived. When no non-empty label is submitted together with it, an empty string deletes the standalone field, but effective filter values still fall back to the first segment of the existing label; to remove both, both fields must be cleared 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:

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.
documentIdpathstringYesTarget document ID.

Output:

204, no response body.

Call example:

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

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

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

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

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

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

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 body text or metadata; changing content (or image description metadata) triggers recomputation of the embedding vector.

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.

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:

curl -X PATCH "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>" \
  -H "Content-Type: application/json" \
  -d '{
    "content": "保修政策:自购买之日起整机保修 24 个月(2026 年更新)。",
    "metadata": {
      "topic": "早餐店经营"
    }
  }'

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

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.
documentIdpathstringYesTarget document ID.
chunkIdpathstringYesTarget chunk ID.

Output:

204, no response body.

Call example:

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

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

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

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

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.
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": "语雀团队空间",
      "config": {
        "repoNamespaces": [
          "acme/manuals"
        ],
        "syncSchedule": "0 2 * * *"
      },
      "credentials": {},
      "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.
namebodystringYesData source name.
typebodystringNoEnum: yuqueData source type; currently only yuque is supported.
configbodyobjectNoNon-sensitive configuration object (for Yuque: repoNamespaces, syncSchedule cron, etc.).
credentialsbodyobjectNoCredential object (e.g., Yuque team token); encrypted at rest and never echoed back in responses.
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:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "语雀团队空间",
    "type": "yuque",
    "config": {
      "repoNamespaces": [
        "acme/manuals"
      ],
      "syncSchedule": "0 2 * * *"
    },
    "credentials": {
      "teamToken": "yq_team_token_xxx"
    },
    "status": "active",
    "triggerSync": true
  }'

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": "语雀团队空间",
  "config": {
    "repoNamespaces": [
      "acme/manuals"
    ],
    "syncSchedule": "0 2 * * *"
  },
  "credentials": {},
  "status": "active",
  "lastSyncAt": "2026-09-14T02:00:00.000+00:00",
  "lastSyncStatus": "ready",
  "lastCursor": "yq-2026-09-14T02:00:00Z",
  "error": ""
}

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.
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": "语雀团队空间",
  "config": {
    "repoNamespaces": [
      "acme/manuals"
    ],
    "syncSchedule": "0 2 * * *"
  },
  "credentials": {},
  "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.
namebodystringNoData source name.
configbodyobjectNoNon-sensitive configuration object.
credentialsbodyobjectNoKey-value pairs incrementally merged into the stored 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:

curl -X PATCH "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>" \
  -H "Content-Type: application/json" \
  -d '{
    "config": {
      "repoNamespaces": [
        "acme/manuals",
        "acme/faq"
      ],
      "syncSchedule": "0 */6 * * *"
    },
    "credentials": {},
    "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": "语雀团队空间",
  "config": {
    "repoNamespaces": [
      "acme/manuals"
    ],
    "syncSchedule": "0 2 * * *"
  },
  "credentials": {},
  "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.
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:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/yuque/repos" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "teamId": "acme",
    "teamToken": "yq_team_token_xxx"
  }'

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:

curl -X POST "https://<your-endpoint>/v1/knowledgebases/kb_product_docs/datasources/yuque/docs" \
  -H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
  -H "X-Appwrite-Key: <YOUR_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "teamId": "acme",
    "teamToken": "yq_team_token_xxx",
    "repoNamespaces": [
      "acme/manuals"
    ]
  }'

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.
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.
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.
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 statistics (dynamic object: scanned/imported/skipped/failed counts, etc.).
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": 2,
  "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": {
        "scanned": 40,
        "imported": 3,
        "unchanged": 36,
        "failed": 1
      },
      "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 statistics (dynamic object: scanned/imported/skipped/failed counts, etc.).
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": "ready",
  "cursorStart": "yq-2026-09-13T02:00:00Z",
  "cursorEnd": "yq-2026-09-14T02:00:00Z",
  "stats": {
    "scanned": 40,
    "imported": 3,
    "unchanged": 36,
    "failed": 1
  },
  "error": "",
  "startedAt": "2026-09-14T02:00:01.000+00:00",
  "finishedAt": "2026-09-14T02:01:12.000+00:00"
}

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.
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 statistics (dynamic object: scanned/imported/skipped/failed counts, etc.).
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": {
    "scanned": 40,
    "imported": 3,
    "unchanged": 36,
    "failed": 1
  },
  "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:

curl -X GET "https://appbuild-sit.oceanbase.com/v1/lexicons?limit=25&offset=0" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>"

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:

curl -X POST "https://appbuild-sit.oceanbase.com/v1/lexicons" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>" \
  -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:

# 1. Get lexicon details
curl -X GET "https://appbuild-sit.oceanbase.com/v1/lexicons/lex_enterprise_synonyms" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>"

# 2. Update the lexicon name and description
curl -X PATCH "https://appbuild-sit.oceanbase.com/v1/lexicons/lex_enterprise_synonyms" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "企业智能客服同义词与扩展词典(v2)",
    "description": "覆盖 OceanBase V4.3、LLM Gateway 与智能体专有术语"
  }'

# 3. Delete an unbound lexicon
curl -X DELETE "https://appbuild-sit.oceanbase.com/v1/lexicons/lex_temp_test" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>"

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:

curl -X POST "https://appbuild-sit.oceanbase.com/v1/lexicons/lex_enterprise_synonyms/entries" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>" \
  -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):

curl -X POST "https://appbuild-sit.oceanbase.com/v1/lexicons/lex_enterprise_synonyms/preview" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>" \
  -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:

curl -X PUT "https://appbuild-sit.oceanbase.com/v1/knowledgebases/kb_enterprise_support/lexicons" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>" \
  -H "Content-Type: application/json" \
  -d '{
    "enabled": true,
    "bindings": [
      {"lexiconId": "lex_enterprise_synonyms", "priority": 1},
      {"lexiconId": "lex_support_stopwords", "priority": 2}
    ]
  }'
# Query the list of lexicons currently bound to the knowledge base (GET /v1/knowledgebases/{kbId}/lexicons)
curl -X GET "https://appbuild-sit.oceanbase.com/v1/knowledgebases/kb_enterprise_support/lexicons" \
  -H "X-Appwrite-Project: enterprise-ai-hub-210" \
  -H "X-Appwrite-Key: <APPBASE_API_KEY>"

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