Skip to content

RAG ​

A knowledge base block describes a document index: how to split documents, which embedding model and vector database to use, and how to search. You can use that index three ways:

PatternWhat runsHow to build it
Standalone RAGYour code ingests, searches, and asks for an answeryaml_to_knowledge
Basic RAGOne search per user message, injected before the agent runsknowledge: with mode: basic
Agentic RAGThe model may rewrite the search for several rounds, then the agent runsknowledge: with mode: agentic

The Python behaviour behind these blocks is in RAG.

Use a separate vector collection

Use a dedicated vector collection for RAG. Do not reuse the collection that stores session memory.


Installation ​

bash
pip install --upgrade --extra-index-url https://elsai-agents.elsai.ai/root/ "elsai-yaml[elsai-knowledge]==0.4.3"

The extra installs the Core packages RAG uses: Embeddings, Vector Stores, Retrieval, Chunking, Text Extractors, and Docloom for PDF parsing.


Embedding providers ​

An EmbeddingBackend block turns text into vectors. These credential fields may be set on the block for that run. A present value must be a non-empty string. Omit the field and the client still reads the environment variable. Use {{$ENV_VAR:}} when the value should not be written in the file.

providerKeysOptional credentials
bedrockmodel_name, aws_regionaws_access_key_id, aws_secret_access_key, aws_session_token
azuremodel, azure_endpoint, azure_api_version, azure_deploymentazure_api_key
yaml
titan_embed:
  type: EmbeddingBackend
  provider: bedrock
  aws_region: us-east-1
  model_name: amazon.titan-embed-text-v1

azure_embed:
  type: EmbeddingBackend
  provider: azure
  model: text-embedding-ada-002
  azure_endpoint: https://my-resource.openai.azure.com
  azure_api_version: "2024-02-01"
  azure_deployment: my-embedding-deployment
  azure_api_key: "{{$AZURE_OPENAI_API_KEY:}}"

See Embeddings for the models behind each provider.


Vector databases ​

A VectorBackend block stores and searches the vectors.

providerKeysSidecar folder
chromacollection_name, persist_directoryWritten under persist_directory
pineconeindex_name, namespace, dimension, optional pinecone_api_keySet elsai_kb_store_dir on the knowledge base
weaviatecollection_name, connection_type, host, port or cluster_url, optional auth_credentialsSet elsai_kb_store_dir on the knowledge base
yaml
chroma_store:
  type: VectorBackend
  provider: chroma
  collection_name: policies_kb
  persist_directory: ./chroma_policies

pinecone_store:
  type: VectorBackend
  provider: pinecone
  index_name: policies
  namespace: support
  dimension: 1536

weaviate_store:
  type: VectorBackend
  provider: weaviate
  collection_name: Policies
  connection_type: local
  host: localhost
  port: 8080

Weaviate connection_type is local (with host and port) or cloud (with cluster_url). The sidecar folder holds the document list and the keyword index used by hybrid search. Pinecone and Weaviate have no local folder, so elsai_kb_store_dir is required with them. pinecone_api_key and Weaviate auth_credentials follow the same rule as the embedding credentials: a present value must be a non-empty string, and an omitted field still reads the environment (PINECONE_API_KEY for Pinecone). See Vector Stores.


Chunking ​

chunking decides how ingest splits a document before it is embedded. Splitting comes from elsai-utilities.

strategychunk_size and chunk_overlap are counted in
characters (default)Characters
tokensTokens

chunk_size defaults to 500 and chunk_overlap to 50.

yaml
chunking:
  strategy: characters
  chunk_size: 400
  chunk_overlap: 40

Retrieval ​

retrieval decides how a search runs. Hybrid search comes from elsai-retrievers.

strategyHow it searches
hybrid (default)Keyword (BM25) plus vector search, combined
denseVector search only

top_k is how many chunks come back. It must be at least 1, and defaults to 5. metadata_filter keeps hits from one file_id, source, chunk_index, or page.

yaml
retrieval:
  strategy: dense
  top_k: 3
  metadata_filter:
    source: refund_policy.csv

The knowledge base block ​

chunking, embedding, vector, and retrieval are required.

KeyWhat it does
name, descriptionLabels
embedding${block} of an EmbeddingBackend
vector${block} of a VectorBackend
chunking, retrievalSee above
modelModel for kb.answer
system_promptInstruction for the written answer
structured_outputmodule:Class the written answer fills. Needs model
parser${block} of a DocumentParse block. Needed for PDF
elsai_kb_store_dirSidecar folder. Required for Pinecone and Weaviate

Ingest accepts .csv, .docx, .xlsx, and .pdf. PDF needs parser:

yaml
docloom_parse:
  type: DocumentParse
  num_workers: 2
  auto_routing: true

pdf_kb:
  type: KnowledgeBaseConfig
  parser: ${docloom_parse}
  # chunking, embedding, vector, retrieval as below
DocumentParse keyWhat it does
auto_routingtrue (default) lets Docloom choose the OCR provider. false requires provider
providerazure_document_intelligence, aws_textract, gemini, mistral_ocr, bedrock, visionai, azure_cognitive_service, or dots_ocr
modelModel for that provider. Checked against the provider when the file loads
include_detailed_structureReturn the detailed document structure from the parser
num_workersPages parsed in parallel. Defaults to 4
verboseLog parsing progress
api_keyOptional Docloom key. A present value must be a non-empty string. Omit it and Docloom reads DOCUMENT_EXTRACTOR_API_KEY

See Document Parsers and OCR Extractors for what each provider handles.


Standalone RAG ​

Build the knowledge base on its own. Your code decides when to ingest, search, and ask.

yaml
openai:
  type: OpenAIModel
  model_id: gpt-4o-mini

azure_embed:
  type: EmbeddingBackend
  provider: azure

chroma_policies:
  type: VectorBackend
  provider: chroma
  collection_name: policies_kb
  persist_directory: ./chroma_policies

policy_kb:
  type: KnowledgeBaseConfig
  name: policies
  chunking:
    strategy: characters
    chunk_size: 400
    chunk_overlap: 40
  embedding: ${azure_embed}
  vector: ${chroma_policies}
  retrieval:
    strategy: hybrid
    top_k: 5
  model: ${openai}
  system_prompt: |
    Answer using only the retrieved context. If unknown, say you do not know.
python
from elsai.config import yaml_to_knowledge

kb = yaml_to_knowledge("rag.yaml", entry="policy_kb")
kb.ingest("./refund_policy.csv", file_id="refund_policy")

for chunk in kb.query("What is the refund window?"):
    print(chunk.source, chunk.text)

result = kb.answer("What is the refund window?")
print(result.answer)

query returns chunks only. answer searches, then writes a reply in plain text with model. A stable file_id makes a second ingest replace the document instead of adding a copy.


Basic RAG ​

Attach the knowledge base to an agent with mode: basic. Before the agent runs, one search is made with the user's message and the results are injected.

Add this block to the same file:

yaml
support_basic:
  type: Agent
  name: Support
  system_prompt: Answer using the injected knowledge context.
  model: ${openai}
  tools: []
  knowledge:
    base: ${policy_kb}
    mode: basic
    injection_mode: system_append
python
from elsai.config import yaml_to_agent, yaml_to_knowledge

yaml_to_knowledge("rag.yaml", entry="policy_kb").ingest(
    "./refund_policy.csv", file_id="refund_policy"
)

agent = yaml_to_agent("rag.yaml", entry="support_basic")
print(agent("What is the refund window?"))

for hit in agent.last_knowledge["results"]:
    print(hit["source"], hit["text"])

injection_mode: system_append writes the passages into the system prompt. user_preamble writes them in front of the user message.


Agentic RAG ​

mode: agentic lets the model rewrite the search when the first results are not enough, up to agentic.max_rounds. max_rounds is required and must be at least 1. The search rounds use the agent's own model. agentic is only allowed when mode is agentic.

yaml
support_agentic:
  type: Agent
  name: Support research
  system_prompt: Answer using the injected knowledge context.
  model: ${openai}
  tools: []
  knowledge:
    base: ${policy_kb}
    mode: agentic
    injection_mode: system_append
    agentic:
      max_rounds: 2
python
agent = yaml_to_agent("rag.yaml", entry="support_agentic")
print(agent("Compare the refund rules for monthly and annual plans."))

for round_ in agent.last_knowledge["rounds"]:
    print(round_["query"], len(round_["results"]))

last_knowledge["results"] is the merged list that was injected. last_knowledge["rounds"] holds one search per round. The next call overwrites both.

Hook order

When an agent also has memory and guardrails, the hooks run as memory, then knowledge, then guardrails.


Copyright © 2026 elsai foundry.