Skip to content

RAG API ​

Signatures for document RAG. The import path is elsai.integrations.knowledge. For when to use each pattern, see RAG.

Installation ​

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

elsai-knowledge installs the same extra. Embedding and vector clients come from Embeddings and Vector Stores.


build_knowledge_base ​

python
from elsai.integrations.knowledge import KnowledgeBaseConfig, build_knowledge_base

kb = build_knowledge_base(config)

Validates config, creates the sidecar directory, and returns a KnowledgeBase.

vector_provider must be "chroma", "pinecone", or "weaviate". vector_collection_name, embedding_client, vectordb_client, chunking, and retrieval are required. retrieval.top_k must be at least 1.


KnowledgeBaseConfig ​

FieldTypeDefaultDescription
embedding_clientembedding client(required)Client with embed_query
vectordb_clientvector client(required)Chroma, Pinecone, or Weaviate client
vector_collection_namestr(required)Collection used only for this RAG index
vector_provider"chroma" | "pinecone" | "weaviate"(required)Backend named above
chunkingChunkingConfig(required)How ingest splits text
retrievalRetrievalConfig(required)Default query behaviour
namestr | NoneNoneOptional label
descriptionstr | NoneNoneOptional description
parserparser | NoneNoneRequired for PDF ingest
vector_persist_directorystr | NoneNoneLocal vector path. Also used as the sidecar parent when elsai_kb_store_dir is unset
elsai_kb_store_dirstr | NoneNoneSidecar directory. Required when the vector backend has no persist directory
parse_defaultsdict{}Keyword arguments forwarded to parser.parse
modelmodel | NoneNoneRequired for answer() and agentic attach
system_promptstr | NoneNoneSystem prompt for answer()
structured_output_modeltype | NoneNoneSchema for answer()
structured_output_promptstr | NoneNoneExtra prompt used with that schema

ChunkingConfig ​

FieldTypeDefaultDescription
strategy"characters" | "tokens""characters"Split unit
chunk_sizeint500Chunk size
chunk_overlapint50Overlap between chunks

RetrievalConfig ​

FieldTypeDefaultDescription
strategy"hybrid" | "dense""hybrid"Default retrieval strategy
top_kint5Maximum chunks returned
metadata_filterdict | NoneNoneFlat equality filter. Keys: file_id, source, chunk_index, page

KnowledgeBase.ingest ​

python
file_id = kb.ingest(file_path, file_id=None)
ParameterTypeDescription
file_pathstr | Path.csv, .docx, .xlsx, or .pdf
file_idstr | NoneId to store. A new UUID is used when omitted

Returns the file_id. If that id is already in the manifest, the previous vectors and sidecar rows are deleted first.

PDF files raise if parser is missing. CSV, DOCX, and XLSX do not use parser.


KnowledgeBase.chunk_text ​

python
rows = kb.chunk_text(parsed, source=source, file_id=None, chunking=None)

Splits already-parsed text. Does not embed, store, or call Docloom.

ParameterTypeDescription
parsedDocloom result or list[dict]A Docloom document, or page dicts with text (or raw_text) and an optional page
sourcestrDocument name stored on every chunk. Required
file_idstr | NoneId written onto the rows. A new UUID is used when omitted
chunkingChunkingConfig | NoneOverrides KnowledgeBaseConfig.chunking for this call

Returns list[dict]. Each row has id, text, file_id, chunk_index, source, and page. Nothing is written to the index.


KnowledgeBase.store_chunks ​

python
file_id = kb.store_chunks(chunks, source=source, file_id=None)

Embeds chunk rows and writes them. Does not parse or split text again.

ParameterTypeDescription
chunkslist[dict]Rows from chunk_text, or the same shape. Each row needs id, text, file_id, and chunk_index
sourcestrDocument name. Required
file_idstr | NoneId to store. Defaults to the file_id on the first row

Returns the file_id. Every row must use that same id. If the id is already in the manifest, the previous vectors and sidecar rows are deleted first. An empty list raises.


KnowledgeBase.ingest_text ​

python
file_id = kb.ingest_text(parsed, source=source, file_id=None, chunking=None)

Calls chunk_text, then store_chunks. Does not call Docloom.

ParameterTypeDescription
parsedDocloom result or list[dict]Same input as chunk_text
sourcestrDocument name. Required
file_idstr | NoneId to store. A new UUID is used when omitted
chunkingChunkingConfig | NoneOverrides KnowledgeBaseConfig.chunking for this call

Returns the file_id. An existing id is replaced, as with store_chunks.


KnowledgeBase.query ​

python
chunks = kb.query(
    query,
    top_k=None,
    metadata_filter=None,
    strategy=None,
)
ParameterTypeDescription
querystrSearch text
top_kint | NoneOverrides RetrievalConfig.top_k
metadata_filterdict | NoneOverrides RetrievalConfig.metadata_filter
strategystr | None"dense" or "hybrid". Unknown values raise

Returns list[KnowledgeChunk]. Hybrid search uses the BM25 sidecar plus the vector index. An empty sidecar corpus falls back to dense search. A corpus of 50,000 chunks or more logs a warning and still runs.


KnowledgeBase.answer ​

python
result = kb.answer(question, **query_overrides)

Requires config.model. Runs query, then one model turn.

query_overrides are the keyword arguments of query (top_k, metadata_filter, strategy).

Returns KnowledgeAnswerResult:

FieldDescription
queryThe question passed in
answerExtracted answer text
resultsKnowledgeChunk list from query
structured_outputSchema instance when structured_output_model is set, otherwise None

KnowledgeBase.list_documents ​

python
rows = kb.list_documents()

Returns manifest rows. Each row has file_id, source, chunk_count, and ingested_at.


KnowledgeBase.delete_documents ​

python
kb.delete_documents(file_ids)

file_ids is a list[str]. For each id, deletes matching vectors and the sidecar rows.


KnowledgeChunk ​

FieldTypeDescription
textstrChunk text
idstrChunk id
sourcestrFile name
pageint | NonePage number when the extractor provided one
chunk_indexintIndex within the file
scorefloat | NoneRetrieval score
score_kind"distance" | "similarity" | "rank" | NoneHow to read score
metadatadictfile_id, source, chunk_index, page, plus extra fields from the vector store

to_dict() returns those fields. agent.last_knowledge["results"] stores that dict form.

At ingest, chunk ids are "<file_id>:<chunk_index>". Use metadata["file_id"] to group hits by document. source is the file name without its directory.

score_kindBackendHow to read score
"distance"Chroma, denseLower is closer
"similarity"Pinecone, denseHigher is closer
"rank"Hybrid, any backendPosition in the fused list. 1 is best
NoneWeaviate, denseNo score returned

attach_knowledge ​

python
from elsai.integrations.knowledge import KnowledgeAttachConfig, attach_knowledge

agent = attach_knowledge(agent, kb, attach_config=None)

Registers a BeforeInvocationEvent hook and sets agent.last_knowledge to {"results": [], "rounds": []}. Returns the same agent. The agent must already have agent.hooks.

The hook runs once per user invocation, not once per tool call.

KnowledgeAttachConfig ​

FieldTypeDefaultDescription
mode"basic" | "agentic""basic"One query, or several rounds
injection_mode"system_append" | "user_preamble""system_append"Where the chunk block is written
max_roundsint | NoneNoneRequired when mode is "agentic", and must be at least 1

basic calls kb.query with the user message. agentic may ask the agent model for another query, up to max_rounds, then injects the merged chunks.

After the hook, agent.last_knowledge is:

KeyContents
resultsInjected chunks as dicts
rounds[] in basic mode. In agentic mode, {"query", "results"} per search

In agentic mode, results is de-duplicated by chunk id across rounds. If the user message has no text, both lists are empty. Each invocation overwrites last_knowledge.

Injected block ​

text
<!-- elsai-knowledge:start -->
Relevant knowledge context:
- [handbook.docx] Refunds are accepted within 30 days of purchase.
- [manual.pdf page=4] Returns must include the original receipt.
<!-- elsai-knowledge:end -->

When nothing is retrieved, the body is (no knowledge context). With system_append, the block is replaced inside agent.system_prompt. With user_preamble, the previous block message is removed and a new one is inserted at the start of agent.messages.

Reading last_knowledge ​

python
result = agent("What is the refund window?")

hits = agent.last_knowledge["results"]
if not hits:
    print("No matching documents")
for hit in hits:
    print(hit["source"], hit["page"], hit["score"], hit["score_kind"])
    print(hit["text"])

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

Example ​

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

model = BedrockModel(model_id="global.anthropic.claude-sonnet-4-6", region_name="us-west-2")

kb = build_knowledge_base(
    KnowledgeBaseConfig(
        embedding_client=build_embedding_client(
            EmbeddingBackendConfig(
                provider="bedrock",
                aws_region="us-east-1",
                model_name="amazon.titan-embed-text-v1",
            )
        ),
        vectordb_client=build_vectordb_client(
            VectorBackendConfig(
                provider="chroma",
                collection_name="product_docs",
                persist_directory="./chroma_rag",
            )
        ),
        vector_collection_name="product_docs",
        vector_provider="chroma",
        vector_persist_directory="./chroma_rag",
        chunking=ChunkingConfig(),
        retrieval=RetrievalConfig(),
        model=model,
    )
)
kb.ingest("./handbook.docx", file_id="handbook")

# Standalone
answer = kb.answer("What is the refund window?")
print(answer.answer, [c.source for c in answer.results])

# Attached to an agent
agent = Agent(model=model)
attach_knowledge(agent, kb, KnowledgeAttachConfig(mode="agentic", max_rounds=3))
print(str(agent("What is the refund window?")))
print([hit["source"] for hit in agent.last_knowledge["results"]])

Copyright © 2026 elsai foundry.