Skip to main content

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

ParameterTypeDefaultDescription
apiKeystringKNOWHERE_API_KEY envAPI key (required)
baseURLstringhttps://api.knowhereto.aiAPI base URL
timeoutnumber60000HTTP request timeout (ms)
uploadTimeoutnumber600000File upload timeout (ms)
maxRetriesnumber5Max retry attempts for retryable errors
defaultHeadersRecord<string, string>Extra headers for every request
httpAgenthttp.AgentCustom HTTP agent
httpsAgenthttps.AgentCustom HTTPS agent

Properties

PropertyTypeDescription
jobsJobsAccess 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

ParameterTypeDefaultDescription
urlstringURL to parse (mutually exclusive with file)
filestring | Buffer | ReadStream | Uint8ArrayLocal file to upload and parse
fileNamestringOverride filename (required for Buffer/Stream)
modelParsingModel"base"Parsing model
ocrbooleanfalseEnable OCR for scanned documents
docTypeDocType"auto"Document type hint
smartTitleParsebooleanEnable smart title detection
summaryImagebooleanGenerate image summaries
summaryTablebooleanGenerate table summaries
summaryTextbooleanGenerate text chunk summaries
addFragDescstringAdditional fragment description
dataIdstringIdempotency / correlation identifier
kbDirstringKnowledge base directory
pollIntervalnumber10000Milliseconds between status polls
pollTimeoutnumber1800000Max milliseconds to wait for completion
verifyChecksumbooleantrueVerify SHA-256 checksum of result
webhookWebhookConfigWebhook for job completion notifications
onUploadProgress(progress: UploadProgress) => voidUpload progress callback
onPollProgress(status: PollProgress) => voidPolling progress callback
signalAbortSignalAbort 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

ParameterTypeDefaultDescription
sourceType"url" | "file"Source type (required)
sourceUrlstringURL to parse (when sourceType: "url")
fileNamestringOriginal filename (when sourceType: "file")
dataIdstringIdempotency / correlation identifier
parsingParamsParsingParamsParsing configuration
webhookWebhookConfigWebhook 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

ParameterTypeDescription
filestring | Buffer | ReadStream | Uint8ArrayThe file to upload
onProgress(progress: UploadProgress) => voidUpload progress callback
signalAbortSignalAbort 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

ParameterTypeDefaultDescription
pollIntervalnumber10000Milliseconds between polls (adaptive backoff applied)
pollTimeoutnumber1800000Max milliseconds to wait
onProgress(status: PollProgress) => voidProgress callback
signalAbortSignalAbort signal for cancellation

Jobs.load()

Download and parse the result ZIP for a completed job.

async load(jobId: string, options?: LoadOptions): Promise<ParseResult>

LoadOptions

ParameterTypeDefaultDescription
verifyChecksumbooleantrueVerify 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}`);
}
}