Knowhere Node.js SDK
Official Node.js/TypeScript SDK for the Knowhere document parsing API.
Features
- ๐ TypeScript-first - Full type safety with comprehensive type definitions
- ๐ฆ Stream-based uploads - Efficient handling of large files
- ๐ Automatic retries - Exponential backoff for transient failures
- ๐ Adaptive polling - Smart waiting for job completion
- ๐ฏ Progressive API - High-level convenience methods + low-level control
- โก Modern JavaScript - ESM and CommonJS support
Installation
npm install @ontos-ai/knowhere-sdk
Requirements:
- Node.js >= 22.13.0
- npm >= 10.0.0
- TypeScript >= 5.0 (optional, for type checking)
Quick Start
import Knowhere from '@ontos-ai/knowhere-sdk';
// Initialize client
const client = new Knowhere({
apiKey: process.env.KNOWHERE_API_KEY,
});
// Parse a document from URL
const result = await client.parse({
url: 'https://example.com/document.pdf',
});
// Access parsed content
console.log(`Found ${result.textChunks.length} text chunks`);
console.log(`Found ${result.imageChunks.length} images`);
console.log(`Found ${result.tableChunks.length} tables`);
console.log(`Found ${result.pageChunks.length} page chunks`);
// Work with chunks โ worker metadata is in chunk.metadata
result.textChunks.forEach((chunk) => {
console.log(chunk.content);
console.log(chunk.metadata.keywords);
console.log(chunk.metadata.summary);
});
result.pageChunks.forEach((chunk) => {
console.log(chunk.contentSource); // "summary"
console.log(chunk.content); // page-level summary
console.log(chunk.metadata.pageNums); // citation pages
});
// Save results to disk
await result.save('./output/');
Configuration
Environment Variables
KNOWHERE_API_KEY=sk_... # Required
KNOWHERE_BASE_URL=https://api.knowhereto.ai # Optional
Client Options
const client = new Knowhere({
apiKey: 'sk_...', // API authentication key
baseURL: 'https://...', // API base URL
timeout: 60000, // Request timeout (ms)
uploadTimeout: 600000, // Upload timeout (ms)
maxRetries: 5, // Max retry attempts
});
Usage Examples
Parse from File
// From file path (recommended)
const result = await client.parse({
file: './document.pdf',
});
// From Buffer
const buffer = await fs.readFile('./document.pdf');
const result = await client.parse({
file: buffer,
fileName: 'document.pdf',
});
// From Stream
const stream = fs.createReadStream('./document.pdf');
const result = await client.parse({
file: stream,
fileName: 'document.pdf',
});
fileName is inferred automatically when file is a local file path. When
file is a Buffer, Uint8Array, or a stream without path metadata, provide
fileName explicitly.
Advanced Options
const result = await client.parse({
url: 'https://example.com/doc.pdf',
model: 'advanced', // 'base' | 'advanced'
ocr: true, // Enable OCR
docType: 'pdf', // Document type hint
smartTitleParse: true, // Smart title detection
summaryImage: true, // Generate image summaries
summaryTable: true, // Generate table summaries
summaryText: true, // Generate text summaries
addFragDesc: 'Custom context', // Additional fragment description
kbDir: 'project_docs', // Knowledge base directory
pollInterval: 10000, // Polling interval (ms)
pollTimeout: 1800000, // Max wait time (ms)
verifyChecksum: true, // Verify ZIP checksum (default: true)
webhook: {
// Webhook for completion
url: 'https://...',
},
onUploadProgress: (progress) => {
console.log(`Upload: ${progress.percent}%`);
},
onPollProgress: (status) => {
console.log(`Status: ${status.status}`);
},
});
Bring Your Own Key (BYOK)
Pass per-request LLM credentials via llmConfig on parse/job create and
retrieval queries. Flat root applies to both channels; use models for
different model ids on the same endpoint, or text / vision for different
provider endpoints. Use camelCase in TypeScript; the HTTP client serializes to
snake_case on the wire.
// Multimodal shorthand โ one model for text + vision
const llmConfig = {
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4o',
baseUrl: 'https://api.openai.com/v1',
};
// Same endpoint, different models per channel
const modelsConfig = {
apiKey: process.env.OPENAI_API_KEY,
baseUrl: 'https://api.openai.com/v1',
models: { text: 'gpt-4o-mini', vision: 'gpt-4o' },
};
// Or two different endpoints
const splitLlmConfig = {
text: {
apiKey: process.env.OPENAI_API_KEY,
model: 'gpt-4o-mini',
baseUrl: 'https://api.openai.com/v1',
},
vision: {
apiKey: process.env.DASHSCOPE_API_KEY,
model: 'qwen-vl-max',
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
},
};
const result = await client.parse({
url: 'https://example.com/doc.pdf',
llmConfig: modelsConfig,
});
const response = await client.retrieval.query({
namespace: 'support-center',
query: 'What is the refund policy?',
useAgentic: true,
llmConfig: splitLlmConfig,
});
Page Citation Assets
Page citation assets are generated by Knowhere during page-memory parsing. The
SDK does not render PDF pages locally; it preserves the page image descriptors
returned by the server on page chunks and retrieval metadata.
import Knowhere from '@ontos-ai/knowhere-sdk';
const client = new Knowhere({ apiKey: process.env.KNOWHERE_API_KEY });
const result = await client.parse({
file: './manual.pdf',
});
for (const chunk of result.pageChunks) {
console.log(chunk.metadata.pageAssets);
}
metadata.pageAssets entries point at concrete page images stored with the Knowhere
result. artifactRef is the durable result artifact path; assetUrl is an
optional server-generated access URL.
type PageCitationAsset = {
pageNum: number;
artifactRef: string;
assetUrl?: string;
contentType: 'image/png' | 'image/jpeg';
width?: number;
height?: number;
source: 'knowhere-rendered-page-citation-source';
};
Document chunk APIs can include signed page image URLs when requested: