Skip to main content











Advanced DSPy prompt optimization: Tuning, tracking with Weave, and evaluating with Ragas
A comprehensive guide to replacing manual prompt engineering with a data driven optimization loop using DSPy, Weights and Biases Weave, and Ragas for financial document RAG with OpenAI and Qdrant.
Last updated: March 31, 2026
So you've built a RAG pipeline. It kind of works. But "kind of works" isn't good enough for production. You've been tweaking your system prompt by hand, testing a few questions, changing a word here, adding a sentence there. Honestly, it feels like guessing.
This article is about replacing that guessing with a system.
We're going to take a Q&A RAG pipeline and optimize it using DSPy's MIPROv2 optimizer. We'll track every single experiment run with Weights & Biases Weave so nothing gets lost. And we'll score the outputs using Ragas metrics (faithfulness, answer relevancy, and context precision).
Here is what we will cover:
Why do we need DSPy optimizers?Comparison of DSPy optimizersBootstrapFewShot (Automatic few-shot learning)BootstrapFewShotWithRandomSearch (Automatic few-shot learning)MIPROv2 (Automatic instruction optimization)Step-by-Step tuturial: Prompt optimizer in DSpy with Weave and RAGAS integrationStep 0: Initial SetupStep 1: Initialize Weave & DSPy LM configureStep 2: Build a traditional RAG pipeline using OpenAI and QdrantStep 3: DSPy signature and DSPy moduleStep 4: LLM-as-a-Judge preprocess RAG metrics for OptimizerStep 5: Train the DSPy OptimizerStep 6: Prepare the evals dataset for RAGAS EvaluateStep 7: Trace and evaluate the base RAG and optimizer RAG using RAGAS and WeaveClosingResources
Why do we need DSPy optimizers?
Here's the uncomfortable truth about prompt engineering: it doesn't scale.
You spend an afternoon writing the perfect system prompt. It works great on your 10 test questions. You ship it. Two weeks later, someone asks a slightly different question, and the whole thing falls apart. You go back and tweak the prompt. Now the old questions break. You're in an endless loop.
The root problem is that you're manually searching a massive space of all possible ways to phrase an instruction, using your intuition as the search function. That's slow, inconsistent, and impossible to reproduce. Someone else on your team can't replicate what you did or understand why one version worked better than another.
DSPy takes a fundamentally different approach. Instead of treating your prompt as a string to be handcrafted, it treats it as a parameter to be optimized. You write your pipeline logic once using: Signatures (what goes in, what comes out) and Modules (how to chain steps together).
The prompt itself, meaning the actual instruction text and a few-shot examples, is separated as something the optimizer will figure out for you.
Comparison of DSPy optimizers
Not all optimizers do the same thing. Picking the right one saves you a lot of wasted compute. A few popular options:
BootstrapFewShot (Automatic few-shot learning)
Uses a teacher module (which defaults to your program) to generate complete demonstrations for every stage of your program, along with labeled examples in the training set.
This is the simplest optimizer and the right first step for most people. It runs your program on your training set, collects traces where the output was correct (according to your metric), and uses those as few-shot examples for future runs. The bootstrapping process employs the metric to validate demonstrations, including only those that pass the metric in the "compiled" prompt.
It only optimizes examples, not the instruction text. Think of it as: show the model what good outputs look like. Works well with as few as 10 to 20 training examples.
BootstrapFewShotWithRandomSearch (Automatic few-shot learning)
Applies BootstrapFewShot several times with random search over generated demonstrations, and selects the best program over the optimization. That is the same idea as above, but instead of stopping at the first K good examples it finds, it generates many candidate example sets and randomly searches for the best combination. Requires 50 or more examples. Gives noticeably better results than plain BootstrapFewShot with moderate compute cost.
MIPROv2 (Automatic instruction optimization)
Multiprompt Instruction Proposal Optimizer (MIPROv2) is the one you want for serious optimization. It does three things:
- Bootstrap a few-shot example candidates
- Proposes multiple candidate instructions using an LM that's aware of your data and task, and
- Uses Bayesian Optimization to find the best combination of instructions and examples across all modules in your pipeline.
Instead of randomly guessing combinations, it builds a probabilistic model of which instruction and example pairings perform well and intelligently explores the space. Use it when you have 50 or more examples and want the best possible prompts.
Some experimentation findings:
| Situation | Use This |
|---|---|
| Under 20 examples, just getting started | BootstrapFewShot |
| 50 to 200 examples, need solid baseline | BootstrapFewShotWithRandomSearch |
| 50+ examples, want best performance | MIPROv2 (auto="medium") |
| 200+ examples, maximum quality | MIPROv2 (auto="heavy") |
| Already have optimized large LM program | BootstrapFinetune |
Step-by-Step tuturial: Prompt optimizer in DSpy with Weave and RAGAS integration

As for the demo, let's build a RAG pipeline that answers questions about a small document corpus. We'll optimize the pipeline using MIPROv2, track every experiment trace in Weights & Biases Weave, and evaluate the before and after with Ragas metrics (faithfulness, answer relevancy, context precision).
Note: MIPROv2 works best when you have around 50 training examples. This article demonstrates how to define it using an LLM-as-a-Judge as the evaluation metric.
If you are new to RAG, we have 2 articles to get started: - Building a financial agentic RAG pipeline - Evaluate your RAG pipeline using LLM as a Judge with custom dataset creation
Step 0: Initial Setup
Let's start with the installation:
pip install dspy weave ragaspip install pypdfium2 qdrant-client openai
Since the goal is to optimize the RAG pipeline, we will first have to build the RAG pipeline as well, then use DSPy optimizers and evaluate using RAGAS. The entire tech stack will be monitored and traced using Weave.
import osimport weaveimport dspyfrom dspy.teleprompt import MIPROv2from ragas import evaluatefrom ragas.metrics import faithfulness, answer_relevancy, context_precisionfrom ragas.llms import LangchainLLMWrapperfrom langchain_openai import ChatOpenAIfrom datasets import Dataset
Once the installation is done, save the credentials inside the .env file or environment variables.
os.environ["OPENAI_API_KEY"] = "<replace-with-your-api-key>"os.environ["WANDB_API_KEY"] = "<replace-with-your-api-key>"os.environ["QDRANT_URL"] = "<endpoint-url-after-creating-cluster>"os.environ["QDRANT_API_KEY"] = "<replace-with-your-api-key>"
Step 1: Initialize Weave & DSPy LM configure
Weave will automatically capture all DSPy module inputs/outputs and configure DSPy LM, i.e., OpenAI gpt-5-nano, that will be used in the optimizer, as well as RAG answer generation.
weave.init(project_name="dspy-optimization-ragas")lm = dspy.LM("openai/gpt-5-nano", max_tokens=16000)dspy.configure(lm=lm)
Step 2: Build a traditional RAG pipeline using OpenAI and Qdrant
We start by setting up three things: pypdfium2 to read the PDF, OpenAI to turn text into vectors, and Qdrant to store and search those vectors in memory.
In the previous RAG article, we discussed the need for a PDFIUM2 loader for financial documents. In this demo, we will use SEC filings data, similar to what we used in the Finance Agentic RAG article. Source: Netflix SEC filings.
import pypdfium2 as pdfiumfrom openai import OpenAIfrom qdrant_client import QdrantClientfrom qdrant_client.models import Distance, VectorParams, PointStructCOLLECTION_NAME = "finance_docs1"EMBEDDING_MODEL = "text-embedding-3-small"EMBEDDING_DIM = 1536CHUNK_SIZE = 1024CHUNK_OVERLAP = 50openai_client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))client = QdrantClient(url = os.getenv("QDRANT_URL"),api_key = os.getenv("QDRANT_API_KEY"),)
Once the PDF is loaded, we pull text from every page and split it into 1024-word chunks with a 50-word overlap so context is never lost at the edges. We are keeping this step simple, but it's very important while building a production RAG app where multi-hop reasoning is important.
def extract_text_from_pdf(pdf_path: str) -> str:pdf = pdfium.PdfDocument(pdf_path)full_text = []for page_index in range(len(pdf)):page = pdf[page_index]textpage = page.get_textpage()full_text.append(textpage.get_text_range())pdf.close()return "\n".join(full_text)def chunk_text(text: str, chunk_size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> list[str]:words = text.split()chunks = []start = 0while start < len(words):end = start + chunk_sizechunk = " ".join(words[start:end])chunks.append(chunk)start += chunk_size - overlapreturn chunks
Next, we need to index the document. Indexing is the process of converting your text chunks into vectors and storing them in a way that makes similarity search efficient. Here we embed each chunk using OpenAI and upsert it into Qdrant, so when a question comes in later, we can instantly find the most relevant passages by comparing vectors.
Each chunk is wrapped in a PointStruct, which is Qdrant's way of storing a single record. It holds three things together:
- id: a unique id to identify the chunk
- vector: the vector for similarity search (main raw data that is indexed)
- payload: Carrying the original text and metadata (mainly can be used if we need to use metadata filtering)
def get_embedding(text: str) -> list[float]:response = openai_client.embeddings.create(input=text,model=EMBEDDING_MODEL)return response.data[0].embeddingdef build_index(pdf_path: str):print(f"Extracting text from {pdf_path}...")raw_text = extract_text_from_pdf(pdf_path)print("Chunking text...")chunks = chunk_text(raw_text)print(f"Created {len(chunks)} chunks.")qdrant_client.create_collection(collection_name=COLLECTION_NAME,vectors_config=VectorParams(size=EMBEDDING_DIM, distance=Distance.COSINE),)print("Embedding and indexing chunks into Qdrant...")points = []for i, chunk in enumerate(chunks):vector = get_embedding(chunk)points.append(PointStruct(id=i,vector=vector,payload={"text": chunk, "chunk_id": i}))qdrant_client.upsert(collection_name=COLLECTION_NAME, points=points)print(f"Indexed {len(points)} chunks into Qdrant.")build_index("form_8k.pdf")
Based on your document, it will take some time to index the data. Once indexing is complete, we can test it by running it against user queries. Since the data was regarding Form-8K, during this time, Netflix had acquired Warner bros, so use RAG to check the share price.
#@weave.opdef retriever(question: str, k: int = 2) -> list[str]:query_vector = get_embedding(question)results = qdrant_client.query_points(collection_name=COLLECTION_NAME,query=query_vector,limit=k,).pointsreturn [hit.payload["text"] for hit in results]print(retriever("warner bros acquired share price"))
Note: For testing, I added @weave.op to trace the results. However, when using this function with DSPy, you can comment out this line, since DSPy signatures and modules are automatically traced once W&B Weave is initialized.

Step 3: DSPy signature and DSPy module
A DSPy Signature defines the contract of your LM call, what goes in (context, question) and what comes out (answer), along with instructions that shape the response.
A Module is where the logic lives. RAGPipeline ties everything together by first calling the retriever to fetch relevant chunks from the Qdrant vector store, then passing those chunks along with the question to ChainOfThought, which reasons step by step before producing the final answer.
class GenerateAnswer(dspy.Signature):"""Answer the question using only the provided context.Be specific and include exact numbers, percentages, and figuresmentioned in the context. Write a complete sentence, not a one word answer."""context = dspy.InputField(desc="Relevant passages from the knowledge base")question = dspy.InputField(desc="The user's question")answer = dspy.OutputField(desc="Proper complete sentence answer with exact figures/details from the context.")class RAGPipeline(dspy.Module):def __init__(self):super().__init__()self.generate = dspy.ChainOfThought(GenerateAnswer)def forward(self, question: str):context_passages = retriever(question, k=2)context = "\n\n".join(context_passages)prediction = self.generate(context=context,question=question)return dspy.Prediction(answer=prediction.answer,context=context_passages,rationale=getattr(prediction, "rationale", ""))rag_baseline = RAGPipeline()result = rag_baseline(question="What was Netflix's total revenue for full year 2025?")print(result.answer)
As mentioned earlier, DSPy components are automatically traced using W&B Weave:

Step 4: LLM-as-a-Judge preprocess RAG metrics for Optimizer
Now that the RAG pipeline is working, we need to give the optimizer something to learn from, i.e., a few Q&A pairs pulled directly from the Netflix earnings PDF, split into training and validation. For testing, we are using 10 question-answer pairs, but around 50-60 questions is ideal.
If you want to know more about how to prepare the dataset for the evals, check out the Evaluation article.
train_data = [{"question": "What was Netflix's total revenue for full year 2025?","answer": "Netflix delivered $45.2 billion of revenue for full year 2025, representing 16% growth year over year."},{"question": "What was Netflix's operating margin for 2025?","answer": "Netflix's operating margin for 2025 was 29.5%, up 3 percentage points from 26.7% in 2024."},{"question": "How many paid memberships did Netflix cross in Q4 2025?","answer": "Netflix crossed the 325 million paid memberships milestone during Q4 2025."},{"question": "How much did Netflix's ad revenue grow in 2025?","answer": "Ad revenue rose more than 2.5x in 2025 to over $1.5 billion."},{"question": "What is Netflix's revenue forecast for full year 2026?","answer": "Netflix forecasts 2026 revenue of $50.7 billion to $51.7 billion, representing 12% to 14% year over year growth."},{"question": "What was Netflix's free cash flow for full year 2025?","answer": "Netflix generated $9.5 billion in free cash flow for full year 2025, up from $6.9 billion in 2024."},{"question": "What acquisition is Netflix working to close in 2026?","answer": "Netflix is working to close its acquisition of Warner Bros., including its film and television studios, HBO Max and HBO, in an all-cash transaction valued at $27.75 per WBD share."},{"question": "What was Netflix's Q4 2025 operating income and how did it compare to the prior year?","answer": "Netflix's Q4 2025 operating income was $3.0 billion, up 30% year over year."},{"question": "What was Netflix's US TV viewing share in December 2025?","answer": "According to Nielsen, Netflix's share of US TV time reached an all-time high of 9.0% in December 2025, up 0.5 points year over year."},{"question": "What is Netflix's target operating margin for 2026?","answer": "Netflix is targeting a 2026 operating margin of 31.5%, up from 29.5% in 2025."},]trainset = [dspy.Example(question=d["question"], answer=d["answer"]).with_inputs("question")for d in train_data]train_examples = trainset[:8]dev_examples = trainset[8:]
To build the optimizer, we need to define a proper evaluation signal. Since this application is RAG-based, using an LLM as a judge is a better choice. Instead of relying on brittle keyword matching, we use GPT-4o-mini as the judge to score each prediction. This allows the optimizer to learn from a signal that understands semantic meaning, rather than simple word overlap.
from pydantic import BaseModelclass JudgeScore(BaseModel):score: floatdef rag_metric(example, prediction, trace=None):judge_prompt = f"""Score if the predicted answer correctly answers the question based on the expected answer.Question: {example.question}Expected: {example.answer}Predicted: {prediction.answer}Rules:- Award high score if key facts and numbers match, exact wording not required- Score 0 if predicted says "not specified", "not mentioned", or refuses to answer- Score 0 if predicted contains wrong numbers or factsScore must be 0.0 to 1.0."""try:response = openai_client.chat.completions.create(model="gpt-4o-mini",messages=[{"role": "user", "content": judge_prompt}],response_format={"type": "json_schema","json_schema": {"name": "JudgeScore","schema": JudgeScore.model_json_schema()}},temperature=0,max_tokens=20,)result = JudgeScore.model_validate_json(response.choices[0].message.content)return result.score >= 0.5except Exception as e:print(f"Judge error: {e}")return False
Test the dev examples on the RAG metric to check if it's parsing as expected:
total = 0passed = 0for example in dev_examples:result = rag_baseline(question=example.question)score = rag_metric(example, result)status = "PASS" if score else "FAIL"passed += int(score)total += 1print(f"\n[{status}] Q : {example.question}")print(f" Expected : {example.answer}")print(f" Got : {result.answer}")evaluator = dspy.Evaluate(devset=dev_examples,metric=rag_metric,num_threads=2,display_progress=True,)baseline_score = evaluator(rag_baseline)

Step 5: Train the DSPy Optimizer
MIPROv2 runs in three phases during optimizer.compile().
- First, it bootstraps example candidates by running your pipeline on the training set and keeping traces that score well on rag_metric.
- Second, it generates multiple candidate instruction sets with different ways to phrase the task description in your Signature. (check the image below that logs the instructions for each query in training data)
- Third, it runs a Bayesian search across instruction and example combinations to find the best-performing prompt for your specific data.
optimizer = MIPROv2(metric=rag_metric,auto="medium", # use "medium" for better results, "heavy" for bestnum_threads=2,verbose=True)optimized_rag = optimizer.compile(rag_baseline,trainset=train_examples)optimized_score = evaluator(optimized_rag)

Notice the instructions during the runtime, as we have kept verbose to be True:


Perfect, we now have the baseline RAG and the Optimizer RAG pipeline. We will now proceed with the evaluation using RAGAS.
Step 6: Prepare the evals dataset for RAGAS Evaluate
Ragas comes in after optimization as the final judge. Because Ragas uses an LLM as a judge approach, it can evaluate things like whether the answer is faithful to the context (not hallucinated) and whether it actually addresses the question, which is a much stronger signal than keyword matching. In a more advanced setup, you'd use a Ragas faithfulness score directly as your DSPy optimization metric, which creates a tight feedback loop between optimization and evaluation.
To proceed with this, Ragas needs a specific format to compute its metrics, i.e., each row must have a question, the model's answer, the retrieved context chunks, and a ground truth to check against.
We will define the testing questions and ground truth then use RAG pipeline to get the model answer and retrieved chunks.
test_questions = ["What was Netflix's total revenue for full year 2025?","What was Netflix's operating margin for 2025?","How many paid memberships did Netflix reach in Q4 2025?","What is Netflix's revenue forecast for 2026?","How much did Netflix's advertising revenue grow in 2025?","What was Netflix's free cash flow for full year 2025?","What acquisition is Netflix planning to close in 2026?","What was Netflix's US TV viewing share in December 2025?",]ground_truths = ["$45.2 billion, 16% growth year over year","29.5%, up 3 percentage points from 2024","325 million paid memberships","$50.7 billion to $51.7 billion, 12% to 14% growth","More than 2.5x growth to over $1.5 billion","$9.5 billion, up from $6.9 billion in 2024","Acquisition of Warner Bros. including HBO Max and HBO, all-cash at $27.75 per share","9.0% all-time high, up 0.5 points year over year",]
We prepare two datasets by running both rag_baseline and optimized_rag on the same 8 test questions from the Netflix PDF, collecting everything collect_ragas_data needs in one pass.
def collect_ragas_data(pipeline, questions, ground_truths):rows = []for q, gt in zip(questions, ground_truths):pred = pipeline(question=q)rows.append({"question": q,"answer": pred.answer,"contexts": pred.context,"ground_truth": gt})return rowsprint("Collecting baseline predictions...")baseline_results = collect_ragas_data(rag_baseline, test_questions, ground_truths)print("Collecting optimized predictions...")optimized_results = collect_ragas_data(optimized_rag, test_questions, ground_truths)
Since we are using RAG pipeline for the each question, the logs are automatically traced:

Once we have the model answers and the ground truth, the dataset is ready to be evaluated.
def to_ragas_dataset(results):return Dataset.from_dict({"question": [r["question"] for r in results],"answer": [r["answer"] for r in results],"contexts": [r["contexts"] for r in results],"ground_truth": [r["ground_truth"] for r in results],})baseline_dataset = to_ragas_dataset(baseline_results)optimized_dataset = to_ragas_dataset(optimized_results)
Step 7: Trace and evaluate the base RAG and optimizer RAG using RAGAS and Weave
We pass both datasets through Ragas using GPT-4o-mini as the evaluator LLM, scoring each answer across three metrics:
- faithfulness: is the answer grounded in the retrieved context
- answer relevancy: Does it actually address the question
- context precision: did the retriever pull the right chunks
ragas_llm = LangchainLLMWrapper(ChatOpenAI(model="gpt-4o-mini"))metrics = [faithfulness, answer_relevancy, context_precision]print("\nRunning Ragas on baseline...")baseline_ragas = evaluate(dataset=baseline_dataset,metrics=metrics,llm=ragas_llm,)print("Running Ragas on optimized pipeline...")optimized_ragas = evaluate(dataset=optimized_dataset,metrics=metrics,llm=ragas_llm,raise_exceptions=False)
Once the results are ready, we can visualize them better by converting them into a pandas DataFrame or saving them as traces in W&B Weave.
Using Pandas Dataframe:
baseline_df = baseline_ragas.to_pandas()print(baseline_df)optimized_df = optimized_ragas.to_pandas()print(optimized_df)


Using Weave:
from weave import Datasetoptimized_trace = Dataset.from_pandas(optimized_df)weave.publish(optimized_trace)baseline__trace = Dataset.from_pandas(baseline_df)weave.publish(baseline__trace)

Closing
Start with auto="light" in MIPROv2. It's fast, cheap, and gives you a working loop. Only go to "medium" or "heavy" once you've verified the pipeline makes sense.
Your metric function is the most important thing to get right. In our case, we used LLM as a Judge; the keywords and the rubric need to be defined by the domain expert. As an alternative, for the rag_metrics function, we can also use a search metric such as semantic similarity or Ragas faithfulness, which yields much better results.
For real projects, use at least 50 training examples. The quality of bootstrapped few-shot examples scales with dataset size. Check Weave during optimization, not just after. You can watch MIPROv2 explore different instructions in real time and stop early if it's clearly converging.
Resources
Add a comment