npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@knowledge2/sdk

v0.3.0

Published

TypeScript SDK for the Knowledge2 retrieval platform API

Readme

@knowledge2/sdk

npm version Node 20+ License: MIT

Official TypeScript SDK for the Knowledge2 retrieval platform API. The supported public customer journey is:

create corpus -> ingest documents -> build indexes -> search -> optimize retrieval

Installation

npm install @knowledge2/sdk

Requires Node.js 20 or later.

Surface Categories

| Category | Surface | |---|---| | Core retrieval workflow | orgs, auth, projects, corpora, documents, indexes, search, jobs | | Enterprise capabilities | agents, feeds, pipelines, A2A |

The main docs and examples below focus on the core retrieval workflow.

Quick Start

import { Knowledge2 } from "@knowledge2/sdk";

const client = new Knowledge2({ apiKey: "k2_..." });

// Search a corpus
const results = await client.search.query("corpus-id", {
  query: "What is retrieval augmented generation?",
  topK: 5,
});

console.log(results?.results);

Authentication

The SDK supports three authentication methods. API key auth is the default choice for server-side programmatic access.

// API key (most common)
const client = new Knowledge2({ apiKey: "k2_..." });

// Bearer token (OAuth)
const client = new Knowledge2({ bearerToken: "..." });

// Admin token
const client = new Knowledge2({ adminToken: "..." });

Examples

Create a corpus and ingest documents

import { Knowledge2 } from "@knowledge2/sdk";

const client = new Knowledge2({ apiKey: "k2_..." });

// Create a corpus
const corpus = await client.corpora.create("project-id", "My Corpus", "A test corpus");

// Upload a document
await client.documents.upload(corpus!.id, {
  rawText: "Knowledge2 is a retrieval platform.",
  metadata: { source: "example" },
});

// Build indexes (waits for completion by default)
await client.indexes.build(corpus!.id);

Queue-first batch upload

const enqueue = await client.documents.uploadBatch(
  corpus!.id,
  [
    {
      sourceUri: "doc://overview",
      rawText: "Knowledge2 builds dense and sparse indexes for hybrid retrieval.",
      metadata: { topic: "overview" },
    },
  ],
  { wait: false },
);

console.log(enqueue.jobId, enqueue.batchId, enqueue.count);

const batch = await client.documents.getBatch(corpus!.id, enqueue.batchId);
console.log(batch.status, batch.docIds);

For raw-text batch uploads, wait: false returns an enqueue handle with jobId, batchId, and count. Fetch completion status, final document IDs, and any per-item errors from client.documents.getBatch(...).

Optimize retrieval defaults

const job = await client.indexes.optimize(corpus!.id, {
  exampleQueries: [
    "how does hybrid retrieval work",
    "what is bm25 tuning",
    "how does rrf combine dense and sparse search",
  ],
  queryCount: 25,
  topK: 10,
  metric: "ndcg",
  wait: false,
});

console.log(job.jobId, job.jobType);

client.indexes.optimize(...) waits for completion by default. Pass wait: false when you want to enqueue the optimization job and poll it later.

Search with generation

const response = await client.search.generate("corpus-id", {
  query: "What is Knowledge2?",
  topK: 10,
});

console.log(response?.answer);
console.log(response?.usedSources);

Agents and feeds

const corpus = await client.corpora.create(
  "project-id",
  "Support Corpus",
  "Knowledge base for the support agent",
);

const agent = await client.agents.create({
  projectId: "project-id",
  corpusId: corpus!.id,
  name: "Support Agent",
  systemPrompt: "Answer using the connected Knowledge2 resources only.",
});

await client.feeds.create({
  projectId: "project-id",
  name: "Support Feed",
  sourceAgentId: agent!.id,
  executionMode: "answer",
});

Enterprise capabilities are available through:

  • client.agents
  • client.feeds
  • client.pipelineSpecs
  • client.a2a

client.feeds now covers the full Feeds API surface — CRUD, run, draft lifecycle (createDraft, getDraft, activateDraft, discardDraft), a read-only listSubscriptions view, and feedback (submitFeedback, getFeedbackStats). Subscription creation still lives on client.agents per the server-side model. Example:

const feedRun = await client.feeds.run(feedId, { returnResults: true });
// `results` is only populated for non-persistent feeds run with
// `returnResults: true`, and may be empty. Guard before indexing.
if (feedRun?.results?.length && feedRun.feedRunId) {
  await client.feeds.submitFeedback(feedId, {
    rating: 1,
    chunkId: feedRun.results[0].chunkId as string,
    feedRunId: feedRun.feedRunId,
  });
}
const stats = await client.feeds.getFeedbackStats(feedId);

Pagination

const page = await client.corpora.list({ limit: 10, offset: 0 });

for await (const corpus of client.corpora.listAll()) {
  console.log(corpus.name);
}

Error handling

import { Knowledge2, NotFoundError, RateLimitError } from "@knowledge2/sdk";

const client = new Knowledge2({ apiKey: "k2_..." });

try {
  await client.corpora.get("nonexistent");
} catch (err) {
  if (err instanceof NotFoundError) {
    console.log("Corpus not found:", err.message);
  } else if (err instanceof RateLimitError) {
    console.log("Rate limited, retry after:", err.retryAfter, "ms");
  }
}

Catching feature-gated and quota errors:

import {
  FeatureNotEnabledError,
  QuotaExceededError,
} from "@knowledge2/sdk";

try {
  await client.agents.list();
} catch (e) {
  if (e instanceof FeatureNotEnabledError) {
    console.log(`Feature '${e.feature}' not enabled. Visit: ${e.consoleUrl}`);
  } else if (e instanceof QuotaExceededError) {
    console.log(`Quota exceeded: ${e.quota} (${e.current}/${e.limit})`);
    // e.retryable is false — don't retry
  }
}

Configuration

const client = new Knowledge2({
  apiKey: "k2_...",
  apiHost: "https://api.knowledge2.ai",  // custom API host
  orgId: "org-123",                        // skip auto-detection
  timeout: 30000,                          // request timeout (ms)
  maxRetries: 3,                           // retry count for transient errors
});

Debug Logging

Knowledge2.setDebug(true);
// All requests will be logged to stderr with [K2 SDK] prefix
// Auth headers are automatically redacted

Security Best Practices

  • Never hardcode credentials — use environment variables or a secrets manager. See .env.example.
  • Always use HTTPS in production. The SDK warns if a custom apiHost uses http://.
  • Rotate API keys regularly with client.auth.rotateApiKey().
  • Handle errors safely — 5xx error details are automatically sanitized to prevent server info leaks.

For full security guidance, see SECURITY.md.

Features

  • Zero runtime dependencies (uses Node.js built-in fetch)
  • Dual ESM/CJS output
  • Full TypeScript types with strict mode
  • Coverage for core retrieval APIs plus enterprise agents, feeds, pipelines, and A2A
  • Automatic retry with exponential backoff for transient errors
  • Automatic snake_case / camelCase conversion
  • Job polling with configurable timeout and AbortSignal support
  • Async iterator pagination
  • Debug logging with credential redaction

Support

License

MIT