RAG Integration (KnowledgeBase)
agent-orca provides native Retrieval-Augmented Generation through the KnowledgeBase CRD. When an Agent references a KnowledgeBase, the model-router automatically injects _rag_search and _rag_ingest as built-in tools, giving the LLM direct access to vector search and runtime document ingestion.
Architecture
flowchart TD
subgraph Operator
KBC[KnowledgeBase Controller]
API[Operator API :8082]
end
subgraph "Per Namespace"
QD[(Qdrant StatefulSet<br/>gRPC :6334 / HTTP :6333)]
CM[ConfigMap Sources]
ING[mcp-ingester Job<br/>detect + extract + chunk + embed]
end
subgraph "Agent Pod"
AC[Agent Container]
MR[model-router sidecar]
end
subgraph "Embedding Provider"
EP[OpenAI / Ollama / etc.]
end
KBC -->|1. auto-deploy| QD
KBC -->|2. create collection| QD
KBC -->|3. launch ingestion Job| ING
ING -->|4. read sources| CM
ING -->|5. embed| EP
ING -->|6. upsert vectors| QD
AC -->|chat completions| MR
MR -->|_rag_search| API
MR -->|_rag_ingest| API
API -->|embed query| EP
API -->|vector search| QD
API -->|chunk + embed + upsert| QD
KnowledgeBase CRD
apiVersion: agentorca.agentorca.io/v1alpha1
kind: KnowledgeBase
metadata:
name: my-kb
spec:
description: "Project documentation"
vectorStore:
provider: qdrant # only supported provider
collectionName: my-kb # defaults to CR name
storageSize: "10Gi" # PVC size for Qdrant
embedding:
modelSelectorRef: local-embeddings # ModelSelector for /v1/embeddings calls
chunkSize: 512 # tokens per chunk
chunkOverlap: 64 # overlap tokens between chunks
ingestion:
configMapRefs:
- name: my-docs # ConfigMap keys → documents
urls:
- https://example.com/docs.txt # fetched at reconcile time
syncIntervalSeconds: 3600 # 0 = one-shot, >0 = periodic re-syncStatus
status:
ready: true
vectorStoreURL: "kb-qdrant-my-kb.default.svc.cluster.local:6334"
collectionName: "my-kb"
documentCount: 3
chunkCount: 12
lastSyncTime: "2026-03-22T10:00:00Z"Connecting an Agent to a KnowledgeBase
Add the KnowledgeBase name to the Agent's knowledgeBases field:
apiVersion: agentorca.agentorca.io/v1alpha1
kind: Agent
metadata:
name: research-agent
spec:
modelSelectorRef: default
knowledgeBases:
- my-kb
systemPrompt: |
You are a research assistant. Use _rag_search to find relevant
information before answering questions.
runtime:
ociRef: ghcr.io/myorg/research-agent:latestWhen knowledgeBases is non-empty, the operator automatically injects two built-in tools into the router config:
| Tool | Description |
|---|---|
_rag_search | Embed a query and return the top-K most relevant chunks |
_rag_ingest | Ingest new documents at runtime (chunk → embed → upsert) |
Built-in Tools
_rag_search
{
"knowledgeBase": "my-kb",
"query": "How does the model-router handle authentication?",
"topK": 5
}Returns an array of results with score, text, doc_id, chunk_index, and any metadata.
_rag_ingest
{
"knowledgeBase": "my-kb",
"documents": [
{
"id": "meeting-notes-2026-03-22",
"content": "Discussed new RAG integration...",
"metadata": {"source": "meeting", "date": "2026-03-22"}
}
]
}Returns {"ingested": 1, "chunks": 3}.
Local Development Setup
This guide walks through testing RAG on a local kind cluster using Ollama for embeddings.
Prerequisites
Step 1: Create a kind cluster
kind create clusterStep 2: Install and configure Ollama
brew install ollama
ollama pull nomic-embed-textOllama runs natively on your Mac (Apple Silicon optimized) and serves /v1/embeddings on localhost:11434.
Step 3: Bridge Ollama into the cluster
Since Ollama runs on the host (not inside kind), create a Service + Endpoints bridge:
kubectl apply -f config/samples/ollama-embedding-bridge.yamlThis creates a ollama Service in the default namespace that forwards traffic to your host's Ollama instance. You may need to update the IP in the Endpoints resource:
# Find your Docker gateway IP
docker run --rm alpine nslookup host.docker.internal
# Update the IP in ollama-embedding-bridge.yaml if it differs from 192.168.65.254Step 4: Install CRDs
make installStep 5: Apply the demo KnowledgeBase
kubectl apply -f config/samples/knowledgebase-demo.yamlThis creates:
- A Secret with a dummy API key (Ollama doesn't need auth)
- A ModelProvider (
ollama-embed) pointing atnomic-embed-textwithbaseURL: http://ollama.default.svc:11434 - A ModelSelector (
local-embeddings) routing to the Ollama provider - A ConfigMap (
demo-knowledge) with 3 sample documents - A KnowledgeBase (
demo-kb) with ConfigMap ingestion (dimensions auto-discovered from the model)
Step 6: Run the operator
make runThe KnowledgeBase controller will:
- Create a dedicated
kb-qdrant-demo-kbStatefulSet + headless Service - Probe the embedding model, discover its output dimension, create the
demo-kbcollection - Read the
demo-knowledgeConfigMap - Chunk the 3 documents, embed via Ollama, upsert into Qdrant
- Update status with
ready: true, document/chunk counts
Step 7: Verify
# Check KnowledgeBase status
kubectl get knowledgebase demo-kb -o yaml
# Check Qdrant is running (each KB gets its own StatefulSet)
kubectl get statefulset kb-qdrant-demo-kb
kubectl get svc kb-qdrant-demo-kb
# Check Qdrant has data (port-forward to HTTP API)
kubectl port-forward svc/kb-qdrant-demo-kb 6333:6333
curl http://localhost:6333/collections/demo-kbAccess Control
Each KnowledgeBase manages its own access list via spec.allowedAgents. Access is denied by default — an agent can only use a KnowledgeBase if its name appears in the list, regardless of what the agent's spec.knowledgeBases field declares.
apiVersion: agentorca.agentorca.io/v1alpha1
kind: KnowledgeBase
metadata:
name: my-kb
spec:
allowedAgents:
- rag-assistant
- search-agent
embedding:
modelSelectorRef: embeddingsThe operator enforces this at two points:
- AgentRun/AgentDeployment creation time — the run is rejected before the pod is scheduled if the agent is not in
allowedAgents. - Runtime — the operator API verifies the calling agent's SA identity via TokenReview and returns
403 Forbiddenfor unauthorised requests.
Migration from Shared Qdrant
Prior to this change, all KnowledgeBases in a namespace shared a single agentorca-qdrant StatefulSet. The legacy StatefulSet is not deleted by the operator — existing clusters keep their data intact. New KnowledgeBases (and re-creates of existing ones) will receive their own dedicated kb-qdrant-<name> instance.
To migrate existing data, port-forward the old instance, export collections via the Qdrant snapshot API, and import them into the new per-KB instance.
ModelProvider baseURL Field
For self-hosted models (Ollama, vLLM, etc.), set baseURL on the ModelProvider to override the default endpoint derived from the LiteLLM model prefix:
apiVersion: agentorca.agentorca.io/v1alpha1
kind: ModelProvider
metadata:
name: ollama-embed
spec:
litellmModel: "ollama/nomic-embed-text"
baseURL: "http://ollama.default.svc:11434" # overrides default localhost:11434
credentialsRef:
name: ollama-credentials
key: api-keyWithout baseURL, the operator maps prefixes to default endpoints:
| Prefix | Default Endpoint |
|---|---|
openai/ | https://api.openai.com |
ollama/ | http://localhost:11434 |
gemini/ | https://generativelanguage.googleapis.com/v1beta/openai |
Setting baseURL is required when the model runs in-cluster rather than on localhost.
Embedding Models
Any model that serves an OpenAI-compatible /v1/embeddings endpoint works. Common options:
| Model | Provider | Dimensions | Notes |
|---|---|---|---|
nomic-embed-text | Ollama | 768 | Free, runs locally on Apple Silicon. Requires queryPrompt / docPrompt (see below). |
text-embedding-3-small | OpenAI | 1536 | Low cost, good quality. No prompt needed. |
text-embedding-3-large | OpenAI | 3072 | Higher quality, higher cost. No prompt needed. |
The dimensions field no longer exists in the KnowledgeBase spec. The controller probes the embedding model on first use and stores the discovered dimension in status.embeddingDimensions.
Prompt Prefixes for Open-Source Embedding Models
Some embedding models — notably nomic-embed-text via Ollama — require task-specific prefixes to produce retrieval-quality vectors. These models were trained with an instruction prefix prepended to the input text; without it, the embedding space is shifted and similarity search quality degrades significantly (or the model may return degenerate vectors).
agent-orca handles this via two optional fields on the ModelProvider CRD:
| Field | Applied to | Example |
|---|---|---|
queryPrompt | Query text before _rag_search | "search_query: " |
docPrompt | Document chunks before _rag_ingest | "search_document: " |
When set, the EmbeddingClient prepends the relevant prefix to each input string before sending it to the model's /v1/embeddings endpoint. Both ingestion and search use the same ModelProvider, so the correct prefix is applied in each context automatically.
Configuration
apiVersion: agentorca.agentorca.io/v1alpha1
kind: ModelProvider
metadata:
name: ollama-embed
spec:
litellmModel: "ollama/nomic-embed-text"
baseURL: "http://ollama-embed.agent-orca-system.svc:11434"
credentialsRef:
name: ollama-embed-credentials
key: api-key
capabilities:
- embeddings
queryPrompt: "search_query: "
docPrompt: "search_document: "When queryPrompt and docPrompt are omitted, raw text is sent as-is — this is suitable for hosted models like OpenAI's text-embedding-3-* which handle instructions internally and do not accept a prompt parameter in the OpenAI-compatible API.
Ollama nomic-embed-text Gotchas
Task prefixes are required. Documents must be prefixed with
search_document:and queries withsearch_query:. Set these asdocPromptandqueryPrompton your ModelProvider respectively. Skipping the prefixes degrades retrieval quality.Context window size. The model card lists 2,048 tokens, but the native context window is actually 8,192 tokens. Ollama's OpenAI-compatible
/v1/embeddingsendpoint does not accept anum_ctxparameter per request, so set it in your OllamaModelfileinstead:dockerfileFROM nomic-embed-text PARAMETER num_ctx 8192The bundled
ollama-nomic-embed-textModelProvider incharts/model-providers/values.yamlalready includes the correctqueryPromptanddocPrompt.No
promptfield in the OpenAI-compatible embeddings API. TheEmbeddingClientsends{"model": "...", "input": ["<prefix><text>"]}— the prefix is prepended to the input text itself, not sent as a separate request parameter. This works for both native Ollama OpenAI-compatible mode and hosted providers.
How It Works Internally
Ingestion Pipeline
Source Documents → Detect type → Extract text → Chunk (sentence-boundary, token-based) → Embed (batch /v1/embeddings) → Upsert (Qdrant gRPC)All source ingestion (ConfigMaps, URLs, S3, MCP) runs in mcp-ingester Kubernetes Jobs, not in the operator — the controller only orchestrates Job lifecycle and queries Qdrant for counts. The pipeline:
- Type detection & extraction:
internal/rag/extractdetects the document type from magic bytes (with Content-Type/extension fallbacks) and extracts plain text. Supported: PDF (text layer), DOCX, PPTX, XLSX, HTML, and plain-text formats (markdown, JSON, YAML, CSV, XML). Base64-encoded binaries returned by MCP tools are decoded and retried. Documents that fail extraction are skipped with a warning. - Chunking: Splits on sentence boundaries, respecting
chunkSizetokens withchunkOverlapoverlap. Uses word count as a token approximation (1 token ~ 1.33 words). - Embedding: Batches up to 100 texts per
/v1/embeddingscall. If the ModelProvider has adocPrompt, it is prepended to each chunk text before embedding. - Upsert: Each chunk gets a deterministic ID (
sha256(docID:chunkIndex)), enabling idempotent re-ingestion. Points include payload:text,doc_id,chunk_index, plus any user metadata (includingdocType).
The controller ensures an egress NetworkPolicy for ingestion Job pods (agentorca-kb-ingest-<kb>) allowing DNS, the Kubernetes API, same-namespace services (Qdrant, MCP servers, in-cluster embedding providers), and HTTP/HTTPS. Add extra ports via ingestion.networkEgress. The policy is additive, so it is safe in namespaces without default-deny policies and required in namespaces that have them.
Search Flow
Query → Embed (with queryPrompt if set) → Qdrant nearest-neighbor (cosine) → Top-K chunks with scoresThe query text is embedded via the same EmbeddingClient, using queryPrompt (if configured) instead of docPrompt. This ensures the query and document vectors share the same prompt-space alignment required by models like nomic-embed-text.
Key Files
| File | Role |
|---|---|
api/v1alpha1/knowledgebase_types.go | KnowledgeBase CRD types |
internal/rag/qdrant.go | Qdrant gRPC client wrapper |
internal/rag/embedding.go | OpenAI-compatible embedding client |
internal/rag/chunker.go | Sentence-boundary document chunker |
internal/rag/extract/ | Document type detection + text extraction (PDF, OOXML, HTML, text) |
internal/rag/pipeline.go | Shared ingest pipeline (chunk → embed → upsert) |
internal/controller/knowledgebase_controller.go | Reconciler: Qdrant deploy, collection create, ingestion Job orchestration |
internal/controller/kb_mcp_ingest.go | Ingestion Job builders (MCP + static sources), ingester RBAC, NetworkPolicy |
cmd/mcp-ingester/ | Ingestion Job binary: fetch sources, detect/extract, chunk, embed, upsert |
internal/apiserver/apiserver.go | /knowledgebase/.../search and /knowledgebase/.../ingest handlers |
internal/controller/agentrun_controller.go | Resolves KB configs + injects RAG tools in buildRouterConfig |
Integration Test
A standalone integration test exercises the full pipeline without Kubernetes:
# Prerequisites: Qdrant on localhost:6334, Ollama with nomic-embed-text
docker run -d --name qdrant -p 6333:6333 -p 6334:6334 qdrant/qdrant:v1.17.1
ollama pull nomic-embed-text
# Run the test
go test -tags integration -v ./internal/rag/ -run TestRAGEndToEndThe test ingests 3 documents, runs semantic queries, and verifies the top results match expected topics.
