Skip to main content























Tutorial: Building a production-ready document QA system with LangChain
Build a RAG pipeline that answers questions from financial documents, then use Weave to systematically detect and eliminate hallucinations at every stage.
Last updated: June 1, 2026

Image By Author
A financial analyst asks your RAG system: "What was Apple's total revenue in FY2022?" The system retrieves the right SEC filing, finds the relevant paragraph, and confidently responds: "$394.3 billion." The actual number is $394.3 billion, so this one is correct. But the next question, "What was Microsoft's operating income growth rate year over year?", gets a confident "12.4%" response, even though the retrieved context never mentions a specific percentage. The system fabricated a plausible number. In finance, a single hallucinated figure can cascade into flawed investment decisions, regulatory violations, or reputational damage.
This is the core problem with RAG: retrieval augmented generation does not eliminate hallucinations. It gives the LLM access to relevant documents, but the model can still fabricate details not present in the context, misattribute information across chunks, or generate confident answers when the retrieved passages are insufficient. A study using FinanceBench found that GPT-4-Turbo incorrectly answered 81% of financial questions, and the RAGAS Faithfulness metric failed to catch hallucinations in 83.5% of cases. The failure is not retrieval. The failure is trusting the generation without verification.
Table of contents
Why catching hallucinations requires more than a better promptPrerequisitesTutorial: The document QA RAG pipeline we are buildingStep 1: Setting up the environmentStep 2: Loading and chunking the financial documentsStep 3: Building the retrieval pipelineStep 4: Debugging with tracesStep 5: Evaluating for hallucinations before productionStep 6: Adding guardrails for runtime safetyStep 7: Monitoring your document QA system in productionWhat to watch forConclusionNext steps
Why catching hallucinations requires more than a better prompt
Catching hallucinations requires tooling at every stage, not just a better prompt. During development of your document QA system, you need visibility into what chunks were retrieved and how the LLM used them. Before deployment, you need systematic tests against known answers to measure hallucination rates. At runtime, you need guardrails that block answers when the evidence is insufficient. In production, you need ongoing monitoring to catch quality drift as documents and queries change.
In this tutorial, we will build a financial document QA system using LangChain and W&B Inference, test it against real SEC filing questions from FinanceBench, and integrate four Weave products. By the end, you will have a pipeline that is not just functional but observable, tested, safe, and monitored.
Prerequisites
Before starting, make sure you have the following:
- Python 3.9+
- Basic familiarity with RAG concepts (retrieval, embeddings, vector stores)
Tutorial: The document QA RAG pipeline we are building
Before writing code, here is the high-level architecture.

Image By Author
The dataset is FinanceBench, a publicly available benchmark of 150 expert-annotated question-answer pairs sourced from real SEC filings. Each example includes a question, the source document, an evidence string (the exact passage that supports the answer), and a ground-truth answer written by financial analysts. This makes it ideal for hallucination testing, as we can verify whether the system's answer is grounded in the evidence.
For the LLM, we will use Qwen3-235B-A22B-Instruct via W&B Inference, which exposes an OpenAI-compatible API, allowing us to use the standard OpenAI SDK.
For retrieval, we will use LangChain's document loading, text splitting, and FAISS vector store components. We are intentionally keeping the retrieval architecture simple to focus on observability and hallucination reduction rather than on building a complex search system.
Step 1: Setting up the environment
Install dependencies and connect to Weave and W&B Inference:
!pip install -q \requests==2.32.4 \weave openai faiss-cpu datasets \"langchain-core>=0.3,<0.4" \"langchain-community>=0.3,<0.4" \"langchain-text-splitters>=0.3,<0.4" \langchain-huggingface sentence-transformers
import osimport jsonimport asyncioimport weavefrom weave import Scorerfrom openai import OpenAIfrom datasets import load_datasetfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_community.vectorstores import FAISS
Initialize Weave. This single line activates tracing for every function we decorate later, automatically capturing inputs, outputs, latency, and token costs:
WANDB_API_KEY = os.getenv("WANDB_API_KEY", "your-api-key")os.environ["WANDB_API_KEY"] = WANDB_API_KEYweave.init("financial-doc-qa")
Set up the W&B Inference client:
client = OpenAI(base_url="https://api.inference.wandb.ai/v1",api_key=WANDB_API_KEY,)AGENT_MODEL = "Qwen/Qwen3-235B-A22B-Instruct-2507"print(f"✓ W&B Inference client ready | Model: {AGENT_MODEL}")
Expected Output:

Step 2: Loading and chunking the financial documents
We load FinanceBench from HuggingFace. Each row contains a question, the answer, the evidence text from the filing, and metadata about the source document:
fb_dataset = load_dataset("PatronusAI/financebench", split="train")print(f"✓ Loaded {len(fb_dataset)} FinanceBench examples")print(f" Sample question: {fb_dataset[0]['question'][:80]}...")print(f" Sample answer: {fb_dataset[0]['answer'][:80]}...")
Expected Output:

For retrieval, we use the evidence strings as our document corpus. In a production system, you would load and chunk the full SEC filings. Here, we use the evidence passages directly so we can isolate retrieval quality from document processing complexity:
documents = []for i, row in enumerate(fb_dataset):evidence_list = row.get("evidence", [])if not evidence_list:continue# Each evidence item is a dict with 'evidence_text' keyevidence_text = "\n".join([e["evidence_text"] for e in evidence_list if e.get("evidence_text")])if len(evidence_text.strip()) > 20:documents.append({"content": evidence_text,"metadata": {"source_id": i,"company": row.get("company", "Unknown"),"doc_type": row.get("doc_type", "SEC Filing"),}})print(f"✓ Built corpus of {len(documents)} evidence passages")
Expected Output:

Now chunk the documents. Financial text often contains tables and multi-paragraph disclosures, so we use a relatively large chunk size with generous overlap to avoid splitting numbers or financial statements mid-sentence:
text_splitter = RecursiveCharacterTextSplitter(chunk_size=800,chunk_overlap=200,separators=["\n\n", "\n", ". ", " "],)chunks = []chunk_metadata = []for doc in documents:splits = text_splitter.split_text(doc["content"])for split in splits:chunks.append(split)chunk_metadata.append(doc["metadata"])print(f"✓ Split into {len(chunks)} chunks (avg {sum(len(c) for c in chunks)//len(chunks)} chars)")
Expected Output:

Step 3: Building the retrieval pipeline
Create embeddings and load them into a FAISS vector store. For retrieval, we use a local Hugging Face embedding model (BAAI/bge-small-en-v1.5) via LangChain’s HuggingFaceEmbeddings, while W&B Inference is used later for answer generation and LLM-as-judge scoring.
from langchain_huggingface import HuggingFaceEmbeddingsembeddings = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5",encode_kwargs={"normalize_embeddings": True},)# Build FAISS indextexts_with_metadata = list(zip(chunks, chunk_metadata))vectorstore = FAISS.from_texts(texts=[t[0] for t in texts_with_metadata],embedding=embeddings,metadatas=[t[1] for t in texts_with_metadata],)retriever = vectorstore.as_retriever(search_kwargs={"k": 3})print(f"✓ FAISS index built with {len(chunks)} vectors")
Expected Output:

Now build the core QA functions. Each function is decorated with @weave.op() so that Weave automatically captures the full execution trace. Think of @weave.op() as a flight recorder for your function: it logs inputs, outputs, latency, and costs without changing what the function does.
QA_SYSTEM_PROMPT = """You are a financial document QA assistant. Answer questions using ONLY the provided context from SEC filings.Rules:- Base your answer strictly on the provided context.- If the context does not contain enough information to answer, say "I cannot answer this based on the provided documents."- When citing numbers, use the exact figures from the context.- Do not infer, calculate, or extrapolate beyond what is explicitly stated."""@weave.op()def retrieve_context(question: str) -> dict:"""Retrieve relevant document chunks for a question."""docs = retriever.invoke(question)return {"chunks": [doc.page_content for doc in docs],"metadata": [doc.metadata for doc in docs],"num_chunks": len(docs),}@weave.op()def generate_answer(question: str, context_chunks: list) -> dict:"""Generate an answer from retrieved context using W&B Inference."""context_text = "\n\n---\n\n".join(context_chunks)response = client.chat.completions.create(model=AGENT_MODEL,messages=[{"role": "system", "content": QA_SYSTEM_PROMPT},{"role": "user", "content": f"Context:\n{context_text}\n\nQuestion: {question}"},],temperature=0.1, # Low temperature for factual accuracy)return {"answer": response.choices[0].message.content,"model": AGENT_MODEL,}@weave.op()def run_qa_pipeline(question: str) -> dict:"""Run the full RAG pipeline: retrieve, then generate."""retrieval = retrieve_context(question)generation = generate_answer(question, retrieval["chunks"])return {"question": question,"answer": generation["answer"],"context_chunks": retrieval["chunks"],"num_chunks": retrieval["num_chunks"],}
Test with a FinanceBench example question (for a reproducible demo):
import reimport textwrapdef clean(text):return re.sub(r"\s+", " ", str(text)).strip()def wrap(text, width=110):return textwrap.fill(clean(text), width=width)sample_idx = 0question = fb_dataset[sample_idx]["question"]ground_truth = fb_dataset[sample_idx]["answer"]print("=== Step 4 Test: Run QA Pipeline ===")print("Question:")print(wrap(question))print(f"Ground truth (dataset): {ground_truth}")result = run_qa_pipeline(question)answer = result["answer"]abstained = "i cannot answer this based on the provided documents" in answer.lower()print("\n=== Pipeline Output ===")print("Answer:")print(wrap(answer, width=110))print(f"Abstained: {abstained}")print(f"Chunks retrieved: {result['num_chunks']}")print("\n=== Retrieved Chunk Previews (cleaned) ===")for i, chunk in enumerate(result["context_chunks"], 1):preview = clean(chunk)[:260]print(f"[Chunk {i}]")print(wrap(preview, width=110))
Expected Output:

Step 4: Debugging with traces
Open your Weave project, then click the Traces tab. You will see the run_qa_pipeline call we just made, along with its full execution tree.

Click on the trace to expand it. The detail view shows:
- The retrieve_context call with the question as input and the three retrieved chunks as output
- The generate_answer call shows the exact context passed to the LLM, and the response Latency and token usage for the LLM call

This visibility is critical for debugging hallucinations in RAG. When the system returns a wrong answer, traces let you determine the root cause in seconds. Was it a retrieval failure (wrong chunks returned)? Or a generation failure (the LLM ignored or misquoted the context)? Without traces, you are guessing. With them, you can pinpoint the exact failure point.
Weave also captures latency and token costs for every LLM call. You can sort the Traces table by these columns to find expensive or slow queries, which is particularly useful for financial QA systems where some SEC filings produce much larger context windows than others.
Run a few more queries to build up a trace history:
import reimport textwrapdef clean(text):return re.sub(r"\s+", " ", str(text)).strip()def short(text, width=110):return textwrap.shorten(clean(text), width=width, placeholder="...")print("=== Step 5 Test: Build Trace History ===")test_cases = [("easy_in_corpus", "Which company is mentioned in the '3M Company and Subsidiaries Consolidated Balance Sheet' excerpt?"),("benchmark", fb_dataset[0]["question"]),("out_of_domain", "What is the recipe for chocolate cake?"),]for i, (label, q) in enumerate(test_cases, 1):result = run_qa_pipeline(q)answer = result["answer"]abstained = "i cannot answer this based on the provided documents" in answer.lower()print(f"\n[{i}] Type: {label}")print(f" Q: {short(q, 100)}")print(f" A: {short(answer, 130)}")print(f" Abstained: {abstained}")print(f" Chunks: {result['num_chunks']}")


Step 5: Evaluating for hallucinations before production
Running individual queries is useful for development, but it does not give you production confidence. What you need is systematic testing:
- Run the pipeline against a dataset of questions with known answers,
- Score every response for hallucinations, and
- Get hard numbers you can compare across versions.
This is exactly what Weave Evaluations provides
Building the evaluation dataset from FinanceBench
We sample from FinanceBench examples that have both a ground-truth answer and evidence text. This gives us a direct way to measure whether the system's answers are faithful to the source documents:
eval_examples = []for i, row in enumerate(fb_dataset):if row["evidence"] and row["answer"] and len(eval_examples) < 20:eval_examples.append({"question": row["question"],"ground_truth": row["answer"],"evidence": row["evidence"],})print(f"✓ Built evaluation dataset: {len(eval_examples)} QA pairs")for ex in eval_examples[:3]:print(f" Q: {ex['question'][:70]}...")print(f" A: {ex['ground_truth'][:70]}...")print()

Writing the scorers
Scorers are functions that grade the pipeline's output on specific dimensions. We build three scorers that target different hallucination failure modes:
@weave.op()def faithfulness_scorer(output: dict, evidence: str) -> dict:"""Check if the answer is grounded in the evidence using an LLM judge."""check_response = client.chat.completions.create(model="meta-llama/Llama-3.3-70B-Instruct",messages=[{"role": "system", "content": ("You are a factual accuracy checker for financial documents. ""Determine if the ANSWER is fully supported by the EVIDENCE. ""Respond with ONLY a JSON object."'{"faithful": true/false, "reason": "brief explanation"}')},{"role": "user", "content": (f"EVIDENCE:\n{evidence}\n\n"f"ANSWER:\n{output['answer']}\n\n""Is the answer fully supported by the evidence?")},],temperature=0.0,)try:result = json.loads(check_response.choices[0].message.content)return {"faithful": result.get("faithful", False)}except (json.JSONDecodeError, KeyError):return {"faithful": False}@weave.op()def relevance_scorer(output: dict, question: str) -> dict:""" Does the answer actually address the question asked?"""answer = output.get("answer", "")is_relevant = len(answer) > 20 and "cannot answer" not in answer.lower()return {"relevant": is_relevant}@weave.op()def completeness_scorer(output: dict, ground_truth: str) -> dict:""" Does the answer contain the key information from the ground truth?"""answer = output.get("answer", "").lower()truth = ground_truth.lower()# Extract numbers from ground truth and check if they appear in the answerimport retruth_numbers = set(re.findall(r'\$?[\d,]+\.?\d*%?', truth))if not truth_numbers:return {"complete": True, "numbers_checked": 0}found = sum(1 for n in truth_numbers if n in answer)return {"complete": found >= len(truth_numbers) * 0.5,"numbers_found": found,"numbers_expected": len(truth_numbers),}
We intentionally use a different LLM (Llama 3.3 70B) as the faithfulness judge to avoid self-evaluation bias, where the same model that generated the answer is asked to evaluate it
Running the evaluation
Wrap the pipeline in a weave.Model subclass so Weave can version the configuration and compare runs:
class FinancialQAv1(weave.Model):model_name: str = AGENT_MODELversion_label: str = "v1_baseline"chunk_size: int = 800temperature: float = 0.1@weave.op()async def predict(self, question: str, ground_truth: str = "", evidence: str = "") -> dict:return run_qa_pipeline(question)evaluation = weave.Evaluation(name="financial_qa_eval_v1",dataset=eval_examples,scorers=[faithfulness_scorer, relevance_scorer, completeness_scorer],)qa_v1 = FinancialQAv1()results_v1 = await evaluation.evaluate(qa_v1)print("\n" + "=" * 60)print(" V1 EVALUATION RESULTS (financial_qa_eval_v1)")print("=" * 60)print(f" Faithfulness: {results_v1['faithfulness_scorer']['faithful']['true_fraction']:.0%} ({results_v1['faithfulness_scorer']['faithful']['true_count']}/20 answers grounded)")print(f" Relevance: {results_v1['relevance_scorer']['relevant']['true_fraction']:.0%} ({results_v1['relevance_scorer']['relevant']['true_count']}/20 answers on-topic)")print(f" Completeness: {results_v1['completeness_scorer']['complete']['true_fraction']:.0%} ({results_v1['completeness_scorer']['complete']['true_count']}/20 answers with key numbers)")print(f" Avg latency: {results_v1['model_latency']['mean']:.1f}s per query")print("=" * 60)


Why these numbers matter: The pipeline retrieves three chunks every time, so retrieval is working. The problem is generation. At 50% faithfulness, half of the answers contain details not supported by the retrieved context. At 30% relevance, most responses fail to address the actual question. And at 25% completeness, three of four answers omit the key financial figures analysts need.
In a production financial application, these numbers mean that a user asking about a company's revenue is more likely to get a hallucinated figure than an accurate one. The pipeline needs a stricter grounding strategy before it can be trusted with real decisions.
Improving with V2
Looking at the V1 failures, the pattern is clear: 800-character chunks were splitting financial tables and statements mid-row, so the retriever returned fragments that rarely contained the key figures. The model then either hallucinated plausible numbers to fill the gap or gave vague answers that dodged the question entirely. The fix targets retrieval, not just generation: we increase chunk size to 1,500 characters to keep tables intact, retrieve 5 chunks instead of 3 to give the model more context, and add a stricter grounding prompt to reduce fabrication:
# Larger chunks to keep financial tables intacttext_splitter_v2 = RecursiveCharacterTextSplitter(chunk_size=1500,chunk_overlap=300,separators=["\n\n", "\n", ". ", " "],)chunks_v2 = []chunk_metadata_v2 = []for doc in documents:splits = text_splitter_v2.split_text(doc["content"])for split in splits:chunks_v2.append(split)chunk_metadata_v2.append(doc["metadata"])# Build new vector storevectorstore_v2 = FAISS.from_texts(texts=chunks_v2,embedding=embeddings,metadatas=chunk_metadata_v2,)retriever_v2 = vectorstore_v2.as_retriever(search_kwargs={"k": 5})print(f"✓ V2 index: {len(chunks_v2)} chunks (avg {sum(len(c) for c in chunks_v2)//len(chunks_v2)} chars)")# Stricter grounding promptIMPROVED_PROMPT = """You are a financial document QA assistant. Answer questions using ONLY the provided context from SEC filings.Rules:- Base your answer strictly on the provided context.- When citing numbers, use the EXACT figures from the context. Do not round, approximate, or calculate new values.- If the context contains relevant information, always provide an answer using that information.- Only say "I cannot answer this based on the provided documents" if the context is completely unrelated to the question.- When multiple chunks contain relevant data, synthesize them but do not invent details that appear in neither chunk.- Start your answer by directly addressing the question before adding any caveats."""@weave.op()def run_qa_pipeline_v2(question: str) -> dict:"""V2: larger chunks + more context + stricter grounding."""docs = retriever_v2.invoke(question)context_chunks = [doc.page_content for doc in docs]context_text = "\n\n---\n\n".join(context_chunks)response = client.chat.completions.create(model=AGENT_MODEL,messages=[{"role": "system", "content": IMPROVED_PROMPT},{"role": "user", "content": f"Context:\n{context_text}\n\nQuestion: {question}"},],temperature=0.1,)return {"question": question,"answer": response.choices[0].message.content,"context_chunks": context_chunks,"num_chunks": len(context_chunks),}class FinancialQAv2(weave.Model):model_name: str = AGENT_MODELversion_label: str = "v2_better_retrieval"chunk_size: int = 1500temperature: float = 0.1@weave.op()async def predict(self, question: str, ground_truth: str = "", evidence: str = "") -> dict:return run_qa_pipeline_v2(question)qa_v2 = FinancialQAv2()results_v2 = await evaluation.evaluate(qa_v2)print("\n" + "=" * 60)print(" V2 EVALUATION RESULTS (financial_qa_eval_v2)")print("=" * 60)print(f" Faithfulness: {results_v2['faithfulness_scorer']['faithful']['true_fraction']:.0%} ({results_v2['faithfulness_scorer']['faithful']['true_count']}/20 answers grounded)")print(f" Relevance: {results_v2['relevance_scorer']['relevant']['true_fraction']:.0%} ({results_v2['relevance_scorer']['relevant']['true_count']}/20 answers on-topic)")print(f" Completeness: {results_v2['completeness_scorer']['complete']['true_fraction']:.0%} ({results_v2['completeness_scorer']['complete']['true_count']}/20 answers with key numbers)")print(f" Avg latency: {results_v2['model_latency']['mean']:.1f}s per query")print("=" * 60)


Step 6: Adding guardrails for runtime safety
Evaluations catch problems during testing. But production traffic is unpredictable: a user might ask a question about a company not in your corpus, or the retriever might return irrelevant chunks. You need a safety layer that intercepts these cases in real time before a hallucinated answer reaches the user.
Guardrails are scorers that run synchronously on every request, blocking or modifying unsafe outputs before they are returned. If evaluations are your pre-flight checklist, guardrails are the circuit breaker that trips mid-flight when something goes wrong.

Image By Author
The key difference between guardrails and monitors:
- Guardrails run synchronously on every request, can block output, and add latency.
- Monitors run asynchronously on a sample (10-25%) and cannot block output, adding no latency. Guardrails prevent harm. Monitors detect drift.
We built two guardrails targeting the two most common hallucination causes in RAG.
- Confidence guardrail: when the retriever returns low-relevance chunks, the system should abstain rather than generate a potentially hallucinated answer. We measure this by checking the similarity scores from the vector store:
class RetrievalConfidenceGuardrail(Scorer):min_similarity: float = 0.3@weave.opdef score(self, output: dict) -> dict:"""Block answers when retrieved chunks are not relevant enough."""chunks = output.get("context_chunks", [])if not chunks:return {"passed": False,"reason": "No context chunks were retrieved",}# Check if any chunk has meaningful overlap with the questionquestion = output.get("question", "")question_words = set(question.lower().split())max_overlap = 0for chunk in chunks:chunk_words = set(chunk.lower().split())overlap = len(question_words & chunk_words) / max(len(question_words), 1)max_overlap = max(max_overlap, overlap)if max_overlap < self.min_similarity:return {"passed": False,"reason": f"Low retrieval confidence ({max_overlap:.2f} < {self.min_similarity})",}return {"passed": True, "reason": "Retrieval confidence sufficient"}
- Grounding guardrail: use an LLM-based check to verify the generated answer is actually supported by the retrieved context before returning it to the user:
class GroundingGuardrail(Scorer):@weave.opdef score(self, output: dict) -> dict:"""Verify the answer is grounded in the retrieved context."""answer = output.get("answer", "")chunks = output.get("context_chunks", [])if "cannot answer" in answer.lower():return {"passed": True, "reason": "Model appropriately abstained"}context = "\n".join(chunks)check = client.chat.completions.create(model="meta-llama/Llama-3.3-70B-Instruct",messages=[{"role": "system", "content": ("Check if the ANSWER is fully supported by the CONTEXT. ""Respond with ONLY 'GROUNDED' or 'NOT_GROUNDED'.")},{"role": "user", "content": (f"CONTEXT:\n{context}\n\nANSWER:\n{answer}")},],temperature=0.0,)is_grounded = "GROUNDED" in check.choices[0].message.content.upper()return {"passed": is_grounded,"reason": "Answer grounded in context" if is_grounded else "Answer not supported by context",}
Wire both guardrails into the pipeline:
confidence_guard = RetrievalConfidenceGuardrail()grounding_guard = GroundingGuardrail()@weave.op()async def run_guarded_qa(question: str) -> dict:"""Run the QA pipeline with guardrails applied."""result, call = run_qa_pipeline_v2.call(question)confidence_check = await call.apply_scorer(confidence_guard)grounding_check = await call.apply_scorer(grounding_guard)checks = {"confidence": confidence_check.result,"grounding": grounding_check.result,}failed = [name for name, c in checks.items() if not c.get("passed", True)]if failed:reasons = [checks[n]["reason"] for n in failed]return {"answer": "I cannot answer this based on the provided documents.","guardrails": checks,"blocked": True,"block_reasons": reasons,}return {"answer": result["answer"],"guardrails": checks,"blocked": False,}
Test with a question that should pass (in-domain financial query):
# Use a real question from the dataset that we know has evidencetest_question = fb_dataset[0]["question"]result = await run_guarded_qa(test_question)print(f"Question: {test_question[:80]}...")print(f"Blocked: {result['blocked']}")print(f"Answer: {result['answer'][:100]}...")print(f"Confidence: {result['guardrails']['confidence']}")print(f"Grounding: {result['guardrails']['grounding']}")

Test with a question that should trigger abstention (out-of-domain query):
result = await run_guarded_qa("What is the recipe for chocolate cake?")print(f"Blocked: {result['blocked']}")print(f"Answer: {result['answer']}")print(f"Confidence: {result['guardrails']['confidence']}")

Every guardrail activation is recorded as a Weave trace, giving you a full audit trail. You can filter the Traces table by guardrail results to see how often each guardrail fires and on which types of queries.

Step 7: Monitoring your document QA system in production
Your RAG pipeline is built, evaluated, and guarded. But your QA system is unpredictable in production. SEC filings get updated quarterly, new companies enter the corpus, and user query patterns shift over time. Without monitoring, you only discover quality degradation when a stakeholder reports a wrong answer, and by then, the damage to trust is done.
Weave Monitors solves this by sampling production traffic and scoring it with a separate LLM judge in the background, without adding any latency to user responses.
If guardrails are the circuit breaker, monitors are the smoke detector: they do not stop anything from happening, but they alert you early so you can investigate before a small issue becomes a systemic problem.
💡
Setting up the monitor
- Navigate to your Weave project and click the Monitors tab:
- Click New Monitor and name it financial_qa_quality_monitor
- Under Operations, select run_qa_pipeline_v2
- Set the Sampling rate to 20%
- For the Judge model, select meta-llama/Llama-3.3-70B-Instruct from W&B Inference
- Set the Scoring prompt to:
You are evaluating the quality of a financial document QA system's responses.User question: {inputs}System response: {output}Rate the response on these dimensions and respond ONLY with a JSON object:{{"faithful": true or false,"addresses_question": true or false,"cites_evidence": true or false,"reasoning": "Brief explanation"}}
- Click Create Monitor

Reading monitor results
Once active, Weave automatically scores 20% of incoming run_qa_pipeline_v2 calls.
- In individual traces, each scored call gets a nested LLMAsAJudgeScorer.score child trace.
Click on it to see the judge's full reasoning about faithfulness and evidence citation.

2. In the monitor dashboard, view aggregate scores over time. This is where you catch drift. If the "faithful" rate drops from 90% to 70% over a week, something changed in the document corpus, the query patterns, or the model behavior, and you need to investigate.
What to watch for
The signals that matter most for a financial QA system in production:

Image By Author
- Faithfulness drift: a declining faithfulness rate is the most dangerous signal. It may indicate that new documents were added without reindexing, that chunk boundaries are splitting financial tables poorly, or that the model started generating more confident-sounding but less accurate responses.
- Retrieval quality: if the monitor shows low "cites_evidence" scores, the retriever may be returning irrelevant chunks. Check whether the embedding model needs fine-tuning or the chunk size needs adjustment.
- Abstention rate: track how often guardrails trigger. A rising rate could indicate the corpus is not covering the questions users are asking, which signals a need to expand the document set. A falling rate might mean guardrails are too permissive.
- Latency trends: rising response times often indicate that the model is processing larger context windows. Weave's Traces table lets you sort by latency to find outliers and determine whether they correlate with specific document types.
You can also wrap everything into a production endpoint:
@weave.op()async def run_production_qa(question: str) -> dict:"""Production wrapper: guardrails on every call, monitoring on a sample."""result = await run_guarded_qa(question)# The UI-configured monitor automatically scores a sample of callsreturn result
Conclusion
Over the course of this tutorial, we built a financial document QA system and integrated four W&B Weave featuures to make it production-ready.
We started with Traces, which gave us visibility into the full retrieval-to-generation pipeline, turning hallucination debugging from guesswork into straightforward inspection. Evaluations let us test against real FinanceBench questions with known answers. V1's 800-character chunks split financial tables mid-row, producing just 50% faithfulness. V2 fixed this by increasing chunk size to 1,500 characters, retrieving 5 chunks instead of 3, and adding a stricter grounding prompt, pushing faithfulness to 80% and relevance from 30% to 70%.
Guardrails added two layers of runtime safety: a confidence check that blocks answers when retrieval quality is low, and a grounding check that verifies the answer is supported by the context before returning it. Monitors closed the loop by sampling production traffic with an LLM judge to detect drift before users notice
Production checklist
Before deploying your financial QA system, verify:
- All retrieval and generation functions are decorated with @weave.op()
- Evaluation faithfulness scores meet your threshold (90%+ for financial applications)
- Guardrails tested with both in-domain and out-of-domain queries
- At least one monitor is active at 10% to 25% sampling rate
- Abstention messages are clear and actionable for end users
Next steps
To take this further, you could scale the document corpus to full SEC filings using LangChain's document loaders, experiment with different chunking strategies (smaller chunks for precise retrieval versus larger chunks for more context), or add a citation guardrail that requires the answer to reference specific passages. You could also integrate Weave's built-in HallucinationFreeScorer to add an additional evaluation dimension, or build a feedback loop in which domain experts flag incorrect answers, which feed back into future evaluations. Each change produces new traces and evaluation results you can compare directly in the Weave UI. For a deeper dive into Weave, check out the free W&B Weave course.
For more W&B tutorials and guides: