Skip to main content

RAG Module

The RAG module provides a thin orchestration layer over Knowledge for retrieval-augmented generation.

Core Classes

RAG

The main pipeline class that orchestrates retrieval and generation.

Methods

query(question, **kwargs) -> RAGResult
Execute a RAG query and return result with citations.
aquery(question, **kwargs) -> RAGResult
Async version of query.
aquery runs retrieval and generation on a worker thread via asyncio.to_thread, so the event loop stays responsive and contextvars set on the awaiting task are visible inside the thread. aretrieve does the same for retrieval only. See Async Safety.
stream(question, **kwargs) -> Iterator[str]
Stream response tokens.
astream(question, **kwargs) -> AsyncIterator[str]
Async streaming.
Retrieval and reranking are offloaded via asyncio.to_thread. When the LLM is sync-only (no astream method), the fallback generator is pumped from a worker thread and reuses the retrieved context — retrieval runs exactly once per astream call.
retrieve(query, top_k=None, rerank=None, **kwargs) -> ContextPack
Retrieve context without generating an answer. top_k and rerank override the config for this call only.
Per-call overrides are scoped to the call. rag.retrieve(top_k=…, rerank=…) uses the override values and leaves rag.config unchanged, including under concurrent aretrieve calls. The effective values appear on ContextPack.metadata["top_k"] and ContextPack.metadata["reranked"].
get_citations(question, **kwargs) -> List[Citation]
Get citations without generating an answer.

RAGConfig

Configuration for the RAG pipeline. top_k and rerank are defaults — passing them to retrieve() overrides only that call and never rewrites RAGConfig.

Retrieval Strategies

RAGResult

Result from a RAG query.

Properties

  • has_citations - Boolean indicating if citations exist
  • format_answer_with_citations() - Format answer with source references

Citation

Source citation for RAG answers.

Protocols

The RAG module uses protocols for extensibility.

ContextBuilderProtocol

Custom context assembly logic.

CitationFormatterProtocol

Custom citation formatting.

Context Utilities

Helper functions for context building that accept both dict and SearchResultItem formats.
build_context and deduplicate_chunks accept a mix of dict results and SearchResultItem objects. When include_source=True, the label is taken from metadata["filename"] / metadata["source"] first, falling back to the top-level filename / source attribute on the item, and finally to Source N.

Result Item Formats

The context utilities support two input formats with automatic fallback for metadata lookups:

Integration with Knowledge

RAG uses Knowledge for all retrieval operations:

Error Handling

At the retriever layer, failures are non-raising by default: a broken vector store returns empty chunks instead of throwing. Check RetrievalResult.retrieval_failed and .error to tell a real failure from a genuine no-match — see Detect Retrieval Failures.

Performance Tips

  1. Batch indexing: Add multiple documents at once
  2. Tune top_k: Start with 5, adjust based on quality
  3. Use min_score: Filter low-relevance results
  4. Enable reranking: For higher precision (costs latency)
  5. Stream responses: Better UX for long answers