Appearance
RAG
AgentKit RAG answers questions from your documents. It is separate from conversation memory: memory keeps chat history, while RAG retrieves chunks from a document index. The same index can be declared in a file. See YAML configuration — RAG.
Use a separate vector collection
Use a dedicated vector collection for RAG. Do not reuse the collection that stores session memory. Sharing one collection mixes document chunks with chat memory.
Three patterns, from least coupled to the agent to most:
| Pattern | What runs | When to use it |
|---|---|---|
| Standalone | query() or answer() from your application | You control retrieval and Q&A |
| Basic attach | One retrieval per user turn, then the normal agent loop | Predictable grounding on every message |
| Agentic attach | The model may rewrite the search for several rounds, then the agent loop | Ambiguous questions that need another search |
Installation
bash
pip install --extra-index-url https://elsai-agents.elsai.ai/root/ "elsai-agents[elsai-classic-rag]==0.4.3"elsai-knowledge is an alias for elsai-classic-rag. The extra installs the Core packages this feature calls: embeddings, vector stores, text extractors, retrievers, utilities, and Docloom.
Build the clients with the factories in Embeddings (Amazon Bedrock and Azure OpenAI) and Vector Stores (Chroma, Pinecone, and Weaviate).
Shared setup
Build the index once. The three patterns below reuse this kb.
python
from elsai_model.bedrock import BedrockModel
from elsai.integrations.embeddings import EmbeddingBackendConfig, build_embedding_client
from elsai.integrations.knowledge import (
ChunkingConfig,
KnowledgeBaseConfig,
RetrievalConfig,
build_knowledge_base,
)
from elsai.integrations.vectordb import VectorBackendConfig, build_vectordb_client
model = BedrockModel(
model_id="global.anthropic.claude-sonnet-4-6",
region_name="us-west-2",
)
embedding = build_embedding_client(
EmbeddingBackendConfig(
provider="bedrock",
aws_region="us-east-1",
model_name="amazon.titan-embed-text-v1",
)
)
vector = build_vectordb_client(
VectorBackendConfig(
provider="chroma",
collection_name="product_docs",
persist_directory="./chroma_rag",
)
)
kb = build_knowledge_base(
KnowledgeBaseConfig(
embedding_client=embedding,
vectordb_client=vector,
vector_collection_name="product_docs",
vector_provider="chroma",
vector_persist_directory="./chroma_rag",
chunking=ChunkingConfig(strategy="characters", chunk_size=500, chunk_overlap=50),
retrieval=RetrievalConfig(strategy="hybrid", top_k=5),
model=model,
)
)
file_id = kb.ingest("./handbook.docx")ingest accepts .csv, .docx, and .xlsx. PDF ingest requires a Docloom parser on KnowledgeBaseConfig.parser. Passing the same file_id again deletes the previous vectors and sidecar rows, then writes the new file.
Text that is already parsed
ingest reads a file and, for a PDF, calls Docloom. When you already have the text, skip that step.
chunk_text splits the text and does not store it. store_chunks embeds those rows and writes them. ingest_text does both. None of the three calls Docloom. source is the document name stored on the chunks. An existing file_id is replaced when the rows are stored.
parsed is a Docloom result, or a list of page dicts. A page dict uses text (or raw_text) and an optional page.
python
pages = [
{"text": "Refunds are accepted within 30 days.", "page": 1},
]
rows = kb.chunk_text(pages, source="refunds.txt", file_id="refunds")
file_id = kb.store_chunks(rows, source="refunds.txt", file_id="refunds")ingest_text is the same two steps in one call:
python
file_id = kb.ingest_text(pages, source="refunds.txt", file_id="refunds")See RAG API.
The setup, explained
build_knowledge_base checks the config from the example above and returns the knowledge base.
What you must pass
- An embedding client (Amazon Bedrock or Azure OpenAI) and a vector client (Chroma, Pinecone, or Weaviate)
- The collection name, matching the name on the vector client
- The provider:
chroma,pinecone, orweaviate, matching that client - How to split text, and how to search
The example uses the defaults: character chunks of 500 with 50 characters of overlap, hybrid search, and five chunks.
Where the files live
Chroma uses vector_persist_directory, the same folder as the vector client. The document list and the keyword index are written under that folder.
Pinecone and Weaviate have no local folder. Set elsai_kb_store_dir to a directory of your own.
How splitting and search work
Split text by characters or by tokens. Search with hybrid (keyword plus vector) or dense (vector only).
top_k is how many chunks come back. It must be at least 1. A metadata filter can keep hits from one file, source, chunk, or page.
One search can override the count, the filter, and the strategy for that call only.
When you need a model
Set model for a written answer, or for an agent that may search more than once.
system_prompt is the instruction for that answer. Set structured_output_model when the answer should also fill a schema. name and description are optional labels.
Every field, type, and default is on the RAG API page.
Standalone RAG
Call the knowledge base from your application. Nothing is attached to an Agent.
query() returns KnowledgeChunk objects. strategy overrides the config for that call ("dense" or "hybrid").
python
chunks = kb.query("What is the refund window?", top_k=3)
for chunk in chunks:
print(chunk.source, chunk.text)answer() retrieves, formats the chunks, and runs one model turn. It returns a KnowledgeAnswerResult.
python
result = kb.answer("What is the refund window?")
print(result.answer)
print(result.results)Set structured_output_model on the config when the answer should also fill a schema. result.structured_output holds that object. result.answer is the text.
Basic attach
attach_knowledge registers a hook that runs once per user invocation, before the agent loop. In basic mode it calls kb.query with the user message and injects the chunks.
python
from elsai import Agent
from elsai.integrations.knowledge import KnowledgeAttachConfig, attach_knowledge
agent = Agent(model=model, system_prompt="Answer from the retrieved documents.")
attach_knowledge(
agent,
kb,
KnowledgeAttachConfig(mode="basic", injection_mode="system_append"),
)
print(agent("What is the refund window?"))
print(agent.last_knowledge["results"])injection_mode defaults to system_append: a marked block is written into the system prompt. user_preamble writes that block onto the user message instead. The block is replaced on the next turn, so an earlier question's chunks do not stay in the prompt.
Agentic attach
Agentic mode is the same hook, with extra searches before the agent loop. The model may decide the first hits are enough, or it may send another query. max_rounds is required and must be at least 1. Those extra model calls add latency.
python
attach_knowledge(
agent,
kb,
KnowledgeAttachConfig(mode="agentic", max_rounds=3),
)
print(agent("Compare the refund rules for monthly and annual plans."))
print(agent.last_knowledge["rounds"])Merged chunks are what get injected. Duplicate chunk ids are dropped.
Which pattern to use
- Standalone when your application decides when to retrieve or when to ask one grounded question.
- Basic attach when every user turn should see the same retrieval step before tools and the model run.
- Agentic attach when the first query is often a poor search and another round is worth the extra model call.
What the agent stored
attach_knowledge sets agent.last_knowledge to {"results": [], "rounds": []} when you attach it. Each call to the agent replaces it with what that turn retrieved:
python
{
"results": [
{
"text": "Refunds are accepted within 30 days of purchase.",
"id": "handbook:0",
"source": "handbook.docx",
"page": None,
"chunk_index": 0,
"score": 1.0,
"score_kind": "rank",
"metadata": {"file_id": "handbook", "source": "handbook.docx", "chunk_index": 0, "page": None},
},
],
"rounds": [],
}results— the chunks injected into the prompt for this turn, as dicts. The same chunks the model saw.rounds— empty in basic mode. In agentic mode, one{"query": ..., "results": [...]}entry per search, in order.resultsis the merged, de-duplicated list across those rounds.- If the turn had no user text, both lists are empty.
Each chunk dict has the fields of KnowledgeChunk:
| Key | Meaning |
|---|---|
text | Chunk text |
id | Chunk id |
source | File name the chunk came from |
page | Page number when the extractor provided one, otherwise None |
chunk_index | Position of the chunk within that file |
score / score_kind | Retrieval score. score_kind says how to read it: "distance" (Chroma, lower is closer), "similarity" (Pinecone, higher is closer), "rank" (hybrid, 1 is best), or None |
metadata | file_id, source, chunk_index, page, plus any extra fields from the vector store |
Using the results
Read last_knowledge right after the call. The next call overwrites it.
python
result = agent("What is the refund window?")
print(str(result))
# Cite the sources the answer was grounded on
for hit in agent.last_knowledge["results"]:
page = f", page {hit['page']}" if hit["page"] is not None else ""
print(f"- {hit['source']}{page}: {hit['text'][:120]}")
# Distinct documents used this turn
file_ids = {hit["metadata"]["file_id"] for hit in agent.last_knowledge["results"]}
# Agentic mode: see how the search was rewritten
for i, round_ in enumerate(agent.last_knowledge["rounds"], start=1):
print(f"Round {i}: {round_['query']} ({len(round_['results'])} hits)")last_knowledge holds dicts. Standalone kb.query() and KnowledgeAnswerResult.results hold KnowledgeChunk objects with the same fields, so use chunk.source instead of hit["source"], or call chunk.to_dict().
If the agent retrieved nothing relevant, results is empty and the injected block says (no knowledge context). Check if not agent.last_knowledge["results"]: to fall back or tell the user.
Documents
python
kb.list_documents()
kb.delete_documents([file_id])list_documents() returns manifest rows (file_id, source, chunk_count, ingested_at). delete_documents removes the vectors and the sidecar rows for those ids.
Retrieval and the sidecar
RetrievalConfig.strategy defaults to "hybrid". Hybrid search combines the local BM25 corpus with dense vector search. An empty corpus falls back to dense search. A corpus of 50,000 chunks or more logs a warning and still runs.
query accepts metadata_filter as a flat equality dict. Allowed keys are file_id, source, chunk_index, and page.
The sidecar is manifest.json plus bm25_corpus.jsonl. Set elsai_kb_store_dir to choose the directory. If you omit it and set vector_persist_directory, the files go under that directory at .elsai_kb/<collection>. Pinecone and Weaviate have no local persist path, so set elsai_kb_store_dir for those backends.
Full example
One script: build the knowledge base, ingest a document, attach it to an agent, and read the sources. Requires AWS credentials for Bedrock.
python
from elsai import Agent
from elsai_model.bedrock import BedrockModel
from elsai.integrations.embeddings import EmbeddingBackendConfig, build_embedding_client
from elsai.integrations.knowledge import (
ChunkingConfig,
KnowledgeAttachConfig,
KnowledgeBaseConfig,
RetrievalConfig,
attach_knowledge,
build_knowledge_base,
)
from elsai.integrations.vectordb import VectorBackendConfig, build_vectordb_client
COLLECTION = "product_docs"
PERSIST_DIR = "./chroma_rag"
# 1. Model, embeddings, and vector store
model = BedrockModel(
model_id="global.anthropic.claude-sonnet-4-6",
region_name="us-west-2",
)
embedding = build_embedding_client(
EmbeddingBackendConfig(
provider="bedrock",
aws_region="us-east-1",
model_name="amazon.titan-embed-text-v1",
)
)
vector = build_vectordb_client(
VectorBackendConfig(
provider="chroma",
collection_name=COLLECTION,
persist_directory=PERSIST_DIR,
)
)
# 2. Knowledge base
kb = build_knowledge_base(
KnowledgeBaseConfig(
embedding_client=embedding,
vectordb_client=vector,
vector_collection_name=COLLECTION,
vector_provider="chroma",
vector_persist_directory=PERSIST_DIR,
chunking=ChunkingConfig(strategy="characters", chunk_size=500, chunk_overlap=50),
retrieval=RetrievalConfig(strategy="hybrid", top_k=5),
model=model,
)
)
# 3. Ingest. A stable file_id makes re-running the script replace the document.
kb.ingest("./handbook.docx", file_id="handbook")
print(kb.list_documents())
# 4. Agent grounded on the knowledge base
agent = Agent(
model=model,
system_prompt=(
"Answer only from the knowledge context. "
"If the context does not contain the answer, say so."
),
)
attach_knowledge(agent, kb, KnowledgeAttachConfig(mode="basic"))
# 5. Ask, then read what was retrieved
result = agent("What is the refund window?")
print(str(result))
for hit in agent.last_knowledge["results"]:
print(f"- {hit['source']} (chunk {hit['chunk_index']})")For agentic attach, change step 4 to:
python
attach_knowledge(agent, kb, KnowledgeAttachConfig(mode="agentic", max_rounds=3))Then print agent.last_knowledge["rounds"] to see each search the model made.
Hook order
When an agent also uses memory and guardrails, register memory first, then attach_knowledge, then guardrails. AgentKit does not enforce this order.