Evaluate a LangChain RAG Pipeline with Future AGI
Build a LangChain RAG pipeline with three retrieval strategies, trace it with traceAI, and score retrieval and groundedness with fi.evals.
Does splitting a return policy differently help an assistant answer the same question? Build three LangChain retrieval strategies over the same Ridgeline Outfitters policies. Trace each answer in Observe, then use Agent Learning Kit to compare context relevance, chunk utilization, and groundedness.
| Time | Difficulty | Packages |
|---|---|---|
| 30 min | Intermediate | Agent Learning Kit, LangChain, Chroma, traceAI |
- Python 3.12 and a terminal with Bash or Zsh
FI_API_KEYandFI_SECRET_KEYfrom your Future AGI workspace for tracing and Turing evaluations- An
OPENAI_API_KEYwith access togpt-4o-miniandtext-embedding-3-smallfor answers and embeddings
Install
python3.12 -m venv .venv
source .venv/bin/activate
python -m pip install agent-learning-kit==0.3.7 fi-instrumentation-otel==1.5.1 traceai-langchain==0.2.4 langchain-openai==1.8.5 langchain-chroma==1.1.0 langchain-text-splitters==1.1.3 langchain-experimental==0.4.2 matplotlib
export FI_API_KEY="your-api-key"
export FI_SECRET_KEY="your-secret-key"
export OPENAI_API_KEY="your-openai-key"
For a self-hosted installation, set FI_BASE_URL to your API base URL and export FI_TRACES_URL=https://your-collector.example.com to your collector base URL.
Tutorial
Run the Python blocks in order in the same Python session.
Build the baseline RAG pipeline
Use three short policies as a fixed corpus. A new collection name for each run keeps chunks from earlier runs out of the comparison.
from uuid import UUID, uuid4
from langchain_chroma import Chroma
from langchain_core.documents import Document
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_text_splitters import RecursiveCharacterTextSplitter
llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
embeddings = OpenAIEmbeddings(model="text-embedding-3-small", check_embedding_ctx_length=False)
policies = {
"returns": "Unused boots can be returned within 30 days of delivery. Put both boots in their original box. Returns are free if you use the prepaid label. Refunds take five business days after inspection.",
"repairs": "A broken buckle on a daypack qualifies for repair. Send a photo of the buckle with your request. A buckle repair takes ten business days after the pack arrives. Repairs ship back at no charge.",
"shipping": "Standard delivery takes five business days. Express delivery takes two business days. Orders over $75 qualify for free standard delivery. Express delivery always costs $12.",
}
docs = [Document(page_content=text, metadata={"source": source}) for source, text in policies.items()]
run_id = uuid4().hex
def index_chunks(chunks, name):
store = Chroma.from_documents(chunks, embeddings, collection_name=f"{name}-{run_id}")
return store.as_retriever(search_kwargs={"k": 2})
splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=20)
recursive_splits = splitter.split_documents(docs)
recursive_retriever = index_chunks(recursive_splits, "recursive")
print(f"Indexed {len(recursive_splits)} chunks from {len(docs)} policies") Configure tracing and evaluation
Register the LangChain instrumentor before you invoke the retriever or the chat model. Each answer will have a parent span in Observe with its retrieval and model calls underneath it.
import json
from pathlib import Path
from statistics import mean
from fi.evals import evaluate
from fi_instrumentation import register
from fi_instrumentation.fi_types import ProjectType
from traceai_langchain import LangChainInstrumentor
provider = register(project_type=ProjectType.OBSERVE, project_name="ridgeline-rag-strategies", verbose=False)
LangChainInstrumentor().instrument(tracer_provider=provider)
tracer = provider.get_tracer("rag-cookbook")The relevance judge needs the question and passages, utilization needs the passages and answer, and groundedness needs all three. Keep the evaluation IDs alongside the scores so you can look up a surprising result later.
Note
Turing models run on Future AGI’s managed service. On Future AGI Cloud, each Turing evaluation uses AI credits from your organization’s plan. A self-hosted deployment needs a license that includes the turing_models feature; its Turing calls use that license’s managed AI credits and are not available in an air-gapped install. On a self-hosted install, set FI_BASE_URL to your API URL first. Without it, your keys and inputs go to Future AGI Cloud.
metrics = ("context_relevance", "chunk_utilization", "groundedness")
def score(question, context, answer):
inputs = (
{"input": question, "context": context},
{"context": context, "output": answer},
{"input": question, "context": context, "output": answer},
)
scores, eval_ids = {}, {}
for name, fields in zip(metrics, inputs):
result = evaluate(name, model="turing_flash", **fields)
if result.score is None or not 0 <= result.score <= 1:
raise ValueError(f"No valid {name} score: {result.error or result.reason}")
scores[name] = result.score
eval_ids[name] = result.metadata["eval_id"]
return scores, eval_ids Run the baseline and score it
Use the same questions, answer prompt, and judges for every strategy. Keep the passages, answer, and trace ID for each question, not just the average.
questions = [
"When can I return unused boots, and when will I get my refund?",
"What should I send for a daypack buckle repair and how long does repair take?",
"Is two-business-day shipping free on an $80 order?",
]
rows = []
def compare(name, get_docs):
group = []
for question in questions:
with tracer.start_as_current_span(f"RAG answer: {name}") as span:
retrieved = get_docs(question)
context = "\n\n".join(doc.page_content for doc in retrieved)
answer = llm.invoke([
("system", "Answer in one or two sentences using only the provided policies. "
"Say what is unknown if the policies do not answer the question."),
("human", f"Policies:\n{context}\n\nQuestion: {question}"),
]).content
scores, eval_ids = score(question, context, answer)
for metric, value in scores.items():
span.set_attribute(f"rag.{metric}", value)
group.append(dict(strategy=name, question=question, context=context, answer=answer,
scores=scores, eval_ids=eval_ids,
trace_id=str(UUID(int=span.get_span_context().trace_id))))
rows.extend(group)
return {key: mean(row["scores"][key] for row in group) for key in metrics}
recursive_avg = compare("Recursive", recursive_retriever.invoke)
print(recursive_avg)Context relevance asks whether retrieval found useful evidence. Groundedness asks whether the answer stays within that evidence. An answer can be grounded but incomplete if retrieval missed a relevant passage.
Switch to semantic chunking
SemanticChunker looks for changes in meaning between sentences using embeddings. Re-index the same three policies and retrieve two chunks per question, just as in the baseline.
from langchain_experimental.text_splitter import SemanticChunker
semantic_chunker = SemanticChunker(embeddings, breakpoint_threshold_type="percentile")
semantic_splits = semantic_chunker.split_documents(docs)
semantic_retriever = index_chunks(semantic_splits, "semantic")
semantic_avg = compare("Semantic", semantic_retriever.invoke)
print(semantic_avg) Add sub-question decomposition
Use the semantic index again, but ask the model to split each question first. Retrieve up to two chunks per sub-question and remove duplicates before passing them to the same answer prompt. This variant costs an extra chat call per question and may retrieve more context; better scores are not guaranteed.
def decomposed_docs(question):
message = llm.invoke([
("system", "Split the question into at most two standalone search questions. "
"Return only the questions, one per line."),
("human", question),
])
parts = [line.strip() for line in message.content.splitlines() if line.strip()][:2]
unique = {}
for part in parts or [question]:
for doc in semantic_retriever.invoke(part):
unique[(doc.metadata["source"], doc.page_content)] = doc
return list(unique.values())
subq_avg = compare("Sub-question", decomposed_docs)
print(subq_avg) Compare the three strategies
Print the exact averages and save the comparison chart and question-level records. Groundedness is a pass/fail judgment, so its average is the fraction of answers that passed. Three questions illustrate the method; they do not establish which strategy is best for your support traffic.
import matplotlib.pyplot as plt
strategies = {"Recursive": recursive_avg, "Semantic": semantic_avg, "Sub-question": subq_avg}
print("Metric Recursive Semantic Sub-question")
fig, axes = plt.subplots(1, 3, figsize=(10, 3.5), sharey=True, layout="constrained")
for ax, metric in zip(axes, metrics):
values = [scores[metric] for scores in strategies.values()]
print(f"{metric:<18}" + "".join(f"{value:11.2f}" for value in values))
ax.barh(list(strategies), values, height=0.45, color="0.35")
ax.set(xlim=(0, 1), title=metric.replace("_", " "), xlabel="Mean score")
axes[0].invert_yaxis()
fig.savefig("rag-comparison.png", dpi=150)
plt.close(fig)
Path("rag-answers.json").write_text(json.dumps(rows, indent=2), encoding="utf-8")
provider.force_flush() Inspect the traces in the dashboard
Open Observe and select ridgeline-rag-strategies. Match a trace_id in rag-answers.json to its trace. Inspect the retrieved chunks and model answer, then check the three rag.* scores on the parent span. These are attributes you recorded from the kit’s evaluations, not a second set of dashboard judgments.
Troubleshooting
| Symptom | What to check |
|---|---|
| An embedding or chat call fails | Check that your OpenAI key has access to both models. |
| No score for a metric | Check the Future AGI keys and the metric’s required fields. A missing score is not zero. |
| The averages tie | Compare the passages and answers for the same question. Both strategies can find the same evidence. |
| No traces in Observe | Check the workspace, project name, and collector URL. Run the last block to flush buffered spans. |
Next: Evaluate a RAG pipeline.
Questions & Discussion