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.
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
Returns all knowledge bases accessible to the authenticated user, filtered by RBAC permissions.
GET /api/agent/kb
bash
curl -X GET "http://kaman.ai/api/agent/kb" \
-H "Authorization: Bearer kam_your_api_key"
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
}
]
}
Field Type Description id integer Knowledge base ID name string Knowledge base name description string Description of the knowledge base created_by string User ID of the creator created_at string ISO 8601 creation timestamp updated_at string ISO 8601 last update timestamp permission_level integer User's RBAC permission level for this KB
Creates a new knowledge base. The knowledge base is created via the marketplace plugin system with type kb.
POST /api/agent/kb
Field Type Required Description name string Yes Name of the knowledge base description string No Description of the knowledge base kb_manifest object No Manifest object (defaults to { files: [] })
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"
}'
json
{
"id": 1,
"name": "Product Documentation",
"description": "Internal product docs and FAQs",
"type": "kb",
"status": "published"
}
Returns a single knowledge base by its ID. Requires READ permission.
GET /api/agent/kb/:id
Parameter Type Description id integer Knowledge base ID
bash
curl -X GET "http://kaman.ai/api/agent/kb/1" \
-H "Authorization: Bearer kam_your_api_key"
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"
}
}
json
{
"error": "Knowledge base not found"
}
Updates the name and/or description of a knowledge base. Requires UPDATE permission.
PUT /api/agent/kb/:id
Parameter Type Description id integer Knowledge base ID
Field Type Required Description name string No Updated name description string No Updated description
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"
}'
No response body on success.
Deletes a knowledge base and all its associated files, RAG chunks, and KMMS memory nodes. Requires DELETE permission.
DELETE /api/agent/kb/:id
Parameter Type Description id integer Knowledge base ID
bash
curl -X DELETE "http://kaman.ai/api/agent/kb/1" \
-H "Authorization: Bearer kam_your_api_key"
No response body on success.
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
Uploads one or more files to a knowledge base. Files are parsed, chunked, and embedded for RAG search. Requires UPDATE permission.
POST /api/agent/kb/:id/uploadfile
Parameter Type Description id integer Knowledge base ID
Multipart form data. The file field accepts any field name (e.g., file, files).
Category Formats Documents PDF, DOCX, DOC, PPTX, PPT, TXT, Markdown Data CSV, JSON, XML, XLSX, XLS Images JPEG, PNG, GIF, WebP, BMP Audio MP3, WAV, OGG Web HTML
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"
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"
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"
}
]
}
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"
}
]
}
Field Type Description message string Success message fileId string Content hash of the file (single-file uploads only) fileHash string Same as fileId (single-file uploads only) fileName string Original filename (single-file uploads only) fileSize integer File size in bytes (single-file uploads only) mimeType string MIME type of the file (single-file uploads only) files array Array of all uploaded file details
json
{
"error": "No files uploaded"
}
Returns all files belonging to a knowledge base.
GET /api/agent/kb/:id/files
Parameter Type Description id integer Knowledge base ID
bash
curl -X GET "http://kaman.ai/api/agent/kb/1/files" \
-H "Authorization: Bearer kam_your_api_key"
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"
}
]
}
Field Type Description id integer File record ID knowledge_base_id integer Parent knowledge base ID file_name string Original filename file_path string Storage path of the file fileHash string Content hash used as the file identifier text string Extracted plain text content created_at string ISO 8601 creation timestamp updated_at string ISO 8601 last update timestamp
Downloads a file from a knowledge base by its file hash.
GET /api/agent/kb/download/:fileId
Parameter Type Description fileId string File hash (the fileHash from the file record)
bash
curl -X GET "http://kaman.ai/api/agent/kb/download/a1b2c3d4e5f6" \
-H "Authorization: Bearer kam_your_api_key" \
-o downloaded_file.pdf
Binary file download with headers:
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="document.pdf"
json
{
"error": "File not found"
}
Returns metadata for a single file by its file hash.
GET /api/agent/kb/file/:id
Parameter Type Description id string File hash (the fileHash from the file record)
bash
curl -X GET "http://kaman.ai/api/agent/kb/file/a1b2c3d4e5f6" \
-H "Authorization: Bearer kam_your_api_key"
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"
}
}
json
{
"error": "File not found"
}
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.
POST /api/agent/kb/:id/search
Parameter Type Description id integer Knowledge base ID
Field Type Required Description query string Yes Search query text
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?"
}'
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"
}
]
}
Field Type Description chunk string The matched text chunk from the document fileId string File hash identifying which file this chunk belongs to metadata string or null Optional metadata stored with the chunk similarity number Relevance score (0 to 1, higher is more relevant) chunkId string Unique identifier for the chunk
The search performs two queries in parallel and merges the results:
Trigram text search -- finds chunks containing the query text using PostgreSQL pg_trgm, ordered by text similarity
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.
Returns a single RAG chunk by its chunk ID.
GET /api/agent/kb/chunk/:id
Parameter Type Description id string Chunk ID
bash
curl -X GET "http://kaman.ai/api/agent/kb/chunk/1719849600000-550e8400-e29b-41d4-a716-446655440000" \
-H "Authorization: Bearer kam_your_api_key"
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"
}
}
json
{
"error": "Chunk not found"
}
Returns all RAG chunks for a specific file with pagination support.
GET /api/agent/kb/chunks/:id
Parameter Type Description id string File ID (used to look up the storage file identifier)
Parameter Type Default Description limit integer 5 Number of chunks to return per page offset integer 0 Number of chunks to skip
bash
curl -X GET "http://kaman.ai/api/agent/kb/chunks/a1b2c3d4e5f6?limit=10&offset=0" \
-H "Authorization: Bearer kam_your_api_key"
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
}
}
Field Type Description chunks array Array of chunk objects pagination.currentPage integer Current page number (1-based) pagination.totalPages integer Total number of pages pagination.totalCount integer Total number of chunks for this file pagination.limit integer Chunks per page pagination.offset integer Current offset
Column Type Description id integer (PK) Auto-incrementing primary key name string Knowledge base name (required) description text Description (optional) created_by string User ID of the creator (required) created_at timestamp Creation timestamp updated_at timestamp Last update timestamp
Column Type Description id integer (PK) Auto-incrementing primary key knowledge_base_id integer (FK) References knowledge_base.id (CASCADE delete) file_name string Original filename file_path text Storage path fileHash string Content hash used as file identifier text text Extracted plain text content created_at timestamp Creation timestamp updated_at timestamp Last update timestamp
Column Type Description chunkId string (PK) Unique chunk identifier (timestamp-uuid) userId string Owner/namespace identifier chunk text Text content of the chunk (max 100,000 characters) vector vector(1536) Embedding vector (text-embedding-3-small) vector_384 vector(384) Compact embedding vector for search fileId string File identifier this chunk belongs to metadata text Optional metadata createdAt timestamp Creation timestamp kmms_synced boolean Whether this chunk has been synced to KMMS
Knowledge base endpoints enforce role-based access control:
Action Required Permission List knowledge bases Authenticated (filtered by RBAC) Create knowledge base Authenticated Get knowledge base READ on knowledge_baseUpdate knowledge base UPDATE on knowledge_baseDelete knowledge base DELETE on knowledge_baseUpload files UPDATE on knowledge_baseList files Authenticated Download file Authenticated Search (RAG) Authenticated Get file by ID Authenticated Get chunk by ID Authenticated Get chunks by file ID Authenticated
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
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]}...")
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
Status Error Description 400 No files uploaded Upload request contained no files 401 Unauthorized Missing or invalid authentication 403 Forbidden Insufficient RBAC permissions 404 Knowledge base not found Invalid knowledge base ID 404 File not found Invalid file hash 404 Chunk not found Invalid chunk ID 500 Internal server error Server-side processing failure
json
{
"error": "Error description message"
}
Tools API - Search and execute individual tools
Workflows API - Chain tools into automated workflows
Authentication - Learn about API authentication