Docs
Contents

Documents and Ingestion

Examples by language for document registration, the ingestion pipeline, image understanding, Yuque data source synchronization, and full rebuild; for concepts, parameters, and boundary rules see knowledge base.

Examples by language

Ingest a document (register → ingest → poll)

createDocument registers the source file, createIngestion asynchronously enqueues it and returns HTTP 202 (meaning the task was accepted, not that it is immediately retrievable). Poll getIngestion until ready, and after confirming that the Document's status=ready, activeGeneration, and this ingestion's generation are consistent, retrieve by the new generation; ingestion 409 means a task for the same document is already in progress. The Web surface has no ingestion capability.

const doc = await kb.createDocument({ knowledgeBaseId: base.$id, fileId: '<storageFileId>' });
// Batch registration: kb.createDocumentsBatch (up to 50 files per batch)
await kb.createIngestion({ knowledgeBaseId: base.$id, documentId: doc.$id });   // Asynchronously enqueued, may carry an idempotency key

// Polling: state machine queued → running → ready | failed | cancelled
const ing = await kb.getIngestion({ knowledgeBaseId: base.$id, documentId: doc.$id, ingestionId: '<ingestionId>' });

Image understanding (optional)

Configured in parserConfig.imageUnderstanding, this is an independent step after parsing: it generates descriptions for informative images and adds them to the retrieval text, without modifying the original chunk's content / span / locator; when enabled=true, model and providerRef are required. Passing null or omitting maxImagesPerDocument means no limit on the number of image-understanding runs. The Web surface has no such capability.

await kb.createDocument({
    knowledgeBaseId: base.$id,
    fileId: '<storageFileId>',
    parserConfig: {
        imageUnderstanding: {
            enabled: true,
            model: '<visionModelId>',             // Project vision model ID
            providerRef: 'project:<providerId>',  // Project Provider reference
            prompt: '用中文概括图片中的关键信息',    // ≤4000 characters; use the built-in prompt when empty
            maxImagesPerDocument: 20,             // 1–20, default 20
            maxDescriptionChars: 800,             // 1–800, default 800
            maxConcurrency: 4                     // 1–8, default 4
        }
    }
});

Excel worksheet parsing (2.7.0)

parserId adds sheet: applies only to Excel .xls / .xlsx, generates one complete chunk for each non-empty worksheet, and saves sheetName / sheetIndex / sheetPages. Excel documents directly support faq or sheet, and smart is automatically parsed as sheet at ingestion; general / title / regex return 400 for Excel ingestion. documentParser can still be stacked: text preserves cell structured text, while vlm / mineru render each target sheet separately into a temporary PDF (suited to charts and images). Empty-output sheets are not ingested; there are hard limits on sheet count per workbook, decompression volume, compression ratio, cell rectangles, and rendering input. The Web surface has no such capability, and this card has no Web tab.

import { ParserId, KnowledgeBaseDocumentParser } from 'agentbase-node-sdk';

// Both database-level defaults and document-level overrides can use sheet; when the document-level parserConfig is non-empty it fully replaces the knowledge base default
await kb.createDocument({
    knowledgeBaseId: base.$id,
    fileId: '<xlsxFileId>',
    parserId: ParserId.Sheet,
    parserConfig: { documentParser: KnowledgeBaseDocumentParser.Text },   // Extract structured text sheet by sheet
});
// Chart-heavy workbooks: use Vlm / Mineru for documentParser (each target Sheet is rendered as a temporary PDF)

Batch delete documents (2.8.0)

knowledgeBases.deleteDocuments({ knowledgeBaseId, documentIds, versionId }) (versionId optional) deletes multiple documents in a single request, at most 50 per batch; success returns 204. The request first runs a precheck: all IDs must belong to the library (when versionId is passed, they must belong to that writable DRAFT version); if the precheck fails, nothing is deleted. Deletion executes in request order; if an external storage or concurrency failure occurs mid-way, re-fetch the list and retry only the IDs that still exist. Requires the knowledgebases.write scope. After versioned activation, the write path must carry versionId.

await kb.deleteDocuments({
    knowledgeBaseId: base.$id,
    documentIds: ['doc_001', 'doc_002']   // At most 50 per batch
});

Index output language and embedding input limit (2.7.0)

Personal Yuque authorization and team synchronization

Personal Yuque authorization and import require the current Console user identity; a project API key or an ordinary application user session cannot substitute for it. The environment must have Yuque authorization configured. Only specific enterprise Yuque domains are supported; ask the environment administrator which are available.

This example uses the Console Python SDK. Use a short-lived JWT issued by a still-valid Console session for a user with knowledge base write permission on the target project. Set the target project, admin mode, and that JWT on the client without attaching another active Cookie. Complete first-time authorization in the browser when prompted; the session, project, knowledge base, and user must remain the same. Set the actual draft ID when versioning is enabled, or an empty string otherwise.

from getpass import getpass
from agentbase_console.client import Client
from agentbase_console.services.knowledge_bases import KnowledgeBases

client = (Client().set_endpoint('<ENDPOINT>/v1').set_project('<PROJECT_ID>')
          .set_mode('admin').set_jwt(getpass('Console user JWT: ')))
kb = KnowledgeBases(client)
knowledge_base_id = '<KNOWLEDGE_BASE_ID>'
draft_version_id = '<DRAFT_VERSION_ID>'

authorization = kb.create_yuque_o_auth_session(knowledge_base_id=knowledge_base_id)
if not authorization['authorized']:
    print(authorization['authorizeUrl'])
    input('Complete authorization in your browser, then press Enter: ')

session = kb.get_yuque_o_auth_session(
    knowledge_base_id=knowledge_base_id, session_id=authorization['sessionId'])
if not session['authorized']:
    raise RuntimeError('Yuque authorization is not complete')
result = kb.create_yuque_documents(
    knowledge_base_id=knowledge_base_id, session_id=authorization['sessionId'],
    urls=['<SUPPORTED_YUQUE_DOCUMENT_URL>'], version_id=draft_version_id or None)
for item in result.results:
    print(item.url, item.status, item.error or '')
if result.failed:
    raise RuntimeError(f'{int(result.failed)} document(s) failed to import')

Team data source synchronization

The following uses an existing team source and server-side client kb with knowledgebases.write. Replace the knowledge base, data source, and draft IDs with actual values. When versioning is disabled, set draftVersionId to an empty string or omit versionId from the REST request.

const knowledgeBaseId = '<knowledgeBaseId>';
const dataSourceId = '<dataSourceId>';
const draftVersionId = '<DRAFT_VERSION_ID>';
const sync = await kb.createDataSourceSync({
    knowledgeBaseId,
    dataSourceId,
    ...(draftVersionId ? { versionId: draftVersionId } : {})
});

Full rebuild

Changing library-level parsing configuration does not rewrite historical chunks; to re-enqueue all ready documents for ingestion in bounded batches, use createReindex (returns 202, does not change embeddingModel), carrying the cursor to continue the next batch when nextCursor is non-null. The Web surface has no such capability.

let res = await kb.createReindex({ knowledgeBaseId: base.$id, limit: 50 });
while (res.nextCursor) {   // Bounded batching: keep enqueueing until nextCursor is null
    res = await kb.createReindex({ knowledgeBaseId: base.$id, limit: 50, cursor: res.nextCursor });
}

2.12.0 — Directory filters and content enhancement

SDK 2.12.0 adds document directory listing/counting, full document and parse artifact reads, and createEnhancementOperation/listEnhancementOperations/getEnhancementOperation/cancelEnhancementOperation. Filter directories by directoryPath or directoryUnclassified; document and chunk updates expose projectId and enabled respectively. Enhancement reruns keywords, questions and metadata on stored chunks without ingesting the source again. kind=clear removes enhancement results. One shot config is not persisted to knowledge base settings. Use a stable idempotencyKey, poll the returned operation ID after 202, inspect failure counts, and use retryOf for an intentional retry.

import { Client, KnowledgeBases } from 'agentbase-node-sdk';
const client = new Client().setEndpoint(process.env.AGENTBASE_ENDPOINT)
 .setProject(process.env.AGENTBASE_PROJECT_ID).setKey(process.env.AGENTBASE_API_KEY);
{
  const prepareRequest = client.prepareRequest.bind(client);
  client.prepareRequest = (...args) => {
    const request = prepareRequest(...args);
    request.options.redirect = 'error';
    return request;
  };
}
const kb = new KnowledgeBases(client);
const operation = await kb.createEnhancementOperation({
 knowledgeBaseId: process.env.AGENTBASE_KNOWLEDGE_BASE_ID, kind: 'enhance',
 scope: 'knowledgebase', onlyMissing: true, idempotencyKey: crypto.randomUUID() });
const state = await kb.getEnhancementOperation({
 knowledgeBaseId: process.env.AGENTBASE_KNOWLEDGE_BASE_ID, operationId: operation.$id });
console.log(state.status);