Node.js
Installation
npm install @knowhere-ai/sdk
Or with pnpm:
pnpm add @knowhere-ai/sdk
Classes
Knowhere
The main client class. All methods are async.
import Knowhere from "@knowhere-ai/sdk";
const client = new Knowhere(options?: KnowhereOptions);
KnowhereOptions
| Parameter | Type | Default | Description |
|---|---|---|---|
apiKey | string | KNOWHERE_API_KEY env | API key (required) |
baseURL | string | https://api.knowhereto.ai | API base URL |
timeout | number | 60000 | HTTP request timeout (ms) |
uploadTimeout | number | 600000 | File upload timeout (ms) |
maxRetries | number | 5 | Max retry attempts for retryable errors |
defaultHeaders | Record<string, string> | — | Extra headers for every request |
httpAgent | http.Agent | — | Custom HTTP agent |
httpsAgent | https.Agent | — | Custom HTTPS agent |
Properties
| Property | Type | Description |
|---|---|---|
jobs | Jobs | Access the jobs resource namespace |
Methods
Knowhere.parse()
Parse a document end-to-end: create job → upload file (if needed) → poll → download and parse results. Provide exactly one of url or file.
async parse(params: ParseParams): Promise<ParseResult>
ParseParams
| Parameter | Type | Default | Description |
|---|---|---|---|
url | string | — | URL to parse (mutually exclusive with file) |
file | string | Buffer | ReadStream | Uint8Array | — | Local file to upload and parse |
fileName | string | — | Override filename (required for Buffer/Stream) |
model | ParsingModel | "base" | Parsing model |
ocr | boolean | false | Enable OCR for scanned documents |
docType | DocType | "auto" | Document type hint |
smartTitleParse | boolean | — | Enable smart title detection |
summaryImage | boolean | — | Generate image summaries |
summaryTable | boolean | — | Generate table summaries |
summaryText | boolean | — | Generate text chunk summaries |
addFragDesc | string | — | Additional fragment description |
dataId | string | — | Idempotency / correlation identifier |
kbDir | string | — | Knowledge base directory |
pollInterval | number | 10000 | Milliseconds between status polls |
pollTimeout | number | 1800000 | Max milliseconds to wait for completion |
verifyChecksum | boolean | true | Verify SHA-256 checksum of result |
webhook | WebhookConfig | — | Webhook for job completion notifications |
onUploadProgress | (progress: UploadProgress) => void | — | Upload progress callback |
onPollProgress | (status: PollProgress) => void | — | Polling progress callback |
signal | AbortSignal | — | Abort signal for cancellation |
Returns
Returns a ParseResult containing the manifest, typed chunks, full markdown, and raw ZIP buffer.
Example
import Knowhere from "@knowhere-ai/sdk";
import { readFileSync } from "fs";
const client = new Knowhere();
// Parse from URL
const result = await client.parse({ url: "https://example.com/report.pdf" });
// Parse a local file with options
const result2 = await client.parse({
file: readFileSync("./report.pdf"),
fileName: "report.pdf",
model: "advanced",
ocr: true,
onUploadProgress: (p) => console.log(`Upload: ${p.percent}%`),
onPollProgress: (p) => console.log(`Status: ${p.status}`),
});
console.log(result.statistics.totalChunks);
console.log(result.fullMarkdown?.slice(0, 500));
Jobs.create()
Create a new parsing job.
async create(params: CreateJobParams): Promise<Job>
CreateJobParams
| Parameter | Type | Default | Description |
|---|---|---|---|
sourceType | "url" | "file" | — | Source type (required) |
sourceUrl | string | — | URL to parse (when sourceType: "url") |
fileName | string | — | Original filename (when sourceType: "file") |
dataId | string | — | Idempotency / correlation identifier |
parsingParams | ParsingParams | — | Parsing configuration |
webhook | WebhookConfig | — | Webhook for job completion notifications |
Returns
A Job object. When sourceType: "file", the object includes uploadUrl and uploadHeaders.
Jobs.get()
Retrieve the current status and result of a job.
async get(jobId: string): Promise<JobResult>
Jobs.upload()
Upload a file for a job created with sourceType: "file".
async upload(jobId: string, params: UploadParams): Promise<void>
UploadParams
| Parameter | Type | Description |
|---|---|---|
file | string | Buffer | ReadStream | Uint8Array | The file to upload |
onProgress | (progress: UploadProgress) => void | Upload progress callback |
signal | AbortSignal | Abort signal for cancellation |
Jobs.wait()
Poll until the job reaches a terminal status (done or failed).
async wait(jobId: string, options?: WaitOptions): Promise<JobResult>
WaitOptions
| Parameter | Type | Default | Description |
|---|---|---|---|
pollInterval | number | 10000 | Milliseconds between polls (adaptive backoff applied) |
pollTimeout | number | 1800000 | Max milliseconds to wait |
onProgress | (status: PollProgress) => void | — | Progress callback |
signal | AbortSignal | — | Abort signal for cancellation |
Jobs.load()
Download and parse the result ZIP for a completed job.
async load(jobId: string, options?: LoadOptions): Promise<ParseResult>
LoadOptions
| Parameter | Type | Default | Description |
|---|---|---|---|
verifyChecksum | boolean | true | Verify SHA-256 checksum from the manifest |
Types
ParsingModel
type ParsingModel = "base" | "advanced";
DocType
type DocType = "auto" | "pdf" | "docx" | "txt" | "md";
WebhookConfig
interface WebhookConfig {
url: string;
}
ParsingParams
Used by Jobs.create() for low-level job creation.
interface ParsingParams {
model?: ParsingModel;
ocrEnabled?: boolean;
kbDir?: string;
docType?: DocType;
smartTitleParse?: boolean;
summaryImage?: boolean;
summaryTable?: boolean;
summaryTxt?: boolean;
addFragDesc?: string;
}
Job
interface Job {
jobId: string;
status: JobStatus;
sourceType: string;
dataId?: string;
createdAt: Date;
uploadUrl?: string;
uploadHeaders?: Record<string, string>;
expiresIn?: number;
}
JobResult
interface JobResult {
jobId: string;
status: JobStatus;
sourceType: string;
dataId?: string;
createdAt: Date;
progress?: Record<string, unknown>;
error?: JobError;
result?: Record<string, unknown>;
resultUrl?: string;
resultUrlExpiresAt?: Date;
fileName?: string;
fileExtension?: string;
model?: string;
ocrEnabled?: boolean;
durationSeconds?: number;
creditsSpent?: number;
readonly isTerminal: boolean;
readonly isDone: boolean;
readonly isFailed: boolean;
}
ParseResult
interface ParseResult {
manifest: Manifest;
chunks: Chunk[];
fullMarkdown?: string;
hierarchy?: unknown;
rawZip: Buffer;
readonly textChunks: TextChunk[];
readonly imageChunks: ImageChunk[];
readonly tableChunks: TableChunk[];
readonly jobId: string;
readonly statistics: Statistics;
getChunk(chunkId: string): Chunk | undefined;
save(directory: string): Promise<string>;
}
Error Handling
All errors inherit from KnowhereError.
import Knowhere, {
AuthenticationError,
APIError,
RateLimitError,
} from "@knowhere-ai/sdk";
const client = new Knowhere();
try {
await client.parse({ url: "https://example.com/report.pdf" });
} catch (error) {
if (error instanceof AuthenticationError) {
console.error("Invalid API key");
} else if (error instanceof RateLimitError) {
console.error(`Retry after ${error.retryAfter}s`);
} else if (error instanceof APIError) {
console.error(`${error.statusCode}: ${error.message}`);
}
}