Knowledge Bases & RAG
Create knowledge bases, upload documents, configure retrieval
Knowledge Bases & RAG
Knowledge bases give your agents access to your organization's documents and data. The platform uses Retrieval-Augmented Generation (RAG) to find relevant information and inject it into the LLM context at query time.
Full architecture reference: See KNOWLEDGE_MANAGEMENT.md for the complete technical deep-dive covering all 8 sprints (K1-K8), security model, data flows, and SOTA techniques.
How It Works
User Question
|
v
Hierarchical Retrieval (RAPTOR-Lite)
|
+---> Level 2: Document Summaries ---> Identify relevant documents
|
+---> Level 0: Fine-grained Chunks ---> Within those documents
|
v
Hybrid Search (Semantic + Keyword + RRF)
|
v
Reranking (Cross-Encoder or LLM)
|
v
Top-K Results --> LLM Context --> Grounded Answer
- User asks a question
- The platform embeds the question using the configured embedding model
- Coarse-to-fine retrieval: Queries document summaries first to identify relevant documents, then searches fine-grained chunks only within those documents
- Hybrid search: Combines semantic (vector) + keyword (BM25) results using Reciprocal Rank Fusion
- Reranking: Cross-encoder or LLM-based reranking for precision
- Injects the top-K results into the LLM prompt as context
- The LLM generates an answer grounded in the retrieved documents
Creating a Knowledge Base
In Agent Studio
- Navigate to Studio > Knowledge
- Click Create Knowledge Base
- Configure:
| Field | Description |
|---|---|
| Name | e.g., "HR Policies", "Product Documentation" |
| Description | What documents this KB contains |
| Embedding Model | jina-embeddings-v2-base-code (default) |
| Chunk Size | 512 tokens (default) -- adjust based on content type |
| Chunk Overlap | 50 tokens (default) -- ensures context isn't split mid-sentence |
| Chunking Strategy | contextual (recommended), recursive, semantic, or fixed |
Adding Content
Method 1: Upload Documents
Supported Formats:
| Format | Extension | Notes |
|---|---|---|
.pdf | Text extraction via UnPDF | |
| Word | .docx | Converted via Mammoth |
| HTML | .html | Converted to markdown via Turndown |
| Markdown | .md | Processed directly |
| Plain Text | .txt | Processed directly |
| CSV | .csv | Rows converted to structured text |
Via Studio UI:
- Select your knowledge base
- Click Upload Documents
- Drag & drop files or browse
- Documents enter
pendingstatus
Via API:
curl -X POST http://localhost:4000/api/studio/knowledge/{kbId}/documents \
-H "Authorization: Bearer <token>" \
-F "file=@./document.pdf"
Method 2: Connect External Sources
Connect enterprise knowledge sources for automatic sync:
| Source | Auth | Incremental Sync | Permission Sync |
|---|---|---|---|
| Confluence | OAuth 2.0 / API Token | CQL-based | Page restrictions |
| SharePoint | Entra ID OAuth 2.0 | Graph delta queries | Graph permissions |
| Google Drive | OAuth 2.0 / Service Account | Changes API | Drive permissions |
| GitHub | GitHub App / PAT | Commit comparison | Repo collaborators |
| Web Crawler | Optional API key | Content hash diff | N/A (public) |
| Database | Vault credential ref | Schema introspection | N/A (tool-grant level) |
Steps:
- Navigate to Studio > Knowledge > [Your KB] > Sources
- Click Add Source
- Select source type (Confluence, SharePoint, etc.)
- Authenticate (OAuth flow or API key)
- Browse and select content (spaces, folders, repos)
- Configure sync schedule (manual / hourly / daily / weekly)
- Configure permission mode:
- Inherit from KB (default) -- simple, all docs share KB visibility
- Sync from source -- per-document permissions from external system
- Manual -- set visibility per document after sync
Via API:
# Add a Confluence source
curl -X POST http://localhost:4000/api/studio/knowledge/{kbId}/sources \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{
"connectorType": "confluence",
"name": "Engineering Space",
"endpoint": "https://company.atlassian.net",
"authCredentialRef": "vault:confluence-oauth",
"settings": { "spaces": ["ENG"] },
"syncSchedule": "0 2 * * *",
"permissionMode": "sync-source"
}'
# Trigger manual sync
curl -X POST http://localhost:4000/api/studio/knowledge/{kbId}/sources/{sourceId}/sync \
-H "Authorization: Bearer <token>"
Document Processing Pipeline
After upload or sync, documents go through:
- Format Detection -- identify file type
- Text Extraction -- convert to plain text
- Chunking -- split using chosen strategy (contextual recommended for high-value docs)
- Context Prefix Generation -- (contextual strategy only) LLM generates 1-2 sentence prefix per chunk
- Embedding -- generate vector embeddings for each chunk (prefix included)
- Document Summary -- LLM generates 200-500 token summary (for hierarchical retrieval)
- Indexing -- store in Qdrant vector database + PostgreSQL metadata
Document status progression: pending -> processing -> embedded (or failed)
Generating Embeddings
After uploading documents, trigger embedding generation:
- In the Knowledge page, select your KB
- Click Generate Embeddings
- The platform processes all pending documents
- Monitor progress -- result shows
embedded: N, failed: N, total: N
Via API:
curl -X POST http://localhost:4000/api/studio/knowledge/{kbId}/embed \
-H "Authorization: Bearer <token>"
Scoping Knowledge Bases to Agents
Knowledge bases are accessed through the Knowledge Base Search tool. To give an agent access:
- Open the agent in Studio > Agents > [Agent]
- Go to the Tools tab
- Grant access to the Knowledge Base Search tool
- In the tool configuration, scope it to specific KBs:
{
"allowedKnowledgeBases": ["kb-hr-policies", "kb-product-docs"],
"maxResults": 5,
"relevanceThreshold": 0.7
}
If no allowedKnowledgeBases is specified, the agent can search all KBs in the tenant.
Loading Complete Documents (KB Document Tools)
Agents with both code_execute and knowledge_base_search capabilities automatically receive two additional virtual tools for working with complete original files:
list_kb_documents
Discovers documents available in the agent's bound knowledge bases.
Parameters:
knowledge_base_id(string, optional) — filter to a specific KB; omit to list documents across all accessible KBs
Returns: Array of documents with metadata:
[
{
"id": "doc-123",
"filename": "Q3_Financials.xlsx",
"format": "xlsx",
"sizeMB": 2.4,
"knowledgeBaseId": "kb-finance",
"knowledgeBaseName": "Finance Documents",
"canLoad": true
}
]
The canLoad flag is true when the original binary file was stored (i.e., storageKey exists). Documents ingested before this feature was added may have canLoad: false.
load_kb_document
Loads a complete original file from a knowledge base into the sandbox for processing.
Parameters:
knowledge_base_id(string, required) — the KB containing the documentdocument_id(string, required) — the document to load
Returns:
{
"filepath": "/tmp/Q3_Financials.xlsx",
"filename": "Q3_Financials.xlsx",
"mimeType": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"sizeBytes": 2516582
}
The file is written to /tmp/{filename} in the sandbox and can be processed with pandas, openpyxl, or other libraries available in the sandbox.
Size limit: 50MB per document.
Permission Model
Both tools use the same intersection permission model as knowledge_base_search:
Accessible KBs = (User-accessible KBs via visibility/ACL) ∩ (Agent-bound KBs via config)
An agent can only list/load documents from knowledge bases that both the current user has access to and the agent is configured to use.
Example Workflow
- Agent calls
list_kb_documentsto discover available files - Agent identifies the spreadsheet needed for analysis
- Agent calls
load_kb_documentto load the file into the sandbox - Agent calls
code_executewith a pandas script to process the file:import pandas as pd df = pd.read_excel('/tmp/Q3_Financials.xlsx') summary = df.describe().to_json() print(summary)
Chunking Strategies
| Strategy | Best For | How It Works |
|---|---|---|
contextual | High-value documents | Uses base strategy + LLM-generated context prefixes (49-67% retrieval improvement) |
recursive | Structured text | LangChain-style hierarchical splitting on separators |
semantic | Natural language | Kamradt algorithm with embedding-based breakpoint detection |
fixed | Simple docs, code | Token-based sliding window with BPE counting |
Chunk size recommendations:
| Content Type | Recommended Size | Overlap | Strategy | Notes |
|---|---|---|---|---|
| Policy documents | 512 tokens | 50 | contextual | High-value, needs context preservation |
| Technical docs | 1024 tokens | 100 | recursive | Larger chunks preserve code context |
| FAQs | 256 tokens | 25 | fixed | Smaller chunks for precise matching |
| Long articles | 768 tokens | 75 | semantic | Natural breakpoints in prose |
| CSV data | Row-level | 0 | fixed | Each row becomes a chunk |
Structured Data: Database Querying
Agents can also query live databases through the database_sql_query tool:
- Register database in Studio > Data Catalog with connection config
- Grant agent access to the database_sql_query tool
- Agent asks questions in natural language -- platform generates SQL
- SQL Guard validates every query (read-only, table whitelist, timeout, audit)
- Results formatted with column statistics within ~1000 token budget
- Results auto-stored in workspace for cross-source analysis
See KNOWLEDGE_MANAGEMENT.md sections 4-5 for full details on SQL Guard, workspace, and cross-source analysis.
Query Testing
Test your knowledge base retrieval quality:
- Navigate to Studio > Knowledge
- Select your KB
- Use the Query Tester panel
- Enter test queries and review the returned chunks
- Check relevance scores -- aim for >0.7 for top results
Via API:
curl -X POST http://localhost:4000/api/studio/knowledge/{kbId}/query \
-H "Authorization: Bearer <token>" \
-H "Content-Type: application/json" \
-d '{"query": "What is the vacation policy?", "limit": 5}'
Best Practices
Document Preparation
- Clean your data -- remove headers, footers, and boilerplate before upload
- Use descriptive filenames -- the filename is stored as metadata
- Organize by topic -- create separate KBs for distinct domains (HR, Engineering, Legal)
- Keep documents current -- use external source connectors with incremental sync for automatic updates
Retrieval Optimization
- Use contextual chunking -- for high-value documents, the LLM-generated prefixes dramatically improve retrieval
- Enable hierarchical retrieval -- document summaries prevent irrelevant chunk retrieval
- Test with real queries -- use the Query Tester to validate retrieval quality
- Adjust chunk size -- if answers span multiple chunks, increase chunk size
- Increase overlap -- if chunks cut off mid-sentence, increase overlap
- Use multiple KBs -- separate by domain to reduce noise
- Set relevance thresholds -- filter out low-confidence results (< 0.5)
External Source Integration
- Use sync-source permission mode for enterprise sources where access control matters
- Map source groups to platform groups in the permission mapping configuration
- Set incremental sync schedules -- daily for content, every 15 min for permissions
- Monitor sync health -- check last sync status and error counts in Source Panel
Agent Integration
- Include retrieval instructions in the system prompt:
Always search the knowledge base before answering. If the KB returns no relevant results, say "I couldn't find information about that." Cite the document name when referencing KB content. - Combine with other tools -- KB search for facts, web search for real-time data
- Use database_sql_query for structured data -- KB search for unstructured docs
- Monitor retrieval metrics -- track hit rate and relevance scores in traces
Troubleshooting
| Issue | Cause | Fix |
|---|---|---|
Documents stuck in pending | Embedding not triggered | Click "Generate Embeddings" button |
| Low relevance scores | Chunk size too large/small | Try contextual strategy, adjust chunk size |
| Missing results | Document not embedded | Check document status, re-embed if failed |
| Irrelevant results | Too broad a KB | Split into topic-specific knowledge bases |
| Agent ignores KB results | System prompt doesn't mention KB | Add explicit retrieval instructions to prompt |
| Sync failed | Expired credentials | Re-authenticate via Source Panel, check Vault |
| Permission denied on synced docs | Group mapping missing | Configure source group -> platform group mapping |
| SQL query blocked | Table not in whitelist | Add table to data catalog allowedTables |
Next Steps
- KNOWLEDGE_MANAGEMENT.md -- Full architecture reference (K1-K8 sprints)
- Tool Integration Guide -- configure Knowledge Base Search and database_sql_query tools
- Memory Configuration Guide -- combine KB with agent memory
- Platform-Managed Agents -- build a RAG-based agent
- SDK Guide -- build external data analyst agents with workspace tools