Skip to main content

How to Use Wildix Knowledge Base API

· 7 min read
Vladimir Gorobets
Vladimir Gorobets
Software Engineer

This guide will help you understand how to use the Wildix Knowledge Base API to create, manage, and search documents in your knowledge base.

Table of Contents

Overview

The Knowledge Base API allows you to build intelligent search systems for your content. You can upload documents in various formats (HTML, Markdown, PDF, etc.), organize them into knowledge bases, and perform semantic searches to find relevant information.

Prerequisites

  • Node.js installed on your system
  • A valid Wildix API key with knowledge base permissions (kb:*)
  • The @wildix/wim-knowledge-base-client package

Installation

Install the Knowledge Base client package:

npm install @wildix/wim-knowledge-base-client

Basic Concepts

Before diving into the code, let's understand the key concepts:

  • Knowledge Base: A collection of data sources that can be searched together. Think of it as a container for related content.
  • Data Source: A source of documents (e.g., files, confluence pages). Documents belong to data sources.
  • Document: Individual pieces of content (HTML, Markdown, PDF, etc.) that are indexed and searchable.
  • Chunk: A portion of a document, typically 500-600 characters.

The hierarchy is: Knowledge Base → Data Sources → Documents -> Chunks

Setting Up the Client

First, you need to initialize the Knowledge Base client with your API key:

import { KnowledgeBaseClient } from '@wildix/wim-knowledge-base-client';

const API_KEY = 'your-api-key-here';

const client = new KnowledgeBaseClient({
token: { token: () => Promise.resolve(API_KEY) },
env: 'stage', // or 'production'
});

Best Practice: Create a singleton instance to reuse the client across your application:

let knowledgeBaseClient: KnowledgeBaseClient | undefined;

function getKnowledgeBaseClient() {
if (!knowledgeBaseClient) {
knowledgeBaseClient = new KnowledgeBaseClient({
token: { token: () => Promise.resolve(API_KEY) },
env: 'stage',
});
}
return knowledgeBaseClient;
}

Working with Data Sources

Creating a Data Source

A data source represents where your documents come from. Create one before adding documents:

import { CreateDataSourceCommand, DataSourceType } from '@wildix/wim-knowledge-base-client';

async function createDataSource(name: string) {
const client = getKnowledgeBaseClient();
const { dataSource } = await client.send(new CreateDataSourceCommand({
name,
type: DataSourceType.FILES,
}));

return dataSource;
}

Listing Data Sources

To see all your existing data sources:

import { ListDataSourcesCommand } from '@wildix/wim-knowledge-base-client';

async function listDataSources() {
const client = getKnowledgeBaseClient();
const { dataSources } = await client.send(new ListDataSourcesCommand({}));

return dataSources;
}

Working with Knowledge Bases

Creating a Knowledge Base

A knowledge base groups one or more data sources together for searching:

import { CreateKnowledgeBaseCommand } from '@wildix/wim-knowledge-base-client';

async function createKnowledgeBase(
name: string,
description: string,
dataSourceIds: string[]
) {
const client = getKnowledgeBaseClient();
const { knowledgeBase } = await client.send(new CreateKnowledgeBaseCommand({
name,
description,
dataSources: dataSourceIds,
}));

return knowledgeBase;
}

Listing Knowledge Bases

To retrieve all your knowledge bases:

import { ListKnowledgeBasesCommand } from '@wildix/wim-knowledge-base-client';

async function listKnowledgeBases() {
const client = getKnowledgeBaseClient();
const { knowledgeBases } = await client.send(new ListKnowledgeBasesCommand({}));

return knowledgeBases;
}

Managing Documents

Creating Text Documents

For text-based content (HTML, Markdown, plain text), you can create documents with the content directly:

import { CreateDocumentCommand } from '@wildix/wim-knowledge-base-client';

async function createTextDocument(
dataSourceId: string,
originalId: string,
title: string,
content: string,
description?: string,
originalFormat?: string
) {
const client = getKnowledgeBaseClient();
const { document } = await client.send(new CreateDocumentCommand({
dataSourceId,
originalFormat: originalFormat || 'html',
originalName: `${originalId}.${originalFormat || 'html'}`,
title,
content,
url: `https://www.example.com/documents/${originalId}`,
description: description || '',
originalId,
metadata: {
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString(),
},
}));

return document;
}

Parameters explained:

  • dataSourceId: The ID of the data source this document belongs to
  • originalId: Your unique identifier for this document (from your system)
  • title: The document title (used in search results)
  • content: The actual document content (HTML, Markdown, or plain text)
  • description: Optional description of the document
  • originalFormat: The format of the content ('html', 'markdown', 'txt')

Example usage:

const htmlContent = '<h1>Getting Started</h1><p>This guide explains how to use our API...</p>';
const document = await createTextDocument(
'datasource-123',
'doc-001',
'Getting Started Guide',
htmlContent,
'A comprehensive guide for new users',
'html'
);

Uploading Binary Documents

For binary files (PDFs, Word documents, etc.), you need to:

  1. Create the document first (with empty content)
  2. Get an upload URL
  3. Upload the file to that URL

Step 1: Create the document

const document = await createTextDocument(
dataSourceId,
'pdf-doc-001',
'User Manual',
'', // Empty content for binary documents
'Complete user manual PDF',
'pdf'
);

Step 2: Get the upload URL

import { GetDocumentUploadUrlCommand } from '@wildix/wim-knowledge-base-client';

async function getDocumentUploadUrl(dataSourceId: string, documentId: string) {
const client = getKnowledgeBaseClient();
const { uploadUrl } = await client.send(new GetDocumentUploadUrlCommand({
dataSourceId,
documentId,
}));

return uploadUrl;
}

Step 3: Upload the file

import * as fs from 'node:fs';

async function uploadDocument(
uploadUrl: string,
filePath: string,
contentType: string
): Promise<number> {
const fileStream = fs.createReadStream(filePath);
const stats = fs.statSync(filePath);

const response = await fetch(uploadUrl, {
method: 'PUT',
body: fileStream as any,
headers: {
'Content-Type': contentType,
'Content-Length': stats.size.toString(),
},
duplex: 'half',
} as any);

return response.status;
}

Complete binary upload example:

// 1. Create document
const pdfDoc = await createTextDocument(
dataSourceId,
'manual-pdf',
'Product Manual',
'',
'Complete product documentation',
'pdf'
);

// 2. Get upload URL
const uploadUrl = await getDocumentUploadUrl(dataSourceId, pdfDoc.id);

// 3. Upload file
const status = await uploadDocument(
uploadUrl,
'/path/to/manual.pdf',
'application/pdf'
);

console.log(`Upload completed with status: ${status}`);

Listing Documents

To see all documents in a data source:

import { ListDocumentsCommand } from '@wildix/wim-knowledge-base-client';

async function listDocumentsForDataSource(dataSourceId: string) {
const client = getKnowledgeBaseClient();
const { documents } = await client.send(new ListDocumentsCommand({
dataSourceId,
}));

return documents;
}

Searching the Knowledge Base

Once your documents are uploaded and indexed, you can search for relevant information:

import { SearchKnowledgeBaseCommand } from '@wildix/wim-knowledge-base-client';

async function searchInKnowledgeBase(knowledgeBaseId: string, query: string) {
const client = getKnowledgeBaseClient();
const { results } = await client.send(new SearchKnowledgeBaseCommand({
knowledgeBaseId,
query,
}));

return results;
}

Example usage:

const results = await searchInKnowledgeBase(
'kb-123',
'How do I reset my password?'
);

console.log('Search results:', results);

Important: After uploading documents, wait a few seconds for indexing to complete before searching. In production, the indexing time may vary based on document size and complexity.

Complete Example

Here's a complete workflow that demonstrates all the key features:

async function completeExample() {
// 1. Create or get a data source
let dataSource = await createDataSource('My Documentation');
console.log('Data Source created:', dataSource.id);

// 2. Create or get a knowledge base
let knowledgeBase = await createKnowledgeBase(
'Product Documentation',
'All product documentation and guides',
[dataSource.id]
);
console.log('Knowledge Base created:', knowledgeBase.id);

// 3. Create a text document (HTML)
const htmlContent = '<h1>FAQ</h1><p>Frequently asked questions...</p>';
const textDoc = await createTextDocument(
dataSource.id,
'faq-001',
'Frequently Asked Questions',
htmlContent,
'Common questions and answers',
'html'
);
console.log('Text document created:', textDoc.id);

// 4. Create and upload a PDF document
const pdfDoc = await createTextDocument(
dataSource.id,
'manual-001',
'User Manual',
'',
'Complete user manual',
'pdf'
);

const uploadUrl = await getDocumentUploadUrl(dataSource.id, pdfDoc.id);
const uploadStatus = await uploadDocument(
uploadUrl,
'/path/to/manual.pdf',
'application/pdf'
);
console.log('PDF uploaded with status:', uploadStatus);

// 5. Wait for indexing (in production, implement proper polling)
await new Promise(resolve => setTimeout(resolve, 10000));

// 6. Search the knowledge base
const searchResults = await searchInKnowledgeBase(
knowledgeBase.id,
'How do I get started?'
);
console.log('Search results:', searchResults);
}

Best Practices

  1. Reuse the client instance: Create a singleton to avoid unnecessary connections.

  2. Use meaningful IDs: The originalId should be unique and meaningful in your system for easier tracking.

  3. Add metadata: Include creation/update timestamps and any custom metadata that helps organize your documents.

  4. Wait for indexing: After uploading documents, allow time for indexing before searching.

  5. Handle errors: Always wrap API calls in try-catch blocks and handle errors appropriately.

  6. Organize with data sources: Group related documents together using data sources for better organization.

  7. Descriptive titles: Use clear, descriptive titles as they appear in search results.

Next Steps

  • Explore advanced search features and filtering options
  • Implement document updates and deletions
  • Set up automated document synchronization
  • Monitor indexing status and performance

For the full list of available endpoints and request/response schemas, see the Knowledge Base API Reference.