A retrieval-augmented generation (RAG) application can answer with the wrong policy because it fetched the wrong document or misread the right one. A LangSmith evaluation runs the same questions against the application and scores the answers and retrieved documents separately.
Reference answers capture what each question should return, and document IDs identify the passages that support those answers. When you rebuild the search index, stable IDs let you compare retrieval scores against the same passages.
The Python SDK can run an evaluation locally with a dataset in memory. A small extractive application and code-based evaluators let you check both scores without an API key or model calls.
Steps to evaluate a RAG application in LangSmith:
- Install the LangSmith SDK in your Python project environment.
python -m pip install langsmith==0.14.9
The commands use Python 3.12 and LangSmith SDK 0.14.9.
- Create
evaluate_rag.pyin your project with the evaluation dataset.- evaluate_rag.py
import argparse import re from uuid import uuid4 from langsmith import Client, evaluate from langsmith.schemas import Example dataset = [ Example( id=uuid4(), inputs={"question": "What is the returns window?"}, outputs={"answer": "30 days", "document_id": "returns-window"}, ), Example( id=uuid4(), inputs={"question": "What is the shipping time?"}, outputs={"answer": "2 business days", "document_id": "shipping-time"}, ), ]
Each question goes into
inputs. The reference answer and expected document ID go into the example'soutputs, where the evaluators can read them after the application runs. - Paste the searchable corpus and RAG function on a new line at the end of
evaluate_rag.py.- evaluate_rag.py
corpus = { "returns-window": "Returns window: 30 days", "returns-postage": "Returns postage: $5", "shipping-time": "Shipping time: 2 business days", } def terms(text): return set(re.findall(r"[a-z0-9]+", text.lower())) def retrieve(question, documents): query = terms(question) ranked = sorted( documents, key=lambda doc_id: len(query & terms(documents[doc_id])), reverse=True, ) return [doc_id for doc_id in ranked[:1] if query & terms(documents[doc_id])] def rag(inputs, documents): retrieved_ids = retrieve(inputs["question"], documents) context = documents[retrieved_ids[0]] if retrieved_ids else "" answer = context.partition(": ")[2] return {"answer": answer, "retrieved_ids": retrieved_ids}
The retriever ranks passages by shared words. The highest-ranked passage with a match supplies the answer text after the colon. The application returns the ID of the passage it actually found.
- Paste the answer and retrieval evaluators on a new line at the end of
evaluate_rag.py.- evaluate_rag.py
def answer_exact_match(outputs, reference_outputs): answer = outputs["answer"].strip().casefold() expected = reference_outputs["answer"].strip().casefold() return {"key": "answer_exact_match", "score": int(answer == expected)} def retrieval_hit_at_1(outputs, reference_outputs): top_ids = outputs["retrieved_ids"][:1] hit = reference_outputs["document_id"] in top_ids return {"key": "retrieval_hit_at_1", "score": int(hit)}
Exact match ignores case and whitespace at the ends of the answer. A paraphrase can still score 0. Hit at 1 checks only the first retrieved ID against the labeled document. Semantic graders can score open-ended answers and judge retrieval relevance.
Related: Semantic grading for RAG applications in LangSmith - Paste the LangSmith experiment runner on a new line at the end of
evaluate_rag.py.- evaluate_rag.py
def main(): parser = argparse.ArgumentParser() parser.add_argument("--omit-doc", choices=corpus) args = parser.parse_args() documents = { doc_id: text for doc_id, text in corpus.items() if doc_id != args.omit_doc } def target(inputs): return rag(inputs, documents) results = evaluate( target, data=dataset, evaluators=[answer_exact_match, retrieval_hit_at_1], client=Client(auto_batch_tracing=False), upload_results=False, max_concurrency=0, ) rows = list(results) passed = len(rows) == len(dataset) for row in rows: outputs = row["run"].outputs or {} scores = { item.key: item.score for item in row["evaluation_results"]["results"] } print(row["example"].inputs["question"]) print(f' answer={outputs.get("answer")!r} ids={outputs.get("retrieved_ids")}') for key in ("answer_exact_match", "retrieval_hit_at_1"): score = scores.get(key) print(f" {key}={score}") if score != 1: passed = False return 0 if passed else 1 if __name__ == "__main__": raise SystemExit(main())
With
upload_results=False, the SDK returns the experiment results locally. This option is beta in SDK 0.14.9. The explicit client disables background trace batching.For an existing RAG pipeline, adapt
targetto passinputs[“question”]to the application and return itsanswerand orderedretrieved_ids. The same evaluators can then score its output against your labeled examples. Any remote model or retriever in that pipeline still makes its own network calls. - Run the baseline experiment against the complete corpus.
LANGSMITH_TRACING=false python evaluate_rag.py
Both questions should report
answer_exact_match=1andretrieval_hit_at_1=1. The script reads those scores from the SDK's result rows. A missing row or a missing or failing score produces a nonzero exit status, which a local CI job can use to fail the build. - Run the experiment with the returns-window document omitted.
LANGSMITH_TRACING=false python evaluate_rag.py --omit-doc returns-window
##### snipped ##### What is the returns window? answer='$5' ids=['returns-postage'] answer_exact_match=0 retrieval_hit_at_1=0 What is the shipping time? answer='2 business days' ids=['shipping-time'] answer_exact_match=1 retrieval_hit_at_1=1
The returns question now retrieves the postage policy, and both of its scores drop to 0. The shipping scores stay at 1. The script exits with status 1 for the regression.