How to Install and Use the WeKnora TypeScript Client SDK

Install the @weknora/dsh-weknora package via npm or Yarn, then instantiate WeKnoraClient with your base URL and optional API key to begin making typed requests to the WeKnora REST API.

The WeKnora TypeScript Client SDK provides a lightweight, ergonomic wrapper around the WeKnora knowledge‑base platform. Located in the packages/dsh‑weknora directory of the Tencent/WeKnora monorepo, this SDK exposes strongly‑typed methods for hybrid search, chat streaming, and document retrieval while handling authentication, JSON encoding, and Server‑Sent Events (SSE) parsing automatically.

Installing the WeKnora TypeScript SDK

The SDK is distributed as a standard NPM package with pre‑compiled TypeScript definitions. No additional build configuration is required.


# Using npm

npm install @weknora/dsh-weknora

# Or with Yarn

yarn add @weknora/dsh-weknora

After installation, import the WeKnoraClient class from the package entry point defined in packages/dsh‑weknora/src/index.ts.

Configuring the WeKnora Client

Configuration is handled by the ClientConfig interface in packages/dsh‑weknora/src/config.ts. The client accepts a base URL (optionally suffixed with /api/v1) and an optional API token for authenticated endpoints.

import { WeKnoraClient } from '@weknora/dsh-weknora';

const client = new WeKnoraClient({
  // The WeKnora deployment URL
  baseUrl: 'https://weknora.example.com/api/v1',
  // Optional: bearer token for privileged operations
  apiKey: process.env.WEKNORA_API_KEY,
});

The config.ts module normalizes the URL and validates the /api/v1 suffix before any request is dispatched.

Core SDK Operations

The WeKnoraClient class in packages/dsh‑weknora/src/client.ts maps each public method directly to a WeKnora REST endpoint, returning strongly‑typed objects such as SearchResult, AskResult, and KnowledgeBase.

Listing Knowledge Bases

Retrieve all available knowledge bases using the listKnowledgeBases() method.

async function listKBs() {
  const kbs = await client.listKnowledgeBases();
  console.log('Available knowledge bases:', kbs);
}

Execute vector‑plus‑keyword searches against a specific knowledge base via the search() method.

async function hybridSearch(query: string) {
  const results = await client.search({
    knowledgeBaseId: 'default',
    query,
    topK: 5, // Restrict to top‑k results
  });
  console.log('Search hits:', results.hits);
}

Streaming Answers with Chat

The ask() and chat() methods support Server‑Sent Events (SSE) for real‑time streaming. Enable streaming by setting stream: true; the client yields incremental message parts until the complete event signals the end of the answer.

async function streamAnswer(query: string) {
  const stream = client.ask({
    knowledgeBaseId: 'default',
    query,
    stream: true, // Enable SSE streaming
  });

  for await (const part of stream) {
    process.stdout.write(part.delta); // Incremental text chunk
    if (part.complete) break;         // Final completion signal
  }
}

The SSE parser logic resides directly in packages/dsh‑weknora/src/client.ts, ensuring robust handling of partial data chunks and connection errors.

Retrieving Documents

Fetch a complete document (reassembled from passages) using the retrieve() method.

async function getDocument(docId: string) {
  const doc = await client.retrieve({
    knowledgeBaseId: 'default',
    documentId: docId,
  });
  console.log('Full text:', doc.text);
}

Error Handling and Streaming Architecture

All HTTP requests route through a centralized fetch wrapper in packages/dsh‑weknora/src/client.ts. When the WeKnora API returns an error status, the client wraps the response in a WeknoraApiError that extracts the human‑readable reason field from the API’s error envelope.

For streaming operations, the client maintains an internal SSE parser that:

  • Buffers incoming text streams
  • Parses event boundaries according to the SSE specification
  • Yields typed StreamPart objects containing delta text and the complete flag

This architecture ensures that consumers receive type‑safe data without manually handling raw fetch responses or SSE formatting.

Key Source Files in the SDK

Understanding the repository structure helps when debugging or extending the client:

  • packages/dsh‑weknora/src/client.ts – Contains the core WeKnoraClient class, request helpers, SSE streaming parser, and WeknoraApiError implementation.
  • packages/dsh‑weknora/src/config.ts – Normalizes base URLs, validates the /api/v1 suffix, and defines the ClientConfig interface.
  • packages/dsh‑weknora/src/index.ts – Public entry point that re‑exports WeKnoraClient and related types for library consumers.
  • packages/dsh‑weknora/src/types.ts – Generated TypeScript definitions for API payloads including SearchResult, AskResult, and KnowledgeBase.
  • packages/dsh‑weknora/test/client.test.ts – Unit tests covering request construction, error handling scenarios, and streaming logic against a mock WeKnora server.

Summary

  • Install the WeKnora TypeScript SDK via npm install @weknora/dsh-weknora or Yarn.
  • Instantiate WeKnoraClient with a baseUrl and optional apiKey as defined in config.ts.
  • Use listKnowledgeBases(), search(), ask(), and retrieve() for typed access to WeKnora endpoints.
  • Enable real‑time streaming by passing stream: true to ask() or chat(); the SDK handles SSE parsing internally.
  • Errors are normalized into WeknoraApiError instances with accessible reason fields.

Frequently Asked Questions

How do I install the WeKnora TypeScript SDK?

Add the package @weknora/dsh-weknora to your project using npm (npm install @weknora/dsh-weknora) or Yarn (yarn add @weknora/dsh-weknora). The package ships with pre‑compiled TypeScript definitions and requires no additional build tools.

What authentication methods does the SDK support?

The SDK supports bearer token authentication via the apiKey configuration option passed to the WeKnoraClient constructor. This token is automatically attached to outgoing requests when provided, as implemented in packages/dsh‑weknora/src/client.ts.

How does streaming work in the WeKnora client?

When you set stream: true in the ask() or chat() methods, the client initiates an SSE connection to the WeKnora API. The client parses incoming Server‑Sent Events incrementally, yielding StreamPart objects containing text deltas until the final complete event marks the end of the response.

Where are the TypeScript types defined?

All TypeScript interfaces and type definitions for API responses—such as SearchResult, AskResult, and KnowledgeBase—are located in packages/dsh‑weknora/src/types.ts. These types are re‑exported through packages/dsh‑weknora/src/index.ts for convenient consumer access.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →