Knowledge Base
Give your AI agents a live, searchable brain. Upload documents or push data via API — the Knowledge Base automatically builds a knowledge graph your agents can query during conversations.
Overview
The Knowledge Base is a domain-agnostic system that turns your data into a structured knowledge graph. AI agents search this graph during conversations to provide accurate, grounded responses instead of hallucinating.
Upload document / API push
|
v
Extract entities + relationships
|
v
Build knowledge graph (deduplicated nodes + edges)
|
v
Run analytics rules (recommendations, trends)
|
v
Agent queries graph during conversationsTwo Ways to Ingest Data
1. Document Upload
Upload PDFs, DOCX, Markdown, or plain text files. The platform automatically processes the document, extracts entities and relationships, and adds them to the knowledge graph.
import fs from "fs";
const doc = await client.knowledge.uploadDocument(projectId, {
file: fs.createReadStream("product_catalog.pdf"),
fileName: "product_catalog.pdf",
});
console.log(doc.documentId, doc.status); // "processing"2. API Push (Structured Data)
Push structured data programmatically — perfect for scrapers, inventory feeds, price trackers, or any external data source.
await client.knowledge.insertFacts(projectId, {
source: "inventory_sync",
facts: [
{
entityType: "product",
label: "Widget Pro X",
properties: {
price: 29.99,
category: "electronics",
inStock: true,
tags: ["wireless", "bluetooth"],
},
},
],
relationships: [
{ fromLabel: "Widget Pro X", toLabel: "Electronics", edgeType: "belongs_to" },
],
});Upsert Semantics
If an entity with the same label + type already exists, properties are merged and the version is incremented. Every change is recorded in the version history with the source and timestamp.
SDK: Insert & Search
Use the SDK to push data and search from your server:
import { Sonzai } from "@sonzai-labs/agents";
const client = new Sonzai({ apiKey: "sk-..." });
// Insert entities
await client.knowledge.insertFacts(projectId, {
source: "price_sync",
facts: [
{
entityType: "item",
label: "Charizard Base Set",
properties: { price: 450, trend: "+12%", condition: "PSA 10" },
},
],
relationships: [
{ fromLabel: "Charizard Base Set", toLabel: "Fire Pokemon", edgeType: "is_type" },
],
});
// Search
const results = await client.knowledge.search(projectId, {
query: "fire pokemon under 500",
type: "item",
limit: 10,
});
for (const r of results.results) {
console.log(r.label, r.properties);
}SDK: Bulk Update
Sync external data (prices, stock, stats) in bulk with bulkUpdate. Only changed fields are updated — efficient for frequent syncs.
await client.knowledge.bulkUpdate(projectId, {
source: "price_sync",
updates: [
{ label: "Charizard Base Set", entityType: "item", properties: { price: 460 } },
{ label: "Blastoise Base Set", entityType: "item", properties: { price: 390 } },
],
});Entity Schemas
Define custom entity types with typed fields. Schemas guide extraction so the platform knows exactly what fields to look for. Supported types: string, number, boolean, date, enum, array.
await client.knowledge.createSchema(projectId, {
entityType: "pokemon_card",
description: "Collectible trading cards",
fields: [
{ name: "price", type: "number", required: true },
{ name: "condition", type: "enum", enumValues: ["PSA 10", "PSA 9", "Raw"] },
{ name: "set", type: "string", required: true },
{ name: "rarity", type: "enum", enumValues: ["Common", "Uncommon", "Rare", "Ultra Rare"] },
{ name: "tags", type: "array" },
],
similarityConfig: {
enabled: true,
threshold: 0.7,
fieldWeights: { price: 0.3, set: 0.4, rarity: 0.3 },
},
});Knowledge Graph
Entities connect via typed relationships. The graph supports arbitrary entity types and relationship types — it's completely domain-agnostic.
Search
Full-text search across all entity labels and properties. Supports type filtering, property filters, and graph traversal to include related entities.
const results = await client.knowledge.search(projectId, {
query: "bluetooth speaker",
type: "product",
limit: 10,
filters: { in_stock: true },
});
for (const r of results.results) {
console.log(r.label, r.score, r.properties);
// r.related[] contains connected nodes from 1-hop traversal
}Recommendation Engine
Define rules that match source entities to target entities based on field matching. The engine prevents feedback loops and improves recommendations over time using conversion feedback.
// Create a recommendation rule
const rule = await client.knowledge.createAnalyticsRule(projectId, {
ruleType: "recommendation",
name: "Similar cards",
config: { matchFields: ["set", "rarity"], limit: 5 },
enabled: true,
});
// Get recommendations
const recs = await client.knowledge.getRecommendations(
projectId, rule.ruleId, sourceNodeId, 5
);
for (const rec of recs.results) {
console.log(rec.label, rec.score);
}
// Record feedback (improves future recommendations)
await client.knowledge.recordFeedback(projectId, {
ruleId: rule.ruleId,
sourceNodeId: sourceNodeId,
targetNodeId: rec.nodeId,
action: "converted", // "shown" | "converted"
});Trend Analytics
Track how entity properties change over time windows (7d, 30d, 90d). Get rankings for top gainers, losers, most volatile, and highest averages.
// Get trend rankings
const trends = await client.knowledge.getTrendRankings(projectId, {
ruleId: ruleId,
type: "top_gainers", // "top_gainers" | "top_losers" | "most_volatile" | "highest_avg"
window: "30d", // "7d" | "30d" | "90d"
limit: 10,
});
for (const item of trends.rankings) {
console.log(item.label, item.currentValue, item.changePercent);
}How Agents Use Knowledge
During conversations, AI agents have access to a knowledge_searchtool that queries the knowledge base. Instead of hallucinating facts, agents pull accurate data from your graph — including entity properties, relationships, and recommendations.
User: "What's the best card under $500?"
|
v
Agent calls knowledge_search("cards under 500")
|
v
KB returns: Charizard ($450, +12%), Blastoise ($380, +8%)
|
v
Agent: "Charizard Base Set at $450 is trending up 12%
this month -- great investment pick under $500."Grounded Responses
Knowledge-backed responses are grounded in your real data. The agent knows current prices, stock levels, specs, and relationships because it queries the graph in real-time.
Use Cases
API Reference
All endpoints use Authorization: Bearer {api_key} header.
| Endpoint | Method | Purpose |
|---|---|---|
| /knowledge/documents | POST | Upload document (multipart) |
| /knowledge/documents | GET | List documents with status |
| /knowledge/documents/{docId} | DELETE | Delete document |
| /knowledge/facts | POST | Create/update entities and relationships |
| /knowledge/search?q=... | GET | Full-text search with filters |
| /knowledge/nodes | GET | List nodes (optional type filter) |
| /knowledge/nodes/{nodeId} | GET | Get node with edges and history |
| /knowledge/schemas | POST | Create entity schema |
| /knowledge/schemas | GET | List schemas |
| /knowledge/schemas/{schemaId} | PUT | Update schema |
| /knowledge/stats | GET | Get KB statistics |
| /knowledge/analytics/rules | POST | Create analytics rule |
| /knowledge/analytics/rules | GET | List rules |
| /knowledge/analytics/rules/{ruleId}/run | POST | Trigger rule execution |
| /knowledge/recommendations | GET | Get pre-computed recommendations |
| /knowledge/trends | GET | Get trend aggregations |
| /knowledge/trends/rankings | GET | Get trend rankings |
| /knowledge/conversions | GET | Get conversion statistics |
| /knowledge/feedback | POST | Record recommendation feedback |
Base Path
All paths above are relative to /api/v1/projects/{projectId}. Get your project ID from the Projects page in the dashboard.