kaman.ai

Docs

Documentation

Guides, use cases & API reference

  • Overview
    • Getting Started
    • Platform Overview
  • Features
    • Features Overview
    • AI Assistant
    • Workflow Automation
    • Intelligent Memory
    • Data Management
    • Universal Integrations
    • Communication Channels
    • Security & Control
  • Use Cases Overview
  • Financial Services
  • Fraud Detection
  • Supply Chain
  • Technical Support
  • Software Development
  • Smart ETL
  • Data Governance
  • ESG Reporting
  • TAC Management
  • Reference
    • API Reference
  • Guides
    • Getting Started
    • Authentication
  • Endpoints
    • Workflows API
    • Tools API
    • KDL (Data Lake) API
    • OpenAI-Compatible API
    • A2A Protocol
    • Skills API
    • Knowledge Base (RAG) API
    • Communication Channels

Knowledge Base (RAG) API

The Knowledge Base API allows you to create and manage knowledge bases for Retrieval-Augmented Generation (RAG). Upload documents, and then search them using semantic and trigram-based queries so your agents can answer questions grounded in your own data.

Base URL

All Knowledge Base API requests go through the marketplace proxy:

/api/agent/kb

For self-hosted installations, prepend your instance URL: http://kaman.ai/api/agent/kb

List Knowledge Bases

Returns all knowledge bases accessible to the authenticated user, filtered by RBAC permissions.

Endpoint

GET /api/agent/kb

Example

bash
curl -X GET "http://kaman.ai/api/agent/kb" \
  -H "Authorization: Bearer kam_your_api_key"

Response

json
{
  "knowledgeBases": [
    {
      "id": 1,
      "name": "Product Documentation",
      "description": "Internal product docs and FAQs",
      "created_by": "user_abc",
      "created_at": "2025-06-20T10:00:00.000Z",
      "updated_at": "2025-06-20T10:00:00.000Z",
      "permission_level": 60
    },
    {
      "id": 2,
      "name": "Engineering Handbook",
      "description": "Engineering best practices and runbooks",
      "created_by": "user_xyz",
      "created_at": "2025-07-01T08:30:00.000Z",
      "updated_at": "2025-07-15T14:00:00.000Z",
      "permission_level": 40
    }
  ]
}

Response Fields

FieldTypeDescription
idintegerKnowledge base ID
namestringKnowledge base name
descriptionstringDescription of the knowledge base
created_bystringUser ID of the creator
created_atstringISO 8601 creation timestamp
updated_atstringISO 8601 last update timestamp
permission_levelintegerUser's RBAC permission level for this KB

Create Knowledge Base

Creates a new knowledge base. The knowledge base is created via the marketplace plugin system with type kb.

Endpoint

POST /api/agent/kb

Request Body

FieldTypeRequiredDescription
namestringYesName of the knowledge base
descriptionstringNoDescription of the knowledge base
kb_manifestobjectNoManifest object (defaults to { files: [] })

Example

bash
curl -X POST "http://kaman.ai/api/agent/kb" \
  -H "Authorization: Bearer kam_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Product Documentation",
    "description": "Internal product docs and FAQs"
  }'

Response (201 Created)

json
{
  "id": 1,
  "name": "Product Documentation",
  "description": "Internal product docs and FAQs",
  "type": "kb",
  "status": "published"
}

Get Knowledge Base by ID

Returns a single knowledge base by its ID. Requires READ permission.

Endpoint

GET /api/agent/kb/:id

Path Parameters

ParameterTypeDescription
idintegerKnowledge base ID

Example

bash
curl -X GET "http://kaman.ai/api/agent/kb/1" \
  -H "Authorization: Bearer kam_your_api_key"

Response

json
{
  "knowledgeBase": {
    "id": 1,
    "name": "Product Documentation",
    "description": "Internal product docs and FAQs",
    "created_by": "user_abc",
    "created_at": "2025-06-20T10:00:00.000Z",
    "updated_at": "2025-06-20T10:00:00.000Z"
  }
}

Error Response (404)

json
{
  "error": "Knowledge base not found"
}

Update Knowledge Base

Updates the name and/or description of a knowledge base. Requires UPDATE permission.

Endpoint

PUT /api/agent/kb/:id

Path Parameters

ParameterTypeDescription
idintegerKnowledge base ID

Request Body

FieldTypeRequiredDescription
namestringNoUpdated name
descriptionstringNoUpdated description

Example

bash
curl -X PUT "http://kaman.ai/api/agent/kb/1" \
  -H "Authorization: Bearer kam_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Product Documentation v2",
    "description": "Updated product docs with new features"
  }'

Response (204 No Content)

No response body on success.

Delete Knowledge Base

Deletes a knowledge base and all its associated files, RAG chunks, and KMMS memory nodes. Requires DELETE permission.

Endpoint

DELETE /api/agent/kb/:id

Path Parameters

ParameterTypeDescription
idintegerKnowledge base ID

Example

bash
curl -X DELETE "http://kaman.ai/api/agent/kb/1" \
  -H "Authorization: Bearer kam_your_api_key"

Response (204 No Content)

No response body on success.

What Gets Deleted

  • All file records in knowledge_base_files
  • All RAG vector chunks associated with each file
  • KMMS memory nodes (if KMMS_KB_SYNC_ENABLED is set to true)
  • The knowledge base record itself

Upload Files

Uploads one or more files to a knowledge base. Files are parsed, chunked, and embedded for RAG search. Requires UPDATE permission.

Endpoint

POST /api/agent/kb/:id/uploadfile

Path Parameters

ParameterTypeDescription
idintegerKnowledge base ID

Request Body

Multipart form data. The file field accepts any field name (e.g., file, files).

Supported File Types

CategoryFormats
DocumentsPDF, DOCX, DOC, PPTX, PPT, TXT, Markdown
DataCSV, JSON, XML, XLSX, XLS
ImagesJPEG, PNG, GIF, WebP, BMP
AudioMP3, WAV, OGG
WebHTML

Example (Single File)

bash
curl -X POST "http://kaman.ai/api/agent/kb/1/uploadfile" \
  -H "Authorization: Bearer kam_your_api_key" \
  -F "file=@/path/to/document.pdf"

Example (Multiple Files)

bash
curl -X POST "http://kaman.ai/api/agent/kb/1/uploadfile" \
  -H "Authorization: Bearer kam_your_api_key" \
  -F "files=@/path/to/doc1.pdf" \
  -F "files=@/path/to/doc2.txt"

Response (201 Created) - Single File

When uploading a single file, the response includes both top-level convenience fields and a files array:

json
{
  "message": "Files uploaded successfully",
  "fileId": "a1b2c3d4e5f6...",
  "fileHash": "a1b2c3d4e5f6...",
  "fileName": "document.pdf",
  "fileSize": 245760,
  "mimeType": "application/pdf",
  "files": [
    {
      "fileId": "a1b2c3d4e5f6...",
      "fileName": "document.pdf",
      "fileSize": 245760,
      "mimeType": "application/pdf"
    }
  ]
}

Response (201 Created) - Multiple Files

json
{
  "message": "Files uploaded successfully",
  "files": [
    {
      "fileId": "a1b2c3d4e5f6...",
      "fileName": "doc1.pdf",
      "fileSize": 245760,
      "mimeType": "application/pdf"
    },
    {
      "fileId": "f6e5d4c3b2a1...",
      "fileName": "doc2.txt",
      "fileSize": 1024,
      "mimeType": "text/plain"
    }
  ]
}

Response Fields

FieldTypeDescription
messagestringSuccess message
fileIdstringContent hash of the file (single-file uploads only)
fileHashstringSame as fileId (single-file uploads only)
fileNamestringOriginal filename (single-file uploads only)
fileSizeintegerFile size in bytes (single-file uploads only)
mimeTypestringMIME type of the file (single-file uploads only)
filesarrayArray of all uploaded file details

Error Response (400)

json
{
  "error": "No files uploaded"
}

List Files in Knowledge Base

Returns all files belonging to a knowledge base.

Endpoint

GET /api/agent/kb/:id/files

Path Parameters

ParameterTypeDescription
idintegerKnowledge base ID

Example

bash
curl -X GET "http://kaman.ai/api/agent/kb/1/files" \
  -H "Authorization: Bearer kam_your_api_key"

Response

json
{
  "files": [
    {
      "id": 1,
      "knowledge_base_id": 1,
      "file_name": "document.pdf",
      "file_path": "/data/user123/a1b2c3d4.pdf",
      "fileHash": "a1b2c3d4e5f6...",
      "text": "Extracted text content from the document...",
      "created_at": "2025-06-20T10:05:00.000Z",
      "updated_at": "2025-06-20T10:05:00.000Z"
    }
  ]
}

Response Fields

FieldTypeDescription
idintegerFile record ID
knowledge_base_idintegerParent knowledge base ID
file_namestringOriginal filename
file_pathstringStorage path of the file
fileHashstringContent hash used as the file identifier
textstringExtracted plain text content
created_atstringISO 8601 creation timestamp
updated_atstringISO 8601 last update timestamp

Download File

Downloads a file from a knowledge base by its file hash.

Endpoint

GET /api/agent/kb/download/:fileId

Path Parameters

ParameterTypeDescription
fileIdstringFile hash (the fileHash from the file record)

Example

bash
curl -X GET "http://kaman.ai/api/agent/kb/download/a1b2c3d4e5f6" \
  -H "Authorization: Bearer kam_your_api_key" \
  -o downloaded_file.pdf

Response

Binary file download with headers:

Content-Type: application/octet-stream Content-Disposition: attachment; filename="document.pdf"

Error Response (404)

json
{
  "error": "File not found"
}

Get File by ID

Returns metadata for a single file by its file hash.

Endpoint

GET /api/agent/kb/file/:id

Path Parameters

ParameterTypeDescription
idstringFile hash (the fileHash from the file record)

Example

bash
curl -X GET "http://kaman.ai/api/agent/kb/file/a1b2c3d4e5f6" \
  -H "Authorization: Bearer kam_your_api_key"

Response

json
{
  "file": {
    "id": 1,
    "knowledge_base_id": 1,
    "file_name": "document.pdf",
    "file_path": "/data/user123/a1b2c3d4.pdf",
    "fileHash": "a1b2c3d4e5f6...",
    "text": "Extracted text content...",
    "created_at": "2025-06-20T10:05:00.000Z",
    "updated_at": "2025-06-20T10:05:00.000Z"
  }
}

Error Response (404)

json
{
  "error": "File not found"
}

Search Knowledge Base (RAG)

Performs a hybrid search across a knowledge base combining semantic vector search and trigram text matching. Returns the most relevant document chunks for a given query.

Endpoint

POST /api/agent/kb/:id/search

Path Parameters

ParameterTypeDescription
idintegerKnowledge base ID

Request Body

FieldTypeRequiredDescription
querystringYesSearch query text

Example

bash
curl -X POST "http://kaman.ai/api/agent/kb/1/search" \
  -H "Authorization: Bearer kam_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "How do I reset my password?"
  }'

Response

json
{
  "results": [
    {
      "chunk": "To reset your password, navigate to Settings > Security and click 'Reset Password'. You will receive a confirmation email...",
      "fileId": "a1b2c3d4e5f6...",
      "metadata": null,
      "similarity": 0.87,
      "chunkId": "1719849600000-550e8400-e29b-41d4-a716-446655440000"
    },
    {
      "chunk": "Password requirements: minimum 8 characters, at least one uppercase letter, one number, and one special character...",
      "fileId": "a1b2c3d4e5f6...",
      "metadata": null,
      "similarity": 0.72,
      "chunkId": "1719849600000-6ba7b810-9dad-11d1-80b4-00c04fd430c8"
    }
  ]
}

Response Fields

FieldTypeDescription
chunkstringThe matched text chunk from the document
fileIdstringFile hash identifying which file this chunk belongs to
metadatastring or nullOptional metadata stored with the chunk
similaritynumberRelevance score (0 to 1, higher is more relevant)
chunkIdstringUnique identifier for the chunk

How Search Works

The search performs two queries in parallel and merges the results:

  1. Trigram text search -- finds chunks containing the query text using PostgreSQL pg_trgm, ordered by text similarity
  2. Semantic vector search -- finds chunks with similar meaning using cosine similarity on vector embeddings (384-dimensional vectors)

Results from both methods are deduplicated by chunkId, keeping the entry with the higher similarity score. The combined results are sorted by similarity and limited to the top 10 matches.

Get Chunk by ID

Returns a single RAG chunk by its chunk ID.

Endpoint

GET /api/agent/kb/chunk/:id

Path Parameters

ParameterTypeDescription
idstringChunk ID

Example

bash
curl -X GET "http://kaman.ai/api/agent/kb/chunk/1719849600000-550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Bearer kam_your_api_key"

Response

json
{
  "chunk": {
    "chunkId": "1719849600000-550e8400-e29b-41d4-a716-446655440000",
    "userId": "client_123",
    "chunk": "To reset your password, navigate to Settings > Security...",
    "fileId": "a1b2c3d4e5f6...",
    "metadata": null,
    "createdAt": "2025-06-20T10:05:00.000Z"
  }
}

Error Response (404)

json
{
  "error": "Chunk not found"
}

Get Chunks by File ID

Returns all RAG chunks for a specific file with pagination support.

Endpoint

GET /api/agent/kb/chunks/:id

Path Parameters

ParameterTypeDescription
idstringFile ID (used to look up the storage file identifier)

Query Parameters

ParameterTypeDefaultDescription
limitinteger5Number of chunks to return per page
offsetinteger0Number of chunks to skip

Example

bash
curl -X GET "http://kaman.ai/api/agent/kb/chunks/a1b2c3d4e5f6?limit=10&offset=0" \
  -H "Authorization: Bearer kam_your_api_key"

Response

json
{
  "chunks": [
    {
      "chunkId": "1719849600000-550e8400-e29b-41d4-a716-446655440000",
      "userId": "client_123",
      "chunk": "Chapter 1: Introduction to the product...",
      "fileId": "a1b2c3d4e5f6...",
      "metadata": null,
      "createdAt": "2025-06-20T10:05:00.000Z"
    },
    {
      "chunkId": "1719849600001-6ba7b810-9dad-11d1-80b4-00c04fd430c8",
      "userId": "client_123",
      "chunk": "Chapter 2: Getting started with setup...",
      "fileId": "a1b2c3d4e5f6...",
      "metadata": null,
      "createdAt": "2025-06-20T10:05:00.000Z"
    }
  ],
  "pagination": {
    "currentPage": 1,
    "totalPages": 5,
    "totalCount": 24,
    "limit": 10,
    "offset": 0
  }
}

Response Fields

FieldTypeDescription
chunksarrayArray of chunk objects
pagination.currentPageintegerCurrent page number (1-based)
pagination.totalPagesintegerTotal number of pages
pagination.totalCountintegerTotal number of chunks for this file
pagination.limitintegerChunks per page
pagination.offsetintegerCurrent offset

Database Schema

knowledge_base Table

ColumnTypeDescription
idinteger (PK)Auto-incrementing primary key
namestringKnowledge base name (required)
descriptiontextDescription (optional)
created_bystringUser ID of the creator (required)
created_attimestampCreation timestamp
updated_attimestampLast update timestamp

knowledge_base_files Table

ColumnTypeDescription
idinteger (PK)Auto-incrementing primary key
knowledge_base_idinteger (FK)References knowledge_base.id (CASCADE delete)
file_namestringOriginal filename
file_pathtextStorage path
fileHashstringContent hash used as file identifier
texttextExtracted plain text content
created_attimestampCreation timestamp
updated_attimestampLast update timestamp

rag Table (Vector Store)

ColumnTypeDescription
chunkIdstring (PK)Unique chunk identifier (timestamp-uuid)
userIdstringOwner/namespace identifier
chunktextText content of the chunk (max 100,000 characters)
vectorvector(1536)Embedding vector (text-embedding-3-small)
vector_384vector(384)Compact embedding vector for search
fileIdstringFile identifier this chunk belongs to
metadatatextOptional metadata
createdAttimestampCreation timestamp
kmms_syncedbooleanWhether this chunk has been synced to KMMS

RBAC Permissions

Knowledge base endpoints enforce role-based access control:

ActionRequired Permission
List knowledge basesAuthenticated (filtered by RBAC)
Create knowledge baseAuthenticated
Get knowledge baseREAD on knowledge_base
Update knowledge baseUPDATE on knowledge_base
Delete knowledge baseDELETE on knowledge_base
Upload filesUPDATE on knowledge_base
List filesAuthenticated
Download fileAuthenticated
Search (RAG)Authenticated
Get file by IDAuthenticated
Get chunk by IDAuthenticated
Get chunks by file IDAuthenticated

Code Examples

TypeScript

typescript
const API_KEY = process.env.KAMAN_API_KEY;
const BASE_URL = 'http://kaman.ai';

// Create a knowledge base
async function createKB(name: string, description: string) {
  const response = await fetch(`${BASE_URL}/api/agent/kb`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ name, description })
  });
  return response.json();
}

// Upload a file
async function uploadFile(kbId: number, file: File) {
  const formData = new FormData();
  formData.append('file', file);

  const response = await fetch(`${BASE_URL}/api/agent/kb/${kbId}/uploadfile`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`
    },
    body: formData
  });
  return response.json();
}

// Search the knowledge base
async function searchKB(kbId: number, query: string) {
  const response = await fetch(`${BASE_URL}/api/agent/kb/${kbId}/search`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ query })
  });
  return response.json();
}

// Example usage
const kb = await createKB('Product Docs', 'All product documentation');
const uploaded = await uploadFile(kb.id, myFile);
const results = await searchKB(kb.id, 'How do I configure SSO?');
console.log(results.results.map(r => r.chunk));

Python

python
import requests
import os
from typing import Optional, Dict, Any, List

class KamanKnowledgeBase:
    def __init__(self, base_url: str):
        self.base_url = f'{base_url}/api/agent/kb'
        self.headers = {
            'Authorization': f'Bearer {os.getenv("KAMAN_API_KEY")}',
            'Content-Type': 'application/json'
        }

    def list(self) -> List[Dict]:
        """List all accessible knowledge bases."""
        response = requests.get(self.base_url, headers=self.headers)
        return response.json()['knowledgeBases']

    def create(self, name: str, description: str = '') -> Dict:
        """Create a new knowledge base."""
        response = requests.post(
            self.base_url,
            json={'name': name, 'description': description},
            headers=self.headers
        )
        return response.json()

    def upload_file(self, kb_id: int, file_path: str) -> Dict:
        """Upload a file to a knowledge base."""
        headers = {'Authorization': self.headers['Authorization']}
        with open(file_path, 'rb') as f:
            response = requests.post(
                f'{self.base_url}/{kb_id}/uploadfile',
                files={'file': f},
                headers=headers
            )
        return response.json()

    def search(self, kb_id: int, query: str) -> List[Dict]:
        """Search a knowledge base using RAG."""
        response = requests.post(
            f'{self.base_url}/{kb_id}/search',
            json={'query': query},
            headers=self.headers
        )
        return response.json()['results']

# Example usage
client = KamanKnowledgeBase('http://kaman.ai')

# Create and populate a knowledge base
kb = client.create('Engineering Docs', 'Internal engineering documentation')
client.upload_file(kb['id'], '/path/to/handbook.pdf')

# Search
results = client.search(kb['id'], 'deployment process')
for result in results:
    print(f"[{result['similarity']:.2f}] {result['chunk'][:100]}...")

cURL

bash
#!/bin/bash
API_KEY="${KAMAN_API_KEY}"
BASE_URL="http://kaman.ai/api/agent/kb"

# List knowledge bases
curl -s "$BASE_URL" \
  -H "Authorization: Bearer $API_KEY"

# Create a knowledge base
curl -s -X POST "$BASE_URL" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"name": "My KB", "description": "Test knowledge base"}'

# Upload a file
curl -s -X POST "$BASE_URL/1/uploadfile" \
  -H "Authorization: Bearer $API_KEY" \
  -F "file=@/path/to/document.pdf"

# Search
curl -s -X POST "$BASE_URL/1/search" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"query": "How do I configure SSO?"}'

# Get files in a knowledge base
curl -s "$BASE_URL/1/files" \
  -H "Authorization: Bearer $API_KEY"

# Download a file
curl -s "$BASE_URL/download/a1b2c3d4e5f6" \
  -H "Authorization: Bearer $API_KEY" \
  -o downloaded_file.pdf

Error Handling

StatusErrorDescription
400No files uploadedUpload request contained no files
401UnauthorizedMissing or invalid authentication
403ForbiddenInsufficient RBAC permissions
404Knowledge base not foundInvalid knowledge base ID
404File not foundInvalid file hash
404Chunk not foundInvalid chunk ID
500Internal server errorServer-side processing failure

Error Response Format

json
{
  "error": "Error description message"
}

Next Steps

  • Tools API - Search and execute individual tools
  • Workflows API - Chain tools into automated workflows
  • Authentication - Learn about API authentication

On this page

  • Base URL
  • List Knowledge Bases
  • Endpoint
  • Example
  • Response
  • Response Fields
  • Create Knowledge Base
  • Endpoint
  • Request Body
  • Example
  • Response (201 Created)
  • Get Knowledge Base by ID
  • Endpoint
  • Path Parameters
  • Example
  • Response
  • Error Response (404)
  • Update Knowledge Base
  • Endpoint
  • Path Parameters
  • Request Body
  • Example
  • Response (204 No Content)
  • Delete Knowledge Base
  • Endpoint
  • Path Parameters
  • Example
  • Response (204 No Content)
  • What Gets Deleted
  • Upload Files
  • Endpoint
  • Path Parameters
  • Request Body
  • Supported File Types
  • Example (Single File)
  • Example (Multiple Files)
  • Response (201 Created) - Single File
  • Response (201 Created) - Multiple Files
  • Response Fields
  • Error Response (400)
  • List Files in Knowledge Base
  • Endpoint
  • Path Parameters
  • Example
  • Response
  • Response Fields
  • Download File
  • Endpoint
  • Path Parameters
  • Example
  • Response
  • Error Response (404)
  • Get File by ID
  • Endpoint
  • Path Parameters
  • Example
  • Response
  • Error Response (404)
  • Search Knowledge Base (RAG)
  • Endpoint
  • Path Parameters
  • Request Body
  • Example
  • Response
  • Response Fields
  • How Search Works
  • Get Chunk by ID
  • Endpoint
  • Path Parameters
  • Example
  • Response
  • Error Response (404)
  • Get Chunks by File ID
  • Endpoint
  • Path Parameters
  • Query Parameters
  • Example
  • Response
  • Response Fields
  • Database Schema
  • knowledge_base Table
  • knowledge_base_files Table
  • rag Table (Vector Store)
  • RBAC Permissions
  • Code Examples
  • TypeScript
  • Python
  • cURL
  • Error Handling
  • Error Response Format
  • Next Steps