On this page
LlamaIndex (formerly GPT Index) is a Python and TypeScript framework for building LLM applications over your own data. Where LangChain started from chains and agents, LlamaIndex started from the data side of Retrieval-Augmented Generation (RAG): loading documents, splitting them into chunks, embedding and indexing them, and retrieving the right chunks at question time. Its integrations are published as separate packages on LlamaHub, so a project installs only the readers, vector stores and model providers it uses.
This guide builds a small production-style RAG service with llama-index-core 0.12.30, the release current in mid-April 2025. Every listing comes from a sample that was run against Azure OpenAI and is on GitHub. It covers ingestion that does not re-embed unchanged files, two vector stores, routing between index types, a chat engine with memory, an agent with tools, sub-question decomposition and evaluation, with the timings measured on that run.
Architecture
A LlamaIndex application has two paths. The ingestion path loads documents, splits them into nodes, embeds each node and writes it to a vector store, with a document store that remembers what has already been processed. The query path embeds the question, retrieves the closest nodes, optionally re-ranks or filters them, and asks the LLM to write an answer from those nodes. Chat engines, routers and agents sit on top of query engines; they do not replace them.

%%{init: {'theme':'base','themeVariables':{'primaryColor':'#FFF3E0','primaryTextColor':'#232F3E','primaryBorderColor':'#FF9900','lineColor':'#232F3E','clusterBkg':'#F8FAFC','clusterBorder':'#CBD5E1','edgeLabelBackground':'#FFFFFF','nodeTextColor':'#232F3E'}}}%%
flowchart TD
A["Markdown, PDF, web pages<br/>(SimpleDirectoryReader, LlamaHub readers)"] --> B["IngestionPipeline"]
B --> C["SentenceSplitter<br/>512-token chunks, 50 overlap"]
C --> D["Embedding model"]
D --> E["Vector store<br/>Chroma, Qdrant, ..."]
B --> F["Document store<br/>file id + content hash"]
G["Question"] --> H["Retriever<br/>top-k similarity"]
E --> H
H --> I["Postprocessors<br/>similarity cutoff, re-rank"]
I --> J["Response synthesizer<br/>LLM writes the answer"]
J --> K["Answer + source nodes"]Capabilities
- Readers:
SimpleDirectoryReaderin core for local files, and LlamaHub packages for databases, SaaS APIs and other formats. - Indexes: vector store, summary, tree, keyword table and property graph indexes.
KnowledgeGraphIndexis deprecated in 0.12 in favour ofPropertyGraphIndex. - Query and chat engines: retrieval with post-processing and several response modes; chat engines that condense follow-up questions using memory.
- Agents:
FunctionAgent,ReActAgentandAgentWorkflowinllama_index.core.agent.workflow, with query engines and Python functions as tools. - Evaluation: LLM-judged faithfulness, relevancy and correctness evaluators, and a batch runner.
Installation
Core and each integration are separate packages. The sample pins the versions published by 15 April 2025; requirements.lock in the repository holds the full set, resolved with uv pip install --exclude-newer 2025-04-15.
# Direct dependencies as of 15 April 2025. requirements.lock pins the full set,
# resolved with: uv pip install --exclude-newer 2025-04-15T00:00:00Z -r requirements.txt
llama-index-core==0.12.30
llama-index-llms-openai==0.3.35
llama-index-llms-azure-openai==0.3.2
llama-index-embeddings-openai==0.3.1
llama-index-embeddings-azure-openai==0.3.2
llama-index-vector-stores-chroma==0.4.1
llama-index-vector-stores-qdrant==0.6.0
llama-index-readers-file==0.4.7
llama-index-question-gen-openai==0.3.0
chromadb==1.0.4
qdrant-client==1.13.3
azure-identity==1.21.0
pytest==8.3.5Model configuration
The global Settings object holds the LLM and the embedding model used by every index and engine unless one is passed explicitly. The sample signs in to Azure OpenAI with Microsoft Entra ID through azure-identity, so no API key is stored anywhere, and falls back to OpenAI with an API key. Deployment names come from the environment, and both models get a timeout and retries.
"""Model configuration for every example.
The sample runs against Azure OpenAI with Microsoft Entra ID (no API keys) or
against OpenAI with OPENAI_API_KEY. Deployment and model names are
configuration, never literals in the examples.
RAG_PROVIDER=azure AZURE_OPENAI_ENDPOINT, AZURE_OPENAI_CHAT_DEPLOYMENT,
AZURE_OPENAI_EMBED_DEPLOYMENT, AZURE_OPENAI_API_VERSION,
AZURE_OPENAI_CHAT_MODEL (the model behind the deployment,
used for context-window and token limits)
RAG_PROVIDER=openai OPENAI_API_KEY, OPENAI_CHAT_MODEL, OPENAI_EMBED_MODEL
"""
from __future__ import annotations
import os
from dataclasses import dataclass
from llama_index.core import Settings
DEFAULT_API_VERSION = "2024-10-21"
@dataclass(frozen=True)
class ModelConfig:
provider: str
chat_model: str # deployment name on Azure, model name on OpenAI
embed_model: str
model_name: str = "gpt-4o"
endpoint: str | None = None
api_version: str = DEFAULT_API_VERSION
def _require(name: str) -> str:
value = os.environ.get(name, "").strip()
if not value:
raise RuntimeError(f"{name} is not set")
return value
def load_config() -> ModelConfig:
provider = os.environ.get("RAG_PROVIDER", "azure").strip().lower()
if provider == "azure":
return ModelConfig(
provider="azure",
endpoint=_require("AZURE_OPENAI_ENDPOINT"),
chat_model=_require("AZURE_OPENAI_CHAT_DEPLOYMENT"),
embed_model=_require("AZURE_OPENAI_EMBED_DEPLOYMENT"),
model_name=os.environ.get("AZURE_OPENAI_CHAT_MODEL", "gpt-4o"),
api_version=os.environ.get("AZURE_OPENAI_API_VERSION", DEFAULT_API_VERSION),
)
if provider == "openai":
_require("OPENAI_API_KEY")
return ModelConfig(
provider="openai",
chat_model=os.environ.get("OPENAI_CHAT_MODEL", "gpt-4o"),
embed_model=os.environ.get("OPENAI_EMBED_MODEL", "text-embedding-3-small"),
)
raise RuntimeError(f"RAG_PROVIDER must be 'azure' or 'openai', not {provider!r}")
def configure(config: ModelConfig | None = None, *, timeout: float = 60.0, max_retries: int = 3) -> ModelConfig:
"""Set the global LLM and embedding model, with timeouts and retries on both."""
config = config or load_config()
if config.provider == "azure":
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
from llama_index.embeddings.azure_openai import AzureOpenAIEmbedding
from llama_index.llms.azure_openai import AzureOpenAI
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://cognitiveservices.azure.com/.default"
)
Settings.llm = AzureOpenAI(
model=config.model_name,
engine=config.chat_model,
azure_endpoint=config.endpoint,
api_version=config.api_version,
azure_ad_token_provider=token_provider,
use_azure_ad=True,
temperature=0.0,
timeout=timeout,
max_retries=max_retries,
)
Settings.embed_model = AzureOpenAIEmbedding(
deployment_name=config.embed_model,
azure_endpoint=config.endpoint,
api_version=config.api_version,
azure_ad_token_provider=token_provider,
use_azure_ad=True,
max_retries=max_retries,
embed_batch_size=64,
)
else:
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.llms.openai import OpenAI
Settings.llm = OpenAI(model=config.chat_model, temperature=0.0, timeout=timeout, max_retries=max_retries)
Settings.embed_model = OpenAIEmbedding(model=config.embed_model, max_retries=max_retries, embed_batch_size=64)
return configOn Azure OpenAI, engine is your deployment name and model is the model behind it. LlamaIndex uses model to look up the context window and whether the model supports function calling, so set it even when the deployment has a different name. Left out, it defaults to gpt-35-turbo with a 4,096-token context window.
Ingestion and vector stores
Building an index with VectorStoreIndex.from_documents embeds every document every time the process starts. In production that costs money on each deploy and duplicates nodes when the same files are loaded twice. An IngestionPipeline with a document store and the UPSERTS strategy keys each document by its id (the file path here) and a hash of its content: unchanged files are skipped, changed files are re-embedded and their old nodes replaced.
"""Load, chunk, embed and store documents.
The pipeline keeps a document store next to the vector store, keyed by
file path. Running it again skips unchanged files and re-embeds changed
ones, so restarting the service does not pay for every embedding again.
"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from llama_index.core import Settings, SimpleDirectoryReader, StorageContext, VectorStoreIndex
from llama_index.core.ingestion import DocstoreStrategy, IngestionPipeline
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.schema import BaseNode, Document
from llama_index.core.storage.docstore import SimpleDocumentStore
from llama_index.core.vector_stores.types import BasePydanticVectorStore
DATA_DIR = Path(__file__).resolve().parent.parent / "data"
def load_documents(path: Path = DATA_DIR, subdir: str | None = None) -> list[Document]:
"""Read Markdown files; the folder name becomes a `collection` metadata field."""
root = path / subdir if subdir else path
reader = SimpleDirectoryReader(
input_dir=str(root),
recursive=True,
required_exts=[".md"],
filename_as_id=True,
raise_on_error=True,
file_metadata=lambda p: {"file_name": Path(p).name, "collection": Path(p).parent.name},
)
return reader.load_data()
def splitter() -> SentenceSplitter:
return SentenceSplitter(chunk_size=512, chunk_overlap=50)
def split(documents: list[Document]) -> list[BaseNode]:
return splitter().get_nodes_from_documents(documents)
@dataclass
class IngestResult:
index: VectorStoreIndex
nodes_written: int
def ingest(
documents: list[Document],
vector_store: BasePydanticVectorStore,
docstore_path: Path | None = None,
) -> IngestResult:
"""Upsert documents into `vector_store`; only new or changed files are embedded."""
docstore = (
SimpleDocumentStore.from_persist_path(str(docstore_path))
if docstore_path and docstore_path.exists()
else SimpleDocumentStore()
)
pipeline = IngestionPipeline(
transformations=[splitter(), Settings.embed_model],
vector_store=vector_store,
docstore=docstore,
docstore_strategy=DocstoreStrategy.UPSERTS,
)
written = pipeline.run(documents=documents)
if docstore_path:
docstore_path.parent.mkdir(parents=True, exist_ok=True)
pipeline.docstore.persist(str(docstore_path))
index = VectorStoreIndex.from_vector_store(vector_store)
return IngestResult(index=index, nodes_written=len(written))
def chroma_store(path: Path, collection: str = "documents") -> BasePydanticVectorStore:
import chromadb
from llama_index.vector_stores.chroma import ChromaVectorStore
client = chromadb.PersistentClient(path=str(path))
return ChromaVectorStore(chroma_collection=client.get_or_create_collection(collection))
def qdrant_store(path: Path | None = None, url: str | None = None, collection: str = "documents") -> BasePydanticVectorStore:
"""Local on-disk Qdrant by default; pass `url` for a Qdrant server or Qdrant Cloud."""
from qdrant_client import QdrantClient
from llama_index.vector_stores.qdrant import QdrantVectorStore
client = QdrantClient(url=url) if url else QdrantClient(path=str(path))
return QdrantVectorStore(client=client, collection_name=collection)
def in_memory_index(documents: list[Document]) -> VectorStoreIndex:
return VectorStoreIndex(split(documents), storage_context=StorageContext.from_defaults())On the test run, the first ingestion into Chroma wrote 4 handbook nodes and 1 sales node in 2.92 s; the second run of the same command wrote 0 nodes in 0.01 s. The same happened with a local on-disk Qdrant collection (4 and 1, then 0 and 0). The offline tests also edit one file and check that only its nodes are written again. Chroma, Qdrant and other stores such as Pinecone plug in the same way, through StorageContext or VectorStoreIndex.from_vector_store; only the client construction differs.
QdrantClient(path=...) locks its folder, so a second client on the same path in the same process fails with “already accessed by another instance”. Create one client per collection for the life of the process, as run.py does, or use a Qdrant server when several processes need the same data.
Query engine
A query engine wraps a retriever and a response synthesizer. The sample uses the five closest nodes, the compact response mode (as many retrieved chunks per LLM call as fit) and an optional similarity cutoff.
engine = engines.query_engine(handbook.index)
response = engine.query("What does the Team edition cost, and how many shipment events does it include?")
print(response)
for node in response.source_nodes:
print(f"{node.score:.3f} {node.metadata['file_name']}")The Team edition costs EUR 1,150 per month, billed annually, and includes 400,000 shipment events per month.
0.390 pricing.md
0.308 product-overview.md
0.267 getting-started.md
0.241 teams-and-ownership.mdThe answer took 1.59 s. The highest-scoring source is the pricing page, but the scores are close together, which is normal for cosine similarity over short documents. Use the source list to check what the answer was built from, and a similarity cutoff only after measuring where relevant and irrelevant chunks fall for your own data.
Index types and routing
Different questions need different indexes. A vector index finds specific facts; a summary index sends every node to the LLM, which is what an overview question needs; a property graph index stores entities and relationships extracted by the LLM, which suits questions about who owns or depends on what. A RouterQueryEngine asks the LLM to pick one tool per question from their descriptions.
"""Query engines, router, chat engine, agent and sub-question engine."""
from __future__ import annotations
from datetime import date
from llama_index.core import PropertyGraphIndex, Settings, SummaryIndex, VectorStoreIndex
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.core.chat_engine.types import BaseChatEngine
from llama_index.core.indices.property_graph import SimpleLLMPathExtractor
from llama_index.core.memory import ChatMemoryBuffer
from llama_index.core.postprocessor import SimilarityPostprocessor
from llama_index.core.query_engine import RouterQueryEngine, SubQuestionQueryEngine
from llama_index.core.schema import BaseNode, Document
from llama_index.core.selectors import LLMSingleSelector
from llama_index.core.tools import FunctionTool, QueryEngineTool
from .safe_calc import calculate
def query_engine(index: VectorStoreIndex, top_k: int = 5, min_score: float | None = None):
postprocessors = [SimilarityPostprocessor(similarity_cutoff=min_score)] if min_score else []
return index.as_query_engine(
similarity_top_k=top_k,
response_mode="compact",
node_postprocessors=postprocessors,
)
def property_graph(documents: list[Document], max_paths_per_chunk: int = 10) -> PropertyGraphIndex:
"""Entity graph built by the LLM. One extraction call per chunk."""
return PropertyGraphIndex.from_documents(
documents,
kg_extractors=[SimpleLLMPathExtractor(llm=Settings.llm, max_paths_per_chunk=max_paths_per_chunk, num_workers=4)],
embed_kg_nodes=True,
)
def router(vector_index: VectorStoreIndex, nodes: list[BaseNode], graph: PropertyGraphIndex) -> RouterQueryEngine:
summary_index = SummaryIndex(nodes)
tools = [
QueryEngineTool.from_defaults(
query_engine=query_engine(vector_index),
name="facts",
description="Specific facts from the product, pricing and onboarding documents.",
),
QueryEngineTool.from_defaults(
query_engine=summary_index.as_query_engine(response_mode="tree_summarize"),
name="summary",
description="Summaries and overviews that need every document, not a few passages.",
),
QueryEngineTool.from_defaults(
query_engine=graph.as_query_engine(include_text=True),
name="relationships",
description="Who owns, leads, reports to or depends on what: people, teams and services.",
),
]
return RouterQueryEngine(selector=LLMSingleSelector.from_defaults(), query_engine_tools=tools, verbose=False)
SYSTEM_PROMPT = (
"You answer questions about Larkfield Insight using only the retrieved documents. "
"If the documents do not contain the answer, say so. Name the document each fact comes from."
)
def chat_engine(index: VectorStoreIndex, token_limit: int = 3000) -> BaseChatEngine:
return index.as_chat_engine(
chat_mode="condense_plus_context",
memory=ChatMemoryBuffer.from_defaults(token_limit=token_limit),
system_prompt=SYSTEM_PROMPT,
similarity_top_k=4,
)
def today() -> str:
"""Return today's date in ISO format."""
return date.today().isoformat()
def agent(handbook_index: VectorStoreIndex, sales_index: VectorStoreIndex) -> FunctionAgent:
tools = [
QueryEngineTool.from_defaults(
query_engine=query_engine(handbook_index),
name="product_docs",
description="Product features, editions, pricing and onboarding for Larkfield Insight.",
),
QueryEngineTool.from_defaults(
query_engine=query_engine(sales_index),
name="sales_results",
description="Quarterly revenue, new subscriptions and retention for 2024.",
),
FunctionTool.from_defaults(fn=calculate),
FunctionTool.from_defaults(fn=today),
]
return FunctionAgent(
tools=tools,
llm=Settings.llm,
system_prompt=SYSTEM_PROMPT + " Use the calculator for any arithmetic instead of doing it yourself.",
)
def sub_question_engine(handbook_index: VectorStoreIndex, sales_index: VectorStoreIndex) -> SubQuestionQueryEngine:
tools = [
QueryEngineTool.from_defaults(
query_engine=query_engine(handbook_index),
name="product_docs",
description="Product features and editions of Larkfield Insight.",
),
QueryEngineTool.from_defaults(
query_engine=query_engine(sales_index),
name="sales_results",
description="Sales results by quarter and by edition for 2024.",
),
]
return SubQuestionQueryEngine.from_defaults(query_engine_tools=tools, use_async=True)Building the property graph for the four handbook documents took 5.09 s (one extraction call per chunk). The router chose the expected tool for all three test questions:
| Question | Tool chosen | Time | Answer |
|---|---|---|---|
| What is the overage charge per 1,000 events on the Team edition? | facts (vector) | 2.29 s | EUR 2.50 |
| Give me an overview of what the Larkfield Insight documentation covers. | summary | 3.79 s | A four-part overview: getting started, product, pricing, teams |
| Who approves new carrier connectors, and who does that person report to? | relationships (graph) | 2.44 s | Priya Raman, who reports to the CTO, Declan Walsh |
TreeIndex and KeywordTableIndex are still in core, but both call the LLM while the index is being built, which gets expensive on real corpora. A summary index with tree_summarize covers most summarisation needs, and a hybrid vector store covers keyword matching. KnowledgeGraphIndex raises a deprecation warning in 0.12; build new graphs with PropertyGraphIndex.
Chat engine with memory
The condense_plus_context chat mode rewrites each follow-up into a standalone question using the conversation so far, retrieves for that question, and answers with the retrieved context and the chat history. ChatMemoryBuffer caps the history by tokens.
chat = engines.chat_engine(handbook.index)
print(chat.chat("Which editions support single sign-on?"))
print(chat.chat("And how much does the cheaper of those cost per month?"))The first answer named Team and Enterprise (0.96 s). The second resolved “the cheaper of those” to the Team edition and answered EUR 1,150 per month, noting that Enterprise is quoted individually (1.89 s). Both answers named the document they came from, as the system prompt asks.
Agent with tools
In 0.12 the agent classes in llama_index.core.agent.workflow run as workflows: FunctionAgent uses the model’s native function calling, ReActAgent uses a text reasoning loop for models without it, and AgentWorkflow coordinates several agents. The agent in the sample has two query engine tools, a calculator and a date function. It runs asynchronously and streams events, so the tool calls can be logged.
agent = engines.agent(handbook.index, sales.index)
async def main():
handler = agent.run(user_msg="What was Q3 2024 revenue, and what was the growth rate compared with Q2 2024?")
async for event in handler.stream_events():
if isinstance(event, ToolCallResult):
print(event.tool_name, event.tool_kwargs, event.tool_output)
print(await handler)
asyncio.run(main())sales_results {'input': 'Q2 2024 revenue'} -> The revenue for Q2 2024 was 4,200,000 EUR.
sales_results {'input': 'Q3 2024 revenue'} -> The revenue for Q3 2024 was 4,830,000 EUR.
calculate {'expression': '(4830000 - 4200000) / 4200000 * 100'} -> 15
The revenue for Q3 2024 was 4,830,000 EUR. The growth rate compared with Q2 2024,
which had a revenue of 4,200,000 EUR, was 15%.The agent made three tool calls and answered in 4.85 s. The arithmetic went through the calculator rather than the model, because the system prompt tells it to use the tool.
A calculator tool written as eval(expression) executes whatever text the model sends, and the model’s text can be steered by a prompt or by a retrieved document. The sample parses the expression with Python’s ast module and allows only numbers and arithmetic operators; its tests check that __import__('os').system('id'), open(...) and a huge exponent are refused.
"""Arithmetic for an agent tool without eval().
An agent passes model-generated text to its tools, so a calculator built on
eval() runs whatever the model (or a prompt-injected document) writes. This
evaluator walks the parsed expression and allows numbers, + - * / // % **,
unary signs and parentheses only.
"""
from __future__ import annotations
import ast
import operator
_BINARY = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
ast.FloorDiv: operator.floordiv,
ast.Mod: operator.mod,
ast.Pow: operator.pow,
}
_UNARY = {ast.UAdd: operator.pos, ast.USub: operator.neg}
MAX_EXPONENT = 100
MAX_LENGTH = 200
def evaluate(expression: str) -> float:
if len(expression) > MAX_LENGTH:
raise ValueError("expression too long")
tree = ast.parse(expression.replace(",", ""), mode="eval")
def walk(node: ast.AST) -> float:
if isinstance(node, ast.Expression):
return walk(node.body)
if isinstance(node, ast.Constant) and type(node.value) in (int, float):
return node.value
if isinstance(node, ast.BinOp) and type(node.op) in _BINARY:
left, right = walk(node.left), walk(node.right)
if isinstance(node.op, ast.Pow) and abs(right) > MAX_EXPONENT:
raise ValueError("exponent too large")
return _BINARY[type(node.op)](left, right)
if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY:
return _UNARY[type(node.op)](walk(node.operand))
raise ValueError(f"unsupported element: {type(node).__name__}")
return walk(tree)
def calculate(expression: str) -> str:
"""Evaluate an arithmetic expression such as (4830000 - 4200000) / 4200000 * 100."""
try:
result = evaluate(expression)
except (ValueError, SyntaxError, ZeroDivisionError, OverflowError) as exc:
return f"Error: {exc}"
return f"{result:.10g}"Sub-question query engine
A SubQuestionQueryEngine splits a question that spans several sources into sub-questions, sends each to the right query engine, and combines the answers. It needs the separate llama-index-question-gen-openai package; without it, from_defaults raises an ImportError.
%%{init: {'theme':'base','themeVariables':{'signalColor':'#0073BB','signalTextColor':'#0F172A','actorBkg':'#FFF3E0','actorBorder':'#FF9900','actorTextColor':'#232F3E','noteBkgColor':'#FFF8E7','noteBorderColor':'#FF9900','noteTextColor':'#232F3E'}}}%%
sequenceDiagram
participant U as Application
participant S as SubQuestionQueryEngine
participant P as product_docs engine
participant R as sales_results engine
U->>S: Which edition sells best, what does it include, what share of revenue?
S->>R: Which edition sold the best in 2024?
S->>P: What features are in the best-selling edition?
S->>R: What share of 2024 revenue did it produce?
R-->>S: Team edition, 61 percent of 2024 revenue
P-->>S: Feature list of the Team edition
S-->>U: Combined answer with the three sub-answers as sourcesOn the test run the engine generated three sub-questions, two for the sales index and one for the product documents, and answered in 4.17 s: the Team edition, its features and 61% of 2024 revenue, all of which match the source documents.
Evaluation
LlamaIndex’s evaluators use an LLM as a judge. FaithfulnessEvaluator checks that the answer is supported by the retrieved context, RelevancyEvaluator that the answer and context match the question, and CorrectnessEvaluator scores the answer from 1 to 5 against a reference answer. The sample adds a plain string check for the facts each answer must contain, so a retrieval regression shows up even if a judge is lenient. The evaluators are asynchronous, so the batch runs inside asyncio.run.
"""Evaluate a query engine with LLM judges and with plain string checks.
The judges (faithfulness, relevancy, correctness) use the configured LLM.
Each question also carries facts that must appear in the answer, checked in
code, so a regression in retrieval shows up even when a judge is lenient.
"""
from __future__ import annotations
import asyncio
import re
from dataclasses import dataclass
from llama_index.core.evaluation import (
BatchEvalRunner,
CorrectnessEvaluator,
FaithfulnessEvaluator,
RelevancyEvaluator,
)
@dataclass(frozen=True)
class EvalCase:
question: str
reference: str
must_contain: tuple[str, ...]
CASES: list[EvalCase] = [
EvalCase("What is the monthly price of the Team edition?", "EUR 1,150 per month, billed annually.", ("1,150",)),
EvalCase("How many shipment events per month does the Starter edition include?", "50,000 shipment events.", ("50,000",)),
EvalCase("Which carriers have connectors?", "DHL, UPS, FedEx, DPD, An Post and GLS.", ("DHL", "An Post", "GLS")),
EvalCase("Can the data residency region be changed after a workspace is created?", "No, it cannot be changed later.", ("cannot",)),
EvalCase("How far back do carrier connectors back-fill events?", "The previous 90 days.", ("90",)),
EvalCase("Which editions support single sign-on?", "Team and Enterprise only.", ("Team", "Enterprise")),
]
@dataclass
class CaseResult:
question: str
answer: str
faithful: bool | None
relevant: bool | None
correctness: float | None
missing: list[str]
def string_check(answer: str, must_contain: tuple[str, ...]) -> list[str]:
normalised = re.sub(r"\s+", " ", answer)
return [fact for fact in must_contain if fact.lower() not in normalised.lower()]
async def evaluate(query_engine, cases: list[EvalCase] = CASES, workers: int = 4) -> list[CaseResult]:
runner = BatchEvalRunner(
{"faithfulness": FaithfulnessEvaluator(), "relevancy": RelevancyEvaluator()},
workers=workers,
)
questions = [c.question for c in cases]
responses = [await query_engine.aquery(q) for q in questions]
judged = await runner.aevaluate_responses(questions, responses=responses)
correctness = CorrectnessEvaluator()
results = []
for i, case in enumerate(cases):
answer = str(responses[i])
scored = await correctness.aevaluate(query=case.question, response=answer, reference=case.reference)
results.append(
CaseResult(
question=case.question,
answer=answer,
faithful=judged["faithfulness"][i].passing,
relevant=judged["relevancy"][i].passing,
correctness=scored.score,
missing=string_check(answer, case.must_contain),
)
)
return results
def run(query_engine, cases: list[EvalCase] = CASES) -> list[CaseResult]:
return asyncio.run(evaluate(query_engine, cases))All six questions passed faithfulness and relevancy, scored 5.0 for correctness and contained every required fact. The whole evaluation took 16.92 s. Six hand-written questions over five documents are a smoke test, not a benchmark; a real evaluation set needs questions that the corpus does not answer, questions that need several documents, and enough of each to see a regression.

Measured performance
These are wall-clock times from one run of python run.py all against Azure OpenAI in Sweden Central, using gpt-4.1-mini and text-embedding-3-small over the five sample documents. They are single measurements on a tiny corpus, useful for comparing the engines with each other rather than as latency targets.
| Operation | Time | Model calls involved |
|---|---|---|
| Ingest 5 documents (first run) | 2.92 s | Embeddings for 5 nodes |
| Ingest again, nothing changed | 0.01 s | None |
| Query engine, one question | 1.59 s | 1 embedding, 1 completion |
| Property graph build, 4 documents | 5.09 s | 1 extraction per chunk, embeddings |
| Router, one question | 2.29 to 3.79 s | Selector, then the chosen engine |
| Chat turn | 0.96 to 1.89 s | Condense, retrieve, answer |
| Agent, 3 tool calls | 4.85 s | Several completions and 2 query engines |
| Sub-question engine, 3 sub-questions | 4.17 s | Question generation, 3 queries in parallel, synthesis |
| Evaluation, 6 questions and 3 judges | 16.92 s | 6 queries, 18 judge calls |
Production considerations
- Ingest once, upsert after. Keep the document store next to the vector store and run the pipeline on change, not on every start. Ids must be stable:
filename_as_id=Trueworks for files, a source system’s primary key for records. - Pin versions. Core and each integration release separately and often. Pin the full set with a lock file and upgrade on purpose, re-running the evaluation set.
- Use identity, not keys. On Azure,
azure_ad_token_providerwith a managed identity or workload identity removes the API key from configuration entirely. - Set timeouts and retries on every model client. The defaults can wait a long time on a slow response; a retrieval service should fail fast and retry with backoff.
- Treat retrieved text as untrusted. Documents can contain instructions. Keep tools narrow, validate their arguments (as the calculator does) and never give an agent a tool that executes code or shell commands from model output.
- Measure before tuning. Chunk size, top-k and similarity cutoffs depend on the corpus. Change one at a time and re-run the evaluation set.
When to use LlamaIndex
| Situation | Fit |
|---|---|
| RAG over your own documents, with control over chunking, retrieval and evaluation | Good fit; this is what the framework is built around. |
| Several data sources behind one question interface | Good fit: routers, sub-question engines and agents with query engine tools. |
| Long-running, branching agent workflows with human approval steps | LlamaIndex workflows can do it; LangGraph is the more common choice for complex state machines. |
| A managed RAG service with no retrieval code | Consider Amazon Bedrock Knowledge Bases, Azure AI Search with its integrated vectorization, or LlamaCloud. |
| Simple prompt chains without retrieval | A model SDK on its own is usually enough. |
Key takeaways
- Use an
IngestionPipelinewith a document store so restarts and re-deploys do not re-embed unchanged documents; on the test run the second ingestion wrote 0 nodes in 0.01 s. - Set both
engineandmodelon Azure OpenAI; the model name drives context-window and function-calling behaviour. - Route between index types by question type: vector for facts, summary for overviews, property graph for relationships. The router picked correctly for all three test questions.
- Never build an agent tool on
eval(); parse and whitelist instead.FunctionAgentmade the arithmetic go through the safe calculator. - Pair LLM judges with plain checks for required facts, and keep a small evaluation set in the repository so every upgrade is re-tested.
Which part of your RAG pipeline needed the most tuning: chunking, retrieval or the evaluation set? Let me know in the comments.
The sample was installed from the packages published on PyPI by 15 April 2025 (llama-index-core 0.12.30, full pins in requirements.lock) on Python 3.12. Thirteen offline tests cover the calculator, document loading, chunking, re-ingestion into Chroma and local Qdrant, the string check and configuration errors. Every example then ran once against Azure OpenAI in Sweden Central with Microsoft Entra ID authentication, using gpt-4.1-mini (2025-04-14) for chat and text-embedding-3-small for embeddings; the article’s outputs and timings are copied from that run. The OpenAI provider path in settings.py was not run. The documents are synthetic: Larkfield Analytics, its products, figures and people are invented.
Glossary
- Node
- A chunk of a document with its metadata and relationships; the unit LlamaIndex embeds and retrieves.
- IngestionPipeline
- A sequence of transformations (splitting, embedding) that writes nodes to a vector store, optionally de-duplicating with a document store.
- Document store
- Storage for document ids and content hashes, used to skip or replace documents on re-ingestion.
- Vector store
- A database of embeddings searched by similarity, such as Chroma or Qdrant.
- Query engine
- A retriever plus a response synthesizer: it fetches nodes and asks the LLM to answer from them.
- Response mode
- How retrieved chunks are sent to the LLM, for example
compactortree_summarize. - Router query engine
- A query engine that asks the LLM to pick one of several query engines from their descriptions.
- Property graph index
- An index of entities and relationships extracted from text by the LLM, queried by graph and by embedding.
- Chat engine
- A conversational wrapper that uses chat history;
condense_plus_contextrewrites follow-ups into standalone questions. - FunctionAgent
- An agent that calls tools through the model’s native function-calling API.
- Sub-question query engine
- A query engine that splits a question into sub-questions for different engines and combines the answers.
- Faithfulness
- Whether an answer is supported by the retrieved context, as judged by an LLM evaluator.
The complete sample for this article is on GitHub: nithinmohantk/blog-samples-working-repo/llamaindex-production-rag. Clone it with git clone https://github.com/nithinmohantk/blog-samples-working-repo.git and open the llamaindex-production-rag folder. Its README says how to run it and what has been verified.
References & Further Reading
- → LlamaIndex documentation— Guides and API reference
- → run-llama/llama_index on GitHub— Source code, including the 0.12.30 release
- → llama-index-core on PyPI— Release 0.12.30, published 10 April 2025
- → LlamaHub— Reader, vector store and model integrations
- → Chroma— Open-source vector database used in the sample
- → Qdrant Python client— Client used for the local Qdrant store
- → Sample code for this article— Tested sample, results and screenshots
Discover more from C4: Container, Code, Cloud & Context
Subscribe to get the latest posts sent to your email.