Appearance
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
| Field | Type | Default | Description |
|---|---|---|---|
embedding_client | embedding client | (required) | Client with embed_query |
vectordb_client | vector client | (required) | Chroma, Pinecone, or Weaviate client |
vector_collection_name | str | (required) | Collection used only for this RAG index |
vector_provider | "chroma" | "pinecone" | "weaviate" | (required) | Backend named above |
chunking | ChunkingConfig | (required) | How ingest splits text |
retrieval | RetrievalConfig | (required) | Default query behaviour |
name | str | None | None | Optional label |
description | str | None | None | Optional description |
parser | parser | None | None | Required for PDF ingest |
vector_persist_directory | str | None | None | Local vector path. Also used as the sidecar parent when elsai_kb_store_dir is unset |
elsai_kb_store_dir | str | None | None | Sidecar directory. Required when the vector backend has no persist directory |
parse_defaults | dict | {} | Keyword arguments forwarded to parser.parse |
model | model | None | None | Required for answer() and agentic attach |
system_prompt | str | None | None | System prompt for answer() |
structured_output_model | type | None | None | Schema for answer() |
structured_output_prompt | str | None | None | Extra prompt used with that schema |
ChunkingConfig
| Field | Type | Default | Description |
|---|---|---|---|
strategy | "characters" | "tokens" | "characters" | Split unit |
chunk_size | int | 500 | Chunk size |
chunk_overlap | int | 50 | Overlap between chunks |
RetrievalConfig
| Field | Type | Default | Description |
|---|---|---|---|
strategy | "hybrid" | "dense" | "hybrid" | Default retrieval strategy |
top_k | int | 5 | Maximum chunks returned |
metadata_filter | dict | None | None | Flat equality filter. Keys: file_id, source, chunk_index, page |
KnowledgeBase.ingest
python
file_id = kb.ingest(file_path, file_id=None)| Parameter | Type | Description |
|---|---|---|
file_path | str | Path | .csv, .docx, .xlsx, or .pdf |
file_id | str | None | Id 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.
| Parameter | Type | Description |
|---|---|---|
parsed | Docloom result or list[dict] | A Docloom document, or page dicts with text (or raw_text) and an optional page |
source | str | Document name stored on every chunk. Required |
file_id | str | None | Id written onto the rows. A new UUID is used when omitted |
chunking | ChunkingConfig | None | Overrides 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.
| Parameter | Type | Description |
|---|---|---|
chunks | list[dict] | Rows from chunk_text, or the same shape. Each row needs id, text, file_id, and chunk_index |
source | str | Document name. Required |
file_id | str | None | Id 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.
| Parameter | Type | Description |
|---|---|---|
parsed | Docloom result or list[dict] | Same input as chunk_text |
source | str | Document name. Required |
file_id | str | None | Id to store. A new UUID is used when omitted |
chunking | ChunkingConfig | None | Overrides 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,
)| Parameter | Type | Description |
|---|---|---|
query | str | Search text |
top_k | int | None | Overrides RetrievalConfig.top_k |
metadata_filter | dict | None | Overrides RetrievalConfig.metadata_filter |
strategy | str | 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:
| Field | Description |
|---|---|
query | The question passed in |
answer | Extracted answer text |
results | KnowledgeChunk list from query |
structured_output | Schema 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
| Field | Type | Description |
|---|---|---|
text | str | Chunk text |
id | str | Chunk id |
source | str | File name |
page | int | None | Page number when the extractor provided one |
chunk_index | int | Index within the file |
score | float | None | Retrieval score |
score_kind | "distance" | "similarity" | "rank" | None | How to read score |
metadata | dict | file_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_kind | Backend | How to read score |
|---|---|---|
"distance" | Chroma, dense | Lower is closer |
"similarity" | Pinecone, dense | Higher is closer |
"rank" | Hybrid, any backend | Position in the fused list. 1 is best |
None | Weaviate, dense | No 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
| Field | Type | Default | Description |
|---|---|---|---|
mode | "basic" | "agentic" | "basic" | One query, or several rounds |
injection_mode | "system_append" | "user_preamble" | "system_append" | Where the chunk block is written |
max_rounds | int | None | None | Required 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:
| Key | Contents |
|---|---|
results | Injected 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"]])