Skip to content

Retrieval & grounding

Grounding happens inside POST /v1/proxy/llm/chat/completions on the Core Proxy. The request needs no extra fields: if the call’s resource group reaches an enabled collection, the proxy retrieves and injects context; otherwise the request is forwarded unchanged.

Terminal window
curl -s http://localhost:8100/v1/proxy/llm/chat/completions \
-H "Authorization: Bearer sk_brutor_api_..." \
-H "Content-Type: application/json" \
-d '{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "You are the EMEA sales assistant."},
{"role": "user", "content": "What are the Q3 EMEA renewal terms?"}
]
}'

The response is an ordinary chat completion. What the provider received was:

{
"model": "gpt-4o",
"messages": [
{"role": "system", "content": "You are the EMEA sales assistant."},
{"role": "system", "content": "Use the following context from the knowledge base to answer the user's question. If the context doesn't contain relevant information, say so.\n\n[1] Renewal terms for EMEA in Q3: multi-year renewals signed before 30 September keep the 2025 list price …\n\n[2] Discount approval above 15% requires the regional VP …"},
{"role": "user", "content": "What are the Q3 EMEA renewal terms?"}
]
}
  1. Resolve the group. For an API key, the key’s own resource group. For a signed-in user (portal JWT), the group named in X-Resource-Group if they are a member (the portal sends the active workspace), else their primary group, else their deepest membership. Only this one group counts, not every group the user belongs to.

  2. Collect collections. Enabled collections bound to that group, plus those bound to each ancestor reachable through inherit_from_parent = true. Settings merge as described in Collections. No collections: stop, forward unchanged.

  3. Build the query from the last user message only. Multi-part content (text plus images) is flattened to its text. Earlier turns are not part of the query, so a follow-up like “and for APAC?” retrieves on those words alone.

  4. Load source principals for a signed-in user (see Source permissions); API-key calls have none and get no ACL filter.

  5. Embed the query with the tenant’s embedding model through /v1/proxy/llm/embeddings, using the caller’s own credentials, so the embedding call is logged and metered to the caller.

  6. Hybrid search in brutor_kb_{tenant_id}, filtered to the collections (and ACL):

    • a dense (semantic) prefetch of 2 × top_k candidates with cosine score ≥ similarity_threshold;
    • a sparse BM25 prefetch of 2 × top_k candidates, with no score cutoff;
    • fused with Reciprocal Rank Fusion, keeping top_k.

    If nothing survives, nothing is injected.

  7. Rerank (optional, see below).

  8. Fill the budget. Chunks are taken in rank order while the running estimate (4 characters per token) stays within max_context_tokens; the first chunk is always kept. The formatted context is then hard-capped at max_context_tokens × 4 + 512 bytes so the injected text never exceeds what the call’s token and spend admission reserved.

  9. Inject one system message built from the template, with chunks numbered [1], [2], …, placed after your leading system messages and before the first non-system message.

  • Response cache is skipped for groups that reach an enabled collection. Two users of the same group can be entitled to different connector chunks, so grounded answers are never served from, or written to, the semantic response cache.
  • Retrieval results are cached in Redis for 5 minutes per tenant, collection set, query text and principal set. Document changes do not clear this cache.
  • Query embeddings are cached for 60 seconds by query text.

Set these on the Core Proxy to re-score the fused top-K with a Cohere-style /rerank endpoint (Cohere, Jina, or a self-hosted TEI/BGE server). Unset means no reranker.

Variable Default Example Purpose
BRUTOR_RERANKER_URL unset http://tei-reranker:8080 Base URL; the proxy posts to {url}/rerank
BRUTOR_RERANKER_MODEL rerank-english-v3.0 BAAI/bge-reranker-v2-m3 Model sent in the request
BRUTOR_RERANKER_TOP_K 10 5 Results kept after reranking
BRUTOR_RERANKER_API_KEY unset co-… Bearer token, if the endpoint needs one

The request is {"model", "query", "documents", "top_n"} with a 5-second timeout; both the {"results": [{index, relevance_score}]} and bare [{index, score}] response shapes are accepted. Any failure falls back to the RRF order. The reranker only reorders and trims what the hybrid search returned, so BRUTOR_RERANKER_TOP_K above top_k has no effect.

Variable Default Example Purpose
KNOWLEDGE_BASE_ENABLED true false Turn retrieval off entirely (e.g. a proxy-only deployment without Qdrant)
QDRANT_URL unset http://qdrant:6334 Without it, retrieval is disabled
QDRANT_JWT_SIGNING_SECRET unset 32+ random chars Without it, retrieval is disabled (fail closed)
EMBEDDING_MODEL unset nomic-embed-text Query-embedding model name when the tenant has no default

Retrieval also requires a Core Proxy build with the semantic-cache feature (the standard images have it).

Every grounded call’s proxy log row carries:

Field Example Meaning
rag_enabled true Context was injected
rag_chunks_retrieved 4 Chunks injected
rag_context_tokens 1180 Estimated tokens of injected context
rag_collection_ids 01K8ZQ3V…,01K8ZQ9A… Collections searched (comma-separated)
rag_top_similarity_score 0.5 Best score among injected chunks (an RRF score unless a reranker re-scored them)
rag_retrieval_duration_ms 41.7 Retrieval time

A call that found nothing has these fields empty. At run level, AI System run details show rag_used, rag_chunks and rag_collection_ids (AI Estate → AI Systems → system → Runs → run). See Logs.

POST /v1/admin/knowledge-base/collections/{collection_id}/search on the Control Plane runs a quick search over one collection, the same call as Test RAG Search in the Admin UI.

Terminal window
curl -s -X POST \
http://localhost:5050/v1/admin/knowledge-base/collections/01K8ZQ3V7M2T4N6P8R0S2U4W6Y/search \
-H "Authorization: Bearer $ADMIN_JWT" -H "Content-Type: application/json" \
-d '{"query": "Q3 EMEA renewal terms", "top_k": 8, "similarity_threshold": 0.5}'
{
"query": "Q3 EMEA renewal terms",
"total": 1,
"results": [
{
"chunk": {
"id": "",
"document_id": "01K8ZR1B9D3F5H7K9M1P3R5T7V",
"chunk_index": 7,
"content": "Renewal terms for EMEA in Q3: multi-year renewals signed before 30 September …",
"token_count": null,
"metadata": null
},
"score": 0.87,
"document_name": "Q3 Playbook",
"document_filename": "q3-playbook.pdf"
}
]
}

query is 1–4096 characters; top_k (1–50) and similarity_threshold (0.0–1.0) override the collection’s values when given. score here is cosine similarity.

Symptom Likely cause
No rag_* fields on the log row The call’s resolved group reaches no enabled collection (check the workspace / API key group and effective-kb-collections), or the endpoint is not chat completions
Grounding works in one portal workspace, not another Retrieval uses only the active workspace group and its inheriting ancestors
Connector content never appears for a user No identity mapping matches the document ACL; see Source permissions
Nothing injected for good questions Threshold too high for the embedding model (scores vary by model); lower it on the collection
kb_vector_dim_mismatch alert The tenant’s embedding model changed without a re-embed; see Embeddings
embedding_generation_failed alert The embedding model’s provider is failing; retrieval is skipped and the call proceeds ungrounded