{"id": "dspy_db6c58a4b861", "topic": "gepa_optimizer_usage", "question": "I'm debugging a tiny GEPA run on a one-step QA module (a single `dspy.Predict('question -> answer')`). My harness wires up two separate `DummyLM`s — one configured as the default task LM and one passed to GEPA as the `reflection_lm` — runs a small optimization with a single budget cap, and a feedback metric so reflection actually fires.\n\nI want to see, for the reflection step specifically: (a) the exact request the reflection model received, (b) its raw response object, (c) the parsed completion, and (d) the final instruction text sitting on the optimized predictor.\n\nRight now I grab the last reflection call with `reflection_lm.history[-1]` and read `[\"messages\"]` to print the request — but it comes back as `None`, even though the task LM's history shows full `messages` for every call. The response and parsed output look fine; it's just the request that's empty for the reflection model.\n\nGive me a corrected, self-contained runnable program (using `DummyLM` for both task and reflection so it needs no real API keys) that reliably prints all four artifacts, with the reflection request showing the actual prompt the reflection model was sent.", "gold_answer": "```python\nimport json\nimport dspy\nfrom dspy.utils.dummies import DummyLM\n\n\nclass QAProgram(dspy.Module):\n def __init__(self):\n super().__init__()\n self.predictor = dspy.Predict('question -> answer')\n\n def forward(self, question):\n return self.predictor(question=question)\n\n\ndef metric(gold, pred, trace=None, pred_name=None, pred_trace=None):\n score = float(pred.answer.strip().lower() == gold.answer.lower())\n feedback = 'Return the exact short answer and nothing else.' if not score else 'Good.'\n return dspy.Prediction(score=score, feedback=feedback)\n\n\ntask_lm = DummyLM({'capital of France': {'answer': 'Lyon'}})\nreflection_lm = DummyLM([\n {'improved_instruction': 'Return the exact short answer and nothing else.'},\n] * 8)\n\ndspy.configure(lm=task_lm)\ntrainset = [\n dspy.Example(question='What is the capital of France?', answer='Paris').with_inputs('question'),\n]\n\noptimized = dspy.GEPA(\n metric=metric,\n reflection_lm=reflection_lm,\n max_metric_calls=4,\n seed=0,\n).compile(QAProgram(), trainset=trainset, valset=trainset)\n\n# GEPA invokes the reflection LM with a positional prompt string (not chat messages),\n# so the logged entry has messages=None and the request text lives in 'prompt'.\nlast = reflection_lm.history[-1]\nreflection_request = last['messages'] or [{'role': 'user', 'content': last['prompt']}]\n\nprint(json.dumps({\n 'reflection_request': reflection_request,\n 'reflection_raw_response': last['response'],\n 'reflection_parsed_output': last['outputs'],\n 'optimized_instruction': optimized.predictor.signature.instructions,\n}, indent=2, default=str))\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 52, "statement": "To surface the exact reflection request, the code recovers it from the `prompt` field of `reflection_lm.history[-1]` (e.g. `last['messages'] or [{'role':'user','content': last['prompt']}]`, or by reading `last['prompt']` directly), because GEPA invokes the reflection LM with a positional prompt STRING (`adapter.stripped_lm_call(x)` -> `self.reflection_lm(x)`), so `BaseLM` logs that entry with `messages == None`. Reading `reflection_lm.history[-1]['messages']` ALONE for the request (the plausible decoy, which yields `None`) does NOT satisfy this claim. The raw response and parsed completion are read from that SAME entry's `response` and `outputs` fields.", "span_ids": ["s4", "s8", "s9", "s10"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "The feedback metric is declared with GEPA's full 5-argument signature `(gold, pred, trace, pred_name, pred_trace)` and returns a score-with-feedback object (e.g. `dspy.Prediction(score=..., feedback=...)`), NOT the ordinary DSPy 3-argument `(gold, pred, trace)` / int-returning metric form. This is what lets reflection actually fire rather than being skipped.", "span_ids": ["s3"]}, {"claim_id": "c3", "claim_type": "supporting", "weight": 12, "statement": "`dspy.GEPA(...)` is constructed with a `reflection_lm` and exactly ONE budget control out of {`max_metric_calls`, `max_full_evals`, `auto`} (optional `seed` is allowed), and `.compile(student, trainset=..., valset=...)` is called on the one-step `dspy.Predict('question -> answer')` module. (Extra non-budget kwargs such as `reflection_minibatch_size` are permitted and do NOT violate the single-budget requirement.)", "span_ids": ["s1", "s2"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 9, "statement": "Two distinct `DummyLM` instances are used with no real API keys: one configured as the default DSPy LM (via `dspy.configure(lm=...)`/`dspy.settings.configure`) for task execution, and a separate `DummyLM` passed to GEPA as `reflection_lm` (not a hand-rolled `dspy.LM` subclass or wrapper).", "span_ids": ["s2", "s6"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 7, "statement": "The optimized predictor's instruction is printed via the returned program's predictor `.signature.instructions` (e.g. `optimized..signature.instructions`), read straight off the compiled program and printed as-is (no claim is made about its runtime value).", "span_ids": ["s7"]}], "evidence": [{"span_id": "s1", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 330, "end_line": 365, "excerpt": "0330: def __init__(\n0331: self,\n0332: metric: GEPAFeedbackMetric,\n0333: *,\n0334: # Budget configuration\n0335: auto: Literal[\"light\", \"medium\", \"heavy\"] | None = None,\n0336: max_full_evals: int | None = None,\n0337: max_metric_calls: int | None = None,\n0338: # Reflection configuration\n0339: reflection_minibatch_size: int = 3,\n0340: candidate_selection_strategy: Literal[\"pareto\", \"current_best\"] = \"pareto\",\n0341: reflection_lm: LM | None = None,\n0342: skip_perfect_score: bool = True,\n0343: add_format_failure_as_feedback: bool = False,\n0344: instruction_proposer: \"ProposalFn | None\" = None,\n0345: component_selector: \"ReflectionComponentSelector | str\" = \"round_robin\",\n0346: # Merge-based configuration\n0347: use_merge: bool = True,\n0348: max_merge_invocations: int | None = 5,\n0349: # Evaluation configuration\n0350: num_threads: int | None = None,\n0351: failure_score: float = 0.0,\n0352: perfect_score: float = 1.0,\n0353: # Logging\n0354: log_dir: str | None = None,\n0355: track_stats: bool = False,\n0356: use_wandb: bool = False,\n0357: wandb_api_key: str | None = None,\n0358: wandb_init_kwargs: dict[str, Any] | None = None,\n0359: track_best_outputs: bool = False,\n0360: warn_on_score_mismatch: bool = True,\n0361: use_mlflow: bool = False,\n0362: # Reproducibility\n0363: seed: int | None = 0,\n0364: # GEPA passthrough kwargs\n0365: gepa_kwargs: dict | None = None,"}, {"span_id": "s2", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 377, "end_line": 399, "excerpt": "0377: # Budget configuration\n0378: assert (max_metric_calls is not None) + (max_full_evals is not None) + (auto is not None) == 1, (\n0379: \"Exactly one of max_metric_calls, max_full_evals, auto must be set. \"\n0380: f\"You set max_metric_calls={max_metric_calls}, \"\n0381: f\"max_full_evals={max_full_evals}, \"\n0382: f\"auto={auto}.\"\n0383: )\n0384: self.auto = auto\n0385: self.max_full_evals = max_full_evals\n0386: self.max_metric_calls = max_metric_calls\n0387: \n0388: # Reflection configuration\n0389: self.reflection_minibatch_size = reflection_minibatch_size\n0390: self.candidate_selection_strategy = candidate_selection_strategy\n0391: \n0392: assert reflection_lm is not None or instruction_proposer is not None, (\n0393: \"GEPA requires a reflection language model, or custom instruction proposer to be provided. \"\n0394: \"Typically, you can use `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)` to get a good reflection model. \"\n0395: \"Reflection LM is used by GEPA to reflect on the behavior of the program and propose new instructions, and will benefit from a strong model. \"\n0396: )\n0397: \n0398: self.reflection_lm = reflection_lm\n0399: self.skip_perfect_score = skip_perfect_score"}, {"span_id": "s3", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 27, "end_line": 55, "excerpt": "0027: class GEPAFeedbackMetric(Protocol):\n0028: def __call__(\n0029: self,\n0030: gold: Example,\n0031: pred: Prediction,\n0032: trace: Optional[\"DSPyTrace\"],\n0033: pred_name: str | None,\n0034: pred_trace: Optional[\"DSPyTrace\"],\n0035: ) -> Union[float, \"ScoreWithFeedback\"]:\n0036: \"\"\"\n0037: This function is called with the following arguments:\n0038: - gold: The gold example.\n0039: - pred: The predicted output.\n0040: - trace: Optional. The trace of the program's execution.\n0041: - pred_name: Optional. The name of the target predictor currently being optimized by GEPA, for which\n0042: the feedback is being requested.\n0043: - pred_trace: Optional. The trace of the target predictor's execution GEPA is seeking feedback for.\n0044: \n0045: Note the `pred_name` and `pred_trace` arguments. During optimization, GEPA will call the metric to obtain\n0046: feedback for individual predictors being optimized. GEPA provides the name of the predictor in `pred_name`\n0047: and the sub-trace (of the trace) corresponding to the predictor in `pred_trace`.\n0048: If available at the predictor level, the metric should return dspy.Prediction(score: float, feedback: str)\n0049: corresponding to the predictor.\n0050: If not available at the predictor level, the metric can also return a text feedback at the program level\n0051: (using just the gold, pred and trace).\n0052: If no feedback is returned, GEPA will use a simple text feedback consisting of just the score:\n0053: f\"This trajectory got a score of {score}.\"\n0054: \"\"\"\n0055: ..."}, {"span_id": "s4", "path": "dspy/clients/base_lm.py", "start_line": 90, "end_line": 120, "excerpt": "0090: def _process_lm_response(self, response, prompt, messages, **kwargs):\n0091: merged_kwargs = {**self.kwargs, **kwargs}\n0092: \n0093: if self.model_type == \"responses\":\n0094: outputs = self._process_response(response)\n0095: else:\n0096: outputs = self._process_completion(response, merged_kwargs)\n0097: \n0098: if settings.disable_history:\n0099: return outputs\n0100: \n0101: # Logging, with removed api key & where `cost` is None on cache hit.\n0102: kwargs = {k: v for k, v in kwargs.items() if not k.startswith(\"api_\")}\n0103: entry = {\n0104: \"prompt\": prompt,\n0105: \"messages\": messages,\n0106: \"kwargs\": kwargs,\n0107: \"response\": response,\n0108: \"outputs\": outputs,\n0109: \"usage\": dict(response.usage),\n0110: \"cost\": getattr(response, \"_hidden_params\", {}).get(\"response_cost\"),\n0111: \"timestamp\": datetime.datetime.now().isoformat(),\n0112: \"uuid\": str(uuid.uuid4()),\n0113: \"model\": self.model,\n0114: \"response_model\": response.model,\n0115: \"model_type\": self.model_type,\n0116: }\n0117: \n0118: self.update_history(entry)\n0119: \n0120: return outputs"}, {"span_id": "s5", "path": "dspy/clients/base_lm.py", "start_line": 122, "end_line": 132, "excerpt": "0122: @with_callbacks\n0123: def __call__(\n0124: self,\n0125: prompt: str | None = None,\n0126: messages: list[dict[str, Any]] | None = None,\n0127: **kwargs\n0128: ) -> list[dict[str, Any] | str]:\n0129: response = self.forward(prompt=prompt, messages=messages, **kwargs)\n0130: outputs = self._process_lm_response(response, prompt, messages, **kwargs)\n0131: \n0132: return outputs"}, {"span_id": "s6", "path": "dspy/utils/dummies.py", "start_line": 69, "end_line": 87, "excerpt": "0069: def __init__(\n0070: self,\n0071: answers: list[dict[str, Any]] | dict[str, dict[str, Any]],\n0072: follow_examples: bool = False,\n0073: reasoning: bool = False,\n0074: adapter=None,\n0075: ):\n0076: super().__init__(\"dummy\", \"chat\", 0.0, 1000, True)\n0077: self.answers = answers\n0078: if isinstance(answers, list):\n0079: self.answers = iter(answers)\n0080: self.follow_examples = follow_examples\n0081: self.reasoning = reasoning\n0082: \n0083: # Set adapter, defaulting to ChatAdapter\n0084: if adapter is None:\n0085: from dspy.adapters.chat_adapter import ChatAdapter\n0086: adapter = ChatAdapter()\n0087: self.adapter = adapter"}, {"span_id": "s7", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 548, "end_line": 599, "excerpt": "0548: # Build the DSPy adapter that encapsulates evaluation, trace capture, feedback extraction, and instruction proposal\n0549: adapter = DspyAdapter(\n0550: student_module=student,\n0551: metric_fn=self.metric_fn,\n0552: feedback_map=feedback_map,\n0553: failure_score=self.failure_score,\n0554: num_threads=self.num_threads,\n0555: add_format_failure_as_feedback=self.add_format_failure_as_feedback,\n0556: rng=rng,\n0557: reflection_lm=self.reflection_lm,\n0558: custom_instruction_proposer=self.custom_instruction_proposer,\n0559: warn_on_score_mismatch=self.warn_on_score_mismatch,\n0560: reflection_minibatch_size=self.reflection_minibatch_size,\n0561: )\n0562: \n0563: # Build the seed candidate: map each predictor name to its current instruction\n0564: seed_candidate = {name: pred.signature.instructions for name, pred in student.named_predictors()}\n0565: \n0566: gepa_result: GEPAResult = optimize(\n0567: seed_candidate=seed_candidate,\n0568: trainset=trainset,\n0569: valset=valset,\n0570: adapter=adapter,\n0571: # Reflection-based configuration\n0572: reflection_lm=(lambda x: adapter.stripped_lm_call(x)[0]) if self.reflection_lm is not None else None,\n0573: candidate_selection_strategy=self.candidate_selection_strategy,\n0574: skip_perfect_score=self.skip_perfect_score,\n0575: reflection_minibatch_size=self.reflection_minibatch_size,\n0576: module_selector=self.component_selector,\n0577: perfect_score=self.perfect_score,\n0578: # Merge-based configuration\n0579: use_merge=self.use_merge,\n0580: max_merge_invocations=self.max_merge_invocations,\n0581: # Budget\n0582: max_metric_calls=self.max_metric_calls,\n0583: # Logging\n0584: logger=LoggerAdapter(logger),\n0585: run_dir=self.log_dir,\n0586: use_wandb=self.use_wandb,\n0587: wandb_api_key=self.wandb_api_key,\n0588: wandb_init_kwargs=self.wandb_init_kwargs,\n0589: use_mlflow=self.use_mlflow,\n0590: track_best_outputs=self.track_best_outputs,\n0591: display_progress_bar=True,\n0592: raise_on_exception=True,\n0593: # Reproducibility\n0594: seed=self.seed,\n0595: **self.gepa_kwargs,\n0596: )\n0597: \n0598: new_prog = adapter.build_program(gepa_result.best_candidate)\n0599: "}, {"span_id": "s8", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 570, "end_line": 572, "excerpt": "0570: adapter=adapter,\n0571: # Reflection-based configuration\n0572: reflection_lm=(lambda x: adapter.stripped_lm_call(x)[0]) if self.reflection_lm is not None else None,"}, {"span_id": "s9", "path": "dspy/teleprompt/gepa/gepa_utils.py", "start_line": 321, "end_line": 336, "excerpt": "0321: # Always return strings from the LM outputs\n0322: # Even when it returns a dict with e.g., \"text\" and \"reasoning\" fields\n0323: def stripped_lm_call(self, x: str) -> list[str]:\n0324: raw_outputs = self.reflection_lm(x)\n0325: outputs = []\n0326: for raw_output in raw_outputs:\n0327: if type(raw_output) == str:\n0328: outputs.append(raw_output)\n0329: elif type(raw_output) == dict:\n0330: if \"text\" not in raw_output:\n0331: raise KeyError(\"Missing 'text' field in the output from the base LM!\")\n0332: outputs.append(raw_output[\"text\"])\n0333: else:\n0334: raise TypeError(\"Unexpected output type from the base LM! Expected str or dict\")\n0335: \n0336: return outputs"}, {"span_id": "s10", "path": "dspy/utils/inspect_history.py", "start_line": 36, "end_line": 41, "excerpt": "0036: use_colors = file is None\n0037: \n0038: for item in history[-n:]:\n0039: messages = item[\"messages\"] or [{\"role\": \"user\", \"content\": item[\"prompt\"]}]\n0040: outputs = item[\"outputs\"]\n0041: timestamp = item.get(\"timestamp\", \"Unknown time\")"}]} {"id": "dspy_024049972dfc", "topic": "gepa_optimizer_usage", "question": "I have a hand-written instruction for a customer-support `dspy.Predict` and I want GEPA to refine *that* wording, not invent one from scratch. My module builds the predictor like this:\n\n```python\nself.reply = dspy.Predict('question -> answer', instructions=BASE_INSTRUCTION)\n```\n\nIt runs without complaint, but when I compile it with `dspy.GEPA` the logs show it starting from the generic `Given the fields ``question``, produce the fields ``answer``.` prompt and refining *that* — my BASE_INSTRUCTION never shows up as the starting point. GEPA's `compile()` doesn't take an instruction or a starting-prompt argument, and its `seed` argument didn't help either. How is GEPA picking which text to start from, why is my hand-written instruction being ignored, and what's the minimal change so GEPA actually refines my wording? Give me a minimal, runnable program that seeds the predictor correctly, runs GEPA on a tiny support dataset, and prints the instruction text before and after optimization.", "gold_answer": "```python\nimport dspy\nfrom dspy.utils.dummies import DummyLM\n\nBASE_INSTRUCTION = (\n 'Answer support questions in one sentence. '\n 'For returns questions, mention the 30-day refund window.'\n)\n\n\nclass SupportProgram(dspy.Module):\n def __init__(self):\n super().__init__()\n self.reply = dspy.Predict('question -> answer')\n self.reply.signature = self.reply.signature.with_instructions(BASE_INSTRUCTION)\n\n def forward(self, question):\n return self.reply(question=question)\n\n\ndef metric(gold, pred, trace=None, pred_name=None, pred_trace=None):\n score = float('30-day' in pred.answer.lower())\n feedback = 'Mention the 30-day refund window for returns questions.' if not score else 'Good.'\n return dspy.Prediction(score=score, feedback=feedback)\n\n\ntask_lm = DummyLM({'return an item': {'answer': 'You can return it.'}})\nreflection_lm = DummyLM([\n {'improved_instruction': 'Answer in one sentence and mention the 30-day refund window for returns questions.'},\n] * 8)\n\ndspy.configure(lm=task_lm)\nprogram = SupportProgram()\ntrainset = [\n dspy.Example(\n question='How do I return an item?',\n answer='You can return it within 30 days.',\n ).with_inputs('question'),\n]\n\nbefore = program.reply.signature.instructions\noptimized = dspy.GEPA(\n metric=metric,\n reflection_lm=reflection_lm,\n max_metric_calls=4,\n seed=0,\n).compile(program, trainset=trainset, valset=trainset)\nafter = optimized.reply.signature.instructions\nprint({'before': before, 'after': after})\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 42, "statement": "The hand-written instruction is attached to the predictor's SIGNATURE so that `predictor.signature.instructions` returns the user's text — via `predictor.signature = predictor.signature.with_instructions(BASE_INSTRUCTION)`, or by building the predictor from `dspy.Signature('question -> answer', BASE_INSTRUCTION)` / a docstring-bearing Signature subclass. It must NOT use the decoy of passing `instructions=` into the `dspy.Predict(...)` constructor, nor set an `.instructions`/`.instruction` attribute on the Predict object: those are silently swallowed into the module's `**config` and leave `signature.instructions` at the auto-generated default. (Static: the BASE text must reach the signature, not the dspy.Predict(...) call.)", "span_ids": ["s1", "s2", "s3"]}, {"claim_id": "c2", "claim_type": "core", "weight": 28, "statement": "The code wires GEPA to refine FROM that signature text and supplies a GEPA-shaped metric — the value read as the starting prompt is `predictor.signature.instructions` (the source GEPA uses for its per-predictor seed candidate), AND the metric passed to `dspy.GEPA(metric=...)` is defined with the five-parameter signature `(gold, pred, trace, pred_name, pred_trace)` (a `reflection_lm` is also passed). It must NOT rely on the decoy 3-argument `metric(gold, pred, trace=None)` convention used by other DSPy optimizers, and must NOT treat a Predict `instructions=`/`config` value as the seed. (Static: count the metric's declared parameters and check what variable is captured as the 'before' seed.)", "span_ids": ["s3", "s5"]}, {"claim_id": "c3", "claim_type": "core", "weight": 18, "statement": "A minimal GEPA run is constructed and compiled: `dspy.GEPA(metric=..., reflection_lm=..., ).compile(program, trainset=, valset=...)` (valset optional / reused as trainset). A tiny support dataset suffices and NO instruction- or starting-prompt argument is passed to `dspy.GEPA(...)` or `.compile(...)` — no such parameter exists in this snapshot. (Static: read the GEPA(...) and .compile(...) call sites.)", "span_ids": ["s4", "s5"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 12, "statement": "The program prints/returns BOTH instruction strings read specifically from `signature.instructions` (plural): the predictor's `signature.instructions` captured before `dspy.GEPA(...).compile(...)`, and the optimized/compiled program's `predictor.signature.instructions` read afterward. Reading a singular `.instruction`, `.config['instructions']`, or any non-signature attribute does NOT satisfy this. (Static: presence of both reads of .instructions in the code text.)", "span_ids": ["s2", "s6"]}], "evidence": [{"span_id": "s1", "path": "dspy/signatures/signature.py", "start_line": 269, "end_line": 297, "excerpt": "0269: @classmethod\n0270: def with_instructions(cls, instructions: str) -> type[\"Signature\"]:\n0271: \"\"\"Return a new Signature class with identical fields and new instructions.\n0272: \n0273: This method does not mutate `cls`. It constructs a fresh Signature\n0274: class using the current fields and the provided `instructions`.\n0275: \n0276: Args:\n0277: instructions (str): Instruction text to attach to the new signature.\n0278: \n0279: Returns:\n0280: A new Signature class whose fields match `cls.fields`\n0281: and whose instructions equal `instructions`.\n0282: \n0283: Examples:\n0284: ```python\n0285: import dspy\n0286: \n0287: class MySig(dspy.Signature):\n0288: input_text: str = dspy.InputField(desc=\"Input text\")\n0289: output_text: str = dspy.OutputField(desc=\"Output text\")\n0290: \n0291: NewSig = MySig.with_instructions(\"Translate to French.\")\n0292: assert NewSig is not MySig\n0293: assert NewSig.instructions == \"Translate to French.\"\n0294: ```\n0295: \"\"\"\n0296: return Signature(cls.fields, instructions)\n0297: "}, {"span_id": "s2", "path": "dspy/signatures/signature.py", "start_line": 215, "end_line": 221, "excerpt": "0215: @property\n0216: def instructions(cls) -> str:\n0217: return inspect.cleandoc(getattr(cls, \"__doc__\", \"\"))\n0218: \n0219: @instructions.setter\n0220: def instructions(cls, instructions: str) -> None:\n0221: cls.__doc__ = instructions"}, {"span_id": "s3", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 554, "end_line": 565, "excerpt": "0554: num_threads=self.num_threads,\n0555: add_format_failure_as_feedback=self.add_format_failure_as_feedback,\n0556: rng=rng,\n0557: reflection_lm=self.reflection_lm,\n0558: custom_instruction_proposer=self.custom_instruction_proposer,\n0559: warn_on_score_mismatch=self.warn_on_score_mismatch,\n0560: reflection_minibatch_size=self.reflection_minibatch_size,\n0561: )\n0562: \n0563: # Build the seed candidate: map each predictor name to its current instruction\n0564: seed_candidate = {name: pred.signature.instructions for name, pred in student.named_predictors()}\n0565: "}, {"span_id": "s4", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 465, "end_line": 509, "excerpt": "0465: def compile(\n0466: self,\n0467: student: Module,\n0468: *,\n0469: trainset: list[Example],\n0470: teacher: Module | None = None,\n0471: valset: list[Example] | None = None,\n0472: ) -> Module:\n0473: \"\"\"\n0474: GEPA uses the trainset to perform reflective updates to the prompt, but uses the valset for tracking Pareto scores.\n0475: If no valset is provided, GEPA will use the trainset for both.\n0476: \n0477: Parameters:\n0478: - student: The student module to optimize.\n0479: - trainset: The training set to use for reflective updates.\n0480: - valset: The validation set to use for tracking Pareto scores. If not provided, GEPA will use the trainset for both.\n0481: \"\"\"\n0482: from gepa import GEPAResult, optimize\n0483: \n0484: from dspy.teleprompt.gepa.gepa_utils import DspyAdapter, LoggerAdapter\n0485: \n0486: assert trainset is not None and len(trainset) > 0, \"Trainset must be provided and non-empty\"\n0487: assert teacher is None, \"Teacher is not supported in DspyGEPA yet.\"\n0488: \n0489: if self.auto is not None:\n0490: self.max_metric_calls = self.auto_budget(\n0491: num_preds=len(student.predictors()),\n0492: num_candidates=AUTO_RUN_SETTINGS[self.auto][\"n\"],\n0493: valset_size=len(valset) if valset is not None else len(trainset),\n0494: )\n0495: elif self.max_full_evals is not None:\n0496: self.max_metric_calls = self.max_full_evals * (len(trainset) + (len(valset) if valset is not None else 0))\n0497: else:\n0498: assert self.max_metric_calls is not None, \"Either auto, max_full_evals, or max_metric_calls must be set.\"\n0499: \n0500: logger.info(\n0501: f\"Running GEPA for approx {self.max_metric_calls} metric calls of the program. This amounts to {self.max_metric_calls / len(trainset) if valset is None else self.max_metric_calls / (len(trainset) + len(valset)):.2f} full evals on the {'train' if valset is None else 'train+val'} set.\"\n0502: )\n0503: \n0504: if valset is None:\n0505: logger.warning(\n0506: \"No valset provided; Using trainset as valset. This is useful as an inference-time scaling strategy where you want GEPA to find the best solutions for the provided tasks in the trainset, as it makes GEPA overfit prompts to the provided trainset. In order to ensure generalization and perform well on unseen tasks, please provide separate trainset and valset. Provide the smallest valset that is just large enough to match the downstream task distribution, while keeping trainset as large as possible.\"\n0507: )\n0508: valset = valset or trainset\n0509: # 35 matches the default minibatch_size in auto_budget(); when the valset is"}, {"span_id": "s5", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 366, "end_line": 397, "excerpt": "0366: ):\n0367: try:\n0368: inspect.signature(metric).bind(None, None, None, None, None)\n0369: except TypeError as e:\n0370: raise TypeError(\n0371: \"GEPA metric must accept five arguments: (gold, pred, trace, pred_name, pred_trace). \"\n0372: \"See https://dspy.ai/api/optimizers/GEPA for details.\"\n0373: ) from e\n0374: \n0375: self.metric_fn = metric\n0376: \n0377: # Budget configuration\n0378: assert (max_metric_calls is not None) + (max_full_evals is not None) + (auto is not None) == 1, (\n0379: \"Exactly one of max_metric_calls, max_full_evals, auto must be set. \"\n0380: f\"You set max_metric_calls={max_metric_calls}, \"\n0381: f\"max_full_evals={max_full_evals}, \"\n0382: f\"auto={auto}.\"\n0383: )\n0384: self.auto = auto\n0385: self.max_full_evals = max_full_evals\n0386: self.max_metric_calls = max_metric_calls\n0387: \n0388: # Reflection configuration\n0389: self.reflection_minibatch_size = reflection_minibatch_size\n0390: self.candidate_selection_strategy = candidate_selection_strategy\n0391: \n0392: assert reflection_lm is not None or instruction_proposer is not None, (\n0393: \"GEPA requires a reflection language model, or custom instruction proposer to be provided. \"\n0394: \"Typically, you can use `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)` to get a good reflection model. \"\n0395: \"Reflection LM is used by GEPA to reflect on the behavior of the program and propose new instructions, and will benefit from a strong model. \"\n0396: )\n0397: "}, {"span_id": "s6", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 598, "end_line": 604, "excerpt": "0598: new_prog = adapter.build_program(gepa_result.best_candidate)\n0599: \n0600: if self.track_stats:\n0601: dspy_gepa_result = DspyGEPAResult.from_gepa_result(gepa_result, adapter)\n0602: new_prog.detailed_results = dspy_gepa_result\n0603: \n0604: return new_prog"}]} {"id": "dspy_89c0e8c85588", "topic": "gepa_optimizer_usage", "question": "I'm optimizing a single-`Predict` question-answering program with `dspy.GEPA`, and I have no reference/gold answers in my trainset. What I do have is a stronger model I trust as an LLM judge: it reads a `(question, response)` pair, decides pass/fail, and writes a short critique explaining *why* it failed. I want GEPA to improve my program's instruction purely from those written critiques.\n\nMy current setup is stuck. First I wrapped `dspy.evaluate.SemanticF1` as my metric since it looked like the built-in LLM judge, and where that didn't fit I fell back to a hand-rolled metric that runs my judge and returns its numeric pass/fail score. Two problems: GEPA keeps complaining that it needs something else from the metric's signature, and even once it runs, the optimized instruction barely changes — the reflection step only ever seems to act on the bare score and never on the judge's written critique. Separately, I can't figure out how to make the judge actually run on my strong judge model; it keeps answering with the same small model that's running the task program.\n\nGive me one complete, runnable `dspy` program (use `dspy.utils.dummies.DummyLM` so it runs offline with no API keys) that does this correctly end to end: the task program on one model, the judge on a *separate* model, and a separate reflection model for GEPA; a trainset that carries only the question with no answer label; and the optimization genuinely driven by the judge's written critique rather than just its score. Print the program's optimized instruction at the end.", "gold_answer": "```python\nimport dspy\nfrom dspy.utils.dummies import DummyLM\n\n\nclass AnswerProgram(dspy.Module):\n def __init__(self):\n super().__init__()\n self.predictor = dspy.Predict('question -> answer')\n\n def forward(self, question):\n return self.predictor(question=question)\n\n\nclass JudgeSignature(dspy.Signature):\n question: str = dspy.InputField()\n response: str = dspy.InputField()\n verdict: str = dspy.OutputField()\n feedback: str = dspy.OutputField()\n\n\njudge = dspy.Predict(JudgeSignature)\n\n\ndef metric(gold, pred, trace=None, pred_name=None, pred_trace=None):\n with dspy.context(lm=judge_lm):\n review = judge(question=gold.question, response=pred.answer)\n score = 1.0 if review.verdict.lower() == 'pass' else 0.0\n return dspy.Prediction(score=score, feedback=review.feedback)\n\n\ntask_lm = DummyLM({'capital of France': {'answer': 'Lyon'}})\njudge_lm = DummyLM({\n 'Lyon': {'verdict': 'fail', 'feedback': 'Say Paris, not Lyon.'},\n 'Paris': {'verdict': 'pass', 'feedback': 'Correct.'},\n})\nreflection_lm = DummyLM([\n {'improved_instruction': 'Return the exact capital city only.'},\n] * 8)\n\ndspy.configure(lm=task_lm)\ntrainset = [\n dspy.Example(question='What is the capital of France?').with_inputs('question'),\n]\n\noptimized = dspy.GEPA(\n metric=metric,\n reflection_lm=reflection_lm,\n max_metric_calls=4,\n seed=0,\n).compile(AnswerProgram(), trainset=trainset, valset=trainset)\nprint(optimized.predictor.signature.instructions)\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 28, "statement": "The metric handed to dspy.GEPA is a PLAIN Python callable whose parameter list is GEPA's five-argument signature `(gold, pred, trace=None, pred_name=None, pred_trace=None)` (a def or lambda accepting these five positional params; extra params with no defaults that break the 5-positional call do not count). Anti-decoy: it must NOT be a built-in scorer module such as `dspy.evaluate.SemanticF1` (or any dspy.Module) wrapped/passed as the metric — those expose `forward(self, example, pred, trace)` (3 args), so GEPA's signature check rejects them; and the program must actually pass this callable as `dspy.GEPA(metric=...)`, NOT replace dspy.GEPA with a hand-rolled optimization loop.", "span_ids": ["s1"]}, {"claim_id": "c2", "claim_type": "core", "weight": 26, "statement": "The metric's return statement constructs an object that carries BOTH a numeric score AND the judge's textual critique under a `feedback` attribute — i.e. `dspy.Prediction(score=..., feedback=)` (or a ScoreWithFeedback). Anti-decoy: returning only the number (a bare `float`, a `(score, info)` tuple, or a Prediction/dict that lacks a `feedback` field) is WRONG, because GEPA keeps the object only when `hasattr(o, 'feedback')` and otherwise substitutes the content-free `\"This trajectory got a score of {score}.\"`, discarding the critique.", "span_ids": ["s2"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "Inside the metric, the judge Predict call is explicitly routed to a SEPARATE LM from the task program's LM — via `with dspy.context(lm=judge_lm):` around the call, an `lm=judge_lm` kwarg on the judge call, or by setting the judge module's own `.lm`. Anti-decoy: a `dspy.Predict` judge that is merely instantiated and then called with no LM routing is WRONG — Predict resolves `lm = kwargs.pop('lm', self.lm) or settings.lm`, so it falls through to the active task LM and the 'separate judge model' requirement is unmet.", "span_ids": ["s3"]}, {"claim_id": "c4", "claim_type": "core", "weight": 18, "statement": "`dspy.GEPA(...)` is constructed with a `reflection_lm=` argument bound to a third LM object distinct from the task LM and the judge LM (no custom instruction_proposer is supplied), satisfying GEPA's `assert reflection_lm is not None or instruction_proposer is not None`.", "span_ids": ["s4"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 8, "statement": "Each trainset (and valset) Example is built carrying only the task input via `.with_inputs('question')` with no answer/reference label, and the metric reads the model's prediction (e.g. `pred.answer`) directly rather than any gold/reference field. Anti-decoy: depending on a gold field such as `example.response` (as SemanticF1 requires) contradicts the no-gold-answers premise.", "span_ids": ["s5"]}], "evidence": [{"span_id": "s1", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 27, "end_line": 35, "excerpt": "0027: class GEPAFeedbackMetric(Protocol):\n0028: def __call__(\n0029: self,\n0030: gold: Example,\n0031: pred: Prediction,\n0032: trace: Optional[\"DSPyTrace\"],\n0033: pred_name: str | None,\n0034: pred_trace: Optional[\"DSPyTrace\"],\n0035: ) -> Union[float, \"ScoreWithFeedback\"]:"}, {"span_id": "s2", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 45, "end_line": 54, "excerpt": "0045: Note the `pred_name` and `pred_trace` arguments. During optimization, GEPA will call the metric to obtain\n0046: feedback for individual predictors being optimized. GEPA provides the name of the predictor in `pred_name`\n0047: and the sub-trace (of the trace) corresponding to the predictor in `pred_trace`.\n0048: If available at the predictor level, the metric should return dspy.Prediction(score: float, feedback: str)\n0049: corresponding to the predictor.\n0050: If not available at the predictor level, the metric can also return a text feedback at the program level\n0051: (using just the gold, pred and trace).\n0052: If no feedback is returned, GEPA will use a simple text feedback consisting of just the score:\n0053: f\"This trajectory got a score of {score}.\"\n0054: \"\"\""}, {"span_id": "s3", "path": "dspy/predict/predict.py", "start_line": 143, "end_line": 147, "excerpt": "0143: config = {**self.config, **kwargs.pop(\"config\", {})}\n0144: \n0145: # Get the right LM to use.\n0146: lm = kwargs.pop(\"lm\", self.lm) or settings.lm\n0147: "}, {"span_id": "s4", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 389, "end_line": 396, "excerpt": "0389: self.reflection_minibatch_size = reflection_minibatch_size\n0390: self.candidate_selection_strategy = candidate_selection_strategy\n0391: \n0392: assert reflection_lm is not None or instruction_proposer is not None, (\n0393: \"GEPA requires a reflection language model, or custom instruction proposer to be provided. \"\n0394: \"Typically, you can use `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)` to get a good reflection model. \"\n0395: \"Reflection LM is used by GEPA to reflect on the behavior of the program and propose new instructions, and will benefit from a strong model. \"\n0396: )"}, {"span_id": "s5", "path": "dspy/primitives/example.py", "start_line": 223, "end_line": 229, "excerpt": "0223: def with_inputs(self, *keys):\n0224: \"\"\"Mark which fields are inputs and return a new `Example`.\n0225: \n0226: Fields not listed here are treated as labels (expected outputs).\n0227: DSPy optimizers and evaluators use this split: they pass\n0228: `example.inputs()` to your program and compare the output against\n0229: `example.labels()`."}]} {"id": "dspy_52b34e22e3eb", "topic": "gepa_optimizer_usage", "question": "I'm using `dspy.GEPA` and I want my own prompt-improvement step to rewrite predictor instructions using a dedicated rewrite model that is completely separate from the model my program uses to answer tasks. I deliberately don't want GEPA to own or manage that rewrite model, so I construct GEPA without giving it any reflection model. Right now I pass my dedicated rewrite model the same way I would with my other optimizers — as a `prompt_model=...` argument to the optimizer — and plug in my own callable that builds a `dspy.Predict` to do the rewriting. It runs end to end with no error, but when I inspect what actually produced the new instructions, the rewrites are clearly coming from my task model, not my dedicated rewrite model. Write the prompt-improvement callable plus a tiny compile example so that the rewrites genuinely run on my own separate model, and the whole thing still works with GEPA constructed without a reflection model. Print something at the end that proves the separate rewrite model (not the task model) did the instruction rewriting.", "gold_answer": "```python\nimport dspy\nfrom dspy.utils.dummies import DummyLM\n\n\nclass RewriteInstruction(dspy.Signature):\n current_instruction: str = dspy.InputField()\n feedback_blob: str = dspy.InputField()\n improved_instruction: str = dspy.OutputField()\n\n\nclass ExternalReflectionProposer:\n def __init__(self):\n self.rewriter = dspy.Predict(RewriteInstruction)\n # Dict-mode DummyLM keyed on the always-present output field name\n # 'improved_instruction', so it NEVER exhausts no matter how many times\n # GEPA's reflection loop invokes the proposer (a fixed-length list-mode\n # DummyLM would, once drained, emit an unparseable response).\n self.external_lm = DummyLM(\n {'improved_instruction': {'improved_instruction': 'Answer with the exact short answer and no extra text.'}}\n )\n\n def __call__(self, candidate, reflective_dataset, components_to_update):\n updated = {}\n with dspy.context(lm=self.external_lm):\n for name in components_to_update:\n feedback_blob = '\\n'.join(ex['Feedback'] for ex in reflective_dataset.get(name, [])) or 'No feedback yet.'\n updated[name] = self.rewriter(\n current_instruction=candidate[name],\n feedback_blob=feedback_blob,\n ).improved_instruction\n return updated\n\n\nclass QAProgram(dspy.Module):\n def __init__(self):\n super().__init__()\n self.predictor = dspy.Predict('question -> answer')\n\n def forward(self, question):\n return self.predictor(question=question)\n\n\ndef metric(gold, pred, trace=None, pred_name=None, pred_trace=None):\n score = float(pred.answer.strip().lower() == gold.answer.lower())\n return dspy.Prediction(score=score, feedback='Return the exact short answer and nothing else.')\n\n\nproposer = ExternalReflectionProposer()\ntask_lm = DummyLM({'capital of France': {'answer': 'Lyon'}})\ndspy.configure(lm=task_lm)\ntrainset = [\n dspy.Example(question='What is the capital of France?', answer='Paris').with_inputs('question'),\n]\n\noptimized = dspy.GEPA(\n metric=metric,\n reflection_lm=None,\n instruction_proposer=proposer,\n max_metric_calls=5,\n seed=0,\n).compile(QAProgram(), trainset=trainset, valset=trainset)\n\nprint({\n 'optimized_instruction': optimized.predictor.signature.instructions,\n 'external_reflection_calls': len(proposer.external_lm.history),\n})\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 35, "statement": "GEPA is constructed with NO separate-prompt-LM constructor argument: the answer relies ONLY on `reflection_lm=None` together with a custom `instruction_proposer=...` (the constructor's `assert reflection_lm is not None or instruction_proposer is not None` is satisfied by the proposer). It must NOT pass any `prompt_model=`, `prompt_improvement_step=`, or `reflection_model=` argument to `dspy.GEPA(...)` — those are the plausible decoy from other optimizers (MIPROv2/COPRO) and do not exist on GEPA.", "span_ids": ["span_1", "span_6"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "The custom instruction proposer is a callable whose call signature is EXACTLY `(candidate, reflective_dataset, components_to_update)` and that returns a `dict[str, str]` mapping each component name to its new instruction string (matching how `DspyAdapter.propose_new_texts` invokes it). It is NOT a `(policy, predictor, trainset)`-style hook and does not mutate predictor objects in place.", "span_ids": ["span_2", "span_3"]}, {"claim_id": "c3", "claim_type": "core", "weight": 25, "statement": "Because GEPA holds no reflection model, `propose_new_texts` runs the proposer inside `with dspy.context(lm=(reflection_lm or dspy.settings.lm))`, i.e. the ambient TASK LM. To rewrite on the SEPARATE model the proposer's `__call__` MUST itself open `with dspy.context(lm=external_rewrite_lm)` around its `dspy.Predict`/LM calls, using the snapshot's convention — NOT by attaching `lm=external_rewrite_lm` to `dspy.Predict(...)`, NOT by passing a `prompt_model`, NOT by setting GEPA's reflection LM, and NOT by relying on the ambient/task LM.", "span_ids": ["span_4", "span_5"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "The compile example configures a normal task LM separately via `dspy.configure(lm=...)`, builds a simple student `dspy.Module`/predictor and a small trainset/valset, and calls `dspy.GEPA(...).compile(...)` with the custom proposer attached and no reflection model and no decoy prompt-model argument given to GEPA.", "span_ids": ["span_6", "span_7"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 10, "statement": "The example sets up two distinct LM objects — a task LM (configured globally) and the proposer's own separate rewrite LM — and the program prints static evidence that the rewrite ran on the separate model rather than the task model (e.g. it prints `len(.history)`, or prints the optimized instruction that originated from the separate rewrite LM).", "span_ids": ["span_5", "span_7"]}], "evidence": [{"span_id": "span_1", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 392, "end_line": 398, "excerpt": "0392: assert reflection_lm is not None or instruction_proposer is not None, (\n0393: \"GEPA requires a reflection language model, or custom instruction proposer to be provided. \"\n0394: \"Typically, you can use `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)` to get a good reflection model. \"\n0395: \"Reflection LM is used by GEPA to reflect on the behavior of the program and propose new instructions, and will benefit from a strong model. \"\n0396: )\n0397: \n0398: self.reflection_lm = reflection_lm"}, {"span_id": "span_2", "path": "dspy/teleprompt/gepa/gepa_utils.py", "start_line": 104, "end_line": 118, "excerpt": "0104: def propose_new_texts(\n0105: self,\n0106: candidate: dict[str, str],\n0107: reflective_dataset: dict[str, list[dict[str, Any]]],\n0108: components_to_update: list[str],\n0109: ) -> dict[str, str]:\n0110: reflection_lm = self.reflection_lm or dspy.settings.lm\n0111: # If custom proposer provided, override everything with custom proposer\n0112: if self.custom_instruction_proposer:\n0113: with dspy.context(lm=reflection_lm):\n0114: return self.custom_instruction_proposer(\n0115: candidate=candidate,\n0116: reflective_dataset=reflective_dataset,\n0117: components_to_update=components_to_update,\n0118: )"}, {"span_id": "span_3", "path": "dspy/teleprompt/gepa/gepa_utils.py", "start_line": 120, "end_line": 134, "excerpt": "0120: results: dict[str, str] = {}\n0121: \n0122: with dspy.context(lm=reflection_lm):\n0123: for name in components_to_update:\n0124: base_instruction = candidate[name]\n0125: dataset_with_feedback = reflective_dataset[name]\n0126: results[name] = InstructionProposalSignature.run(\n0127: lm=(lambda x: self.stripped_lm_call(x)[0]),\n0128: input_dict={\n0129: \"current_instruction_doc\": base_instruction,\n0130: \"dataset_with_feedback\": dataset_with_feedback,\n0131: },\n0132: )[\"new_instruction\"]\n0133: \n0134: return results"}, {"span_id": "span_4", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 244, "end_line": 247, "excerpt": "0244: \n0245: Note: When both instruction_proposer and reflection_lm are set, the instruction_proposer is called\n0246: in the reflection_lm context. However, reflection_lm is optional when using a custom instruction_proposer.\n0247: Custom instruction proposers can invoke their own LLMs if needed."}, {"span_id": "span_5", "path": "tests/teleprompt/test_gepa_instruction_proposer.py", "start_line": 147, "end_line": 153, "excerpt": "0147: class ProposerWithExternalLM:\n0148: def __call__(self, candidate, reflective_dataset, components_to_update):\n0149: # This proposer manages its own external reflection LM\n0150: with dspy.context(lm=external_reflection_lm):\n0151: # Use external LM for reflection (optional - could be any custom logic)\n0152: external_reflection_lm([{\"role\": \"user\", \"content\": \"Improve this instruction\"}])\n0153: return {name: f\"Externally-improved: {candidate[name]}\" for name in components_to_update}"}, {"span_id": "span_6", "path": "tests/teleprompt/test_gepa_instruction_proposer.py", "start_line": 180, "end_line": 189, "excerpt": "0180: # Test the full flexibility: no reflection_lm provided to GEPA at all!\n0181: # The updated GEPA core library now allows this when using custom proposers\n0182: gepa = dspy.GEPA(\n0183: metric=lambda gold, pred, trace=None, pred_name=None, pred_trace=None: 0.7, # Score to trigger optimization\n0184: max_metric_calls=5, # More calls to allow proper optimization\n0185: reflection_lm=None, # No reflection_lm provided - this now works!\n0186: instruction_proposer=ProposerWithExternalLM(),\n0187: )\n0188: \n0189: result = gepa.compile(student, trainset=[example], valset=[example])"}, {"span_id": "span_7", "path": "tests/teleprompt/test_gepa_instruction_proposer.py", "start_line": 155, "end_line": 179, "excerpt": "0155: student = dspy.Predict(\"text -> label\")\n0156: example = dspy.Example(text=\"test input\", label=\"test\").with_inputs(\"text\")\n0157: \n0158: # Use a robust dummy LM with enough responses for optimization steps\n0159: lm = DummyLM(\n0160: [\n0161: {\"label\": \"test\"},\n0162: {\"label\": \"result\"},\n0163: {\"label\": \"output\"},\n0164: {\"label\": \"response\"},\n0165: {\"label\": \"classification\"},\n0166: {\"label\": \"prediction\"},\n0167: {\"label\": \"category\"},\n0168: {\"label\": \"type\"},\n0169: {\"label\": \"class\"},\n0170: {\"label\": \"group\"},\n0171: {\"label\": \"kind\"},\n0172: {\"label\": \"variant\"},\n0173: {\"label\": \"form\"},\n0174: {\"label\": \"style\"},\n0175: {\"label\": \"mode\"},\n0176: ]\n0177: )\n0178: dspy.configure(lm=lm)\n0179: "}]} {"id": "dspy_9e8d3c68af73", "topic": "gepa_optimizer_usage", "question": "I'm setting up a GEPA run with `auto=\"light\"` and a small QA program (one `Predict`), and I keep mixing up the three example collections: the trainset, the validation set, and the per-step reflection minibatch. Before I launch, I want a helper that prints what each of those three is actually used for, and that estimates how many metric calls the `light` budget will spend so I can sanity-check cost.\n\nRight now my cost estimate is way off. I size the budget by taking my per-step reflection minibatch size (I set it to 2) and feeding that in as the per-step evaluation count, and I get a number around 50. But when I actually call compile, GEPA logs that it's going to run hundreds of metric calls — nowhere near my estimate. I must be feeding the wrong knob into the budget math.\n\nWrite a single runnable Python program that defines the helper, prints the role of the trainset vs. the validation set vs. the reflection minibatch (including what happens to the validation set if I don't pass one), computes the estimated `light` metric-call budget, then runs a GEPA compile on the same split and shows that my estimate now matches the budget GEPA actually used. Use `dspy.utils.dummies.DummyLM` for both the task LM and the reflection LM so it runs offline.", "gold_answer": "```python\nimport json\nimport dspy\nfrom dspy.utils.dummies import DummyLM\n\n# GEPA's \"light\" / \"medium\" / \"heavy\" auto presets resolve to these candidate counts.\nAUTO_CANDIDATE_COUNTS = {'light': 6, 'medium': 12, 'heavy': 18}\n\n\nclass QAProgram(dspy.Module):\n def __init__(self):\n super().__init__()\n self.predictor = dspy.Predict('question -> answer')\n\n def forward(self, question):\n return self.predictor(question=question)\n\n\ndef metric(gold, pred, trace=None, pred_name=None, pred_trace=None):\n score = float(pred.answer.strip().lower() == gold.answer.lower())\n return dspy.Prediction(score=score, feedback='Return the exact answer only.')\n\n\ndef summarize_gepa_setup(student, trainset, valset, reflection_minibatch_size, auto_level, reflection_lm):\n optimizer = dspy.GEPA(\n metric=metric,\n reflection_lm=reflection_lm,\n auto=auto_level,\n reflection_minibatch_size=reflection_minibatch_size,\n seed=0,\n )\n\n # The auto budget is computed exactly the way compile() computes it: from the\n # predictor count, the light-preset candidate count, and the size of the set\n # used for full candidate scoring (the valset). reflection_minibatch_size is a\n # reflection/trainset setting and is NOT an input to the budget estimate -- the\n # budget's own per-step evaluation sample size keeps its default.\n valset_for_scoring = valset if valset is not None else trainset\n estimated_calls = optimizer.auto_budget(\n num_preds=len(student.predictors()),\n num_candidates=AUTO_CANDIDATE_COUNTS[auto_level],\n valset_size=len(valset_for_scoring),\n )\n\n summary = {\n 'trainset_role': 'sampled for reflective instruction updates',\n 'valset_role': 'used for full candidate scoring and Pareto-frontier tracking',\n 'reflection_minibatch_role': 'how many trainset examples are used for reflection in a single GEPA step',\n 'valset_fallback': 'if no valset is passed, the trainset is reused as the valset for scoring',\n 'trainset_size': len(trainset),\n 'valset_size': len(valset_for_scoring),\n 'reflection_minibatch_size': reflection_minibatch_size,\n 'estimated_max_metric_calls': estimated_calls,\n }\n return optimizer, summary\n\n\ntask_lm = DummyLM({'capital of France': {'answer': 'Lyon'}})\nreflection_lm = DummyLM([{'improved_instruction': 'Return the exact answer only.'}] * 8)\ndspy.configure(lm=task_lm)\n\ntrainset = [\n dspy.Example(question='What is the capital of France?', answer='Paris').with_inputs('question'),\n dspy.Example(question='Name the capital of France.', answer='Paris').with_inputs('question'),\n]\nvalset = [\n dspy.Example(question='Which city is the capital of France?', answer='Paris').with_inputs('question'),\n]\n\nstudent = QAProgram()\noptimizer, summary = summarize_gepa_setup(\n student,\n trainset=trainset,\n valset=valset,\n reflection_minibatch_size=2,\n auto_level='light',\n reflection_lm=reflection_lm,\n)\n\noptimized = optimizer.compile(student, trainset=trainset, valset=valset)\n\n# After compile(), the optimizer stores the budget it actually used. Our estimate\n# must match it exactly, which only happens if reflection_minibatch_size was kept\n# out of the estimate.\nsummary['actual_max_metric_calls'] = optimizer.max_metric_calls\nsummary['estimate_matches_actual'] = (summary['estimated_max_metric_calls'] == optimizer.max_metric_calls)\nsummary['optimized_instruction'] = optimized.predictor.signature.instructions\nprint(json.dumps(summary, indent=2))\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 50, "statement": "DOMINANT ANTI-DECOY GATE: the light metric-call budget must be estimated via the snapshot's auto_budget estimator computed from only the student predictor count and the scoring valset size with the light-preset candidate count — i.e. auto_budget(num_preds=len(student.predictors()), num_candidates=6, valset_size=len(valset)) — letting auto_budget's internal per-step evaluation sample size keep its DEFAULT of 35. This is satisfied either by calling optimizer.auto_budget(...) directly or by an exact reproduction of that same estimator using the default minibatch_size=35. It must NOT feed the reflection minibatch size (reflection_minibatch_size=2) in as the per-step evaluation/minibatch sample, NOT substitute a hand-rolled heuristic, and NOT use MIPRO's valset-resizing val_size; doing any of those (e.g. yielding ~50/54 or a num_configs-style guess) FAILS this claim. The correct mechanism yields 384.", "span_ids": ["s3", "s4", "s6", "s7"]}, {"claim_id": "c2", "claim_type": "core", "weight": 12, "statement": "The helper must state GEPA's split semantics correctly — the trainset is sampled for reflective instruction updates while the valset is used for full candidate scoring / Pareto-frontier tracking — and must note the actual fallback that when no valset is passed GEPA REUSES the trainset as the valset for scoring, NOT that GEPA internally carves an auto train/validation split out of the trainset.", "span_ids": ["s1"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "CASCADE: the reflection minibatch must be presented as a reflection/trainset setting (how many trainset examples are used for reflection in a single GEPA step), separate and distinct from the validation set; the answer must NOT treat the reflection minibatch size as the validation / full-evaluation sample. (A budget-knob decoy commitment that feeds reflection_minibatch_size in as the per-step eval sample necessarily violates this claim as well as c1.)", "span_ids": ["s2", "s5"]}, {"claim_id": "c4", "claim_type": "core", "weight": 10, "statement": "When estimating the light budget the helper must use GEPA's light-preset candidate count of 6 (AUTO_RUN_SETTINGS['light']['n']), NOT MIPRO's preset and NOT the valset-resizing val_size=100.", "span_ids": ["s3"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 8, "statement": "STATIC MECHANISM CHECK: the GEPA run must be compiled on the same explicit split used for the summary — optimizer.compile(student, trainset=trainset, valset=valset) — and the answer must read the budget back from the optimizer's post-compile attribute optimizer.max_metric_calls (the attribute compile() assigns from auto_budget), rather than collapsing/changing the split or reading a different or invented stats field (e.g. detailed_results.total_metric_calls, search_stats). Judge only that the code references optimizer.max_metric_calls on the compiled optimizer; do NOT grade the runtime value or whether the printed numbers are equal.", "span_ids": ["s1", "s7"]}], "evidence": [{"span_id": "s1", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 465, "end_line": 480, "excerpt": "0465: def compile(\n0466: self,\n0467: student: Module,\n0468: *,\n0469: trainset: list[Example],\n0470: teacher: Module | None = None,\n0471: valset: list[Example] | None = None,\n0472: ) -> Module:\n0473: \"\"\"\n0474: GEPA uses the trainset to perform reflective updates to the prompt, but uses the valset for tracking Pareto scores.\n0475: If no valset is provided, GEPA will use the trainset for both.\n0476: \n0477: Parameters:\n0478: - student: The student module to optimize.\n0479: - trainset: The training set to use for reflective updates.\n0480: - valset: The validation set to use for tracking Pareto scores. If not provided, GEPA will use the trainset for both."}, {"span_id": "s2", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 520, "end_line": 561, "excerpt": "0520: \n0521: def feedback_fn_creator(pred_name: str, predictor) -> \"PredictorFeedbackFn\":\n0522: def feedback_fn(\n0523: predictor_output: dict[str, Any],\n0524: predictor_inputs: dict[str, Any],\n0525: module_inputs: Example,\n0526: module_outputs: Prediction,\n0527: captured_trace: \"DSPyTrace\",\n0528: ) -> \"ScoreWithFeedback\":\n0529: trace_for_pred = [(predictor, predictor_inputs, predictor_output)]\n0530: o = self.metric_fn(\n0531: module_inputs,\n0532: module_outputs,\n0533: captured_trace,\n0534: pred_name,\n0535: trace_for_pred,\n0536: )\n0537: if hasattr(o, \"feedback\"):\n0538: if o[\"feedback\"] is None:\n0539: o[\"feedback\"] = f\"This trajectory got a score of {o['score']}.\"\n0540: return o\n0541: else:\n0542: return dict(score=o, feedback=f\"This trajectory got a score of {o}.\")\n0543: \n0544: return feedback_fn\n0545: \n0546: feedback_map = {k: feedback_fn_creator(k, v) for k, v in student.named_predictors()}\n0547: \n0548: # Build the DSPy adapter that encapsulates evaluation, trace capture, feedback extraction, and instruction proposal\n0549: adapter = DspyAdapter(\n0550: student_module=student,\n0551: metric_fn=self.metric_fn,\n0552: feedback_map=feedback_map,\n0553: failure_score=self.failure_score,\n0554: num_threads=self.num_threads,\n0555: add_format_failure_as_feedback=self.add_format_failure_as_feedback,\n0556: rng=rng,\n0557: reflection_lm=self.reflection_lm,\n0558: custom_instruction_proposer=self.custom_instruction_proposer,\n0559: warn_on_score_mismatch=self.warn_on_score_mismatch,\n0560: reflection_minibatch_size=self.reflection_minibatch_size,\n0561: )"}, {"span_id": "s3", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 19, "end_line": 23, "excerpt": "0019: AUTO_RUN_SETTINGS = {\n0020: \"light\": {\"n\": 6},\n0021: \"medium\": {\"n\": 12},\n0022: \"heavy\": {\"n\": 18},\n0023: }"}, {"span_id": "s4", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 431, "end_line": 463, "excerpt": "0431: def auto_budget(\n0432: self, num_preds, num_candidates, valset_size: int, minibatch_size: int = 35, full_eval_steps: int = 5\n0433: ) -> int:\n0434: import numpy as np\n0435: \n0436: num_trials = int(max(2 * (num_preds * 2) * np.log2(num_candidates), 1.5 * num_candidates))\n0437: if num_trials < 0 or valset_size < 0 or minibatch_size < 0:\n0438: raise ValueError(\"num_trials, valset_size, and minibatch_size must be >= 0.\")\n0439: if full_eval_steps < 1:\n0440: raise ValueError(\"full_eval_steps must be >= 1.\")\n0441: \n0442: V = valset_size\n0443: N = num_trials\n0444: M = minibatch_size\n0445: m = full_eval_steps\n0446: \n0447: # Initial full evaluation on the default program\n0448: total = V\n0449: \n0450: # Assume upto 5 trials for bootstrapping each candidate\n0451: total += num_candidates * 5\n0452: \n0453: # N minibatch evaluations\n0454: total += N * M\n0455: if N == 0:\n0456: return total # no periodic/full evals inside the loop\n0457: # Periodic full evals occur when trial_num % (m+1) == 0, where trial_num runs 2..N+1\n0458: periodic_fulls = (N + 1) // (m) + 1\n0459: # If 1 <= N < m, the code triggers one final full eval at the end\n0460: extra_final = 1 if N < m else 0\n0461: \n0462: total += (periodic_fulls + extra_final) * V\n0463: return total"}, {"span_id": "s5", "path": "tests/teleprompt/test_gepa.py", "start_line": 46, "end_line": 88, "excerpt": "0046: @pytest.mark.parametrize(\"reflection_minibatch_size, batch, expected_callback_metadata\", [\n0047: (None, [], {\"metric_key\": \"eval_full\"}),\n0048: (None, [Example(input=\"What is the color of the sky?\", output=\"blue\")], {\"metric_key\": \"eval_full\"}),\n0049: (1, [], {\"disable_logging\": True}),\n0050: (1, [\n0051: Example(input=\"What is the color of the sky?\", output=\"blue\"),\n0052: Example(input=\"What does the fox say?\", output=\"Ring-ding-ding-ding-dingeringeding!\"),\n0053: ], {\"metric_key\": \"eval_full\"}),\n0054: ])\n0055: def test_gepa_adapter_disables_logging_on_minibatch_eval(monkeypatch, reflection_minibatch_size, batch, expected_callback_metadata):\n0056: from dspy.teleprompt import bootstrap_trace as bootstrap_trace_module\n0057: from dspy.teleprompt.gepa import gepa_utils\n0058: \n0059: class DummyModule(dspy.Module):\n0060: def forward(self, **kwargs): # pragma: no cover - stub forward\n0061: return dspy.Prediction()\n0062: \n0063: # Exercise the adapter evaluate path directly.\n0064: adapter = gepa_utils.DspyAdapter(\n0065: student_module=SimpleModule(\"input -> output\"),\n0066: metric_fn=simple_metric,\n0067: feedback_map={},\n0068: failure_score=0.0,\n0069: reflection_minibatch_size=reflection_minibatch_size,\n0070: )\n0071: \n0072: captured_kwargs: dict[str, Any] = {}\n0073: \n0074: def dummy_bootstrap_trace_data(*args, **kwargs):\n0075: captured_kwargs.update(kwargs)\n0076: return []\n0077: \n0078: monkeypatch.setattr(bootstrap_trace_module, \"bootstrap_trace_data\", dummy_bootstrap_trace_data)\n0079: monkeypatch.setattr(\n0080: gepa_utils.DspyAdapter,\n0081: \"build_program\",\n0082: lambda self, candidate: DummyModule(),\n0083: )\n0084: \n0085: adapter.evaluate(batch=batch, candidate={}, capture_traces=True)\n0086: \n0087: assert captured_kwargs[\"callback_metadata\"] == expected_callback_metadata\n0088: "}, {"span_id": "s6", "path": "dspy/primitives/module.py", "start_line": 160, "end_line": 177, "excerpt": "0160: def predictors(self):\n0161: \"\"\"Return all Predict modules in this module.\n0162: \n0163: Returns:\n0164: list[Predict]: A list of all Predict instances in this module.\n0165: \n0166: Examples:\n0167: >>> import dspy\n0168: >>> class MyProgram(dspy.Module):\n0169: ... def __init__(self):\n0170: ... super().__init__()\n0171: ... self.qa = dspy.Predict(\"question -> answer\")\n0172: ...\n0173: >>> program = MyProgram()\n0174: >>> len(program.predictors())\n0175: 1\n0176: \"\"\"\n0177: return [param for _, param in self.named_predictors()]"}, {"span_id": "s7", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 489, "end_line": 494, "excerpt": "0489: if self.auto is not None:\n0490: self.max_metric_calls = self.auto_budget(\n0491: num_preds=len(student.predictors()),\n0492: num_candidates=AUTO_RUN_SETTINGS[self.auto][\"n\"],\n0493: valset_size=len(valset) if valset is not None else len(trainset),\n0494: )"}]} {"id": "dspy_064741a8777f", "topic": "prompt_optimization_workflows", "question": "I'm building a support-ticket classifier and I want prompt optimization to rewrite my own seed instruction (not invent one from scratch), while keeping the deployed program completely demo-free — just the one optimized instruction, no few-shot examples baked in.\n\nRight now I'm running `dspy.COPRO`: I attach my seed wording to the signature, pass my labeled examples as the trainset, and it does rewrite the instruction with no demos. The problem is generalization. I can't get it to score candidate instructions against a *separate* held-out validation split — it keeps measuring quality on the very same examples it's tuning against, so the \"best\" instruction it picks is overfit and disappointing on fresh tickets.\n\nWrite a minimal 0-shot DSPy workflow that: defines the seed instruction, uses a labeled train set with a distinct held-out validation split that actually drives candidate selection, compiles the classifier so the final program carries the rewritten instruction but no demonstrations, and returns both the compiled predictor and its rewritten instruction.", "gold_answer": "```python\nimport dspy\n\n\ndef build_compiled_classifier():\n seed_instruction = (\n \"Classify each support ticket as billing, account, or technical. \"\n \"Return only the label.\"\n )\n program = dspy.Predict(dspy.Signature(\"ticket -> label\").with_instructions(seed_instruction))\n\n dataset = [\n dspy.Example(ticket=\"refund still pending\", label=\"billing\").with_inputs(\"ticket\"),\n dspy.Example(ticket=\"can't reset my password\", label=\"account\").with_inputs(\"ticket\"),\n dspy.Example(ticket=\"app crashes on launch\", label=\"technical\").with_inputs(\"ticket\"),\n dspy.Example(ticket=\"double charged for March\", label=\"billing\").with_inputs(\"ticket\"),\n dspy.Example(ticket=\"2FA code never arrives\", label=\"account\").with_inputs(\"ticket\"),\n ]\n trainset, valset = dataset[:3], dataset[3:]\n\n def metric(gold, pred, trace=None):\n return gold.label == pred.label\n\n task_lm = dspy.LM(\"openai/gpt-4o-mini\", cache=False)\n prompt_lm = dspy.LM(\"openai/gpt-4o-mini\", cache=False)\n dspy.configure(lm=task_lm)\n\n optimizer = dspy.MIPROv2(\n metric=metric,\n prompt_model=prompt_lm,\n task_model=task_lm,\n auto=\"light\",\n num_threads=1,\n )\n compiled = optimizer.compile(\n program,\n trainset=trainset,\n valset=valset,\n max_bootstrapped_demos=0,\n max_labeled_demos=0,\n )\n return compiled, compiled.signature.instructions\n\n\ncompiled_program, optimized_instruction = build_compiled_classifier()\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 30, "statement": "The workflow seeds the predictor with the user's own instruction by building a signature like `\"ticket -> label\"` and calling `with_instructions(seed_instruction)` on it before wrapping in `dspy.Predict`, rather than letting the optimizer invent the base wording.", "span_ids": ["s1"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "The compile call passes an explicit labeled `valset` alongside `trainset` so candidate instructions are scored on a held-out split, rather than relying on the optimizer's implicit 80/20 autosplit of the trainset.", "span_ids": ["s2"]}, {"claim_id": "c3", "claim_type": "core", "weight": 30, "statement": "The classifier is optimized with `dspy.MIPROv2` and the compile call passes BOTH `max_bootstrapped_demos=0` and `max_labeled_demos=0` (the zero-shot configuration that sets `zeroshot_opt` and drops demo candidates so the deployed program carries no demonstrations). It does NOT use `dspy.COPRO`/SignatureOptimizer, whose `compile` takes no `valset` and scores instructions on the trainset.", "span_ids": ["s3", "s4"]}, {"claim_id": "c4", "claim_type": "core", "weight": 15, "statement": "The function returns the compiled predictor itself together with the rewritten instruction read from that compiled predictor's active signature via `compiled.signature.instructions`.", "span_ids": ["s5", "s6"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 5, "statement": "The answer relies on `Predict` keeping its active signature on `self.signature` (rather than a separately tracked instruction string), so the optimized instruction is read off the compiled predictor's own signature.", "span_ids": ["s6"]}], "evidence": [{"span_id": "s1", "path": "dspy/signatures/signature.py", "start_line": 269, "end_line": 297, "excerpt": "0269: @classmethod\n0270: def with_instructions(cls, instructions: str) -> type[\"Signature\"]:\n0271: \"\"\"Return a new Signature class with identical fields and new instructions.\n0272: \n0273: This method does not mutate `cls`. It constructs a fresh Signature\n0274: class using the current fields and the provided `instructions`.\n0275: \n0276: Args:\n0277: instructions (str): Instruction text to attach to the new signature.\n0278: \n0279: Returns:\n0280: A new Signature class whose fields match `cls.fields`\n0281: and whose instructions equal `instructions`.\n0282: \n0283: Examples:\n0284: ```python\n0285: import dspy\n0286: \n0287: class MySig(dspy.Signature):\n0288: input_text: str = dspy.InputField(desc=\"Input text\")\n0289: output_text: str = dspy.OutputField(desc=\"Output text\")\n0290: \n0291: NewSig = MySig.with_instructions(\"Translate to French.\")\n0292: assert NewSig is not MySig\n0293: assert NewSig.instructions == \"Translate to French.\"\n0294: ```\n0295: \"\"\"\n0296: return Signature(cls.fields, instructions)\n0297: "}, {"span_id": "s2", "path": "dspy/teleprompt/mipro_optimizer_v2.py", "start_line": 111, "end_line": 131, "excerpt": "0111: self,\n0112: student: Any,\n0113: *,\n0114: trainset: list,\n0115: teacher: Any = None,\n0116: valset: list | None = None,\n0117: num_trials: int | None = None,\n0118: max_bootstrapped_demos: int | None = None,\n0119: max_labeled_demos: int | None = None,\n0120: seed: int | None = None,\n0121: minibatch: bool = True,\n0122: minibatch_size: int = 35,\n0123: minibatch_full_eval_steps: int = 5,\n0124: program_aware_proposer: bool = True,\n0125: data_aware_proposer: bool = True,\n0126: view_data_batch_size: int = 10,\n0127: tip_aware_proposer: bool = True,\n0128: fewshot_aware_proposer: bool = True,\n0129: requires_permission_to_run: bool | None = None, # deprecated\n0130: provide_traceback: bool | None = None,\n0131: ) -> Any:"}, {"span_id": "s3", "path": "dspy/teleprompt/mipro_optimizer_v2.py", "start_line": 145, "end_line": 153, "excerpt": "0145: effective_max_bootstrapped_demos = (\n0146: max_bootstrapped_demos if max_bootstrapped_demos is not None else self.max_bootstrapped_demos\n0147: )\n0148: effective_max_labeled_demos = (\n0149: max_labeled_demos if max_labeled_demos is not None else self.max_labeled_demos\n0150: )\n0151: \n0152: zeroshot_opt = (effective_max_bootstrapped_demos == 0) and (effective_max_labeled_demos == 0)\n0153: "}, {"span_id": "s4", "path": "dspy/teleprompt/mipro_optimizer_v2.py", "start_line": 257, "end_line": 260, "excerpt": "0257: # If zero-shot, discard demos\n0258: if zeroshot_opt:\n0259: demo_candidates = None\n0260: "}, {"span_id": "s5", "path": "dspy/predict/predict.py", "start_line": 58, "end_line": 63, "excerpt": "0058: def __init__(self, signature: str | type[Signature], callbacks: list[BaseCallback] | None = None, **config):\n0059: super().__init__(callbacks=callbacks)\n0060: self.stage = random.randbytes(8).hex()\n0061: self.signature = ensure_signature(signature)\n0062: self.config = config\n0063: self.reset()"}, {"span_id": "s6", "path": "dspy/predict/predict.py", "start_line": 88, "end_line": 90, "excerpt": "0088: state[\"signature\"] = self.signature.dump_state()\n0089: state[\"lm\"] = self.lm.dump_state() if self.lm else None\n0090: return state"}]} {"id": "dspy_9f98ea7f1ef5", "topic": "prompt_optimization_workflows", "question": "I'm building a customer-support classifier in DSPy. There's a fixed policy block of musts/nevers (e.g. \"MUST ask for an order ID before refunds; NEVER request a full card number\") that has to reach the model **word-for-word at runtime** and must NOT be paraphrased or absorbed into anything the optimizer rewrites — only the short per-task instruction should be tuned. The dynamic customer message is the only thing the caller passes in.\n\nRight now I'm running `dspy.BetterTogether` to \"lock in\" the policy: the idea was to prompt-optimize and then fine-tune so the policy gets burned in and stops drifting. But this feels wrong — the policy keeps getting rewritten, and I don't want it living in model weights or in auto-generated few-shot examples; I want it to stay literal input data that I supply on every call. I also need to know the program's real quality on data the optimizer never touched.\n\nShow me a complete, runnable DSPy program that: keeps the policy as literal runtime data, optimizes only the task instruction (nothing baked into weights or demos), compiles with proper train/validation splits, and then reports a score on a separate held-out split.", "gold_answer": "```python\nimport dspy\nfrom typing import Literal\n\nPOLICY = \"\"\"MUST request an order ID before discussing refunds.\nNEVER ask for a full card number.\"\"\"\n\n\nclass SafeDecision(dspy.Signature):\n policy: str = dspy.InputField()\n message: str = dspy.InputField()\n decision: Literal[\"ask_order_id\", \"decline_sensitive\", \"general_help\"] = dspy.OutputField()\n\n\nclass SafeResponder(dspy.Module):\n def __init__(self):\n super().__init__()\n sig = SafeDecision.with_instructions(\n \"Read the customer message and return the next action label only.\"\n )\n self.decide = dspy.Predict(sig)\n\n def forward(self, message: str):\n return self.decide(policy=POLICY, message=message)\n\n\nexamples = [\n dspy.Example(message=\"Where is my refund?\", decision=\"ask_order_id\").with_inputs(\"message\"),\n dspy.Example(message=\"My card number is 4242 4242 4242 4242\", decision=\"decline_sensitive\").with_inputs(\"message\"),\n dspy.Example(message=\"How do I update my shipping address?\", decision=\"general_help\").with_inputs(\"message\"),\n dspy.Example(message=\"Refund this order please\", decision=\"ask_order_id\").with_inputs(\"message\"),\n dspy.Example(message=\"Here is my full card number\", decision=\"decline_sensitive\").with_inputs(\"message\"),\n dspy.Example(message=\"Can I change the email on my account?\", decision=\"general_help\").with_inputs(\"message\"),\n dspy.Example(message=\"Refund my cancelled purchase\", decision=\"ask_order_id\").with_inputs(\"message\"),\n]\ntrainset = examples[:3]\nopt_valset = examples[3:5]\nheldout = examples[5:]\n\n\ndef metric(gold, pred, trace=None):\n return gold.decision == pred.decision\n\n\ntask_lm = dspy.LM(\"openai/gpt-4o-mini\", cache=False)\nprompt_lm = dspy.LM(\"openai/gpt-4o-mini\", cache=False)\ndspy.configure(lm=task_lm)\n\noptimizer = dspy.MIPROv2(\n metric=metric,\n prompt_model=prompt_lm,\n task_model=task_lm,\n auto=\"light\",\n num_threads=1,\n)\ncompiled = optimizer.compile(\n SafeResponder(),\n trainset=trainset,\n valset=opt_valset,\n max_bootstrapped_demos=0,\n max_labeled_demos=0,\n)\nheldout_score = dspy.Evaluate(devset=heldout, metric=metric, num_threads=1)(compiled).score\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 50, "statement": "Optimization is performed by calling MIPROv2.compile(...) on the whole module in its instruction-only (zero-shot) regime, selected by passing BOTH max_bootstrapped_demos=0 AND max_labeled_demos=0 (the zeroshot_opt path). It must NOT use a fine-tuning / weight-optimizing or prompt+weights meta-optimizer (e.g. BetterTogether or BootstrapFinetune), which would bake behavior into model weights, and it must NOT rely on demo/few-shot bootstrapping, which would bake the policy into auto-generated demonstrations -- NOT either of those decoys that the user proposes.", "span_ids": ["s2", "s7", "s8"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "The fixed policy is carried as the value of a signature InputField and supplied to the predictor at call time as literal runtime data; it is NOT placed into, nor rewritten as part of, the instruction text that the optimizer edits (and not stuffed into the signature docstring), so the optimizer never touches the policy text.", "span_ids": ["s1", "s2"]}, {"claim_id": "c3", "claim_type": "core", "weight": 15, "statement": "The predictor's tunable-instruction signature variant is produced with Signature.with_instructions(...), which yields a new signature with identical fields and a fresh instruction string while leaving the policy InputField value untouched -- NOT by hand-reconstructing a generic ad-hoc signature (e.g. dspy.Signature('policy, message -> decision', instr)) or by editing the docstring.", "span_ids": ["s5", "s6"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 15, "statement": "Final scoring is performed on a separate held-out split via dspy.Evaluate(devset=, metric=...) applied to the compiled program, reading the .score off the returned evaluation result -- a split distinct from the valset used during MIPROv2 compilation.", "span_ids": ["s9"]}], "evidence": [{"span_id": "s1", "path": "dspy/signatures/signature.py", "start_line": 193, "end_line": 245, "excerpt": "0193: # Ensure all fields are declared with InputField or OutputField\n0194: cls._validate_fields()\n0195: \n0196: # Ensure all fields have a prefix\n0197: for name, field in cls.model_fields.items():\n0198: if \"prefix\" not in field.json_schema_extra:\n0199: field.json_schema_extra[\"prefix\"] = infer_prefix(name) + \":\"\n0200: if \"desc\" not in field.json_schema_extra:\n0201: field.json_schema_extra[\"desc\"] = f\"${{{name}}}\"\n0202: \n0203: return cls\n0204: \n0205: def _validate_fields(cls):\n0206: for name, field in cls.model_fields.items():\n0207: extra = field.json_schema_extra or {}\n0208: field_type = extra.get(\"__dspy_field_type\")\n0209: if field_type not in [\"input\", \"output\"]:\n0210: raise TypeError(\n0211: f\"Field `{name}` in `{cls.__name__}` must be declared with InputField or OutputField, but \"\n0212: f\"field `{name}` has `field.json_schema_extra={field.json_schema_extra}`\",\n0213: )\n0214: \n0215: @property\n0216: def instructions(cls) -> str:\n0217: return inspect.cleandoc(getattr(cls, \"__doc__\", \"\"))\n0218: \n0219: @instructions.setter\n0220: def instructions(cls, instructions: str) -> None:\n0221: cls.__doc__ = instructions\n0222: \n0223: @property\n0224: def input_fields(cls) -> dict[str, FieldInfo]:\n0225: return cls._get_fields_with_type(\"input\")\n0226: \n0227: @property\n0228: def output_fields(cls) -> dict[str, FieldInfo]:\n0229: return cls._get_fields_with_type(\"output\")\n0230: \n0231: @property\n0232: def fields(cls) -> dict[str, FieldInfo]:\n0233: # Make sure to give input fields before output fields\n0234: return {**cls.input_fields, **cls.output_fields}\n0235: \n0236: @property\n0237: def signature(cls) -> str:\n0238: \"\"\"The string representation of the signature.\"\"\"\n0239: input_fields = \", \".join(cls.input_fields.keys())\n0240: output_fields = \", \".join(cls.output_fields.keys())\n0241: return f\"{input_fields} -> {output_fields}\"\n0242: \n0243: def _get_fields_with_type(cls, field_type) -> dict[str, FieldInfo]:\n0244: return {k: v for k, v in cls.model_fields.items() if v.json_schema_extra[\"__dspy_field_type\"] == field_type}\n0245: "}, {"span_id": "s2", "path": "dspy/teleprompt/mipro_optimizer_v2.py", "start_line": 754, "end_line": 785, "excerpt": "0754: def _select_and_insert_instructions_and_demos(\n0755: self,\n0756: candidate_program: Any,\n0757: instruction_candidates: dict[int, list[str]],\n0758: demo_candidates: list | None,\n0759: trial: \"optuna.trial.Trial\",\n0760: trial_logs: dict,\n0761: trial_num: int,\n0762: ) -> list[str]:\n0763: chosen_params = []\n0764: raw_chosen_params = {}\n0765: \n0766: for i, predictor in enumerate(candidate_program.predictors()):\n0767: # Select instruction\n0768: instruction_idx = trial.suggest_categorical(\n0769: f\"{i}_predictor_instruction\", range(len(instruction_candidates[i]))\n0770: )\n0771: selected_instruction = instruction_candidates[i][instruction_idx]\n0772: updated_signature = get_signature(predictor).with_instructions(selected_instruction)\n0773: set_signature(predictor, updated_signature)\n0774: trial_logs[trial_num][f\"{i}_predictor_instruction\"] = instruction_idx\n0775: chosen_params.append(f\"Predictor {i}: Instruction {instruction_idx}\")\n0776: raw_chosen_params[f\"{i}_predictor_instruction\"] = instruction_idx\n0777: # Select demos if available\n0778: if demo_candidates:\n0779: demos_idx = trial.suggest_categorical(f\"{i}_predictor_demos\", range(len(demo_candidates[i])))\n0780: predictor.demos = demo_candidates[i][demos_idx]\n0781: trial_logs[trial_num][f\"{i}_predictor_demos\"] = demos_idx\n0782: chosen_params.append(f\"Predictor {i}: Few-Shot Set {demos_idx}\")\n0783: raw_chosen_params[f\"{i}_predictor_demos\"] = instruction_idx\n0784: \n0785: return chosen_params, raw_chosen_params"}, {"span_id": "s3", "path": "dspy/primitives/module.py", "start_line": 40, "end_line": 67, "excerpt": "0040: class Module(BaseModule, metaclass=ProgramMeta):\n0041: \"\"\"Base class for all DSPy modules (programs).\n0042: \n0043: A Module is a building block for DSPy programs that can contain predictors,\n0044: sub-modules, and custom logic. Modules can be composed together to create\n0045: complex pipelines and can be optimized using DSPy's teleprompters.\n0046: \n0047: All DSPy programs should inherit from this class and implement a ``forward``\n0048: method that defines the program's logic.\n0049: \n0050: Args:\n0051: callbacks: Optional list of callback handlers for instrumentation\n0052: and monitoring.\n0053: \n0054: Attributes:\n0055: callbacks: List of registered callback handlers.\n0056: history: List of LM call history for this module.\n0057: \n0058: Examples:\n0059: >>> import dspy\n0060: >>> class MyProgram(dspy.Module):\n0061: ... def __init__(self):\n0062: ... super().__init__()\n0063: ... self.predictor = dspy.Predict(\"question -> answer\")\n0064: ...\n0065: ... def forward(self, question):\n0066: ... return self.predictor(question=question)\n0067: \"\"\""}, {"span_id": "s4", "path": "dspy/primitives/module.py", "start_line": 93, "end_line": 110, "excerpt": "0093: @with_callbacks\n0094: def __call__(self, *args, **kwargs) -> Prediction:\n0095: from dspy.dsp.utils.settings import thread_local_overrides\n0096: \n0097: caller_modules = settings.caller_modules or []\n0098: caller_modules = list(caller_modules)\n0099: caller_modules.append(self)\n0100: \n0101: with settings.context(caller_modules=caller_modules):\n0102: if settings.track_usage and thread_local_overrides.get().get(\"usage_tracker\") is None:\n0103: with track_usage() as usage_tracker:\n0104: output = self.forward(*args, **kwargs)\n0105: tokens = usage_tracker.get_total_tokens()\n0106: self._set_lm_usage(tokens, output)\n0107: \n0108: return output\n0109: \n0110: return self.forward(*args, **kwargs)"}, {"span_id": "s5", "path": "dspy/signatures/signature.py", "start_line": 269, "end_line": 297, "excerpt": "0269: @classmethod\n0270: def with_instructions(cls, instructions: str) -> type[\"Signature\"]:\n0271: \"\"\"Return a new Signature class with identical fields and new instructions.\n0272: \n0273: This method does not mutate `cls`. It constructs a fresh Signature\n0274: class using the current fields and the provided `instructions`.\n0275: \n0276: Args:\n0277: instructions (str): Instruction text to attach to the new signature.\n0278: \n0279: Returns:\n0280: A new Signature class whose fields match `cls.fields`\n0281: and whose instructions equal `instructions`.\n0282: \n0283: Examples:\n0284: ```python\n0285: import dspy\n0286: \n0287: class MySig(dspy.Signature):\n0288: input_text: str = dspy.InputField(desc=\"Input text\")\n0289: output_text: str = dspy.OutputField(desc=\"Output text\")\n0290: \n0291: NewSig = MySig.with_instructions(\"Translate to French.\")\n0292: assert NewSig is not MySig\n0293: assert NewSig.instructions == \"Translate to French.\"\n0294: ```\n0295: \"\"\"\n0296: return Signature(cls.fields, instructions)\n0297: "}, {"span_id": "s6", "path": "dspy/teleprompt/mipro_optimizer_v2.py", "start_line": 766, "end_line": 774, "excerpt": "0766: for i, predictor in enumerate(candidate_program.predictors()):\n0767: # Select instruction\n0768: instruction_idx = trial.suggest_categorical(\n0769: f\"{i}_predictor_instruction\", range(len(instruction_candidates[i]))\n0770: )\n0771: selected_instruction = instruction_candidates[i][instruction_idx]\n0772: updated_signature = get_signature(predictor).with_instructions(selected_instruction)\n0773: set_signature(predictor, updated_signature)\n0774: trial_logs[trial_num][f\"{i}_predictor_instruction\"] = instruction_idx"}, {"span_id": "s7", "path": "dspy/teleprompt/mipro_optimizer_v2.py", "start_line": 110, "end_line": 176, "excerpt": "0110: def compile(\n0111: self,\n0112: student: Any,\n0113: *,\n0114: trainset: list,\n0115: teacher: Any = None,\n0116: valset: list | None = None,\n0117: num_trials: int | None = None,\n0118: max_bootstrapped_demos: int | None = None,\n0119: max_labeled_demos: int | None = None,\n0120: seed: int | None = None,\n0121: minibatch: bool = True,\n0122: minibatch_size: int = 35,\n0123: minibatch_full_eval_steps: int = 5,\n0124: program_aware_proposer: bool = True,\n0125: data_aware_proposer: bool = True,\n0126: view_data_batch_size: int = 10,\n0127: tip_aware_proposer: bool = True,\n0128: fewshot_aware_proposer: bool = True,\n0129: requires_permission_to_run: bool | None = None, # deprecated\n0130: provide_traceback: bool | None = None,\n0131: ) -> Any:\n0132: if requires_permission_to_run == False:\n0133: logger.warning(\n0134: \"'requires_permission_to_run' is deprecated and will be removed in a future version.\"\n0135: )\n0136: elif requires_permission_to_run == True:\n0137: raise ValueError(\"User confirmation is removed from MIPROv2. Please remove the 'requires_permission_to_run' argument.\")\n0138: \n0139: effective_max_errors = (\n0140: self.max_errors\n0141: if self.max_errors is not None\n0142: else dspy.settings.max_errors\n0143: )\n0144: \n0145: effective_max_bootstrapped_demos = (\n0146: max_bootstrapped_demos if max_bootstrapped_demos is not None else self.max_bootstrapped_demos\n0147: )\n0148: effective_max_labeled_demos = (\n0149: max_labeled_demos if max_labeled_demos is not None else self.max_labeled_demos\n0150: )\n0151: \n0152: zeroshot_opt = (effective_max_bootstrapped_demos == 0) and (effective_max_labeled_demos == 0)\n0153: \n0154: # If auto is None, and num_trials is not provided (but num_candidates is), raise an error that suggests a good num_trials value\n0155: if self.auto is None and (self.num_candidates is not None and num_trials is None):\n0156: raise ValueError(\n0157: f\"If auto is None, num_trials must also be provided. Given num_candidates={self.num_candidates}, we'd recommend setting num_trials to ~{self._set_num_trials_from_num_candidates(student, zeroshot_opt, self.num_candidates)}.\"\n0158: )\n0159: \n0160: # If auto is None, and num_candidates or num_trials is None, raise an error\n0161: if self.auto is None and (self.num_candidates is None or num_trials is None):\n0162: raise ValueError(\"If auto is None, num_candidates must also be provided.\")\n0163: \n0164: # If auto is provided, and either num_candidates or num_trials is not None, raise an error\n0165: if self.auto is not None and (self.num_candidates is not None or num_trials is not None):\n0166: raise ValueError(\n0167: \"If auto is not None, num_candidates and num_trials cannot be set, since they would be overridden by the auto settings. Please either set auto to None, or do not specify num_candidates and num_trials.\"\n0168: )\n0169: \n0170: # Set random seeds\n0171: seed = seed or self.seed\n0172: self._set_random_seeds(seed)\n0173: \n0174: \n0175: # Set training & validation sets\n0176: trainset, valset = self._set_and_validate_datasets(trainset, valset)"}, {"span_id": "s8", "path": "dspy/teleprompt/mipro_optimizer_v2.py", "start_line": 145, "end_line": 153, "excerpt": "0145: effective_max_bootstrapped_demos = (\n0146: max_bootstrapped_demos if max_bootstrapped_demos is not None else self.max_bootstrapped_demos\n0147: )\n0148: effective_max_labeled_demos = (\n0149: max_labeled_demos if max_labeled_demos is not None else self.max_labeled_demos\n0150: )\n0151: \n0152: zeroshot_opt = (effective_max_bootstrapped_demos == 0) and (effective_max_labeled_demos == 0)\n0153: "}, {"span_id": "s9", "path": "dspy/evaluate/evaluate.py", "start_line": 64, "end_line": 128, "excerpt": "0064: class Evaluate:\n0065: \"\"\"DSPy Evaluate class.\n0066: \n0067: This class is used to evaluate the performance of a DSPy program. Users need to provide a evaluation dataset and\n0068: a metric function in order to use this class. This class supports parallel evaluation on the provided dataset.\n0069: \"\"\"\n0070: \n0071: def __init__(\n0072: self,\n0073: *,\n0074: devset: list[\"dspy.Example\"],\n0075: metric: Callable | None = None,\n0076: num_threads: int | None = None,\n0077: display_progress: bool = False,\n0078: display_table: bool | int = False,\n0079: max_errors: int | None = None,\n0080: provide_traceback: bool | None = None,\n0081: failure_score: float = 0.0,\n0082: save_as_csv: str | None = None,\n0083: save_as_json: str | None = None,\n0084: **kwargs,\n0085: ):\n0086: \"\"\"\n0087: Args:\n0088: devset (list[dspy.Example]): the evaluation dataset.\n0089: metric (Callable): The metric function to use for evaluation.\n0090: num_threads (Optional[int]): The number of threads to use for parallel evaluation.\n0091: display_progress (bool): Whether to display progress during evaluation.\n0092: display_table (Union[bool, int]): Whether to display the evaluation results in a table.\n0093: If a number is passed, the evaluation results will be truncated to that number before displayed.\n0094: max_errors (Optional[int]): The maximum number of errors to allow before\n0095: stopping evaluation. If ``None``, inherits from ``dspy.settings.max_errors``.\n0096: provide_traceback (Optional[bool]): Whether to provide traceback information during evaluation.\n0097: failure_score (float): The default score to use if evaluation fails due to an exception.\n0098: save_as_csv (Optional[str]): The file name where the csv will be saved.\n0099: save_as_json (Optional[str]): The file name where the json will be saved.\n0100: \n0101: \"\"\"\n0102: self.devset = devset\n0103: self.metric = metric\n0104: self.num_threads = num_threads\n0105: self.display_progress = display_progress\n0106: self.display_table = display_table\n0107: self.max_errors = max_errors\n0108: self.provide_traceback = provide_traceback\n0109: self.failure_score = failure_score\n0110: self.save_as_csv = save_as_csv\n0111: self.save_as_json = save_as_json\n0112: \n0113: if \"return_outputs\" in kwargs:\n0114: raise ValueError(\"`return_outputs` is no longer supported. Results are always returned inside the `results` field of the `EvaluationResult` object.\")\n0115: \n0116: @with_callbacks\n0117: def __call__(\n0118: self,\n0119: program: \"dspy.Module\",\n0120: metric: Callable | None = None,\n0121: devset: list[\"dspy.Example\"] | None = None,\n0122: num_threads: int | None = None,\n0123: display_progress: bool | None = None,\n0124: display_table: bool | int | None = None,\n0125: callback_metadata: dict[str, Any] | None = None,\n0126: save_as_csv: str | None = None,\n0127: save_as_json: str | None = None,\n0128: ) -> EvaluationResult:"}]} {"id": "dspy_962f53473587", "topic": "prompt_optimization_workflows", "question": "I have a two-step support agent: it first picks a route (billing / account / technical) for an incoming request, then drafts the reply conditioned on that route. I'm compiling the whole thing with `MIPROv2` against a metric that returns a single 0-1 score, and it plateaus quickly — the proposer never seems to figure out that most failures are a wrong *route*, not a bad reply. The thing is, when I grade an example I know exactly what went wrong in words (\"routed to billing but this is technical\", \"reply never mentioned the duplicate charge\"), and I want the optimizer to actually *read* those per-step explanations and use them to rewrite the two prompts — not just see the number. Give me a runnable Python program that builds the two-step module and optimizes both prompts end-to-end while feeding my written critique of the route step and of the answer step into the optimization.", "gold_answer": "```python\nimport dspy\n\n\nclass SupportAgent(dspy.Module):\n def __init__(self):\n super().__init__()\n self.route = dspy.Predict(\"question -> route\")\n self.reply = dspy.Predict(\"question, route -> answer\")\n\n def forward(self, question: str):\n route = self.route(question=question).route\n answer = self.reply(question=question, route=route).answer\n return dspy.Prediction(route=route, answer=answer)\n\n\ndataset = [\n dspy.Example(question=\"I was charged twice for one order\", route=\"billing\", answer=\"Ask billing to review the duplicate charge.\").with_inputs(\"question\"),\n dspy.Example(question=\"I cannot sign in after changing phones\", route=\"account\", answer=\"Ask account support to verify the sign-in issue.\").with_inputs(\"question\"),\n dspy.Example(question=\"The mobile app crashes on launch\", route=\"technical\", answer=\"Ask technical support to troubleshoot the crash.\").with_inputs(\"question\"),\n dspy.Example(question=\"My invoice has the wrong tax total\", route=\"billing\", answer=\"Ask billing to review the invoice tax total.\").with_inputs(\"question\"),\n]\ntrainset, valset = dataset[:3], dataset[3:]\n\n\ndef metric(gold, pred, trace=None, pred_name=None, pred_trace=None):\n route_ok = pred.route == gold.route\n answer_ok = pred.answer.strip().lower() == gold.answer.strip().lower()\n score = 0.4 * float(route_ok) + 0.6 * float(answer_ok)\n\n feedback = []\n if not route_ok:\n feedback.append(f\"Expected route {gold.route}, got {pred.route}.\")\n if not answer_ok:\n feedback.append(f\"Expected answer {gold.answer!r}.\")\n\n return dspy.Prediction(score=score, feedback=\" \".join(feedback) or \"Correct.\")\n\n\ntask_lm = dspy.LM(\"openai/gpt-4o-mini\", cache=False)\nreflection_lm = dspy.LM(\"openai/gpt-4o\", cache=False)\ndspy.configure(lm=task_lm)\n\ncompiled = dspy.GEPA(\n metric=metric,\n reflection_lm=reflection_lm,\n max_metric_calls=24,\n num_threads=1,\n).compile(SupportAgent(), trainset=trainset, valset=valset)\n\noptimized_prompts = {\n name: predictor.signature.instructions\n for name, predictor in compiled.named_predictors()\n}\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 22, "statement": "The solution defines one composed DSPy Module containing two predictors wired sequentially: a routing step (question -> route) feeding an answer step (question + the predicted route -> answer), and `forward` returns BOTH the route and the answer in a single `dspy.Prediction(...)`.", "span_ids": ["s1", "s2"]}, {"claim_id": "c2", "claim_type": "core", "weight": 30, "statement": "The optimizer is `dspy.GEPA`, whose `.compile(student, trainset=..., valset=...)` optimizes the whole two-step student module end-to-end. It is NOT the user's named `MIPROv2`, and NOT any other optimizer whose metric is a plain numeric `Callable` (e.g. SIMBA / COPRO / BootstrapFewShot): those route only the scalar score and structurally cannot consume the user's written per-step critique, which is exactly the plateau the user describes.", "span_ids": ["s3", "s4"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "The metric handed to GEPA is declared with the five-argument feedback signature `(gold, pred, trace, pred_name, pred_trace)`. A 2-argument numeric metric is rejected by GEPA's constructor (it does `inspect.signature(metric).bind(None, None, None, None, None)` and raises `TypeError`), which is precisely why the user's MIPROv2 setup could never read the critique.", "span_ids": ["s5", "s6"]}, {"claim_id": "c4", "claim_type": "core", "weight": 18, "statement": "That metric RETURNS a `dspy.Prediction(...)` (the ScoreWithFeedback shape) carrying BOTH a numeric `score` and a textual `feedback` string — not a bare float. GEPA feeds the `feedback` text into reflection to rewrite predictor instructions; feedback may be supplied at the predictor level (via `pred_name`) or at the program level.", "span_ids": ["s6", "s7"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 5, "statement": "The textual `feedback` string is built to explicitly distinguish a wrong-route mistake from a wrong-answer mistake (separate conditioned branches/messages for the route step and the answer step), so reflection can act on whichever step actually failed.", "span_ids": ["s6"]}, {"claim_id": "c6", "claim_type": "supporting", "weight": 5, "statement": "After compilation the optimized prompts for both steps are read back off the GEPA-compiled program by iterating `compiled.named_predictors()` and accessing each predictor's `signature.instructions`.", "span_ids": ["s8", "s9"]}], "evidence": [{"span_id": "s1", "path": "tests/teleprompt/test_gepa.py", "start_line": 271, "end_line": 282, "excerpt": "0271: class MultiComponentModule(dspy.Module):\n0272: \"\"\"Test module with multiple predictors.\"\"\"\n0273: \n0274: def __init__(self):\n0275: super().__init__()\n0276: self.classifier = Predict(\"input -> category\")\n0277: self.generator = Predict(\"category, input -> output\")\n0278: \n0279: def forward(self, input):\n0280: category = self.classifier(input=input).category\n0281: output = self.generator(category=category, input=input).output\n0282: return dspy.Prediction(category=category, output=output)"}, {"span_id": "s2", "path": "dspy/primitives/module.py", "start_line": 131, "end_line": 159, "excerpt": "0131: def named_predictors(self):\n0132: \"\"\"Return all named Predict modules in this module.\n0133: \n0134: Iterates through all parameters and returns those that are instances\n0135: of ``dspy.Predict``, along with their names.\n0136: \n0137: Returns:\n0138: list[tuple[str, Predict]]: A list of (name, predictor) tuples\n0139: where name is the attribute path and predictor is the\n0140: Predict instance.\n0141: \n0142: Examples:\n0143: >>> import dspy\n0144: >>> class MyProgram(dspy.Module):\n0145: ... def __init__(self):\n0146: ... super().__init__()\n0147: ... self.qa = dspy.Predict(\"question -> answer\")\n0148: ... self.summarize = dspy.Predict(\"text -> summary\")\n0149: ...\n0150: >>> program = MyProgram()\n0151: >>> for name, p in program.named_predictors():\n0152: ... print(name)\n0153: qa\n0154: summarize\n0155: \"\"\"\n0156: from dspy.predict.predict import Predict\n0157: \n0158: return [(name, param) for name, param in self.named_parameters() if isinstance(param, Predict)]\n0159: "}, {"span_id": "s3", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 465, "end_line": 599, "excerpt": "0465: def compile(\n0466: self,\n0467: student: Module,\n0468: *,\n0469: trainset: list[Example],\n0470: teacher: Module | None = None,\n0471: valset: list[Example] | None = None,\n0472: ) -> Module:\n0473: \"\"\"\n0474: GEPA uses the trainset to perform reflective updates to the prompt, but uses the valset for tracking Pareto scores.\n0475: If no valset is provided, GEPA will use the trainset for both.\n0476: \n0477: Parameters:\n0478: - student: The student module to optimize.\n0479: - trainset: The training set to use for reflective updates.\n0480: - valset: The validation set to use for tracking Pareto scores. If not provided, GEPA will use the trainset for both.\n0481: \"\"\"\n0482: from gepa import GEPAResult, optimize\n0483: \n0484: from dspy.teleprompt.gepa.gepa_utils import DspyAdapter, LoggerAdapter\n0485: \n0486: assert trainset is not None and len(trainset) > 0, \"Trainset must be provided and non-empty\"\n0487: assert teacher is None, \"Teacher is not supported in DspyGEPA yet.\"\n0488: \n0489: if self.auto is not None:\n0490: self.max_metric_calls = self.auto_budget(\n0491: num_preds=len(student.predictors()),\n0492: num_candidates=AUTO_RUN_SETTINGS[self.auto][\"n\"],\n0493: valset_size=len(valset) if valset is not None else len(trainset),\n0494: )\n0495: elif self.max_full_evals is not None:\n0496: self.max_metric_calls = self.max_full_evals * (len(trainset) + (len(valset) if valset is not None else 0))\n0497: else:\n0498: assert self.max_metric_calls is not None, \"Either auto, max_full_evals, or max_metric_calls must be set.\"\n0499: \n0500: logger.info(\n0501: f\"Running GEPA for approx {self.max_metric_calls} metric calls of the program. This amounts to {self.max_metric_calls / len(trainset) if valset is None else self.max_metric_calls / (len(trainset) + len(valset)):.2f} full evals on the {'train' if valset is None else 'train+val'} set.\"\n0502: )\n0503: \n0504: if valset is None:\n0505: logger.warning(\n0506: \"No valset provided; Using trainset as valset. This is useful as an inference-time scaling strategy where you want GEPA to find the best solutions for the provided tasks in the trainset, as it makes GEPA overfit prompts to the provided trainset. In order to ensure generalization and perform well on unseen tasks, please provide separate trainset and valset. Provide the smallest valset that is just large enough to match the downstream task distribution, while keeping trainset as large as possible.\"\n0507: )\n0508: valset = valset or trainset\n0509: # 35 matches the default minibatch_size in auto_budget(); when the valset is\n0510: # at or below this size, suggesting further reduction is unhelpful since GEPA\n0511: # would already evaluate the full valset per step.\n0512: if len(valset) > 35:\n0513: logger.info(\n0514: f\"Using {len(valset)} examples for tracking Pareto scores. You can consider using a smaller sample of the valset to allow GEPA to explore more diverse solutions within the same budget. GEPA requires you to provide the smallest valset that is just large enough to match your downstream task distribution, while providing as large trainset as possible.\"\n0515: )\n0516: else:\n0517: logger.info(f\"Using {len(valset)} examples for tracking Pareto scores.\")\n0518: \n0519: rng = random.Random(self.seed)\n0520: \n0521: def feedback_fn_creator(pred_name: str, predictor) -> \"PredictorFeedbackFn\":\n0522: def feedback_fn(\n0523: predictor_output: dict[str, Any],\n0524: predictor_inputs: dict[str, Any],\n0525: module_inputs: Example,\n0526: module_outputs: Prediction,\n0527: captured_trace: \"DSPyTrace\",\n0528: ) -> \"ScoreWithFeedback\":\n0529: trace_for_pred = [(predictor, predictor_inputs, predictor_output)]\n0530: o = self.metric_fn(\n0531: module_inputs,\n0532: module_outputs,\n0533: captured_trace,\n0534: pred_name,\n0535: trace_for_pred,\n0536: )\n0537: if hasattr(o, \"feedback\"):\n0538: if o[\"feedback\"] is None:\n0539: o[\"feedback\"] = f\"This trajectory got a score of {o['score']}.\"\n0540: return o\n0541: else:\n0542: return dict(score=o, feedback=f\"This trajectory got a score of {o}.\")\n0543: \n0544: return feedback_fn\n0545: \n0546: feedback_map = {k: feedback_fn_creator(k, v) for k, v in student.named_predictors()}\n0547: \n0548: # Build the DSPy adapter that encapsulates evaluation, trace capture, feedback extraction, and instruction proposal\n0549: adapter = DspyAdapter(\n0550: student_module=student,\n0551: metric_fn=self.metric_fn,\n0552: feedback_map=feedback_map,\n0553: failure_score=self.failure_score,\n0554: num_threads=self.num_threads,\n0555: add_format_failure_as_feedback=self.add_format_failure_as_feedback,\n0556: rng=rng,\n0557: reflection_lm=self.reflection_lm,\n0558: custom_instruction_proposer=self.custom_instruction_proposer,\n0559: warn_on_score_mismatch=self.warn_on_score_mismatch,\n0560: reflection_minibatch_size=self.reflection_minibatch_size,\n0561: )\n0562: \n0563: # Build the seed candidate: map each predictor name to its current instruction\n0564: seed_candidate = {name: pred.signature.instructions for name, pred in student.named_predictors()}\n0565: \n0566: gepa_result: GEPAResult = optimize(\n0567: seed_candidate=seed_candidate,\n0568: trainset=trainset,\n0569: valset=valset,\n0570: adapter=adapter,\n0571: # Reflection-based configuration\n0572: reflection_lm=(lambda x: adapter.stripped_lm_call(x)[0]) if self.reflection_lm is not None else None,\n0573: candidate_selection_strategy=self.candidate_selection_strategy,\n0574: skip_perfect_score=self.skip_perfect_score,\n0575: reflection_minibatch_size=self.reflection_minibatch_size,\n0576: module_selector=self.component_selector,\n0577: perfect_score=self.perfect_score,\n0578: # Merge-based configuration\n0579: use_merge=self.use_merge,\n0580: max_merge_invocations=self.max_merge_invocations,\n0581: # Budget\n0582: max_metric_calls=self.max_metric_calls,\n0583: # Logging\n0584: logger=LoggerAdapter(logger),\n0585: run_dir=self.log_dir,\n0586: use_wandb=self.use_wandb,\n0587: wandb_api_key=self.wandb_api_key,\n0588: wandb_init_kwargs=self.wandb_init_kwargs,\n0589: use_mlflow=self.use_mlflow,\n0590: track_best_outputs=self.track_best_outputs,\n0591: display_progress_bar=True,\n0592: raise_on_exception=True,\n0593: # Reproducibility\n0594: seed=self.seed,\n0595: **self.gepa_kwargs,\n0596: )\n0597: \n0598: new_prog = adapter.build_program(gepa_result.best_candidate)\n0599: "}, {"span_id": "s4", "path": "tests/teleprompt/test_gepa.py", "start_line": 99, "end_line": 126, "excerpt": "0099: def test_basic_workflow(use_mlflow, mock_mlflow):\n0100: \"\"\"Test to ensure the basic compile flow runs without errors.\"\"\"\n0101: student = SimpleModule(\"input -> output\")\n0102: \n0103: with open(\"tests/teleprompt/gepa_dummy_lm.json\") as f:\n0104: data = json.load(f)\n0105: lm_history = data[\"lm\"]\n0106: reflection_lm_history = data[\"reflection_lm\"]\n0107: \n0108: lm_main = DictDummyLM(lm_history)\n0109: dspy.configure(lm=lm_main)\n0110: reflection_lm = DictDummyLM(reflection_lm_history)\n0111: \n0112: optimizer = dspy.GEPA(\n0113: metric=simple_metric,\n0114: reflection_lm=reflection_lm,\n0115: max_metric_calls=5,\n0116: use_mlflow=use_mlflow\n0117: )\n0118: \n0119: \n0120: trainset = [\n0121: Example(input=\"What is the color of the sky?\", output=\"blue\").with_inputs(\"input\"),\n0122: Example(input=\"What does the fox say?\", output=\"Ring-ding-ding-ding-dingeringeding!\").with_inputs(\"input\"),\n0123: ]\n0124: \n0125: optimized_program = optimizer.compile(student, trainset=trainset, valset=trainset)\n0126: assert optimized_program.predictor.signature.instructions == 'Given the field `input` containing a question or phrase, produce the field `output` containing the exact, direct, and contextually appropriate answer or response that the user expects, without additional explanations, commentary, or general knowledge unless explicitly requested.\\n\\nKey details and guidelines:\\n\\n1. The `input` field contains a question or phrase that may be literal, factual, or culturally specific (e.g., references to popular culture or memes).\\n\\n2. The `output` must be the precise answer or response that directly addresses the `input` as intended by the user, not a general or encyclopedic explanation.\\n\\n3. If the `input` is a well-known phrase or question from popular culture (e.g., \"What does the fox say?\"), the `output` should reflect the expected or canonical answer associated with that phrase, rather than a factual or scientific explanation.\\n\\n4. Avoid providing additional background information, scientific explanations, or alternative interpretations unless explicitly requested.\\n\\n5. The goal is to produce the answer that the user expects or the \"correct\" answer in the context of the question, including culturally recognized or meme-based answers.\\n\\n6. If the `input` is a straightforward factual question (e.g., \"What is the color of the sky?\"), provide the commonly accepted direct answer (e.g., \"Blue\") rather than a detailed scientific explanation.\\n\\n7. The output should be concise, clear, and focused solely on answering the question or phrase in the `input`.\\n\\nExample:\\n\\n- Input: \"What is the color of the sky?\"\\n- Output: \"Blue.\"\\n\\n- Input: \"What does the fox say?\"\\n- Output: \"Ring-ding-ding-ding-dingeringeding!\"\\n\\nThis approach ensures that the assistant provides the expected, contextually appropriate answers rather than general or overly detailed responses that may be considered incorrect by the user.'"}, {"span_id": "s5", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 330, "end_line": 373, "excerpt": "0330: def __init__(\n0331: self,\n0332: metric: GEPAFeedbackMetric,\n0333: *,\n0334: # Budget configuration\n0335: auto: Literal[\"light\", \"medium\", \"heavy\"] | None = None,\n0336: max_full_evals: int | None = None,\n0337: max_metric_calls: int | None = None,\n0338: # Reflection configuration\n0339: reflection_minibatch_size: int = 3,\n0340: candidate_selection_strategy: Literal[\"pareto\", \"current_best\"] = \"pareto\",\n0341: reflection_lm: LM | None = None,\n0342: skip_perfect_score: bool = True,\n0343: add_format_failure_as_feedback: bool = False,\n0344: instruction_proposer: \"ProposalFn | None\" = None,\n0345: component_selector: \"ReflectionComponentSelector | str\" = \"round_robin\",\n0346: # Merge-based configuration\n0347: use_merge: bool = True,\n0348: max_merge_invocations: int | None = 5,\n0349: # Evaluation configuration\n0350: num_threads: int | None = None,\n0351: failure_score: float = 0.0,\n0352: perfect_score: float = 1.0,\n0353: # Logging\n0354: log_dir: str | None = None,\n0355: track_stats: bool = False,\n0356: use_wandb: bool = False,\n0357: wandb_api_key: str | None = None,\n0358: wandb_init_kwargs: dict[str, Any] | None = None,\n0359: track_best_outputs: bool = False,\n0360: warn_on_score_mismatch: bool = True,\n0361: use_mlflow: bool = False,\n0362: # Reproducibility\n0363: seed: int | None = 0,\n0364: # GEPA passthrough kwargs\n0365: gepa_kwargs: dict | None = None,\n0366: ):\n0367: try:\n0368: inspect.signature(metric).bind(None, None, None, None, None)\n0369: except TypeError as e:\n0370: raise TypeError(\n0371: \"GEPA metric must accept five arguments: (gold, pred, trace, pred_name, pred_trace). \"\n0372: \"See https://dspy.ai/api/optimizers/GEPA for details.\"\n0373: ) from e"}, {"span_id": "s6", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 27, "end_line": 55, "excerpt": "0027: class GEPAFeedbackMetric(Protocol):\n0028: def __call__(\n0029: self,\n0030: gold: Example,\n0031: pred: Prediction,\n0032: trace: Optional[\"DSPyTrace\"],\n0033: pred_name: str | None,\n0034: pred_trace: Optional[\"DSPyTrace\"],\n0035: ) -> Union[float, \"ScoreWithFeedback\"]:\n0036: \"\"\"\n0037: This function is called with the following arguments:\n0038: - gold: The gold example.\n0039: - pred: The predicted output.\n0040: - trace: Optional. The trace of the program's execution.\n0041: - pred_name: Optional. The name of the target predictor currently being optimized by GEPA, for which\n0042: the feedback is being requested.\n0043: - pred_trace: Optional. The trace of the target predictor's execution GEPA is seeking feedback for.\n0044: \n0045: Note the `pred_name` and `pred_trace` arguments. During optimization, GEPA will call the metric to obtain\n0046: feedback for individual predictors being optimized. GEPA provides the name of the predictor in `pred_name`\n0047: and the sub-trace (of the trace) corresponding to the predictor in `pred_trace`.\n0048: If available at the predictor level, the metric should return dspy.Prediction(score: float, feedback: str)\n0049: corresponding to the predictor.\n0050: If not available at the predictor level, the metric can also return a text feedback at the program level\n0051: (using just the gold, pred and trace).\n0052: If no feedback is returned, GEPA will use a simple text feedback consisting of just the score:\n0053: f\"This trajectory got a score of {score}.\"\n0054: \"\"\"\n0055: ..."}, {"span_id": "s7", "path": "tests/teleprompt/test_gepa.py", "start_line": 38, "end_line": 43, "excerpt": "0038: def simple_metric(example, prediction, trace=None, pred_name=None, pred_trace=None):\n0039: return dspy.Prediction(score=example.output == prediction.output, feedback=\"Wrong answer.\")\n0040: \n0041: \n0042: def bad_metric(example, prediction):\n0043: return 0.0"}, {"span_id": "s8", "path": "dspy/primitives/module.py", "start_line": 131, "end_line": 159, "excerpt": "0131: def named_predictors(self):\n0132: \"\"\"Return all named Predict modules in this module.\n0133: \n0134: Iterates through all parameters and returns those that are instances\n0135: of ``dspy.Predict``, along with their names.\n0136: \n0137: Returns:\n0138: list[tuple[str, Predict]]: A list of (name, predictor) tuples\n0139: where name is the attribute path and predictor is the\n0140: Predict instance.\n0141: \n0142: Examples:\n0143: >>> import dspy\n0144: >>> class MyProgram(dspy.Module):\n0145: ... def __init__(self):\n0146: ... super().__init__()\n0147: ... self.qa = dspy.Predict(\"question -> answer\")\n0148: ... self.summarize = dspy.Predict(\"text -> summary\")\n0149: ...\n0150: >>> program = MyProgram()\n0151: >>> for name, p in program.named_predictors():\n0152: ... print(name)\n0153: qa\n0154: summarize\n0155: \"\"\"\n0156: from dspy.predict.predict import Predict\n0157: \n0158: return [(name, param) for name, param in self.named_parameters() if isinstance(param, Predict)]\n0159: "}, {"span_id": "s9", "path": "dspy/teleprompt/gepa/gepa.py", "start_line": 563, "end_line": 599, "excerpt": "0563: # Build the seed candidate: map each predictor name to its current instruction\n0564: seed_candidate = {name: pred.signature.instructions for name, pred in student.named_predictors()}\n0565: \n0566: gepa_result: GEPAResult = optimize(\n0567: seed_candidate=seed_candidate,\n0568: trainset=trainset,\n0569: valset=valset,\n0570: adapter=adapter,\n0571: # Reflection-based configuration\n0572: reflection_lm=(lambda x: adapter.stripped_lm_call(x)[0]) if self.reflection_lm is not None else None,\n0573: candidate_selection_strategy=self.candidate_selection_strategy,\n0574: skip_perfect_score=self.skip_perfect_score,\n0575: reflection_minibatch_size=self.reflection_minibatch_size,\n0576: module_selector=self.component_selector,\n0577: perfect_score=self.perfect_score,\n0578: # Merge-based configuration\n0579: use_merge=self.use_merge,\n0580: max_merge_invocations=self.max_merge_invocations,\n0581: # Budget\n0582: max_metric_calls=self.max_metric_calls,\n0583: # Logging\n0584: logger=LoggerAdapter(logger),\n0585: run_dir=self.log_dir,\n0586: use_wandb=self.use_wandb,\n0587: wandb_api_key=self.wandb_api_key,\n0588: wandb_init_kwargs=self.wandb_init_kwargs,\n0589: use_mlflow=self.use_mlflow,\n0590: track_best_outputs=self.track_best_outputs,\n0591: display_progress_bar=True,\n0592: raise_on_exception=True,\n0593: # Reproducibility\n0594: seed=self.seed,\n0595: **self.gepa_kwargs,\n0596: )\n0597: \n0598: new_prog = adapter.build_program(gepa_result.best_candidate)\n0599: "}]} {"id": "dspy_81c16cac1a88", "topic": "prompt_optimization_workflows", "question": "I'm prototyping a tiny retrieval-augmented QA program in DSPy and I need it to run fully offline — no calls to any hosted service. Right now my module retrieves by instantiating `dspy.retrievers.Embeddings` over my list of passages and calling it directly inside `forward`, but that forces me to stand up an embedding model: the docs hand it `dspy.Embedder(\"openai/text-embedding-3-small\")`, which goes over the network, and hand-rolling my own embedding function to fake it feels like the wrong layer to be working at.\n\nWhat I actually want is for the retrieval step inside my module to pull from whatever retriever I've registered on DSPy's global configuration — so the module code stays fixed and I can swap the retrieval backend later just by reconfiguring DSPy — and for that configured backend to be a self-contained, in-memory index built directly from my handful of passages that needs no embedding model and no third-party packages installed. Then I want to compile the whole thing end-to-end with `BootstrapFewShot` on a tiny QA trainset and score the compiled program on a held-out example.\n\nGive me one runnable Python program: define the corpus and the QA examples inline, build the module so its retrieval step reads from the globally-configured retriever (not a retriever object you construct and call yourself), wire up the local in-memory backend, compile, and evaluate.", "gold_answer": "```python\nimport dspy\nfrom dspy.utils import dummy_rm\n\ncorpus = [\n \"Paris | Paris is the capital of France.\",\n \"Berlin | Berlin is the capital of Germany.\",\n \"Madrid | Madrid is the capital of Spain.\",\n \"Rome | Rome is the capital of Italy.\",\n]\n\n\nclass WriteQuery(dspy.Signature):\n question: str = dspy.InputField()\n query: str = dspy.OutputField()\n\n\nclass AnswerWithContext(dspy.Signature):\n context: list[str] = dspy.InputField()\n question: str = dspy.InputField()\n answer: str = dspy.OutputField()\n\n\nclass LocalRAG(dspy.Module):\n def __init__(self):\n super().__init__()\n self.write_query = dspy.Predict(WriteQuery)\n self.retrieve = dspy.Retrieve(k=2)\n self.answer = dspy.Predict(AnswerWithContext)\n\n def forward(self, question: str):\n query = self.write_query(question=question).query\n context = self.retrieve(query=query).passages\n answer = self.answer(context=context, question=question).answer\n return dspy.Prediction(query=query, context=context, answer=answer)\n\n\ndataset = [\n dspy.Example(question=\"What is the capital of France?\", answer=\"Paris\").with_inputs(\"question\"),\n dspy.Example(question=\"What is the capital of Germany?\", answer=\"Berlin\").with_inputs(\"question\"),\n dspy.Example(question=\"What is the capital of Spain?\", answer=\"Madrid\").with_inputs(\"question\"),\n dspy.Example(question=\"What is the capital of Italy?\", answer=\"Rome\").with_inputs(\"question\"),\n]\ntrainset, valset = dataset[:3], dataset[3:]\n\n\ndef metric(gold, pred, trace=None):\n exact = pred.answer.strip().lower() == gold.answer.strip().lower()\n grounded = any(gold.answer.lower() in passage.lower() for passage in pred.context)\n return float(exact and grounded)\n\n\nlm = dspy.LM(\"openai/gpt-4o-mini\", cache=False)\ndspy.configure(lm=lm, rm=dummy_rm(corpus))\n\ncompiled = dspy.BootstrapFewShot(\n metric=metric,\n max_bootstrapped_demos=2,\n max_labeled_demos=1,\n).compile(LocalRAG(), trainset=trainset)\n\nscore = dspy.Evaluate(devset=valset, metric=metric, num_threads=1)(compiled).score\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 30, "statement": "Inside the module's `forward`, retrieval is performed by DSPy's built-in `dspy.Retrieve(k=...)` (which pulls from the globally-configured rm), invoked on a SEPARATELY GENERATED search query passed as the query argument (positionally `self.retrieve(query)` or `query=query`, NOT `question=`) and consumed via its `.passages` attribute -- NOT by constructing and directly calling a retriever object inside `forward` (e.g. `dspy.retrievers.Embeddings(...)`/`Embeddings(...)` or a hand-rolled in-memory retriever instance).", "span_ids": ["s1", "s2", "s3"]}, {"claim_id": "c2", "claim_type": "core", "weight": 28, "statement": "The retrieval backend is registered on DSPy's global configuration via `dspy.configure(rm=...)` and is the snapshot's local, self-contained in-memory retriever built from the provided passages with `dummy_rm(corpus)` (no embedding model, no third-party packages, returns objects exposing `long_text`) -- NOT `dspy.Embedder`/`dspy.retrievers.Embeddings` or any embedding model, NOT a hand-rolled custom retriever object, and NOT a live service such as ColBERTv2/Databricks/Weaviate, and NOT attached through `dspy.settings.retriever`.", "span_ids": ["s2", "s4"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "The module is a retrieval-backed QA pipeline that generates a search query from the question, retrieves passages THROUGH THE GLOBALLY-CONFIGURED retriever, answers using the retrieved context, and returns a `dspy.Prediction` containing at least the retrieved context and the answer (it does not skip query generation and does not drop the context from the returned Prediction).", "span_ids": ["s3"]}, {"claim_id": "c4", "claim_type": "core", "weight": 12, "statement": "The program is compiled end-to-end with `BootstrapFewShot(...).compile(, trainset=...)` on a small inline QA training set (the `.compile(program, trainset=...)` form, NOT calling the optimizer instance directly like `optimizer(program, trainset)`).", "span_ids": ["s5"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 10, "statement": "The compiled program is scored on a held-out dev/validation example with a metric via `dspy.Evaluate(devset=..., metric=...)(compiled)` (or an equivalent explicit metric-over-devset evaluation of the compiled program).", "span_ids": ["s6"]}], "evidence": [{"span_id": "s1", "path": "dspy/retrievers/retrieve.py", "start_line": 18, "end_line": 25, "excerpt": "0018: class Retrieve(Parameter):\n0019: name = \"Search\"\n0020: input_variable = \"query\"\n0021: desc = \"takes a search query and returns one or more potentially relevant passages from a corpus\"\n0022: \n0023: def __init__(self, k=3, callbacks=None):\n0024: self.stage = random.randbytes(8).hex()\n0025: self.k = k"}, {"span_id": "s2", "path": "dspy/retrievers/retrieve.py", "start_line": 43, "end_line": 65, "excerpt": "0043: def forward(\n0044: self,\n0045: query: str,\n0046: k: int | None = None,\n0047: **kwargs,\n0048: ) -> list[str] | Prediction | list[Prediction]:\n0049: k = k if k is not None else self.k\n0050: \n0051: import dspy\n0052: \n0053: if not dspy.settings.rm:\n0054: raise AssertionError(\"No RM is loaded.\")\n0055: \n0056: passages = dspy.settings.rm(query, k=k, **kwargs)\n0057: \n0058: from collections.abc import Iterable\n0059: if not isinstance(passages, Iterable):\n0060: # it's not an iterable yet; make it one.\n0061: # TODO: we should unify the type signatures of dspy.Retriever\n0062: passages = [passages]\n0063: passages = [psg.long_text for psg in passages]\n0064: \n0065: return Prediction(passages=passages)"}, {"span_id": "s3", "path": "tests/examples/test_baleen.py", "start_line": 25, "end_line": 43, "excerpt": "0025: class SimplifiedBaleen(dspy.Module):\n0026: def __init__(self, passages_per_hop=3, max_hops=2):\n0027: super().__init__()\n0028: \n0029: self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]\n0030: self.retrieve = dspy.Retrieve(k=passages_per_hop)\n0031: self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n0032: self.max_hops = max_hops\n0033: \n0034: def forward(self, question):\n0035: context = []\n0036: \n0037: for hop in range(self.max_hops):\n0038: query = self.generate_query[hop](context=context, question=question).query\n0039: passages = self.retrieve(query).passages\n0040: context = deduplicate(context + passages)\n0041: \n0042: pred = self.generate_answer(context=context, question=question)\n0043: return dspy.Prediction(context=context, answer=pred.answer)"}, {"span_id": "s4", "path": "dspy/utils/dummies.py", "start_line": 157, "end_line": 176, "excerpt": "0157: def dummy_rm(passages=()) -> callable:\n0158: if not passages:\n0159: \n0160: def inner(query: str, *, k: int, **kwargs):\n0161: raise ValueError(\"No passages defined\")\n0162: \n0163: return inner\n0164: max_length = max(map(len, passages)) + 100\n0165: vectorizer = DummyVectorizer(max_length)\n0166: passage_vecs = vectorizer(passages)\n0167: \n0168: def inner(query: str, *, k: int, **kwargs):\n0169: assert k <= len(passages)\n0170: query_vec = vectorizer([query])[0]\n0171: scores = passage_vecs @ query_vec\n0172: largest_idx = (-scores).argsort()[:k]\n0173: \n0174: return [dotdict(long_text=passages[i]) for i in largest_idx]\n0175: \n0176: return inner"}, {"span_id": "s5", "path": "tests/examples/test_baleen.py", "start_line": 103, "end_line": 110, "excerpt": "0103: uncompiled_baleen = SimplifiedBaleen() # uncompiled (i.e., zero-shot) program\n0104: \n0105: teleprompter = BootstrapFewShot(metric=validate_context_and_answer_and_hops)\n0106: compiled_baleen = teleprompter.compile(\n0107: SimplifiedBaleen(),\n0108: teacher=SimplifiedBaleen(passages_per_hop=2),\n0109: trainset=trainset,\n0110: )"}, {"span_id": "s6", "path": "tests/examples/test_baleen.py", "start_line": 112, "end_line": 120, "excerpt": "0112: evaluate_on_hotpotqa = Evaluate(devset=devset, num_threads=1, display_progress=True, display_table=5)\n0113: uncompiled_baleen_retrieval_score = evaluate_on_hotpotqa(\n0114: uncompiled_baleen, metric=gold_passages_retrieved, display=False\n0115: )\n0116: # assert uncompiled_baleen_retrieval_score / 100 == 18 / 50\n0117: \n0118: compiled_baleen_retrieval_score = evaluate_on_hotpotqa(compiled_baleen, metric=gold_passages_retrieved)\n0119: # assert compiled_baleen_retrieval_score / 100 == 27 / 50\n0120: assert uncompiled_baleen_retrieval_score < compiled_baleen_retrieval_score"}]} {"id": "dspy_898cf1643d8a", "topic": "prompt_optimization_workflows", "question": "I'm building an inference-time guardrail for one stage of a DSPy program. There's no labeled data for this stage, but for every individual request I can score the model's output with a plain Python function that returns a float (higher = better), and I know the score I need to clear.\n\nRight now I wrap that stage in `dspy.BestOfN`, passing my scoring function as `reward_fn` with my cutoff as `threshold`, so it draws several candidates per request and returns the one that clears the bar (stopping early when one does). The early-stop and \"keep the best\" parts work fine. My problem is that the attempts don't compound: when a candidate misses, the next draw is just another independent roll at the same prompt, so on hard inputs all N attempts tend to repeat the *same* mistake and I burn the whole budget without ever clearing the threshold.\n\nWhat I actually want is for each retry to be told, in its own prompt, what went wrong on the previous attempt(s) and how to fix it — i.e. the failure should be turned into concrete guidance that's fed back into the next attempt automatically, while still keeping the per-request `reward_fn`, the threshold-based early stop, and needing no trainset. Write a runnable DSPy program that does this.", "gold_answer": "```python\nimport dspy\n\n# One stage of a larger program; no trainset for it, only a per-request scorer.\nstage = dspy.Predict(\n dspy.Signature(\"question -> answer\").with_instructions(\n \"Answer in one short, direct sentence. Do not hedge.\"\n )\n)\n\n\n# Per-request Python reward: higher is better, with a known passing cutoff.\ndef reward_fn(inputs, pred):\n answer = pred.answer.strip().lower()\n short_enough = len(answer.split()) <= 8\n no_hedging = all(word not in answer for word in [\"maybe\", \"probably\", \"might\"])\n return 1.0 if short_enough and no_hedging else 0.0\n\n\nlm = dspy.LM(\"openai/gpt-4o-mini\", cache=False, temperature=1.0)\ndspy.configure(lm=lm)\n\n# Refine (NOT BestOfN): on a below-threshold attempt it auto-generates concrete\n# advice about what went wrong and feeds it into the next attempt's prompt,\n# retrying up to N times and stopping early once reward_fn clears the threshold.\nguarded_stage = dspy.Refine(\n module=stage,\n N=4,\n reward_fn=reward_fn,\n threshold=1.0,\n)\n\nresult = guarded_stage(question=\"What is the capital of France?\")\nbest_answer = result.answer\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 55, "statement": "The guarded stage is built by wrapping the base prediction module in this snapshot's `dspy.Refine(module=..., N=..., reward_fn=..., threshold=...)` -- the answer must actually instantiate `dspy.Refine` (the snapshot exposes it with that exact `(module, N, reward_fn, threshold[, fail_count])` constructor). It must NOT instead use `dspy.BestOfN` and must NOT hand-roll its own retry loop (e.g. a custom `dspy.Module` subclass / `for`-loop that calls the inner module N times). Any answer that resamples without DSPy's built-in advice-injection module -- whether via `BestOfN` or a bespoke wrapper -- fails this claim, because both beasts and an unstudied model default to the bespoke wrapper that does not exist in the snapshot as the intended one-liner.", "span_ids": ["s1", "s2"]}, {"claim_id": "c2", "claim_type": "core", "weight": 25, "statement": "The failure-feedback compounding is delegated to `Refine`'s OWN built-in mechanism rather than reconstructed by hand: the answer relies on `Refine` internally calling `dspy.Predict(OfferFeedback)` after a below-threshold attempt and reinjecting the generated advice as a `hint_` input on the next retry (it does NOT manually assemble a critique/feedback string and splice it into the next prompt itself). An answer that writes its own `_build_feedback`/feedback-string-and-inject code path -- as opposed to letting `dspy.Refine` do it -- does not satisfy this claim.", "span_ids": ["s4"]}, {"claim_id": "c3", "claim_type": "supporting", "weight": 12, "statement": "The reward function is declared as a plain Python callable with the `(inputs, pred) -> float` shape (positional request-inputs first, the module's `Prediction` second) and is passed as `reward_fn`. (This shape is identical for `Refine` and `BestOfN`, so on its own it does not distinguish the correct answer -- hence supporting, not core.)", "span_ids": ["s3", "s2"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 8, "statement": "A numeric `threshold=` and a finite `N=` are passed into the retry mechanism, which is what configures the threshold-based early stop (return the first attempt whose reward reaches/exceeds the threshold, otherwise the best of up to N) and the no-trainset, per-request operation the question requires. Verified by the presence of the `threshold=`/`N=` arguments in the code text, not by any runtime value.", "span_ids": ["s5"]}], "evidence": [{"span_id": "s1", "path": "dspy/predict/refine.py", "start_line": 41, "end_line": 57, "excerpt": "0041: class Refine(Module):\n0042: def __init__(\n0043: self,\n0044: module: Module,\n0045: N: int, # noqa: N803\n0046: reward_fn: Callable[[dict, Prediction], float],\n0047: threshold: float,\n0048: fail_count: int | None = None,\n0049: ):\n0050: \"\"\"\n0051: Refines a module by running it up to N times with different rollout IDs at `temperature=1.0`\n0052: and returns the best prediction.\n0053: \n0054: This module runs the provided module multiple times with varying rollout identifiers and selects\n0055: either the first prediction that exceeds the specified threshold or the one with the highest reward.\n0056: If no prediction meets the threshold, it automatically generates feedback to improve future predictions.\n0057: "}, {"span_id": "s2", "path": "tests/predict/test_refine.py", "start_line": 31, "end_line": 39, "excerpt": "0031: def reward_fn(kwargs, pred: Prediction) -> float:\n0032: reward_call_count[0] += 1\n0033: # The answer should always be one word.\n0034: return 1.0 if len(pred.answer) == 1 else 0.0\n0035: \n0036: predict = DummyModule(\"question -> answer\", count_calls)\n0037: \n0038: refine = Refine(module=predict, N=3, reward_fn=reward_fn, threshold=1.0)\n0039: result = refine(question=\"What is the capital of Belgium?\")"}, {"span_id": "s3", "path": "dspy/predict/refine.py", "start_line": 87, "end_line": 89, "excerpt": "0087: self.module = module\n0088: self.reward_fn = lambda *args: reward_fn(*args) # to prevent this from becoming a parameter\n0089: self.threshold = threshold"}, {"span_id": "s4", "path": "dspy/predict/refine.py", "start_line": 115, "end_line": 167, "excerpt": "0115: try:\n0116: with dspy.context(trace=[]):\n0117: if not advice:\n0118: outputs = mod(**kwargs)\n0119: else:\n0120: \n0121: class WrapperAdapter(adapter.__class__):\n0122: def __call__(self, lm, lm_kwargs, signature, demos, inputs):\n0123: inputs[\"hint_\"] = advice.get(signature2name[signature], \"N/A\") # noqa: B023\n0124: signature = signature.append(\n0125: \"hint_\", InputField(desc=\"A hint to the module from an earlier run\")\n0126: )\n0127: return adapter(lm, lm_kwargs, signature, demos, inputs)\n0128: \n0129: with dspy.context(adapter=WrapperAdapter()):\n0130: outputs = mod(**kwargs)\n0131: \n0132: trace = dspy.settings.trace.copy()\n0133: \n0134: # TODO: Remove the hint from the trace, if it's there.\n0135: \n0136: # NOTE: Not including the trace of reward_fn.\n0137: reward = self.reward_fn(kwargs, outputs)\n0138: \n0139: if reward > best_reward:\n0140: best_reward, best_pred, best_trace = reward, outputs, trace\n0141: \n0142: if self.threshold is not None and reward >= self.threshold:\n0143: break\n0144: \n0145: if idx == self.N - 1:\n0146: break\n0147: \n0148: modules = {\"program_code\": self.module_code, \"modules_defn\": inspect_modules(mod)}\n0149: trajectory = [{\"module_name\": predictor2name[p], \"inputs\": i, \"outputs\": dict(o)} for p, i, o in trace]\n0150: trajectory = {\n0151: \"program_inputs\": kwargs,\n0152: \"program_trajectory\": trajectory,\n0153: \"program_outputs\": dict(outputs),\n0154: }\n0155: reward = {\n0156: \"reward_code\": self.reward_fn_code,\n0157: \"target_threshold\": self.threshold,\n0158: \"reward_value\": reward,\n0159: }\n0160: \n0161: advise_kwargs = dict(**modules, **trajectory, **reward, module_names=module_names)\n0162: # only dumps if it's a list or dict\n0163: advise_kwargs = {\n0164: k: v if isinstance(v, str) else orjson.dumps(recursive_mask(v), option=orjson.OPT_INDENT_2).decode()\n0165: for k, v in advise_kwargs.items()\n0166: }\n0167: advice = dspy.Predict(OfferFeedback)(**advise_kwargs).advice"}, {"span_id": "s5", "path": "dspy/predict/refine.py", "start_line": 137, "end_line": 145, "excerpt": "0137: reward = self.reward_fn(kwargs, outputs)\n0138: \n0139: if reward > best_reward:\n0140: best_reward, best_pred, best_trace = reward, outputs, trace\n0141: \n0142: if self.threshold is not None and reward >= self.threshold:\n0143: break\n0144: \n0145: if idx == self.N - 1:"}]} {"id": "dspy_2de37073e8e4", "topic": "react_agents_and_tools", "question": "I'm building a customer-facing support chatbot on a `dspy.ReAct` agent. Each user should have their own ongoing conversation, and the agent also needs a tool to look up our internal support notes. Today I keep a per-user dict of past turns and I've registered a `recall_history(user_id)` tool on the agent so the model can pull up earlier turns when it decides it needs them — but it's flaky: the model frequently answers a follow-up without ever calling `recall_history`, so it forgets what the user said two turns ago, and when two users chat at the same time their context bleeds together. What I actually want is for each user's own earlier turns to simply *be there* in the model's context for that user — the way prior chat messages would be — without me hand-assembling the prompt string and without depending on the model to fetch them. Write a runnable DSPy module that does this: separate conversation state per user, an internal-notes lookup tool on the agent, and a short demo of two users talking to the same bot with no leakage (include a follow-up from one user that relies on that same user's earlier turn).", "gold_answer": "```python\nfrom collections import defaultdict\n\nimport dspy\nfrom dspy.utils import DummyLM\n\n\nclass SupportTurn(dspy.Signature):\n user_message: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n reply: str = dspy.OutputField()\n\n\nclass StatefulSupportBot(dspy.Module):\n def __init__(self):\n super().__init__()\n self.notes = {\n 'refund': 'Refunds over $500 require manual review.',\n 'hours': 'Support hours are 9am-5pm Eastern.',\n }\n self.sessions = defaultdict(list)\n self.agent = dspy.ReAct(SupportTurn, tools=[self.lookup_note], max_iters=1)\n\n def lookup_note(self, query: str) -> str:\n matches = [text for key, text in self.notes.items() if key in query.lower()]\n return '\\\\n'.join(matches) or 'No matching note.'\n\n def forward(self, user_id: str, user_message: str) -> dspy.Prediction:\n history = dspy.History(messages=list(self.sessions[user_id]))\n pred = self.agent(user_message=user_message, history=history)\n self.sessions[user_id].append({'user_message': user_message, 'reply': pred.reply})\n return pred\n\n\nlm = DummyLM(\n [\n {'next_thought': 'Search the refund notes.', 'next_tool_name': 'lookup_note', 'next_tool_args': {'query': 'refund policy'}},\n {'reasoning': 'The note directly answers the refund question.', 'reply': 'Refunds over $500 require manual review.'},\n {'next_thought': 'Search the hours note.', 'next_tool_name': 'lookup_note', 'next_tool_args': {'query': 'support hours'}},\n {'reasoning': 'The hours note answers this directly.', 'reply': 'Support hours are 9am-5pm Eastern.'},\n {'next_thought': 'I already have the refund context from the earlier turn for this user.', 'next_tool_name': 'finish', 'next_tool_args': {}},\n {'reasoning': 'The follow-up refers to the earlier refund question from Alice, not the hours question from Bob.', 'reply': 'Yes. A $700 refund would still need manual review.'},\n ]\n)\ndspy.configure(lm=lm)\n\nbot = StatefulSupportBot()\nalice_1 = bot(user_id='alice', user_message='Explain the refund policy.')\nbob_1 = bot(user_id='bob', user_message='When are you open?')\nalice_2 = bot(user_id='alice', user_message='Does that apply to my $700 order too?')\nalice_history = bot.sessions['alice']\nbob_history = bot.sessions['bob']\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 40, "statement": "Per-user prior turns are surfaced to the model by declaring an input field of type `dspy.History` on the signature (e.g. `history: dspy.History = dspy.InputField()`) and passing it `dspy.History(messages=[...])` built from that user's stored turns — the snapshot's typed conversational-history input. The code must NOT instead hand-concatenate prior turns into a prompt/question/context string, and must NOT route prior turns through a recall/memory tool the agent has to choose to call. (Static: presence of a `dspy.History`-typed InputField wired with `dspy.History(messages=...)`, and absence of a stringified-history prompt field or a history-recall tool.)", "span_ids": ["s1", "s2"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "The tool-using agent is a `dspy.ReAct(signature, tools=[...])` constructed over the SAME signature that carries the `dspy.History` input field (so ReAct, which preserves the signature's input fields, sees that history field), and the tool list wired into ReAct is the internal-notes lookup function — NOT a recall_history/memory tool. ReAct must NOT be invoked with a single bare `question`/`prompt` string carrying the history. (Static: from the dspy.ReAct(, tools=[]) call and that declares the dspy.History field.)", "span_ids": ["s3", "s4"]}, {"claim_id": "c3", "claim_type": "supporting", "weight": 20, "statement": "Conversation state is stored separately keyed by user id (e.g. a per-user dict/list), the agent for a given call is given only that user's stored turns, and the new (user_message, reply) turn is appended back into that same per-user store. (Static: from a user_id-keyed container read into the History for the call and appended afterward.)", "span_ids": ["s2"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 12, "statement": "The demo runs two distinct user ids against the same single bot/agent instance with interleaved calls, and includes a follow-up message for one user that depends on that same user's own earlier turn (not the other user's turn). (Static: from the demo's interleaved calls under two user ids on one shared bot and a later same-user follow-up referencing the earlier turn.)", "span_ids": ["s2"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 8, "statement": "Each stored turn is a dict whose keys are signature field names (e.g. the user-input field name and the output field name), matching the dspy.History(messages=[...]) contract that each message is keyed by the associated signature's fields — NOT free-form {role, content}-only messages that don't correspond to the signature fields. (Static: from the message-dict keys used when appending/constructing dspy.History.)", "span_ids": ["s1"]}], "evidence": [{"span_id": "s1", "path": "dspy/adapters/types/history.py", "start_line": 6, "end_line": 19, "excerpt": "0006: class History(pydantic.BaseModel):\n0007: \"\"\"Class representing the conversation history.\n0008: \n0009: The conversation history is a list of messages, each message entity should have keys from the associated signature.\n0010: For example, if you have the following signature:\n0011: \n0012: ```\n0013: class MySignature(dspy.Signature):\n0014: question: str = dspy.InputField()\n0015: history: dspy.History = dspy.InputField()\n0016: answer: str = dspy.OutputField()\n0017: ```\n0018: \n0019: Then the history should be a list of dictionaries with keys \"question\" and \"answer\"."}, {"span_id": "s2", "path": "tests/predict/test_predict.py", "start_line": 683, "end_line": 725, "excerpt": "0683: @pytest.mark.parametrize(\"adapter_type\", [\"chat\", \"json\"])\n0684: def test_call_predict_with_chat_history(adapter_type):\n0685: class SpyLM(dspy.LM):\n0686: def __init__(self, *args, return_json=False, **kwargs):\n0687: super().__init__(*args, **kwargs)\n0688: self.calls = []\n0689: self.return_json = return_json\n0690: \n0691: def __call__(self, prompt=None, messages=None, **kwargs):\n0692: self.calls.append({\"prompt\": prompt, \"messages\": messages, \"kwargs\": kwargs})\n0693: if self.return_json:\n0694: return [\"{'answer':'100%'}\"]\n0695: return [\"[[ ## answer ## ]]\\n100%!\"]\n0696: \n0697: class MySignature(dspy.Signature):\n0698: question: str = dspy.InputField()\n0699: history: dspy.History = dspy.InputField()\n0700: answer: str = dspy.OutputField()\n0701: \n0702: program = Predict(MySignature)\n0703: \n0704: if adapter_type == \"chat\":\n0705: lm = SpyLM(\"dummy_model\")\n0706: dspy.configure(adapter=dspy.ChatAdapter(), lm=lm)\n0707: else:\n0708: lm = SpyLM(\"dummy_model\", return_json=True)\n0709: dspy.configure(adapter=dspy.JSONAdapter(), lm=lm)\n0710: \n0711: program(\n0712: question=\"are you sure that's correct?\",\n0713: history=dspy.History(messages=[{\"question\": \"what's the capital of france?\", \"answer\": \"paris\"}]),\n0714: )\n0715: \n0716: # Verify the LM was called with correct messages\n0717: assert len(lm.calls) == 1\n0718: messages = lm.calls[0][\"messages\"]\n0719: \n0720: assert len(messages) == 4\n0721: \n0722: assert \"what's the capital of france?\" in messages[1][\"content\"]\n0723: assert \"paris\" in messages[2][\"content\"]\n0724: assert \"are you sure that's correct\" in messages[3][\"content\"]\n0725: "}, {"span_id": "s3", "path": "dspy/predict/react.py", "start_line": 16, "end_line": 29, "excerpt": "0016: class ReAct(Module):\n0017: def __init__(self, signature: type[\"Signature\"], tools: list[Callable], max_iters: int = 20):\n0018: \"\"\"\n0019: ReAct stands for \"Reasoning and Acting,\" a popular paradigm for building tool-using agents.\n0020: In this approach, the language model is iteratively provided with a list of tools and has\n0021: to reason about the current situation. The model decides whether to call a tool to gather more\n0022: information or to finish the task based on its reasoning process. The DSPy version of ReAct is\n0023: generalized to work over any signature, thanks to signature polymorphism.\n0024: \n0025: Args:\n0026: signature: The signature of the module, which defines the input and output of the react module.\n0027: tools (list[Callable]): A list of functions, callable objects, or `dspy.Tool` instances.\n0028: max_iters (Optional[int]): The maximum number of iterations to run. Defaults to 10.\n0029: "}, {"span_id": "s4", "path": "dspy/predict/react.py", "start_line": 73, "end_line": 88, "excerpt": "0073: react_signature = (\n0074: dspy.Signature({**signature.input_fields}, \"\\n\".join(instr))\n0075: .append(\"trajectory\", dspy.InputField(), type_=str)\n0076: .append(\"next_thought\", dspy.OutputField(), type_=str)\n0077: .append(\"next_tool_name\", dspy.OutputField(), type_=Literal[tuple(tools.keys())])\n0078: .append(\"next_tool_args\", dspy.OutputField(), type_=dict[str, Any])\n0079: )\n0080: \n0081: fallback_signature = dspy.Signature(\n0082: {**signature.input_fields, **signature.output_fields},\n0083: signature.instructions,\n0084: ).append(\"trajectory\", dspy.InputField(), type_=str)\n0085: \n0086: self.tools = tools\n0087: self.react = dspy.Predict(react_signature)\n0088: self.extract = dspy.ChainOfThought(fallback_signature)"}]} {"id": "dspy_7329144ef1e9", "topic": "react_agents_and_tools", "question": "I'm building a carpool assistant and I want my tools to pass real ride objects around — a search step, a \"pick cheapest\" step, and a booking step — instead of stringly-typed blobs. Right now I expose the tools through a `dspy.Signature` with a `tool_calls: dspy.ToolCalls` output field and let native function calling drive it, then I loop over the returned tool calls and run them myself. The problem: my `pick_best_offer` and `confirm_booking` tools keep receiving plain `dict`s, so `offer.price` and `rider.name` blow up with `AttributeError`, and I'm hand-rolling the multi-step dispatch loop on top of that. I have Pydantic models for the ride offer, the rider profile, and the booking, and the rider profile is a typed input to the whole task. Show me the idiomatic DSPy program that runs the search → choose-best → confirm-booking steps as one agent and actually hands each tool the typed Pydantic objects (including a list of offers) rather than raw dicts. Make it runnable end-to-end without a live LM. Provide the full program as a fenced ```python block.", "gold_answer": "```python\nfrom pydantic import BaseModel\n\nimport dspy\nfrom dspy.utils import DummyLM\n\n\nclass RideOffer(BaseModel):\n driver: str\n origin: str\n destination: str\n seats: int\n price: float\n\n\nclass RiderProfile(BaseModel):\n name: str\n seats_needed: int\n\n\nclass Booking(BaseModel):\n driver: str\n rider: str\n total_price: float\n\n\nclass RideRequest(dspy.Signature):\n request: str = dspy.InputField()\n rider: RiderProfile = dspy.InputField()\n confirmation: str = dspy.OutputField()\n\n\nclass RideAssistant(dspy.Module):\n def __init__(self, market: list[RideOffer]):\n super().__init__()\n self.market = market\n self.agent = dspy.ReAct(\n RideRequest,\n tools=[self.find_matching_rides, self.pick_best_offer, self.confirm_booking],\n max_iters=3,\n )\n\n def find_matching_rides(self, origin: str, destination: str, seats_needed: int) -> list[RideOffer]:\n return [\n ride\n for ride in self.market\n if ride.origin == origin and ride.destination == destination and ride.seats >= seats_needed\n ]\n\n def pick_best_offer(self, offers: list[RideOffer]) -> RideOffer:\n return min(offers, key=lambda offer: offer.price)\n\n def confirm_booking(self, offer: RideOffer, rider: RiderProfile) -> Booking:\n return Booking(driver=offer.driver, rider=rider.name, total_price=offer.price * rider.seats_needed)\n\n def forward(self, request: str, rider: RiderProfile) -> dspy.Prediction:\n return self.agent(request=request, rider=rider)\n\n\nmarket = [\n RideOffer(driver='Maya', origin='SFO', destination='Palo Alto', seats=2, price=14.0),\n RideOffer(driver='Leo', origin='SFO', destination='Palo Alto', seats=3, price=11.5),\n]\nrider = RiderProfile(name='Ava', seats_needed=1)\noffers_payload = [offer.model_dump() for offer in market]\nchosen_offer = min(offers_payload, key=lambda offer: offer['price'])\n\nlm = DummyLM(\n [\n {'next_thought': 'Find matching rides first.', 'next_tool_name': 'find_matching_rides', 'next_tool_args': {'origin': 'SFO', 'destination': 'Palo Alto', 'seats_needed': 1}},\n {'next_thought': 'Choose the cheapest valid ride.', 'next_tool_name': 'pick_best_offer', 'next_tool_args': {'offers': offers_payload}},\n {'next_thought': 'Confirm the booking for the rider.', 'next_tool_name': 'confirm_booking', 'next_tool_args': {'offer': chosen_offer, 'rider': rider.model_dump()}},\n {'reasoning': 'I found matching rides, selected the best one, and confirmed it.', 'confirmation': 'Booked Leo from SFO to Palo Alto for Ava at $11.5.'},\n ]\n)\ndspy.configure(lm=lm)\n\nassistant = RideAssistant(market)\nresult = assistant(request='Book the cheapest SFO to Palo Alto ride for Ava.', rider=rider)\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 28, "statement": "The assistant is a single `dspy.ReAct` agent: it constructs `dspy.ReAct(signature, tools=[search, pick_best, confirm], ...)` (one agent driving the whole search -> choose-best -> confirm-booking flow) and does NOT hand-roll a multi-step dispatch loop that iterates over returned tool calls and executes them manually.", "span_ids": ["s1", "s5", "s4"]}, {"claim_id": "c2", "claim_type": "core", "weight": 32, "statement": "Each tool's *parameters* are annotated with the Pydantic models so they receive parsed/validated model INSTANCES via the `dspy.ReAct`/`dspy.Tool` argument-coercion path — in particular pick-best takes a `list[RideOffer]` (a list of model instances, not raw dicts) and confirm takes a direct `RideOffer`/rider-profile model argument. The solution does NOT route tools through a `dspy.ToolCalls` output field with native function calling and manual dispatch (the decoy, which would hand the tools plain dicts).", "span_ids": ["s3", "s4", "s6"]}, {"claim_id": "c3", "claim_type": "core", "weight": 15, "statement": "The solution defines typed Pydantic (BaseModel) models for the ride offer, the rider profile, and the booking, and uses them as the actual data passed between tools (and the rider profile is the typed input field on the agent's signature) rather than flattening to strings or untyped dicts.", "span_ids": ["s3", "s4"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "The search tool returns structured offers filtered by origin, destination, AND seat capacity, and the pick-best tool selects the cheapest matching offer (e.g. via `min(offers, key=lambda o: o.price)` over the typed offers).", "span_ids": ["s6"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 10, "statement": "The confirmation tool accepts the structured selected offer plus the typed rider profile and returns a structured Booking with at least the driver, the rider's name, and a total price derived from the offer price and the rider's seat count.", "span_ids": ["s3"]}, {"claim_id": "c6", "claim_type": "supporting", "weight": 5, "statement": "A `DummyLM`-driven example exercises that SAME `dspy.ReAct` agent end-to-end with no live LM, supplying multi-turn `next_thought`/`next_tool_name`/`next_tool_args` steps followed by a final extract step that produces the signature's confirmation output field.", "span_ids": ["s1", "s5"]}], "evidence": [{"span_id": "s1", "path": "dspy/predict/react.py", "start_line": 16, "end_line": 18, "excerpt": "0016: class ReAct(Module):\n0017: def __init__(self, signature: type[\"Signature\"], tools: list[Callable], max_iters: int = 20):\n0018: \"\"\""}, {"span_id": "s3", "path": "dspy/adapters/types/tool.py", "start_line": 95, "end_line": 146, "excerpt": "0095: # Process each argument's type to generate its JSON schema.\n0096: for k, v in hints.items():\n0097: arg_types[k] = v\n0098: if k == \"return\":\n0099: continue\n0100: # Check if the type (or its origin) is a subclass of Pydantic's BaseModel\n0101: origin = get_origin(v) or v\n0102: if isinstance(origin, type) and issubclass(origin, BaseModel):\n0103: # Get json schema, and replace $ref with the actual schema\n0104: v_json_schema = _resolve_json_schema_reference(v.model_json_schema())\n0105: args[k] = v_json_schema\n0106: else:\n0107: args[k] = _resolve_json_schema_reference(TypeAdapter(v).json_schema())\n0108: if default_values[k] is not inspect.Parameter.empty:\n0109: args[k][\"default\"] = default_values[k]\n0110: if arg_desc and k in arg_desc:\n0111: args[k][\"description\"] = arg_desc[k]\n0112: \n0113: self.name = self.name or name\n0114: self.desc = self.desc or desc\n0115: self.args = self.args if self.args is not None else args\n0116: self.arg_types = self.arg_types if self.arg_types is not None else arg_types\n0117: self.has_kwargs = any(param.kind == param.VAR_KEYWORD for param in sig.parameters.values())\n0118: \n0119: def _validate_and_parse_args(self, **kwargs):\n0120: # Validate the args value comply to the json schema.\n0121: for k, v in kwargs.items():\n0122: if k not in self.args:\n0123: if self.has_kwargs:\n0124: continue\n0125: else:\n0126: raise ValueError(f\"Arg {k} is not in the tool's args.\")\n0127: try:\n0128: instance = v.model_dump() if hasattr(v, \"model_dump\") else v\n0129: type_str = self.args[k].get(\"type\")\n0130: if type_str is not None and type_str != \"Any\":\n0131: validate(instance=instance, schema=self.args[k])\n0132: except ValidationError as e:\n0133: raise ValueError(f\"Arg {k} is invalid: {e.message}\")\n0134: \n0135: # Parse the args to the correct type.\n0136: parsed_kwargs = {}\n0137: for k, v in kwargs.items():\n0138: if k in self.arg_types and self.arg_types[k] != Any:\n0139: # Create a pydantic model wrapper with a dummy field `value` to parse the arg to the correct type.\n0140: # This is specifically useful for handling nested Pydantic models like `list[list[MyPydanticModel]]`\n0141: pydantic_wrapper = create_model(\"Wrapper\", value=(self.arg_types[k], ...))\n0142: parsed = pydantic_wrapper.model_validate({\"value\": v})\n0143: parsed_kwargs[k] = parsed.value\n0144: else:\n0145: parsed_kwargs[k] = v\n0146: return parsed_kwargs"}, {"span_id": "s4", "path": "tests/predict/test_react.py", "start_line": 58, "end_line": 114, "excerpt": "0058: def test_tool_calling_with_pydantic_args():\n0059: class CalendarEvent(BaseModel):\n0060: name: str\n0061: date: str\n0062: participants: dict[str, str]\n0063: \n0064: def write_invitation_letter(participant_name: str, event_info: CalendarEvent):\n0065: if participant_name not in event_info.participants:\n0066: return None\n0067: return f\"It's my honor to invite {participant_name} to event {event_info.name} on {event_info.date}\"\n0068: \n0069: class InvitationSignature(dspy.Signature):\n0070: participant_name: str = dspy.InputField(desc=\"The name of the participant to invite\")\n0071: event_info: CalendarEvent = dspy.InputField(desc=\"The information about the event\")\n0072: invitation_letter: str = dspy.OutputField(desc=\"The invitation letter to be sent to the participant\")\n0073: \n0074: react = dspy.ReAct(InvitationSignature, tools=[write_invitation_letter])\n0075: \n0076: lm = DummyLM(\n0077: [\n0078: {\n0079: \"next_thought\": \"I need to write an invitation letter for Alice to the Science Fair event.\",\n0080: \"next_tool_name\": \"write_invitation_letter\",\n0081: \"next_tool_args\": {\n0082: \"participant_name\": \"Alice\",\n0083: \"event_info\": {\n0084: \"name\": \"Science Fair\",\n0085: \"date\": \"Friday\",\n0086: \"participants\": {\"Alice\": \"female\", \"Bob\": \"male\"},\n0087: },\n0088: },\n0089: },\n0090: {\n0091: \"next_thought\": (\n0092: \"I have successfully written the invitation letter for Alice to the Science Fair. Now \"\n0093: \"I can finish the task.\"\n0094: ),\n0095: \"next_tool_name\": \"finish\",\n0096: \"next_tool_args\": {},\n0097: },\n0098: {\n0099: \"reasoning\": \"This is a very rigorous reasoning process, trust me bro!\",\n0100: \"invitation_letter\": \"It's my honor to invite Alice to the Science Fair event on Friday.\",\n0101: },\n0102: ]\n0103: )\n0104: dspy.configure(lm=lm)\n0105: \n0106: outputs = react(\n0107: participant_name=\"Alice\",\n0108: event_info=CalendarEvent(\n0109: name=\"Science Fair\",\n0110: date=\"Friday\",\n0111: participants={\"Alice\": \"female\", \"Bob\": \"male\"},\n0112: ),\n0113: )\n0114: assert outputs.invitation_letter == \"It's my honor to invite Alice to the Science Fair event on Friday.\""}, {"span_id": "s5", "path": "dspy/predict/react.py", "start_line": 44, "end_line": 88, "excerpt": "0044: tools = [t if isinstance(t, Tool) else Tool(t) for t in tools]\n0045: tools = {tool.name: tool for tool in tools}\n0046: \n0047: inputs = \", \".join([f\"`{k}`\" for k in signature.input_fields.keys()])\n0048: outputs = \", \".join([f\"`{k}`\" for k in signature.output_fields.keys()])\n0049: instr = [f\"{signature.instructions}\\n\"] if signature.instructions else []\n0050: \n0051: instr.extend(\n0052: [\n0053: f\"You are an Agent. In each episode, you will be given the fields {inputs} as input. And you can see your past trajectory so far.\",\n0054: f\"Your goal is to use one or more of the supplied tools to collect any necessary information for producing {outputs}.\\n\",\n0055: \"To do this, you will interleave next_thought, next_tool_name, and next_tool_args in each turn, and also when finishing the task.\",\n0056: \"After each tool call, you receive a resulting observation, which gets appended to your trajectory.\\n\",\n0057: \"When writing next_thought, you may reason about the current situation and plan for future steps.\",\n0058: \"When selecting the next_tool_name and its next_tool_args, the tool must be one of:\\n\",\n0059: ]\n0060: )\n0061: \n0062: tools[\"finish\"] = Tool(\n0063: func=lambda: \"Completed.\",\n0064: name=\"finish\",\n0065: desc=f\"Marks the task as complete. That is, signals that all information for producing the outputs, i.e. {outputs}, are now available to be extracted.\",\n0066: args={},\n0067: )\n0068: \n0069: for idx, tool in enumerate(tools.values()):\n0070: instr.append(f\"({idx + 1}) {tool}\")\n0071: instr.append(\"When providing `next_tool_args`, the value inside the field must be in JSON format\")\n0072: \n0073: react_signature = (\n0074: dspy.Signature({**signature.input_fields}, \"\\n\".join(instr))\n0075: .append(\"trajectory\", dspy.InputField(), type_=str)\n0076: .append(\"next_thought\", dspy.OutputField(), type_=str)\n0077: .append(\"next_tool_name\", dspy.OutputField(), type_=Literal[tuple(tools.keys())])\n0078: .append(\"next_tool_args\", dspy.OutputField(), type_=dict[str, Any])\n0079: )\n0080: \n0081: fallback_signature = dspy.Signature(\n0082: {**signature.input_fields, **signature.output_fields},\n0083: signature.instructions,\n0084: ).append(\"trajectory\", dspy.InputField(), type_=str)\n0085: \n0086: self.tools = tools\n0087: self.react = dspy.Predict(react_signature)\n0088: self.extract = dspy.ChainOfThought(fallback_signature)"}, {"span_id": "s6", "path": "tests/predict/test_react.py", "start_line": 116, "end_line": 133, "excerpt": "0116: expected_trajectory = {\n0117: \"thought_0\": \"I need to write an invitation letter for Alice to the Science Fair event.\",\n0118: \"tool_name_0\": \"write_invitation_letter\",\n0119: \"tool_args_0\": {\n0120: \"participant_name\": \"Alice\",\n0121: \"event_info\": {\n0122: \"name\": \"Science Fair\",\n0123: \"date\": \"Friday\",\n0124: \"participants\": {\"Alice\": \"female\", \"Bob\": \"male\"},\n0125: },\n0126: },\n0127: \"observation_0\": \"It's my honor to invite Alice to event Science Fair on Friday\",\n0128: \"thought_1\": \"I have successfully written the invitation letter for Alice to the Science Fair. Now I can finish the task.\",\n0129: \"tool_name_1\": \"finish\",\n0130: \"tool_args_1\": {},\n0131: \"observation_1\": \"Completed.\",\n0132: }\n0133: assert outputs.trajectory == expected_trajectory"}]} {"id": "dspy_a5b116f00083", "topic": "react_agents_and_tools", "question": "I've got a mostly chat-style DSPy app and one step that needs to be different: a single planning call that's handed a tool inventory and has to emit machine-readable tool calls so my own Python code can run them afterward (no agent loop, no iterative tool execution inside DSPy — just one call that returns the plan).\n\nRight now I keep the global config as-is and, for just that planner `Predict`, I wrap it in `dspy.context` and pass `dspy.ChatAdapter(use_native_function_calling=True)` so it'll do tool calling. The tool-call field comes back fine, but the rest of that step is still emitting the bracketed `[[ ## field ## ]]` chat-protocol text for its other output field instead of clean structured/JSON output — flipping that boolean clearly didn't actually put this one call into a real structured-output mode, and I don't want to start hand-setting low-level flags to force it.\n\nWhat I want: leave the whole rest of the app on its normal chat-style default untouched, and override ONLY this planner call into a proper structured-output tool-calling mode — ideally just by selecting the right built-in adapter for that one call rather than toggling flags. Show me the full runnable program: the planner signature, how I scope the override to only this call, and how my Python executes the returned tool calls afterward.", "gold_answer": "```python\nimport dspy\nfrom dspy.utils import DummyLM\n\n\nclass PlanStep(dspy.Signature):\n request: str = dspy.InputField()\n tools: list[dspy.Tool] = dspy.InputField()\n plan_summary: str = dspy.OutputField()\n tool_calls: dspy.ToolCalls = dspy.OutputField()\n\n\ndef lookup_balance(user_id: str) -> str:\n return f'balance for {user_id}: $125'\n\n\ndef freeze_card(user_id: str) -> str:\n return f'card for {user_id} frozen'\n\n\nstructured_adapter = dspy.JSONAdapter()\nstructured_lm = DummyLM(\n [\n {\n 'plan_summary': 'Check the balance, then freeze the card.',\n 'tool_calls': [\n {'name': 'lookup_balance', 'args': {'user_id': 'u-17'}},\n {'name': 'freeze_card', 'args': {'user_id': 'u-17'}},\n ],\n }\n ],\n adapter=structured_adapter,\n)\n\ntools = [dspy.Tool(lookup_balance), dspy.Tool(freeze_card)]\ntool_map = {'lookup_balance': lookup_balance, 'freeze_card': freeze_card}\n\nplanner = dspy.Predict(PlanStep)\ndspy.configure(adapter=dspy.ChatAdapter())\n\nwith dspy.context(lm=structured_lm, adapter=structured_adapter):\n plan = planner(\n request='User u-17 lost their card. Check their balance and then lock it.',\n tools=tools,\n )\n\nexecutions = [call.execute(functions=tool_map) for call in plan.tool_calls.tool_calls]\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 35, "statement": "The single planner call is overridden into structured tool-calling mode by SELECTING the built-in adapter dspy.JSONAdapter() for that call -- chosen because JSONAdapter already defaults use_native_function_calling to True AND emits JSON/structured output (so the other output field is no longer in the bracketed chat protocol). The answer must NOT instead keep ChatAdapter and merely set use_native_function_calling=True on it (that leaves the step in the [[ ## field ## ]] chat protocol), and must NOT achieve structured mode by manually toggling the native-function-calling / structured-output flags rather than by selecting the right built-in adapter.", "span_ids": ["s4", "s5"]}, {"claim_id": "c2", "claim_type": "core", "weight": 25, "statement": "The global default adapter stays in normal chat mode (dspy.configure(adapter=dspy.ChatAdapter()), i.e. the settings.adapter or ChatAdapter() default) and ONLY the planner call is overridden, by scoping a DIFFERENT adapter inside a with dspy.context(adapter=...) block; the rest of the app is left untouched and unaffected.", "span_ids": ["s3", "s4"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "The planner step is a single DSPy signature / dspy.Predict that takes the user request plus a tool inventory typed list[dspy.Tool] as an input field and returns a dspy.ToolCalls output field, producing the whole plan in one call rather than running an iterative agent / tool-execution loop inside DSPy.", "span_ids": ["s1", "s2"]}, {"claim_id": "c4", "claim_type": "core", "weight": 12, "statement": "After the call returns, the machine-readable tool calls are replayed later in plain Python by iterating plan.tool_calls.tool_calls and invoking .execute(...) on each ToolCall (passing a function mapping or a tool list), NOT by manually dispatching func(**args) over hand-parsed dicts.", "span_ids": ["s6", "s7"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 8, "statement": "DSPy recognizes the tool-calling signature from an input field annotated dspy.Tool / list[dspy.Tool] together with an output field annotated dspy.ToolCalls.", "span_ids": ["s1"]}], "evidence": [{"span_id": "s1", "path": "dspy/adapters/base.py", "start_line": 464, "end_line": 478, "excerpt": "0464: def _get_tool_call_input_field_name(self, signature: type[Signature]) -> bool:\n0465: for name, field in signature.input_fields.items():\n0466: # Look for annotation `list[dspy.Tool]` or `dspy.Tool`\n0467: origin = get_origin(field.annotation)\n0468: if origin is list and field.annotation.__args__[0] == Tool:\n0469: return name\n0470: if field.annotation == Tool:\n0471: return name\n0472: return None\n0473: \n0474: def _get_tool_call_output_field_name(self, signature: type[Signature]) -> bool:\n0475: for name, field in signature.output_fields.items():\n0476: if field.annotation == ToolCalls:\n0477: return name\n0478: return None"}, {"span_id": "s2", "path": "dspy/adapters/base.py", "start_line": 73, "end_line": 97, "excerpt": "0073: if self.use_native_function_calling:\n0074: tool_call_input_field_name = self._get_tool_call_input_field_name(signature)\n0075: tool_call_output_field_name = self._get_tool_call_output_field_name(signature)\n0076: \n0077: if tool_call_output_field_name and tool_call_input_field_name is None:\n0078: raise ValueError(\n0079: f\"You provided an output field {tool_call_output_field_name} to receive the tool calls information, \"\n0080: \"but did not provide any tools as the input. Please provide a list of tools as the input by adding an \"\n0081: \"input field with type `list[dspy.Tool]`.\"\n0082: )\n0083: \n0084: if tool_call_output_field_name and lm.supports_function_calling:\n0085: tools = inputs[tool_call_input_field_name]\n0086: tools = tools if isinstance(tools, list) else [tools]\n0087: \n0088: lm_tools = [tool.format_as_litellm_function_call() for tool in tools]\n0089: \n0090: lm_kwargs[\"tools\"] = lm_tools\n0091: \n0092: signature_for_native_function_calling = signature.delete(tool_call_output_field_name)\n0093: signature_for_native_function_calling = signature_for_native_function_calling.delete(\n0094: tool_call_input_field_name\n0095: )\n0096: \n0097: return signature_for_native_function_calling"}, {"span_id": "s3", "path": "dspy/adapters/base.py", "start_line": 178, "end_line": 206, "excerpt": "0178: def __call__(\n0179: self,\n0180: lm: BaseLM,\n0181: lm_kwargs: dict[str, Any],\n0182: signature: type[Signature],\n0183: demos: list[dict[str, Any]],\n0184: inputs: dict[str, Any],\n0185: ) -> list[dict[str, Any]]:\n0186: \"\"\"\n0187: Execute the adapter pipeline: format inputs, call LM, and parse outputs.\n0188: \n0189: Args:\n0190: lm: The Language Model instance to use for generation. Must be an instance of `dspy.BaseLM`.\n0191: lm_kwargs: Additional keyword arguments to pass to the LM call (e.g., temperature, max_tokens). These are\n0192: passed directly to the LM.\n0193: signature: The DSPy signature associated with this LM call.\n0194: demos: List of few-shot examples to include in the prompt. Each dictionary should contain keys matching the\n0195: signature's input and output field names. Examples are formatted as user/assistant message pairs.\n0196: inputs: The current input values for this call. Keys must match the signature's input field names.\n0197: \n0198: Returns:\n0199: List of dictionaries representing parsed LM responses. Each dictionary contains keys matching the\n0200: signature's output field names. For multiple generations (n > 1), returns multiple dictionaries.\n0201: \"\"\"\n0202: processed_signature = self._call_preprocess(lm, lm_kwargs, signature, inputs)\n0203: inputs = self.format(processed_signature, demos, inputs)\n0204: \n0205: outputs = lm(messages=inputs, **lm_kwargs)\n0206: return self._call_postprocess(processed_signature, signature, outputs, lm, lm_kwargs)"}, {"span_id": "s4", "path": "dspy/adapters/json_adapter.py", "start_line": 40, "end_line": 79, "excerpt": "0040: class JSONAdapter(ChatAdapter):\n0041: def __init__(self, callbacks: list[BaseCallback] | None = None, use_native_function_calling: bool = True):\n0042: # JSONAdapter uses native function calling by default.\n0043: super().__init__(callbacks=callbacks, use_native_function_calling=use_native_function_calling)\n0044: \n0045: def _json_adapter_call_common(self, lm, lm_kwargs, signature, demos, inputs, call_fn):\n0046: \"\"\"Common call logic to be used for both sync and async calls.\"\"\"\n0047: if \"response_format\" not in lm.supported_params:\n0048: return call_fn(lm, lm_kwargs, signature, demos, inputs)\n0049: \n0050: has_tool_calls = any(field.annotation == ToolCalls for field in signature.output_fields.values())\n0051: \n0052: if _has_open_ended_mapping(signature) or (not self.use_native_function_calling and has_tool_calls) or not lm.supports_response_schema:\n0053: # We found that structured output mode doesn't work well with dspy.ToolCalls as output field.\n0054: # So we fall back to json mode if native function calling is disabled and ToolCalls is present.\n0055: lm_kwargs[\"response_format\"] = {\"type\": \"json_object\"}\n0056: return call_fn(lm, lm_kwargs, signature, demos, inputs)\n0057: \n0058: def __call__(\n0059: self,\n0060: lm: BaseLM,\n0061: lm_kwargs: dict[str, Any],\n0062: signature: type[Signature],\n0063: demos: list[dict[str, Any]],\n0064: inputs: dict[str, Any],\n0065: ) -> list[dict[str, Any]]:\n0066: result = self._json_adapter_call_common(lm, lm_kwargs, signature, demos, inputs, super().__call__)\n0067: if result:\n0068: return result\n0069: \n0070: try:\n0071: structured_output_model = _get_structured_outputs_response_format(\n0072: signature, self.use_native_function_calling\n0073: )\n0074: lm_kwargs[\"response_format\"] = structured_output_model\n0075: return super().__call__(lm, lm_kwargs, signature, demos, inputs)\n0076: except Exception:\n0077: logger.warning(\"Failed to use structured output format, falling back to JSON mode.\")\n0078: lm_kwargs[\"response_format\"] = {\"type\": \"json_object\"}\n0079: return super().__call__(lm, lm_kwargs, signature, demos, inputs)"}, {"span_id": "s5", "path": "dspy/adapters/json_adapter.py", "start_line": 212, "end_line": 240, "excerpt": "0212: def _get_structured_outputs_response_format(\n0213: signature: SignatureMeta,\n0214: use_native_function_calling: bool = True,\n0215: ) -> type[pydantic.BaseModel]:\n0216: \"\"\"\n0217: Builds a Pydantic model from a DSPy signature's output_fields and ensures the generated JSON schema\n0218: is compatible with OpenAI Structured Outputs (all objects have a \"required\" key listing every property,\n0219: and additionalProperties is always false).\n0220: \n0221: IMPORTANT: If any field's annotation is an open-ended mapping (e.g. dict[str, Any]), then a structured\n0222: schema cannot be generated since all properties must be explicitly declared. In that case, an exception\n0223: is raised so that the caller can fall back to using a plain \"json_object\" response_format.\n0224: \"\"\"\n0225: # Although we've already performed an early check, we keep this here as a final guard.\n0226: for name, field in signature.output_fields.items():\n0227: annotation = field.annotation\n0228: if get_origin(annotation) is dict:\n0229: raise ValueError(\n0230: f\"Field '{name}' has an open-ended mapping type which is not supported by Structured Outputs.\"\n0231: )\n0232: \n0233: fields = {}\n0234: for name, field in signature.output_fields.items():\n0235: annotation = field.annotation\n0236: if use_native_function_calling and annotation == ToolCalls:\n0237: # Skip ToolCalls field if native function calling is enabled.\n0238: continue\n0239: default = field.default if hasattr(field, \"default\") else ...\n0240: fields[name] = (annotation, default)"}, {"span_id": "s6", "path": "dspy/adapters/types/tool.py", "start_line": 262, "end_line": 319, "excerpt": "0262: class ToolCalls(Type):\n0263: class ToolCall(Type):\n0264: name: str\n0265: args: dict[str, Any]\n0266: \n0267: def format(self):\n0268: return {\n0269: \"type\": \"function\",\n0270: \"function\": {\n0271: \"name\": self.name,\n0272: \"arguments\": self.args,\n0273: },\n0274: }\n0275: \n0276: def execute(self, functions: dict[str, Any] | list[Tool] | None = None) -> Any:\n0277: \"\"\"Execute this individual tool call and return its result.\n0278: \n0279: Args:\n0280: functions: Functions to search for the tool. Can be:\n0281: - Dict mapping tool names to functions: {\"tool_name\": function}\n0282: - List of Tool objects: [Tool(function), ...]\n0283: - None: Will search in caller's locals and globals (automatic lookup)\n0284: \n0285: Returns:\n0286: The result from executing this tool call.\n0287: \n0288: Raises:\n0289: ValueError: If the tool function cannot be found.\n0290: Exception: Any exception raised by the tool function.\n0291: \"\"\"\n0292: func = None\n0293: \n0294: if functions is None:\n0295: # Automatic lookup in caller's globals and locals\n0296: frame = inspect.currentframe().f_back\n0297: try:\n0298: caller_globals = frame.f_globals\n0299: caller_locals = frame.f_locals\n0300: func = caller_locals.get(self.name) or caller_globals.get(self.name)\n0301: finally:\n0302: del frame\n0303: \n0304: elif isinstance(functions, dict):\n0305: func = functions.get(self.name)\n0306: elif isinstance(functions, list):\n0307: for tool in functions:\n0308: if tool.name == self.name:\n0309: func = tool.func\n0310: break\n0311: \n0312: if func is None:\n0313: raise ValueError(f\"Tool function '{self.name}' not found. Please pass the tool functions to the `execute` method.\")\n0314: \n0315: try:\n0316: args = self.args or {}\n0317: return func(**args)\n0318: except Exception as e:\n0319: raise RuntimeError(f\"Error executing tool '{self.name}': {e}\") from e"}, {"span_id": "s7", "path": "dspy/adapters/types/tool.py", "start_line": 321, "end_line": 345, "excerpt": "0321: tool_calls: list[ToolCall]\n0322: \n0323: @classmethod\n0324: def from_dict_list(cls, tool_calls_dicts: list[dict[str, Any]]) -> \"ToolCalls\":\n0325: \"\"\"Convert a list of dictionaries to a ToolCalls instance.\n0326: \n0327: Args:\n0328: dict_list: A list of dictionaries, where each dictionary should have 'name' and 'args' keys.\n0329: \n0330: Returns:\n0331: A ToolCalls instance.\n0332: \n0333: Examples:\n0334: \n0335: ```python\n0336: tool_calls_dict = [\n0337: {\"name\": \"search\", \"args\": {\"query\": \"hello\"}},\n0338: {\"name\": \"translate\", \"args\": {\"text\": \"world\"}}\n0339: ]\n0340: tool_calls = ToolCalls.from_dict_list(tool_calls_dict)\n0341: ```\n0342: \"\"\"\n0343: tool_calls = [cls.ToolCall(**item) for item in tool_calls_dicts]\n0344: return cls(tool_calls=tool_calls)\n0345: "}]} {"id": "dspy_e175093485fd", "topic": "react_agents_and_tools", "question": "I'm building a two-layer support bot in DSPy: a top-level `dspy.ReAct` router decides which specialist to hand a request to, and the chosen specialist is itself a module that runs its own `dspy.ReAct` to pick a concrete business tool (search/book a trip, look up/refund an invoice, etc.). Delegation and business-tool use must stay as separate layers.\n\nThe hard part is the iteration budgets. The router should be allowed exactly **one** step — delegate to a single specialist and stop, never ping-pong between specialists — while each specialist needs **several** steps to actually do its job (e.g. search, then book). My current approach is to construct a brand-new `dspy.ReAct` for the router on every incoming request with `max_iters=1`, and rebuild each specialist's `dspy.ReAct` per request with a larger `max_iters`, because that's the only way I can see to give the two layers different budgets. This is slow under load and feels wrong to rebuild the agents on every call.\n\nShow me a single runnable Python program where the router and specialists are each ordinary `dspy.Module`s constructed **once** (no per-request reconstruction of any agent), yet the outer routing layer is constrained to one step and the inner specialist layer gets its own larger budget on each request. Use `dspy.utils.DummyLM` so it runs offline. Walk one travel request end to end (router delegates once → travel specialist searches then books) and return the final response.", "gold_answer": "```python\nimport dspy\nfrom dspy.utils import DummyLM\n\n\nclass TravelSpecialist(dspy.Module):\n def __init__(self):\n super().__init__()\n # Built ONCE. No max_iters fixed here; the budget is chosen per call.\n self.agent = dspy.ReAct('request -> reply', tools=[self.search_trips, self.book_trip])\n\n def search_trips(self, origin: str, destination: str) -> list[dict]:\n return [\n {'id': 'T1', 'origin': origin, 'destination': destination, 'price': 120},\n {'id': 'T2', 'origin': origin, 'destination': destination, 'price': 180},\n ]\n\n def book_trip(self, trip: dict, traveler: str) -> str:\n return 'Booked {} for {} at ${}.'.format(trip['id'], traveler, trip['price'])\n\n def handle_travel(self, request: str) -> str:\n # Inner layer gets its own larger budget, passed in the CALL (not the constructor).\n return self.agent(request=request, max_iters=2).reply\n\n\nclass BillingSpecialist(dspy.Module):\n def __init__(self):\n super().__init__()\n self.agent = dspy.ReAct('request -> reply', tools=[self.lookup_invoice, self.issue_credit])\n\n def lookup_invoice(self, invoice_id: str) -> str:\n return f'invoice {invoice_id}: unpaid'\n\n def issue_credit(self, invoice_id: str, amount: int) -> str:\n return f'credit of ${amount} issued for {invoice_id}'\n\n def handle_billing(self, request: str) -> str:\n return self.agent(request=request, max_iters=2).reply\n\n\nclass Dispatcher(dspy.Module):\n def __init__(self):\n super().__init__()\n self.travel = TravelSpecialist()\n self.billing = BillingSpecialist()\n # Router built ONCE and reused for every request.\n self.router = dspy.ReAct(\n 'request -> response',\n tools=[self.travel.handle_travel, self.billing.handle_billing],\n )\n\n def forward(self, request: str, route_budget: int = 1) -> dspy.Prediction:\n # Outer routing layer is capped to one step PER CALL via the call-time\n # max_iters override, so it delegates to a single specialist and stops.\n return self.router(request=request, max_iters=route_budget)\n\n\nlm = DummyLM(\n [\n {'next_thought': 'This belongs to travel.', 'next_tool_name': 'handle_travel', 'next_tool_args': {'request': 'Book Ava the cheapest SFO to LAX trip.'}},\n {'next_thought': 'Search the travel options first.', 'next_tool_name': 'search_trips', 'next_tool_args': {'origin': 'SFO', 'destination': 'LAX'}},\n {'next_thought': 'Now book the cheapest option.', 'next_tool_name': 'book_trip', 'next_tool_args': {'trip': {'id': 'T1', 'origin': 'SFO', 'destination': 'LAX', 'price': 120}, 'traveler': 'Ava'}},\n {'reasoning': 'The specialist found and booked the cheapest travel option.', 'reply': 'Booked T1 for Ava at $120.'},\n {'reasoning': 'The travel specialist completed the request.', 'response': 'Booked T1 for Ava at $120.'},\n ]\n)\ndspy.configure(lm=lm)\n\ndispatcher = Dispatcher()\nresult = dispatcher(request='Book Ava the cheapest SFO to LAX trip.')\nprint(result.response) # Booked T1 for Ava at $120.\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 45, "statement": "The two layers get their differing iteration budgets by passing `max_iters=` DIRECTLY IN THE CALL to each agent (the router agent invoked with max_iters=1 and the specialist agent invoked with a larger max_iters), with every `dspy.ReAct` constructed exactly once in `__init__` and reused as-is — NOT by rebuilding/reconstructing a `dspy.ReAct` per request, NOT by relying on the constructor's `max_iters` alone, and NOT by wrapping ReAct in a custom module that manually drives the loop via a homemade `budget`/`internal_max_iters` argument or invented per-step methods (e.g. init_trace/step_trace/read_trace).", "span_ids": ["s2", "s3"]}, {"claim_id": "c2", "claim_type": "core", "weight": 25, "statement": "The top-level router/dispatcher is a `dspy.Module` whose `forward` runs its OWN `dspy.ReAct` whose tool list is the specialists' entrypoint methods, so the specialist is chosen by ReAct tool-SELECTION — NOT by a manual `if`/dispatch branch on a predicted decision string and NOT by directly calling the business functions from the router.", "span_ids": ["s1", "s2", "s5"]}, {"claim_id": "c3", "claim_type": "core", "weight": 15, "statement": "Each specialist is its own `dspy.Module` containing a separate inner `dspy.ReAct` whose tool list holds that specialist's concrete business methods (e.g. search/book), so business-tool selection stays inside the chosen specialist as a distinct inner agent (not the `Avatar` actor and not a code-execution / `CodeAct` agent).", "span_ids": ["s2", "s3"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "Plain callable methods are supplied as the tools to `dspy.ReAct` (a list of bare callables, not pre-wrapped) at the delegating layer and inside the specialist, relying on DSPy to wrap each non-`Tool` callable into a `Tool` whose selectable name is taken from the method's `__name__`.", "span_ids": ["s2", "s4"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 5, "statement": "The runnable flow relies on module composition: calling the outer module instance runs its `forward`, keyword arguments passed to a module call flow into that module's `forward`, and the selected specialist entrypoint invokes another module layer whose reply is returned upward.", "span_ids": ["s1", "s5"]}], "evidence": [{"span_id": "s1", "path": "dspy/primitives/module.py", "start_line": 40, "end_line": 49, "excerpt": "0040: class Module(BaseModule, metaclass=ProgramMeta):\n0041: \"\"\"Base class for all DSPy modules (programs).\n0042: \n0043: A Module is a building block for DSPy programs that can contain predictors,\n0044: sub-modules, and custom logic. Modules can be composed together to create\n0045: complex pipelines and can be optimized using DSPy's teleprompters.\n0046: \n0047: All DSPy programs should inherit from this class and implement a ``forward``\n0048: method that defines the program's logic.\n0049: "}, {"span_id": "s2", "path": "dspy/predict/react.py", "start_line": 16, "end_line": 89, "excerpt": "0016: class ReAct(Module):\n0017: def __init__(self, signature: type[\"Signature\"], tools: list[Callable], max_iters: int = 20):\n0018: \"\"\"\n0019: ReAct stands for \"Reasoning and Acting,\" a popular paradigm for building tool-using agents.\n0020: In this approach, the language model is iteratively provided with a list of tools and has\n0021: to reason about the current situation. The model decides whether to call a tool to gather more\n0022: information or to finish the task based on its reasoning process. The DSPy version of ReAct is\n0023: generalized to work over any signature, thanks to signature polymorphism.\n0024: \n0025: Args:\n0026: signature: The signature of the module, which defines the input and output of the react module.\n0027: tools (list[Callable]): A list of functions, callable objects, or `dspy.Tool` instances.\n0028: max_iters (Optional[int]): The maximum number of iterations to run. Defaults to 10.\n0029: \n0030: Examples:\n0031: \n0032: ```python\n0033: def get_weather(city: str) -> str:\n0034: return f\"The weather in {city} is sunny.\"\n0035: \n0036: react = dspy.ReAct(signature=\"question->answer\", tools=[get_weather])\n0037: pred = react(question=\"What is the weather in Tokyo?\")\n0038: ```\n0039: \"\"\"\n0040: super().__init__()\n0041: self.signature = signature = ensure_signature(signature)\n0042: self.max_iters = max_iters\n0043: \n0044: tools = [t if isinstance(t, Tool) else Tool(t) for t in tools]\n0045: tools = {tool.name: tool for tool in tools}\n0046: \n0047: inputs = \", \".join([f\"`{k}`\" for k in signature.input_fields.keys()])\n0048: outputs = \", \".join([f\"`{k}`\" for k in signature.output_fields.keys()])\n0049: instr = [f\"{signature.instructions}\\n\"] if signature.instructions else []\n0050: \n0051: instr.extend(\n0052: [\n0053: f\"You are an Agent. In each episode, you will be given the fields {inputs} as input. And you can see your past trajectory so far.\",\n0054: f\"Your goal is to use one or more of the supplied tools to collect any necessary information for producing {outputs}.\\n\",\n0055: \"To do this, you will interleave next_thought, next_tool_name, and next_tool_args in each turn, and also when finishing the task.\",\n0056: \"After each tool call, you receive a resulting observation, which gets appended to your trajectory.\\n\",\n0057: \"When writing next_thought, you may reason about the current situation and plan for future steps.\",\n0058: \"When selecting the next_tool_name and its next_tool_args, the tool must be one of:\\n\",\n0059: ]\n0060: )\n0061: \n0062: tools[\"finish\"] = Tool(\n0063: func=lambda: \"Completed.\",\n0064: name=\"finish\",\n0065: desc=f\"Marks the task as complete. That is, signals that all information for producing the outputs, i.e. {outputs}, are now available to be extracted.\",\n0066: args={},\n0067: )\n0068: \n0069: for idx, tool in enumerate(tools.values()):\n0070: instr.append(f\"({idx + 1}) {tool}\")\n0071: instr.append(\"When providing `next_tool_args`, the value inside the field must be in JSON format\")\n0072: \n0073: react_signature = (\n0074: dspy.Signature({**signature.input_fields}, \"\\n\".join(instr))\n0075: .append(\"trajectory\", dspy.InputField(), type_=str)\n0076: .append(\"next_thought\", dspy.OutputField(), type_=str)\n0077: .append(\"next_tool_name\", dspy.OutputField(), type_=Literal[tuple(tools.keys())])\n0078: .append(\"next_tool_args\", dspy.OutputField(), type_=dict[str, Any])\n0079: )\n0080: \n0081: fallback_signature = dspy.Signature(\n0082: {**signature.input_fields, **signature.output_fields},\n0083: signature.instructions,\n0084: ).append(\"trajectory\", dspy.InputField(), type_=str)\n0085: \n0086: self.tools = tools\n0087: self.react = dspy.Predict(react_signature)\n0088: self.extract = dspy.ChainOfThought(fallback_signature)\n0089: "}, {"span_id": "s3", "path": "dspy/predict/react.py", "start_line": 95, "end_line": 118, "excerpt": "0095: def forward(self, **input_args):\n0096: trajectory = {}\n0097: max_iters = input_args.pop(\"max_iters\", self.max_iters)\n0098: for idx in range(max_iters):\n0099: try:\n0100: pred = self._call_with_potential_trajectory_truncation(self.react, trajectory, **input_args)\n0101: except ValueError as err:\n0102: logger.warning(f\"Ending the trajectory: Agent failed to select a valid tool: {_fmt_exc(err)}\")\n0103: break\n0104: \n0105: trajectory[f\"thought_{idx}\"] = pred.next_thought\n0106: trajectory[f\"tool_name_{idx}\"] = pred.next_tool_name\n0107: trajectory[f\"tool_args_{idx}\"] = pred.next_tool_args\n0108: \n0109: try:\n0110: trajectory[f\"observation_{idx}\"] = self.tools[pred.next_tool_name](**pred.next_tool_args)\n0111: except Exception as err:\n0112: trajectory[f\"observation_{idx}\"] = f\"Execution error in {pred.next_tool_name}: {_fmt_exc(err)}\"\n0113: \n0114: if pred.next_tool_name == \"finish\":\n0115: break\n0116: \n0117: extract = self._call_with_potential_trajectory_truncation(self.extract, trajectory, **input_args)\n0118: return dspy.Prediction(trajectory=trajectory, **extract)"}, {"span_id": "s4", "path": "dspy/adapters/types/tool.py", "start_line": 75, "end_line": 117, "excerpt": "0075: def _parse_function(self, func: Callable, arg_desc: dict[str, str] | None = None):\n0076: \"\"\"Helper method that parses a function to extract the name, description, and args.\n0077: \n0078: This is a helper function that automatically infers the name, description, and args of the tool from the\n0079: provided function. In order to make the inference work, the function must have valid type hints.\n0080: \"\"\"\n0081: annotations_func = func if inspect.isfunction(func) or inspect.ismethod(func) else func.__call__\n0082: name = getattr(func, \"__name__\", type(func).__name__)\n0083: desc = getattr(func, \"__doc__\", None) or getattr(annotations_func, \"__doc__\", \"\")\n0084: args = {}\n0085: arg_types = {}\n0086: \n0087: # Use inspect.signature to get all arg names\n0088: sig = inspect.signature(annotations_func)\n0089: # Get available type hints\n0090: available_hints = get_type_hints(annotations_func)\n0091: # Build a dictionary of arg name -> type (defaulting to Any when missing)\n0092: hints = {param_name: available_hints.get(param_name, Any) for param_name in sig.parameters.keys()}\n0093: default_values = {param_name: sig.parameters[param_name].default for param_name in sig.parameters.keys()}\n0094: \n0095: # Process each argument's type to generate its JSON schema.\n0096: for k, v in hints.items():\n0097: arg_types[k] = v\n0098: if k == \"return\":\n0099: continue\n0100: # Check if the type (or its origin) is a subclass of Pydantic's BaseModel\n0101: origin = get_origin(v) or v\n0102: if isinstance(origin, type) and issubclass(origin, BaseModel):\n0103: # Get json schema, and replace $ref with the actual schema\n0104: v_json_schema = _resolve_json_schema_reference(v.model_json_schema())\n0105: args[k] = v_json_schema\n0106: else:\n0107: args[k] = _resolve_json_schema_reference(TypeAdapter(v).json_schema())\n0108: if default_values[k] is not inspect.Parameter.empty:\n0109: args[k][\"default\"] = default_values[k]\n0110: if arg_desc and k in arg_desc:\n0111: args[k][\"description\"] = arg_desc[k]\n0112: \n0113: self.name = self.name or name\n0114: self.desc = self.desc or desc\n0115: self.args = self.args if self.args is not None else args\n0116: self.arg_types = self.arg_types if self.arg_types is not None else arg_types\n0117: self.has_kwargs = any(param.kind == param.VAR_KEYWORD for param in sig.parameters.values())"}, {"span_id": "s5", "path": "dspy/primitives/module.py", "start_line": 93, "end_line": 110, "excerpt": "0093: @with_callbacks\n0094: def __call__(self, *args, **kwargs) -> Prediction:\n0095: from dspy.dsp.utils.settings import thread_local_overrides\n0096: \n0097: caller_modules = settings.caller_modules or []\n0098: caller_modules = list(caller_modules)\n0099: caller_modules.append(self)\n0100: \n0101: with settings.context(caller_modules=caller_modules):\n0102: if settings.track_usage and thread_local_overrides.get().get(\"usage_tracker\") is None:\n0103: with track_usage() as usage_tracker:\n0104: output = self.forward(*args, **kwargs)\n0105: tokens = usage_tracker.get_total_tokens()\n0106: self._set_lm_usage(tokens, output)\n0107: \n0108: return output\n0109: \n0110: return self.forward(*args, **kwargs)"}]} {"id": "dspy_0b4b420ebeb4", "topic": "react_agents_and_tools", "question": "I'm building a small DSPy program that plays a text adventure. The world exposes three operations the player can perform — `ask(question)` to query an NPC, `move(direction)` to change rooms, and `take(item)` to pick something up — and each one takes its own differently-named argument. I want a single language model to play through to a goal (\"find the brass key and pick it up\"), deciding at each step which of the three operations to call next based on what the previous operation returned: e.g. it asks where the key is, then moves to that room, then takes it.\n\nMy current version is a `dspy.ChainOfThought(\"state -> next_action\")` that I call in a Python `while` loop. I read its `next_action` string and branch on it — `if action.startswith(\"ask\"): obs = ask(...) elif \"move\" in action: obs = move(...) elif ...` — to dispatch to the right function, then feed the result back as the next `state`. It's becoming unmaintainable: the model keeps phrasing actions in ways my `if/elif` chain doesn't match, I'm hand-writing the argument extraction separately for each operation, and adding a fourth operation means yet another branch.\n\nIs there a single DSPy module where the language model itself selects which named operation to invoke — with the correct structured arguments for that specific operation — and that automatically feeds each operation's return value back in as input to the next decision, so I can delete all of my dispatch branching and per-operation arg parsing? Give me one complete runnable program. Use `dspy.utils.DummyLM` with scripted steps so it runs offline with no real API calls, and show me how to inspect the full sequence of decisions and observations after the run.", "gold_answer": "```python\nimport dspy\nfrom dspy.utils import DummyLM\n\n\nclass TinyWorld:\n def __init__(self):\n self.room = 'hall'\n self.inventory: list[str] = []\n\n def ask(self, question: str) -> str:\n return 'The brass key is in the attic.' if 'key' in question.lower() else 'I only know about the key.'\n\n def move(self, direction: str) -> str:\n self.room = 'attic' if direction.lower() == 'attic' else self.room\n return f'You are now in the {self.room}.'\n\n def take(self, item: str) -> str:\n if self.room == 'attic' and item.lower() == 'brass key':\n self.inventory.append('brass key')\n return 'You picked up the brass key.'\n return f'There is no {item} here.'\n\n\nclass QuestAgent(dspy.Module):\n def __init__(self, env: TinyWorld):\n super().__init__()\n self.agent = dspy.ReAct('goal -> outcome', tools=[env.ask, env.move, env.take], max_iters=3)\n\n def forward(self, goal: str) -> dspy.Prediction:\n return self.agent(goal=goal)\n\n\nlm = DummyLM(\n [\n {'next_thought': 'Ask the environment where the key is.', 'next_tool_name': 'ask', 'next_tool_args': {'question': 'Where is the key?'}},\n {'next_thought': 'Move to the attic.', 'next_tool_name': 'move', 'next_tool_args': {'direction': 'attic'}},\n {'next_thought': 'Take the key now.', 'next_tool_name': 'take', 'next_tool_args': {'item': 'brass key'}},\n {'reasoning': 'The agent located the key, moved to the right room, and picked it up.', 'outcome': 'Success: the brass key is now in inventory.'},\n ]\n)\ndspy.configure(lm=lm)\n\nworld = TinyWorld()\nresult = QuestAgent(world)(goal='Find the brass key and pick it up.')\ntrajectory = result.trajectory\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 45, "statement": "The agent is a single `dspy.ReAct(...)` module so the language model itself selects which operation to invoke at each step from ReAct's accumulated trajectory. It must NOT use the decoy of a developer-written `while`/`for` loop that branches (`if`/`elif`) on a model-produced action string/field and hand-dispatches to ask/move/take, NOR a custom `dspy.ChainOfThought`/`dspy.Predict` policy that returns an action which application code then routes — and NOT `dspy.Avatar`/`dspy.CodeAct`/`dspy.RLM`. (Static: there must be a `dspy.ReAct(...)` construction and there must be NO hand-written loop dispatching tool calls based on a predicted action field.)", "span_ids": ["s1", "s2"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "The three operations `ask`, `move`, and `take` are supplied in the ReAct `tools=[...]` list and the model selects among them BY NAME, replacing the manual dispatch entirely. Passing them either as plain Python callables (`tools=[ask, move, take]`) OR as explicitly constructed `dspy.Tool(ask)`/`dspy.Tool(move)`/`dspy.Tool(take)` instances BOTH satisfy this (react.py:44 auto-wraps either). It must NOT collapse the three operations into one combined single-string dispatcher tool, and must NOT keep an `if`/`elif` chain over a predicted action field. (Static: read the `tools=` argument of the ReAct construction and confirm the three named operations are present as separate tools.)", "span_ids": ["s1", "s3"]}, {"claim_id": "c3", "claim_type": "core", "weight": 15, "statement": "Each chosen operation is invoked with its OWN structured, per-operation named arguments produced by the model (e.g. `take` receives `item=...`, `move` receives `direction=...`, `ask` receives `question=...` via `next_tool_args`), and each operation's return value is automatically appended into ReAct's trajectory as the observation that feeds the next decision. It must NOT reuse one shared string query for every operation, and must NOT manually concatenate observations into a hand-maintained history/state string. (Static: the scripted steps carry distinct per-tool arg keys, and observations are read from ReAct's `trajectory`, not a developer-built log.)", "span_ids": ["s2", "s4"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "The ReAct module is constructed with a signature like `goal -> outcome` (string shorthand or a `dspy.Signature` subclass with a goal input and a summary output), invoked with a `goal=...` input, and returns a `dspy.Prediction` produced after the ReAct acting loop completes (the object carrying `.trajectory` plus the extracted output field). (Static: signature shape, `goal` invocation, and a returned ReAct prediction in the code text.)", "span_ids": ["s1", "s2"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 10, "statement": "The example runs offline with `dspy.utils.DummyLM` constructed from a positional list of scripted dicts in ReAct's expected shape (`next_thought`/`next_tool_name`/`next_tool_args`, with a final extraction dict for the output field), and it inspects `result.trajectory` to see the full sequence of thoughts, selected tool names, structured tool args, and observations. It must NOT subclass/override DummyLM with a custom `__call__`, pass a non-existent `responses=` kwarg, or substitute a hand-built trace for `result.trajectory`. (Static: a real `dspy.utils.DummyLM([...])` list and a read of `result.trajectory` in the code text.)", "span_ids": ["s2", "s4"]}], "evidence": [{"span_id": "s1", "path": "dspy/predict/react.py", "start_line": 16, "end_line": 18, "excerpt": "0016: class ReAct(Module):\n0017: def __init__(self, signature: type[\"Signature\"], tools: list[Callable], max_iters: int = 20):\n0018: \"\"\""}, {"span_id": "s2", "path": "dspy/predict/react.py", "start_line": 95, "end_line": 118, "excerpt": "0095: def forward(self, **input_args):\n0096: trajectory = {}\n0097: max_iters = input_args.pop(\"max_iters\", self.max_iters)\n0098: for idx in range(max_iters):\n0099: try:\n0100: pred = self._call_with_potential_trajectory_truncation(self.react, trajectory, **input_args)\n0101: except ValueError as err:\n0102: logger.warning(f\"Ending the trajectory: Agent failed to select a valid tool: {_fmt_exc(err)}\")\n0103: break\n0104: \n0105: trajectory[f\"thought_{idx}\"] = pred.next_thought\n0106: trajectory[f\"tool_name_{idx}\"] = pred.next_tool_name\n0107: trajectory[f\"tool_args_{idx}\"] = pred.next_tool_args\n0108: \n0109: try:\n0110: trajectory[f\"observation_{idx}\"] = self.tools[pred.next_tool_name](**pred.next_tool_args)\n0111: except Exception as err:\n0112: trajectory[f\"observation_{idx}\"] = f\"Execution error in {pred.next_tool_name}: {_fmt_exc(err)}\"\n0113: \n0114: if pred.next_tool_name == \"finish\":\n0115: break\n0116: \n0117: extract = self._call_with_potential_trajectory_truncation(self.extract, trajectory, **input_args)\n0118: return dspy.Prediction(trajectory=trajectory, **extract)"}, {"span_id": "s3", "path": "dspy/adapters/types/tool.py", "start_line": 35, "end_line": 74, "excerpt": "0035: def __init__(\n0036: self,\n0037: func: Callable,\n0038: name: str | None = None,\n0039: desc: str | None = None,\n0040: args: dict[str, Any] | None = None,\n0041: arg_types: dict[str, Any] | None = None,\n0042: arg_desc: dict[str, str] | None = None,\n0043: ):\n0044: \"\"\"Initialize the Tool class.\n0045: \n0046: Users can choose to specify the `name`, `desc`, `args`, and `arg_types`, or let the `dspy.Tool`\n0047: automatically infer the values from the function. For values that are specified by the user, automatic inference\n0048: will not be performed on them.\n0049: \n0050: Args:\n0051: func (Callable): The actual function that is being wrapped by the tool.\n0052: name (Optional[str], optional): The name of the tool. Defaults to None.\n0053: desc (Optional[str], optional): The description of the tool. Defaults to None.\n0054: args (Optional[dict[str, Any]], optional): The args and their schema of the tool, represented as a\n0055: dictionary from arg name to arg's json schema. Defaults to None.\n0056: arg_types (Optional[dict[str, Any]], optional): The argument types of the tool, represented as a dictionary\n0057: from arg name to the type of the argument. Defaults to None.\n0058: arg_desc (Optional[dict[str, str]], optional): Descriptions for each arg, represented as a\n0059: dictionary from arg name to description string. Defaults to None.\n0060: \n0061: Examples:\n0062: \n0063: ```python\n0064: def foo(x: int, y: str = \"hello\"):\n0065: return str(x) + y\n0066: \n0067: tool = Tool(foo)\n0068: print(tool.args)\n0069: # Expected output: {'x': {'type': 'integer'}, 'y': {'type': 'string', 'default': 'hello'}}\n0070: ```\n0071: \"\"\"\n0072: super().__init__(func=func, name=name, desc=desc, args=args, arg_types=arg_types, arg_desc=arg_desc)\n0073: self._parse_function(func, arg_desc)\n0074: "}, {"span_id": "s4", "path": "tests/predict/test_react.py", "start_line": 58, "end_line": 114, "excerpt": "0058: def test_tool_calling_with_pydantic_args():\n0059: class CalendarEvent(BaseModel):\n0060: name: str\n0061: date: str\n0062: participants: dict[str, str]\n0063: \n0064: def write_invitation_letter(participant_name: str, event_info: CalendarEvent):\n0065: if participant_name not in event_info.participants:\n0066: return None\n0067: return f\"It's my honor to invite {participant_name} to event {event_info.name} on {event_info.date}\"\n0068: \n0069: class InvitationSignature(dspy.Signature):\n0070: participant_name: str = dspy.InputField(desc=\"The name of the participant to invite\")\n0071: event_info: CalendarEvent = dspy.InputField(desc=\"The information about the event\")\n0072: invitation_letter: str = dspy.OutputField(desc=\"The invitation letter to be sent to the participant\")\n0073: \n0074: react = dspy.ReAct(InvitationSignature, tools=[write_invitation_letter])\n0075: \n0076: lm = DummyLM(\n0077: [\n0078: {\n0079: \"next_thought\": \"I need to write an invitation letter for Alice to the Science Fair event.\",\n0080: \"next_tool_name\": \"write_invitation_letter\",\n0081: \"next_tool_args\": {\n0082: \"participant_name\": \"Alice\",\n0083: \"event_info\": {\n0084: \"name\": \"Science Fair\",\n0085: \"date\": \"Friday\",\n0086: \"participants\": {\"Alice\": \"female\", \"Bob\": \"male\"},\n0087: },\n0088: },\n0089: },\n0090: {\n0091: \"next_thought\": (\n0092: \"I have successfully written the invitation letter for Alice to the Science Fair. Now \"\n0093: \"I can finish the task.\"\n0094: ),\n0095: \"next_tool_name\": \"finish\",\n0096: \"next_tool_args\": {},\n0097: },\n0098: {\n0099: \"reasoning\": \"This is a very rigorous reasoning process, trust me bro!\",\n0100: \"invitation_letter\": \"It's my honor to invite Alice to the Science Fair event on Friday.\",\n0101: },\n0102: ]\n0103: )\n0104: dspy.configure(lm=lm)\n0105: \n0106: outputs = react(\n0107: participant_name=\"Alice\",\n0108: event_info=CalendarEvent(\n0109: name=\"Science Fair\",\n0110: date=\"Friday\",\n0111: participants={\"Alice\": \"female\", \"Bob\": \"male\"},\n0112: ),\n0113: )\n0114: assert outputs.invitation_letter == \"It's my honor to invite Alice to the Science Fair event on Friday.\""}]} {"id": "dspy_188039f2a0d6", "topic": "rag_and_retrieval_pipelines", "question": "Our policy corpus is ~30k documents and encoding it takes minutes, so I want to pay that cost exactly once: encode at build time, write everything needed for retrieval to disk, and have a separate serving process start up and answer questions without ever touching the embedding model for the corpus again.\n\nI built a `dspy.Module` whose `forward` runs a top-k embedding search over the corpus and feeds the hits into a `dspy.ChainOfThought` answer step, then persisted it the way the docs show for DSPy programs — `program.save(\"rag_program.json\")` and reloading with `dspy.load(...)`. It doesn't do what I need: when I flip to `save_program=True` to capture the whole thing it dies with `cannot pickle '_thread.lock' object`, and the state-only `.json` round-trips fine but the reloaded program has lost the corpus index, so my first query just re-encodes all 30k docs again.\n\nWrite a complete, runnable Python program that builds the retriever from the corpus and persists it so that a second, fresh process loads it and answers a question with the corpus encoded only once, ever. Use a self-contained embedder so it runs without network access. Show both phases (build-and-save, then load-and-serve) in one file.", "gold_answer": "```python\nfrom pathlib import Path\n\nimport dspy\nfrom dspy.utils import DummyVectorizer\n\n\nINDEX_DIR = Path('saved_policy_index')\ncorpus = [\n 'Finance keeps invoices for seven years.',\n 'Security incidents must be reported within one hour.',\n 'Customer data exports require director approval.',\n]\nembedder = dspy.Embedder(DummyVectorizer(max_length=256))\n\n# Build once and persist the retriever state.\nif not INDEX_DIR.exists():\n retriever = dspy.Embeddings(corpus=corpus, embedder=embedder, k=3)\n retriever.save(INDEX_DIR)\n\n# Later, in a fresh process, reload the saved retriever.\nloaded_retriever = dspy.Embeddings.from_saved(INDEX_DIR, embedder)\n\n\nclass AnswerFromContext(dspy.Signature):\n context = dspy.InputField()\n question = dspy.InputField()\n answer = dspy.OutputField()\n\n\nclass PersistentRAG(dspy.Module):\n def __init__(self, retriever):\n super().__init__()\n self.retriever = retriever\n self.answer = dspy.ChainOfThought(AnswerFromContext)\n\n def forward(self, question: str):\n hits = self.retriever(question)\n pred = self.answer(context=hits.passages, question=question)\n return dspy.Prediction(context=hits.passages, answer=pred.answer)\n\n\ndspy.configure(lm=dspy.LM('openai/gpt-4o-mini'))\nprogram = PersistentRAG(loaded_retriever)\nresult = program(question='How long do we retain invoices?')\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 50, "statement": "Builds the index by instantiating `dspy.Embeddings` directly with the in-memory corpus and an embedder (so the corpus is encoded once at construction, `corpus_embeddings = embedder(corpus)`) and persists it by calling the RETRIEVER'S OWN `save(path)`, which writes `config.json` + `corpus_embeddings.npy` (and a FAISS index when present). It does NOT roll its own persistence (custom embedder/index plus manual `faiss.write_index` / `np.save` / `json` / `pickle`) and does NOT rely on generic DSPy program persistence (`module.save(...json)` / `save_program=True` / `dspy.load`) to carry the corpus embeddings, and does NOT model the corpus via `dspy.Retrieve` / `dspy.settings.rm` / an external or ColBERT server.", "span_ids": ["s1", "s2", "s3"]}, {"claim_id": "c2", "claim_type": "core", "weight": 30, "statement": "In the fresh/serving process, reloads the retriever with `dspy.Embeddings.from_saved(path, embedder)` (or `instance.load(path, embedder)`), passing the embedder ONLY for new queries. It does NOT re-construct `dspy.Embeddings(corpus=..., embedder=...)` at serve time and does NOT otherwise re-embed the corpus on load — i.e. it takes the `from_saved`/`load` code path (which bypasses `__init__`), NOT a serve-time re-instantiation that would call `embedder(corpus)` again.", "span_ids": ["s4", "s5"]}, {"claim_id": "c3", "claim_type": "supporting", "weight": 12, "statement": "Uses the loaded retriever inside a subclass of `dspy.Module` whose `forward` calls the retriever on the question and passes the retrieved `hits.passages` as context into an answer stage such as `dspy.ChainOfThought`, and `forward` returns a `dspy.Prediction(...)`.", "span_ids": ["s6", "s7", "s8"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 8, "statement": "For a network-free, self-contained example, constructs the embedder as `dspy.Embedder(DummyVectorizer(...))` (a callable mapping `list[str]` to an embedding array), rather than a hand-rolled embedder or a hosted/network embedding model.", "span_ids": ["s9"]}], "evidence": [{"span_id": "s1", "path": "dspy/retrievers/embeddings.py", "start_line": 18, "end_line": 39, "excerpt": "0018: def __init__(\n0019: self,\n0020: corpus: list[str],\n0021: embedder,\n0022: k: int = 5,\n0023: callbacks: list[Any] | None = None,\n0024: cache: bool = False,\n0025: brute_force_threshold: int = 20_000,\n0026: normalize: bool = True,\n0027: ):\n0028: assert cache is False, \"Caching is not supported for embeddings-based retrievers\"\n0029: \n0030: self.embedder = embedder\n0031: self.k = k\n0032: self.corpus = corpus\n0033: self.normalize = normalize\n0034: \n0035: self.corpus_embeddings = self.embedder(self.corpus)\n0036: self.corpus_embeddings = self._normalize(self.corpus_embeddings) if self.normalize else self.corpus_embeddings\n0037: \n0038: self.index = self._build_faiss() if len(corpus) >= brute_force_threshold else None\n0039: self.search_fn = Unbatchify(self._batch_forward)"}, {"span_id": "s2", "path": "tests/retrievers/test_embeddings.py", "start_line": 78, "end_line": 88, "excerpt": "0078: def test_embeddings_save_load():\n0079: corpus = dummy_corpus()\n0080: embedder = dummy_embedder\n0081: \n0082: original_retriever = Embeddings(corpus=corpus, embedder=embedder, k=2, normalize=False, brute_force_threshold=1000)\n0083: \n0084: with tempfile.TemporaryDirectory() as temp_dir:\n0085: save_path = os.path.join(temp_dir, \"test_embeddings\")\n0086: \n0087: # Save original\n0088: original_retriever.save(save_path)"}, {"span_id": "s3", "path": "dspy/retrievers/embeddings.py", "start_line": 111, "end_line": 145, "excerpt": "0111: def save(self, path: str):\n0112: \"\"\"\n0113: Save the embeddings index to disk.\n0114: \n0115: This saves the corpus, embeddings, FAISS index (if present), and configuration\n0116: to allow for fast loading without recomputing embeddings.\n0117: \n0118: Args:\n0119: path: Directory path where the embeddings will be saved\n0120: \"\"\"\n0121: os.makedirs(path, exist_ok=True)\n0122: \n0123: # Save configuration and corpus\n0124: config = {\n0125: \"k\": self.k,\n0126: \"normalize\": self.normalize,\n0127: \"corpus\": self.corpus,\n0128: \"has_faiss_index\": self.index is not None,\n0129: }\n0130: \n0131: with open(os.path.join(path, \"config.json\"), \"w\") as f:\n0132: json.dump(config, f, indent=2)\n0133: \n0134: # Save embeddings\n0135: np.save(os.path.join(path, \"corpus_embeddings.npy\"), self.corpus_embeddings)\n0136: \n0137: # Save FAISS index if it exists\n0138: if self.index is not None:\n0139: try:\n0140: import faiss\n0141: faiss.write_index(self.index, os.path.join(path, \"faiss_index.bin\"))\n0142: except ImportError:\n0143: # If FAISS is not available, we can't save the index\n0144: # but we can still save the embeddings for brute force search\n0145: pass"}, {"span_id": "s4", "path": "dspy/retrievers/embeddings.py", "start_line": 147, "end_line": 236, "excerpt": "0147: def load(self, path: str, embedder):\n0148: \"\"\"\n0149: Load the embeddings index from disk into the current instance.\n0150: \n0151: Args:\n0152: path: Directory path where the embeddings were saved\n0153: embedder: The embedder function to use for new queries\n0154: \n0155: Returns:\n0156: self: Returns self for method chaining\n0157: \n0158: Raises:\n0159: FileNotFoundError: If the save directory or required files don't exist\n0160: ValueError: If the saved config is invalid or incompatible\n0161: \"\"\"\n0162: if not os.path.exists(path):\n0163: raise FileNotFoundError(f\"Save directory not found: {path}\")\n0164: \n0165: config_path = os.path.join(path, \"config.json\")\n0166: embeddings_path = os.path.join(path, \"corpus_embeddings.npy\")\n0167: \n0168: if not os.path.exists(config_path):\n0169: raise FileNotFoundError(f\"Config file not found: {config_path}\")\n0170: if not os.path.exists(embeddings_path):\n0171: raise FileNotFoundError(f\"Embeddings file not found: {embeddings_path}\")\n0172: \n0173: # Load configuration and corpus\n0174: with open(config_path) as f:\n0175: config = json.load(f)\n0176: \n0177: # Validate required config fields\n0178: required_fields = [\"k\", \"normalize\", \"corpus\", \"has_faiss_index\"]\n0179: for field in required_fields:\n0180: if field not in config:\n0181: raise ValueError(f\"Invalid config: missing required field '{field}'\")\n0182: \n0183: # Restore configuration\n0184: self.k = config[\"k\"]\n0185: self.normalize = config[\"normalize\"]\n0186: self.corpus = config[\"corpus\"]\n0187: self.embedder = embedder\n0188: \n0189: # Load embeddings\n0190: self.corpus_embeddings = np.load(embeddings_path)\n0191: \n0192: # Load FAISS index if it was saved and FAISS is available\n0193: faiss_index_path = os.path.join(path, \"faiss_index.bin\")\n0194: if config[\"has_faiss_index\"] and os.path.exists(faiss_index_path):\n0195: try:\n0196: import faiss\n0197: self.index = faiss.read_index(faiss_index_path)\n0198: except ImportError:\n0199: # If FAISS is not available, fall back to brute force\n0200: self.index = None\n0201: else:\n0202: self.index = None\n0203: \n0204: return self\n0205: \n0206: @classmethod\n0207: def from_saved(cls, path: str, embedder):\n0208: \"\"\"\n0209: Create an Embeddings instance from a saved index.\n0210: \n0211: This is the recommended way to load saved embeddings as it creates a new\n0212: instance without unnecessarily computing embeddings.\n0213: \n0214: Args:\n0215: path: Directory path where the embeddings were saved\n0216: embedder: The embedder function to use for new queries\n0217: \n0218: Returns:\n0219: Embeddings instance loaded from disk\n0220: \n0221: Examples:\n0222: ```python\n0223: # Save embeddings\n0224: embeddings = Embeddings(corpus, embedder)\n0225: embeddings.save(\"./saved_embeddings\")\n0226: \n0227: # Load embeddings later\n0228: loaded_embeddings = Embeddings.from_saved(\"./saved_embeddings\", embedder)\n0229: ```\n0230: \"\"\"\n0231: # Create a minimal instance without triggering embedding computation\n0232: instance = cls.__new__(cls)\n0233: # Initialize the search function (required since we bypassed __init__)\n0234: instance.search_fn = Unbatchify(instance._batch_forward)\n0235: instance.load(path, embedder)\n0236: return instance"}, {"span_id": "s5", "path": "tests/retrievers/test_embeddings.py", "start_line": 114, "end_line": 135, "excerpt": "0114: def test_embeddings_from_saved():\n0115: corpus = dummy_corpus()\n0116: embedder = dummy_embedder\n0117: \n0118: original_retriever = Embeddings(corpus=corpus, embedder=embedder, k=3, normalize=True, brute_force_threshold=1000)\n0119: \n0120: with tempfile.TemporaryDirectory() as temp_dir:\n0121: save_path = os.path.join(temp_dir, \"test_embeddings\")\n0122: \n0123: original_retriever.save(save_path)\n0124: loaded_retriever = Embeddings.from_saved(save_path, embedder)\n0125: \n0126: assert loaded_retriever.k == original_retriever.k\n0127: assert loaded_retriever.normalize == original_retriever.normalize\n0128: assert loaded_retriever.corpus == original_retriever.corpus\n0129: \n0130: \n0131: \n0132: def test_embeddings_load_nonexistent_path():\n0133: with pytest.raises((FileNotFoundError, OSError)):\n0134: Embeddings.from_saved(\"/nonexistent/path\", dummy_embedder)\n0135: "}, {"span_id": "s6", "path": "dspy/primitives/module.py", "start_line": 40, "end_line": 49, "excerpt": "0040: class Module(BaseModule, metaclass=ProgramMeta):\n0041: \"\"\"Base class for all DSPy modules (programs).\n0042: \n0043: A Module is a building block for DSPy programs that can contain predictors,\n0044: sub-modules, and custom logic. Modules can be composed together to create\n0045: complex pipelines and can be optimized using DSPy's teleprompters.\n0046: \n0047: All DSPy programs should inherit from this class and implement a ``forward``\n0048: method that defines the program's logic.\n0049: "}, {"span_id": "s7", "path": "dspy/primitives/module.py", "start_line": 93, "end_line": 111, "excerpt": "0093: @with_callbacks\n0094: def __call__(self, *args, **kwargs) -> Prediction:\n0095: from dspy.dsp.utils.settings import thread_local_overrides\n0096: \n0097: caller_modules = settings.caller_modules or []\n0098: caller_modules = list(caller_modules)\n0099: caller_modules.append(self)\n0100: \n0101: with settings.context(caller_modules=caller_modules):\n0102: if settings.track_usage and thread_local_overrides.get().get(\"usage_tracker\") is None:\n0103: with track_usage() as usage_tracker:\n0104: output = self.forward(*args, **kwargs)\n0105: tokens = usage_tracker.get_total_tokens()\n0106: self._set_lm_usage(tokens, output)\n0107: \n0108: return output\n0109: \n0110: return self.forward(*args, **kwargs)\n0111: "}, {"span_id": "s8", "path": "dspy/predict/chain_of_thought.py", "start_line": 12, "end_line": 38, "excerpt": "0012: class ChainOfThought(Module):\n0013: def __init__(\n0014: self,\n0015: signature: str | type[Signature],\n0016: rationale_field: FieldInfo | None = None,\n0017: rationale_field_type: type = str,\n0018: **config: dict[str, Any],\n0019: ):\n0020: \"\"\"\n0021: A module that reasons step by step in order to predict the output of a task.\n0022: \n0023: Args:\n0024: signature (Type[dspy.Signature]): The signature of the module.\n0025: rationale_field (Optional[Union[dspy.OutputField, pydantic.fields.FieldInfo]]): The field that will contain the reasoning.\n0026: rationale_field_type (Type): The type of the rationale field.\n0027: **config: The configuration for the module.\n0028: \"\"\"\n0029: super().__init__()\n0030: signature = ensure_signature(signature)\n0031: desc = \"${reasoning}\"\n0032: rationale_field_type = rationale_field.annotation if rationale_field else rationale_field_type\n0033: rationale_field = rationale_field if rationale_field else dspy.OutputField(desc=desc)\n0034: extended_signature = signature.prepend(name=\"reasoning\", field=rationale_field, type_=rationale_field_type)\n0035: self.predict = dspy.Predict(extended_signature, **config)\n0036: \n0037: def forward(self, **kwargs):\n0038: return self.predict(**kwargs)"}, {"span_id": "s9", "path": "dspy/utils/dummies.py", "start_line": 179, "end_line": 209, "excerpt": "0179: class DummyVectorizer:\n0180: \"\"\"Simple vectorizer based on n-grams.\"\"\"\n0181: \n0182: def __init__(self, max_length=100, n_gram=2):\n0183: self.max_length = max_length\n0184: self.n_gram = n_gram\n0185: self.P = 10**9 + 7 # A large prime number\n0186: random.seed(123)\n0187: self.coeffs = [random.randrange(1, self.P) for _ in range(n_gram)]\n0188: \n0189: def _hash(self, gram):\n0190: \"\"\"Hashes a string using a polynomial hash function.\"\"\"\n0191: h = 1\n0192: for coeff, c in zip(self.coeffs, gram, strict=False):\n0193: h = h * coeff + ord(c)\n0194: h %= self.P\n0195: return h % self.max_length\n0196: \n0197: def __call__(self, texts: list[str]) -> np.ndarray:\n0198: vecs = []\n0199: for text in texts:\n0200: grams = [text[i : i + self.n_gram] for i in range(len(text) - self.n_gram + 1)]\n0201: vec = [0] * self.max_length\n0202: for gram in grams:\n0203: vec[self._hash(gram)] += 1\n0204: vecs.append(vec)\n0205: \n0206: vecs = np.array(vecs, dtype=np.float32)\n0207: vecs -= np.mean(vecs, axis=1, keepdims=True)\n0208: vecs /= np.linalg.norm(vecs, axis=1, keepdims=True) + 1e-10 # Added epsilon to avoid division by zero\n0209: return vecs"}]} {"id": "dspy_0ab31a81ea0b", "topic": "rag_and_retrieval_pipelines", "question": "I have an in-memory list of strings (an internal knowledge base) and I'm standing up a lightweight DSPy search service over it — no answer generation yet, just retrieval. I'm building it on `dspy.Embeddings`, and it does return the right top-k passages with their corpus positions. The problem: for each hit I also need the numeric match strength so the caller can drop weak matches below a relevance cutoff, but the result object my retriever hands back only carries the passages and their indices — there's nowhere on it that exposes how strongly each passage matched the query. On top of that I need to fan this out over a whole batch of incoming queries at once instead of looping one query at a time. Give me a runnable Python program that builds the search service over a small example corpus and runs it across several queries concurrently, returning the per-hit match strength for every query.", "gold_answer": "```python\nimport dspy\nfrom dspy.utils import DummyVectorizer\n\n\nclass SearchService(dspy.Module):\n def __init__(self, corpus: list[str], top_k: int = 3):\n super().__init__()\n self.search = dspy.EmbeddingsWithScores(\n corpus=corpus,\n embedder=dspy.Embedder(DummyVectorizer(max_length=256)),\n k=top_k,\n )\n\n def forward(self, question: str):\n hits = self.search(question)\n return dspy.Prediction(\n passages=hits.passages,\n scores=hits.scores,\n indices=hits.indices,\n )\n\n\nservice = SearchService(\n corpus=[\n 'The refund exception is documented in FIN-204.',\n 'VPN outage steps live in the network operations runbook.',\n 'API token rotation is handled from the admin console.',\n ],\n top_k=2,\n)\n\nqueries = [\n dspy.Example(question='Where is the refund exception documented?').with_inputs('question'),\n dspy.Example(question='How do I rotate API tokens?').with_inputs('question'),\n]\n\nresults = service.batch(queries, num_threads=4, disable_progress_bar=True)\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 35, "statement": "The service is a `dspy.Module` (a class subclassing `dspy.Module` with a `forward` method) that performs retrieval-only search over a provided corpus with configurable top-k, and surfaces per-hit match strength by instantiating `dspy.EmbeddingsWithScores`, NOT the base `dspy.Embeddings` (whose `forward` constructs a `Prediction` with only passages and indices, omitting scores). A local embedder such as `dspy.Embedder(DummyVectorizer(...))` is acceptable.", "span_ids": ["s1", "s2"]}, {"claim_id": "c2", "claim_type": "core", "weight": 25, "statement": "For each query the module's `forward` returns a `dspy.Prediction(...)` whose constructor names the retrieved `passages`, their numeric similarity `scores`, and their corpus `indices` as fields, rather than returning a plain tuple/list/dict/dataclass; the `scores` field is the one a base `dspy.Embeddings` retriever's `Prediction` does not include.", "span_ids": ["s1", "s3"]}, {"claim_id": "c3", "claim_type": "core", "weight": 25, "statement": "Multiple queries are processed concurrently by calling `Module.batch(..., num_threads=...)` on the retrieval module (i.e. by wrapping the retriever in a `dspy.Module` so the inherited `.batch` is available), NOT by calling `.batch` on the raw retriever object and NOT by hand-rolling a thread pool such as `ThreadPoolExecutor` / `threading`.", "span_ids": ["s4"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 15, "statement": "The inputs passed to `batch` are `dspy.Example(...)` objects whose query field is marked via `.with_inputs(...)` (so that `Module.batch`, which reads `example.inputs()`, receives only the declared input field), rather than passing raw query strings or plain dicts to `batch`.", "span_ids": ["s4", "s5"]}], "evidence": [{"span_id": "s1", "path": "dspy/retrievers/embeddings.py", "start_line": 239, "end_line": 258, "excerpt": "0239: class EmbeddingsWithScores(Embeddings):\n0240: \"\"\"DSPy EmbeddingsWithScores retriever.\n0241: \n0242: This class extends the Embeddings retriever to also return similarity scores alongside passages and indices.\n0243: Similarity scores enable downstream such as thresholding and re-ranking.\n0244: \"\"\"\n0245: \n0246: def forward(self, query: str):\n0247: \"\"\"Search for the top-k passages most similar to the query.\n0248: \n0249: Args:\n0250: query (str): The search query string.\n0251: \n0252: Returns:\n0253: dspy.Prediction: A prediction containing passages, indices, and similarity scores.\n0254: \"\"\"\n0255: import dspy\n0256: \n0257: passages, indices, scores = self.search_fn(query)\n0258: return dspy.Prediction(passages=passages, indices=indices, scores=scores)"}, {"span_id": "s2", "path": "dspy/utils/dummies.py", "start_line": 179, "end_line": 209, "excerpt": "0179: class DummyVectorizer:\n0180: \"\"\"Simple vectorizer based on n-grams.\"\"\"\n0181: \n0182: def __init__(self, max_length=100, n_gram=2):\n0183: self.max_length = max_length\n0184: self.n_gram = n_gram\n0185: self.P = 10**9 + 7 # A large prime number\n0186: random.seed(123)\n0187: self.coeffs = [random.randrange(1, self.P) for _ in range(n_gram)]\n0188: \n0189: def _hash(self, gram):\n0190: \"\"\"Hashes a string using a polynomial hash function.\"\"\"\n0191: h = 1\n0192: for coeff, c in zip(self.coeffs, gram, strict=False):\n0193: h = h * coeff + ord(c)\n0194: h %= self.P\n0195: return h % self.max_length\n0196: \n0197: def __call__(self, texts: list[str]) -> np.ndarray:\n0198: vecs = []\n0199: for text in texts:\n0200: grams = [text[i : i + self.n_gram] for i in range(len(text) - self.n_gram + 1)]\n0201: vec = [0] * self.max_length\n0202: for gram in grams:\n0203: vec[self._hash(gram)] += 1\n0204: vecs.append(vec)\n0205: \n0206: vecs = np.array(vecs, dtype=np.float32)\n0207: vecs -= np.mean(vecs, axis=1, keepdims=True)\n0208: vecs /= np.linalg.norm(vecs, axis=1, keepdims=True) + 1e-10 # Added epsilon to avoid division by zero\n0209: return vecs"}, {"span_id": "s3", "path": "tests/retrievers/test_embeddings.py", "start_line": 137, "end_line": 146, "excerpt": "0137: def test_embeddings_with_scores_basic_search():\n0138: corpus = dummy_corpus()\n0139: retriever = EmbeddingsWithScores(corpus=corpus, embedder=dummy_embedder, k=2)\n0140: \n0141: result = retriever(\"A dog is barking.\")\n0142: \n0143: assert result.passages == [\"The dog barked at the mailman.\", \"The cat sat on the mat.\"]\n0144: assert result.indices == [1, 0]\n0145: assert result.scores == pytest.approx([1.0, 0.0])\n0146: "}, {"span_id": "s4", "path": "dspy/primitives/module.py", "start_line": 269, "end_line": 317, "excerpt": "0269: def batch(\n0270: self,\n0271: examples: list[Example],\n0272: num_threads: int | None = None,\n0273: max_errors: int | None = None,\n0274: return_failed_examples: bool = False,\n0275: provide_traceback: bool | None = None,\n0276: disable_progress_bar: bool = False,\n0277: timeout: int = 120,\n0278: straggler_limit: int = 3,\n0279: ) -> list[Example] | tuple[list[Example], list[Example], list[Exception]]:\n0280: \"\"\"\n0281: Processes a list of dspy.Example instances in parallel using the Parallel module.\n0282: \n0283: Args:\n0284: examples: List of dspy.Example instances to process.\n0285: num_threads: Number of threads to use for parallel processing.\n0286: max_errors: Maximum number of errors allowed before stopping execution.\n0287: If ``None``, inherits from ``dspy.settings.max_errors``.\n0288: return_failed_examples: Whether to return failed examples and exceptions.\n0289: provide_traceback: Whether to include traceback information in error logs.\n0290: disable_progress_bar: Whether to display the progress bar.\n0291: timeout: Seconds before a straggler task is resubmitted. Set to 0 to disable.\n0292: straggler_limit: Only check for stragglers when this many or fewer tasks remain.\n0293: \n0294: Returns:\n0295: List of results, and optionally failed examples and exceptions.\n0296: \"\"\"\n0297: # Create a list of execution pairs (self, example)\n0298: exec_pairs = [(self, example.inputs()) for example in examples]\n0299: \n0300: # Create an instance of Parallel\n0301: parallel_executor = Parallel(\n0302: num_threads=num_threads,\n0303: max_errors=max_errors,\n0304: return_failed_examples=return_failed_examples,\n0305: provide_traceback=provide_traceback,\n0306: disable_progress_bar=disable_progress_bar,\n0307: timeout=timeout,\n0308: straggler_limit=straggler_limit,\n0309: )\n0310: \n0311: # Execute the forward method of Parallel\n0312: if return_failed_examples:\n0313: results, failed_examples, exceptions = parallel_executor.forward(exec_pairs)\n0314: return results, failed_examples, exceptions\n0315: else:\n0316: results = parallel_executor.forward(exec_pairs)\n0317: return results"}, {"span_id": "s5", "path": "dspy/primitives/example.py", "start_line": 223, "end_line": 271, "excerpt": "0223: def with_inputs(self, *keys):\n0224: \"\"\"Mark which fields are inputs and return a new `Example`.\n0225: \n0226: Fields not listed here are treated as labels (expected outputs).\n0227: DSPy optimizers and evaluators use this split: they pass\n0228: `example.inputs()` to your program and compare the output against\n0229: `example.labels()`.\n0230: \n0231: Args:\n0232: *keys: Names of the input fields.\n0233: \n0234: Returns:\n0235: A copy of this `Example` with the input keys set.\n0236: \n0237: Examples:\n0238: >>> import dspy\n0239: >>> ex = dspy.Example(question=\"Why?\", answer=\"Because.\").with_inputs(\"question\")\n0240: >>> ex.inputs().keys()\n0241: ['question']\n0242: >>> ex.labels().keys()\n0243: ['answer']\n0244: \"\"\"\n0245: copied = self.copy()\n0246: copied._input_keys = set(keys)\n0247: return copied\n0248: \n0249: def inputs(self):\n0250: \"\"\"Return a new `Example` containing only the input fields.\n0251: \n0252: Requires `with_inputs` to have been called first.\n0253: \n0254: Raises:\n0255: ValueError: If `with_inputs` was not called on this example.\n0256: \n0257: Examples:\n0258: >>> import dspy\n0259: >>> ex = dspy.Example(question=\"Why?\", answer=\"Because.\").with_inputs(\"question\")\n0260: >>> ex.inputs()\n0261: Example({'question': 'Why?'}) (input_keys={'question'})\n0262: \"\"\"\n0263: if self._input_keys is None:\n0264: raise ValueError(\"Inputs have not been set for this example. Use `example.with_inputs()` to set them.\")\n0265: \n0266: # return items that are in input_keys\n0267: d = {key: self._store[key] for key in self._store if key in self._input_keys}\n0268: # return type(self)(d)\n0269: new_instance = type(self)(base=d)\n0270: new_instance._input_keys = self._input_keys # Preserve input_keys in new instance\n0271: return new_instance"}]} {"id": "dspy_aa7467f4bdc2", "topic": "rag_and_retrieval_pipelines", "question": "I'm building a DSPy app on top of an existing in-house retrieval stack. I already have a Python search client with a method like `client.search(query, limit, namespace) -> list[str]` (it returns the raw document strings, ranked). Right now, in each of my `dspy.Module`s I wrap that client as a `dspy.Tool` and call it directly inside `forward` to get my context strings. This is getting unwieldy: I have several modules and a couple of multi-hop ones, and I keep threading the same retriever object through every `__init__`. I want to register my retriever **once** so that any retrieval step in any module picks it up automatically as the shared search backend, without me passing it around — and then answer the question from whatever passages come back. The documents are domain support snippets and my client also needs a `namespace` argument forwarded on each lookup. Show me a complete, runnable Python program that wires my existing search client in this \"set it once, used everywhere\" way and answers a question from the retrieved passages. Use `'openai/gpt-4o-mini'` as the LM.", "gold_answer": "```python\nfrom types import SimpleNamespace\n\nimport dspy\n\n\nclass ExistingVectorClient:\n def __init__(self, namespaces: dict[str, list[str]]):\n self.namespaces = namespaces\n\n def search(self, query: str, limit: int, namespace: str) -> list[str]:\n docs = self.namespaces[namespace]\n scored = sorted(\n docs,\n key=lambda doc: sum(token.lower() in doc.lower() for token in query.split()),\n reverse=True,\n )\n return scored[:limit]\n\n\nclass ExistingRM:\n def __init__(self, client: ExistingVectorClient):\n self.client = client\n\n def __call__(self, query: str, k: int = 3, **kwargs):\n namespace = kwargs.get('namespace', 'support')\n docs = self.client.search(query, limit=k, namespace=namespace)\n return [SimpleNamespace(long_text=text) for text in docs]\n\n\nclass AnswerFromContext(dspy.Signature):\n context = dspy.InputField()\n question = dspy.InputField()\n answer = dspy.OutputField()\n\n\nclass ExistingRAG(dspy.Module):\n def __init__(self):\n super().__init__()\n self.retrieve = dspy.Retrieve(k=3)\n self.answer = dspy.ChainOfThought(AnswerFromContext)\n\n def forward(self, question: str, namespace: str = 'support'):\n context = self.retrieve(question, namespace=namespace).passages\n pred = self.answer(context=context, question=question)\n return dspy.Prediction(context=context, answer=pred.answer)\n\n\nclient = ExistingVectorClient(\n {\n 'support': [\n 'TLS certificate renewals are tracked in the ops checklist.',\n 'Refund exceptions are approved by finance directors.',\n 'API tokens are rotated from the admin console.',\n ]\n }\n)\n\ndspy.configure(lm=dspy.LM('openai/gpt-4o-mini'), rm=ExistingRM(client))\nprogram = ExistingRAG()\nresult = program(question='Where do we track TLS certificate renewals?')\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 40, "statement": "Registers the existing client ONCE as the program-wide retrieval backend by setting the global `rm` slot via `dspy.configure(rm=...)` (or `dspy.settings.configure(rm=...)`), AND performs retrieval through `dspy.Retrieve` (e.g. `self.retrieve = dspy.Retrieve(k=...)`), which reads `dspy.settings.rm`. It must NOT instead (a) use a `retriever`/other slot or a `dspy.Retriever` base class, (b) call the search client (or read `dspy.settings`) directly inside `forward`, or (c) route retrieval through `dspy.Tool`/an agent -- none of those register the snapshot's program-wide default backend.", "span_ids": ["s1", "s2"]}, {"claim_id": "c2", "claim_type": "core", "weight": 25, "statement": "The registered RM returns an iterable of objects that each expose a `long_text` attribute (e.g. `SimpleNamespace(long_text=doc)` / a small dataclass with `long_text`), because `Retrieve.forward` does `passages = [psg.long_text for psg in passages]`. Returning the raw document strings, dicts (e.g. `{\"text\": ...}`/`{\"passage\": ...}`), or a `dspy.Prediction(passages=...)` is incorrect -- it raises `AttributeError`.", "span_ids": ["s1"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "The registered RM callable accepts the query positionally plus a keyword `k` and arbitrary extra keyword arguments (e.g. `def __call__(self, query, k=3, **kwargs)`), because `Retrieve.forward` invokes it as `rm(query, k=k, **kwargs)`; the user's `namespace` is forwarded through these `**kwargs` (and on to `client.search(..., namespace=...)`). An RM that only accepts `top_k`/positional-k, or that rejects extra kwargs, is incorrect.", "span_ids": ["s1"]}, {"claim_id": "c4", "claim_type": "core", "weight": 10, "statement": "The program is a `dspy.Module` whose `forward` composes the `dspy.Retrieve` retrieval step and the answering predictor, and is invoked via the module call (e.g. `program(question=...)`) rather than by calling `.forward(...)` directly.", "span_ids": ["s3"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 5, "statement": "Answers from the retrieved passages using a predictor such as `dspy.ChainOfThought` (or `dspy.Predict`) over a context+question signature, passing the retrieved `.passages` from the `dspy.Retrieve` call as the context input.", "span_ids": ["s4", "s1"]}], "evidence": [{"span_id": "s1", "path": "dspy/retrievers/retrieve.py", "start_line": 43, "end_line": 65, "excerpt": "0043: def forward(\n0044: self,\n0045: query: str,\n0046: k: int | None = None,\n0047: **kwargs,\n0048: ) -> list[str] | Prediction | list[Prediction]:\n0049: k = k if k is not None else self.k\n0050: \n0051: import dspy\n0052: \n0053: if not dspy.settings.rm:\n0054: raise AssertionError(\"No RM is loaded.\")\n0055: \n0056: passages = dspy.settings.rm(query, k=k, **kwargs)\n0057: \n0058: from collections.abc import Iterable\n0059: if not isinstance(passages, Iterable):\n0060: # it's not an iterable yet; make it one.\n0061: # TODO: we should unify the type signatures of dspy.Retriever\n0062: passages = [passages]\n0063: passages = [psg.long_text for psg in passages]\n0064: \n0065: return Prediction(passages=passages)"}, {"span_id": "s2", "path": "dspy/dsp/utils/settings.py", "start_line": 15, "end_line": 18, "excerpt": "0015: DEFAULT_CONFIG = dotdict(\n0016: lm=None,\n0017: adapter=None,\n0018: rm=None,"}, {"span_id": "s3", "path": "dspy/primitives/module.py", "start_line": 40, "end_line": 49, "excerpt": "0040: class Module(BaseModule, metaclass=ProgramMeta):\n0041: \"\"\"Base class for all DSPy modules (programs).\n0042: \n0043: A Module is a building block for DSPy programs that can contain predictors,\n0044: sub-modules, and custom logic. Modules can be composed together to create\n0045: complex pipelines and can be optimized using DSPy's teleprompters.\n0046: \n0047: All DSPy programs should inherit from this class and implement a ``forward``\n0048: method that defines the program's logic.\n0049: "}, {"span_id": "s4", "path": "dspy/predict/chain_of_thought.py", "start_line": 12, "end_line": 38, "excerpt": "0012: class ChainOfThought(Module):\n0013: def __init__(\n0014: self,\n0015: signature: str | type[Signature],\n0016: rationale_field: FieldInfo | None = None,\n0017: rationale_field_type: type = str,\n0018: **config: dict[str, Any],\n0019: ):\n0020: \"\"\"\n0021: A module that reasons step by step in order to predict the output of a task.\n0022: \n0023: Args:\n0024: signature (Type[dspy.Signature]): The signature of the module.\n0025: rationale_field (Optional[Union[dspy.OutputField, pydantic.fields.FieldInfo]]): The field that will contain the reasoning.\n0026: rationale_field_type (Type): The type of the rationale field.\n0027: **config: The configuration for the module.\n0028: \"\"\"\n0029: super().__init__()\n0030: signature = ensure_signature(signature)\n0031: desc = \"${reasoning}\"\n0032: rationale_field_type = rationale_field.annotation if rationale_field else rationale_field_type\n0033: rationale_field = rationale_field if rationale_field else dspy.OutputField(desc=desc)\n0034: extended_signature = signature.prepend(name=\"reasoning\", field=rationale_field, type_=rationale_field_type)\n0035: self.predict = dspy.Predict(extended_signature, **config)\n0036: \n0037: def forward(self, **kwargs):\n0038: return self.predict(**kwargs)"}]} {"id": "dspy_136c0583928c", "topic": "rag_and_retrieval_pipelines", "question": "I'm answering compositional support questions over a fixed in-memory corpus of incident/runbook snippets (a Python `list[str]`), where one lookup is rarely enough — the answer to the first lookup tells you what to search for next. Right now I wrap my corpus in `dspy.Embeddings` and set it as my `rm`, and I drive the whole thing with a single `dspy.ReAct` agent that has a `search(query)` tool, expecting it to keep searching and then answer. Two problems: the retrieval layer throws (something about an unexpected `k` argument / objects with no `long_text`), and even when I stub past that, I can't get back a clean, deduplicated list of exactly the passages that were actually used — ReAct just hands me a trajectory blob. I want a single self-contained `dspy.Module` that, for a small fixed number of search rounds, writes the next search query from what it has gathered so far together with the original question, looks passages up against my `dspy.Embeddings` corpus, accumulates them while dropping duplicates, and at the end returns the short answer alongside the exact set of passages it retained. Give me a complete runnable program, including however I need to expose my embedding corpus so it actually works as the `rm`.", "gold_answer": "```python\nfrom types import SimpleNamespace\n\nimport dspy\nfrom dspy.dsp.utils import deduplicate\nfrom dspy.utils import DummyVectorizer\n\n\nclass GenerateSearchQuery(dspy.Signature):\n context = dspy.InputField(desc=\"may contain relevant facts\")\n question = dspy.InputField()\n query = dspy.OutputField()\n\n\nclass GenerateAnswer(dspy.Signature):\n context = dspy.InputField(desc=\"may contain relevant facts\")\n question = dspy.InputField()\n answer = dspy.OutputField(desc=\"short factoid answer\")\n\n\n# dspy.Embeddings is a standalone retriever: it is called as embeddings(query)\n# (NO k=) and returns a Prediction whose `.passages` is a list of plain strings.\n# dspy.Retrieve, however, calls dspy.settings.rm(query, k=k) and then reads\n# `.long_text` off each returned item. So Embeddings cannot be dropped in as the\n# rm directly; wrap it in a tiny RM that accepts k and re-exposes long_text.\nclass EmbeddingRM:\n def __init__(self, corpus: list[str]):\n self.base = dspy.Embeddings(\n corpus=corpus,\n embedder=dspy.Embedder(DummyVectorizer(max_length=256)),\n k=6,\n )\n\n def __call__(self, query: str, k: int = 3, **kwargs):\n hits = self.base(query)\n return [SimpleNamespace(long_text=text) for text in hits.passages[:k]]\n\n\nclass MultiHopRAG(dspy.Module):\n def __init__(self, max_hops: int = 2, passages_per_hop: int = 2):\n super().__init__()\n self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]\n self.retrieve = dspy.Retrieve(k=passages_per_hop)\n self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n self.max_hops = max_hops\n\n def forward(self, question: str):\n context = []\n for hop in range(self.max_hops):\n query = self.generate_query[hop](context=context, question=question).query\n passages = self.retrieve(query).passages\n context = deduplicate(context + passages)\n\n pred = self.generate_answer(context=context, question=question)\n return dspy.Prediction(context=context, answer=pred.answer)\n\n\ncorpus = [\n \"The outage memo says the primary database vendor was acquired by Contoso.\",\n \"Contoso's enterprise status page is managed by the platform reliability group.\",\n \"The incident handbook names platform reliability as the escalation owner.\",\n]\n\ndspy.configure(lm=dspy.LM(\"openai/gpt-4o-mini\"), rm=EmbeddingRM(corpus))\nprogram = MultiHopRAG(max_hops=2, passages_per_hop=2)\nresult = program(question=\"Who owns the status page for the vendor mentioned in the outage memo?\")\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 50, "statement": "Retrieval each round goes through `dspy.Retrieve` (constructed with `k=`), and the configured retrieval model is a THIN RM ADAPTER wrapping `dspy.Embeddings` that accepts a `k` argument and returns items exposing `.long_text`, registered via `dspy.configure(rm=...)` / `dspy.settings.rm`. It uses the snapshot's `dspy.Retrieve` + configured-`rm` convention, NOT the decoy of calling the corpus retriever object directly as the search step and NOT passing `dspy.Embeddings` straight in as the `rm`.", "span_ids": ["s2", "s3", "es1"]}, {"claim_id": "c2", "claim_type": "core", "weight": 22, "statement": "The adapter reconciles the two distinct snapshot contracts: `dspy.Embeddings` is invoked as `embeddings(query)` with NO `k` and yields a `Prediction` whose `.passages` are plain strings, while `dspy.Retrieve` requires the rm to be callable as `rm(query, k=k)` and to return items with a `.long_text` attribute. The adapter therefore calls the inner `dspy.Embeddings` with the query only and re-wraps each `.passages` string into an object carrying `.long_text`; it must NOT assume `dspy.Embeddings` itself accepts `k` or already exposes `.long_text`/`.search`.", "span_ids": ["s3", "es1"]}, {"claim_id": "c3", "claim_type": "core", "weight": 10, "statement": "The module performs the search in a bounded loop over a fixed number of rounds, and at each round generates a NEW search query from the currently accumulated context plus the original question (e.g. a per-round `dspy.ChainOfThought`/`dspy.Predict` over a context+question->query signature). It must be an explicit query-rewriting loop, NOT a single `dspy.ReAct` agent whose only output is a trajectory.", "span_ids": ["s1", "s2"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "After every retrieval round, the kept evidence is updated by concatenating the prior context with the newly retrieved passages and removing duplicates while preserving order (e.g. via `deduplicate` / `dict.fromkeys`).", "span_ids": ["s1", "s4"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 8, "statement": "After the rounds finish, the final short answer is produced from the accumulated context and the original question via a prediction module such as `dspy.ChainOfThought` over an answer signature, and the module returns BOTH that answer and the exact retained passages (e.g. `dspy.Prediction(answer=..., context=...)` where `context` is the deduplicated kept-evidence list), not a raw ReAct trajectory blob.", "span_ids": ["s1", "s5"]}], "evidence": [{"span_id": "s1", "path": "tests/examples/test_baleen.py", "start_line": 25, "end_line": 43, "excerpt": "0025: class SimplifiedBaleen(dspy.Module):\n0026: def __init__(self, passages_per_hop=3, max_hops=2):\n0027: super().__init__()\n0028: \n0029: self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]\n0030: self.retrieve = dspy.Retrieve(k=passages_per_hop)\n0031: self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n0032: self.max_hops = max_hops\n0033: \n0034: def forward(self, question):\n0035: context = []\n0036: \n0037: for hop in range(self.max_hops):\n0038: query = self.generate_query[hop](context=context, question=question).query\n0039: passages = self.retrieve(query).passages\n0040: context = deduplicate(context + passages)\n0041: \n0042: pred = self.generate_answer(context=context, question=question)\n0043: return dspy.Prediction(context=context, answer=pred.answer)"}, {"span_id": "s2", "path": "tests/examples/test_baleen.py", "start_line": 29, "end_line": 40, "excerpt": "0029: self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]\n0030: self.retrieve = dspy.Retrieve(k=passages_per_hop)\n0031: self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n0032: self.max_hops = max_hops\n0033: \n0034: def forward(self, question):\n0035: context = []\n0036: \n0037: for hop in range(self.max_hops):\n0038: query = self.generate_query[hop](context=context, question=question).query\n0039: passages = self.retrieve(query).passages\n0040: context = deduplicate(context + passages)"}, {"span_id": "s3", "path": "dspy/retrievers/retrieve.py", "start_line": 43, "end_line": 65, "excerpt": "0043: def forward(\n0044: self,\n0045: query: str,\n0046: k: int | None = None,\n0047: **kwargs,\n0048: ) -> list[str] | Prediction | list[Prediction]:\n0049: k = k if k is not None else self.k\n0050: \n0051: import dspy\n0052: \n0053: if not dspy.settings.rm:\n0054: raise AssertionError(\"No RM is loaded.\")\n0055: \n0056: passages = dspy.settings.rm(query, k=k, **kwargs)\n0057: \n0058: from collections.abc import Iterable\n0059: if not isinstance(passages, Iterable):\n0060: # it's not an iterable yet; make it one.\n0061: # TODO: we should unify the type signatures of dspy.Retriever\n0062: passages = [passages]\n0063: passages = [psg.long_text for psg in passages]\n0064: \n0065: return Prediction(passages=passages)"}, {"span_id": "s4", "path": "dspy/dsp/utils/utils.py", "start_line": 72, "end_line": 79, "excerpt": "0072: def deduplicate(seq: list[str]) -> list[str]:\n0073: \"\"\"\n0074: From Raymond Hettinger\n0075: https://twitter.com/raymondh/status/944125570534621185\n0076: Since Python 3.6 Dict are ordered\n0077: Benchmark: https://gist.github.com/peterbe/67b9e40af60a1d5bcb1cfb4b2937b088\n0078: \"\"\"\n0079: return list(dict.fromkeys(seq))"}, {"span_id": "s5", "path": "dspy/predict/chain_of_thought.py", "start_line": 12, "end_line": 38, "excerpt": "0012: class ChainOfThought(Module):\n0013: def __init__(\n0014: self,\n0015: signature: str | type[Signature],\n0016: rationale_field: FieldInfo | None = None,\n0017: rationale_field_type: type = str,\n0018: **config: dict[str, Any],\n0019: ):\n0020: \"\"\"\n0021: A module that reasons step by step in order to predict the output of a task.\n0022: \n0023: Args:\n0024: signature (Type[dspy.Signature]): The signature of the module.\n0025: rationale_field (Optional[Union[dspy.OutputField, pydantic.fields.FieldInfo]]): The field that will contain the reasoning.\n0026: rationale_field_type (Type): The type of the rationale field.\n0027: **config: The configuration for the module.\n0028: \"\"\"\n0029: super().__init__()\n0030: signature = ensure_signature(signature)\n0031: desc = \"${reasoning}\"\n0032: rationale_field_type = rationale_field.annotation if rationale_field else rationale_field_type\n0033: rationale_field = rationale_field if rationale_field else dspy.OutputField(desc=desc)\n0034: extended_signature = signature.prepend(name=\"reasoning\", field=rationale_field, type_=rationale_field_type)\n0035: self.predict = dspy.Predict(extended_signature, **config)\n0036: \n0037: def forward(self, **kwargs):\n0038: return self.predict(**kwargs)"}, {"span_id": "es1", "path": "dspy/retrievers/embeddings.py", "start_line": 41, "end_line": 56, "excerpt": "0041: def __call__(self, query: str):\n0042: return self.forward(query)\n0043: \n0044: def forward(self, query: str):\n0045: \"\"\"Search for the top-k passages most similar to the query.\n0046: \n0047: Args:\n0048: query (str): The search query string\n0049: \n0050: Returns:\n0051: dspy.Prediction: A prediction containing passages and their corpus indices.\n0052: \"\"\"\n0053: import dspy\n0054: \n0055: passages, indices, _scores = self.search_fn(query)\n0056: return dspy.Prediction(passages=passages, indices=indices)"}]} {"id": "dspy_0f329f8e4a71", "topic": "rag_and_retrieval_pipelines", "question": "I have a fixed corpus plus labeled question/answer pairs and a retrieval-backed DSPy module (an embeddings retriever feeding a ChainOfThought answer step). I want `BootstrapFewShot` to tune the prompting around the answer step while leaving retrieval untouched, and I only want it to keep a bootstrapped trajectory when the answer is actually supported by what was retrieved — not a lucky hallucination.\n\nI wired the optimizer up with `metric=dspy.evaluate.CompleteAndGrounded()` because its docstring says it scores both completeness and groundedness, which sounded exactly like \"correct and grounded in the passages.\" It imports and runs without error, but after `compile` the optimized program is byte-for-byte the same as the uncompiled baseline — it never picks up a single bootstrapped demo, no matter how I set the threshold.\n\nGive me a corrected, fully runnable program. The rule for accepting a bootstrapped trajectory must be **deterministic and label-based** — no extra model/judge calls — and must accept a trajectory only when the predicted answer matches the labeled answer AND the labeled answer actually appears in the retrieved passages. Reuse one fixed retriever instance for both the baseline and the compiled program, and evaluate both on a dev set with the same rule so I can compare scores.", "gold_answer": "```python\nimport dspy\nfrom dspy.evaluate import Evaluate, answer_exact_match, answer_passage_match\nfrom dspy.utils import DummyVectorizer\n\n\nclass AnswerFromContext(dspy.Signature):\n context = dspy.InputField()\n question = dspy.InputField()\n answer = dspy.OutputField()\n\n\nclass RetrievalQA(dspy.Module):\n def __init__(self, retriever):\n super().__init__()\n self.retriever = retriever\n self.answer = dspy.ChainOfThought(AnswerFromContext)\n\n def forward(self, question: str):\n hits = self.retriever(question)\n pred = self.answer(context=hits.passages, question=question)\n return dspy.Prediction(context=hits.passages, answer=pred.answer)\n\n\ndef grounded_exact(example, pred, trace=None):\n return answer_exact_match(example, pred) and answer_passage_match(example, pred)\n\n\ncorpus = [\n 'Finance keeps invoices for seven years.',\n 'Security incidents must be reported within one hour.',\n 'Customer data exports require director approval.',\n]\nretriever = dspy.Embeddings(\n corpus=corpus,\n embedder=dspy.Embedder(DummyVectorizer(max_length=256)),\n k=3,\n)\n\ntrainset = [\n dspy.Example(question='How long do we keep invoices?', answer='seven years').with_inputs('question'),\n dspy.Example(question='How quickly must incidents be reported?', answer='one hour').with_inputs('question'),\n]\ndevset = [\n dspy.Example(question='Who must approve customer data exports?', answer='director approval').with_inputs('question'),\n]\n\ndspy.configure(lm=dspy.LM('openai/gpt-4o-mini'))\n\nbaseline = RetrievalQA(retriever)\noptimizer = dspy.BootstrapFewShot(\n metric=grounded_exact,\n max_bootstrapped_demos=4,\n max_labeled_demos=8,\n)\ncompiled = optimizer.compile(RetrievalQA(retriever), trainset=trainset)\n\nevaluator = Evaluate(devset=devset, metric=grounded_exact, num_threads=1)\nbaseline_score = evaluator(baseline).score\ncompiled_score = evaluator(compiled).score\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 45, "statement": "The metric passed to BootstrapFewShot is deterministic and label-based with NO model/judge call: it returns a boolean that is true only when the predicted answer matches the labeled answer AND the labeled answer is present in the passages the prediction exposes under `pred.context` -- i.e. it combines answer-exact-match with passage-grounding via logical AND (e.g. `answer_exact_match` AND `answer_passage_match`, both of which DSPy's passage-grounding convention reads off `pred.context`). It must NOT use an LLM-judge groundedness metric such as `dspy.evaluate.CompleteAndGrounded` or `SemanticF1`, and must NOT establish groundedness by reconstructing passages from the bootstrap `trace` or from a differently-named field instead of the prediction's `context`. This boolean result is what BootstrapFewShot checks to accept/reject a bootstrapped trajectory. (Static: read the metric body -- it ANDs an answer-equality check with a `pred.context` membership check and calls no predictor/LM.)", "span_ids": ["s3", "s4", "s5"]}, {"claim_id": "c2", "claim_type": "core", "weight": 25, "statement": "The retrieval-backed module's `forward` calls the fixed retriever, feeds the retrieved passages into the ChainOfThought answer step, and returns `dspy.Prediction(context=, answer=...)` -- exposing the retrieved passages under the field name `context` (alongside the generated `answer`), the exact field the passage-grounding check reads. It must NOT expose the passages only under the retriever's own `passages` name, only inside the execution trace, or as a positional/other-named field. (Static: the returned Prediction names a `context=` field holding the retrieved passages.)", "span_ids": ["s1", "s2"]}, {"claim_id": "c3", "claim_type": "core", "weight": 5, "statement": "Compilation is performed by calling `BootstrapFewShot.compile` on the retrieval-backed student program with the labeled `trainset`, so optimization assigns few-shot demos onto the student's predictors (changing prompting around the answer step) rather than altering retrieval logic. (Static: a `BootstrapFewShot(...).compile(student, trainset=...)` call site on the RAG program.)", "span_ids": ["s6", "s7"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 15, "statement": "A single embeddings retriever, constructed once from the fixed corpus/embedder/k and returning top-k passages, is reused unchanged for both the baseline and the compiled program by passing that one instance into the module constructor. It must NOT create the retrieval step from a global `dspy.settings.rm` / `dspy.Retrieve()` or build a separate retriever per program. (Static: one retriever object is instantiated and passed into both module constructions.)", "span_ids": ["s1", "s8"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 10, "statement": "Both the uncompiled baseline and the compiled program are evaluated on a dev set with `dspy.Evaluate` using the same deterministic grounding-aware metric, and their `.score` values are obtained for comparison. It must NOT substitute a hand-rolled per-example evaluation loop. (Static: two `Evaluate(...)`-based evaluations whose `.score` is read for baseline and compiled.)", "span_ids": ["s9", "s10"]}], "evidence": [{"span_id": "s1", "path": "dspy/retrievers/embeddings.py", "start_line": 41, "end_line": 56, "excerpt": "0041: def __call__(self, query: str):\n0042: return self.forward(query)\n0043: \n0044: def forward(self, query: str):\n0045: \"\"\"Search for the top-k passages most similar to the query.\n0046: \n0047: Args:\n0048: query (str): The search query string\n0049: \n0050: Returns:\n0051: dspy.Prediction: A prediction containing passages and their corpus indices.\n0052: \"\"\"\n0053: import dspy\n0054: \n0055: passages, indices, _scores = self.search_fn(query)\n0056: return dspy.Prediction(passages=passages, indices=indices)"}, {"span_id": "s2", "path": "tests/examples/test_baleen.py", "start_line": 25, "end_line": 43, "excerpt": "0025: class SimplifiedBaleen(dspy.Module):\n0026: def __init__(self, passages_per_hop=3, max_hops=2):\n0027: super().__init__()\n0028: \n0029: self.generate_query = [dspy.ChainOfThought(GenerateSearchQuery) for _ in range(max_hops)]\n0030: self.retrieve = dspy.Retrieve(k=passages_per_hop)\n0031: self.generate_answer = dspy.ChainOfThought(GenerateAnswer)\n0032: self.max_hops = max_hops\n0033: \n0034: def forward(self, question):\n0035: context = []\n0036: \n0037: for hop in range(self.max_hops):\n0038: query = self.generate_query[hop](context=context, question=question).query\n0039: passages = self.retrieve(query).passages\n0040: context = deduplicate(context + passages)\n0041: \n0042: pred = self.generate_answer(context=context, question=question)\n0043: return dspy.Prediction(context=context, answer=pred.answer)"}, {"span_id": "s3", "path": "dspy/evaluate/metrics.py", "start_line": 285, "end_line": 348, "excerpt": "0285: def answer_exact_match(example, pred, trace=None, frac=1.0):\n0286: \"\"\"Evaluate exact match or F1-thresholded match for an example/prediction pair.\n0287: \n0288: If `example.answer` is a string, compare `pred.answer` against it. If it's a list,\n0289: compare against any of the references. When `frac >= 1.0` (default), use EM;\n0290: otherwise require that the maximum F1 across references is at least `frac`.\n0291: \n0292: Args:\n0293: example: `dspy.Example` object with field `answer` (str or list[str]).\n0294: pred: `dspy.Prediction` object with field `answer` (str).\n0295: trace: Unused; reserved for compatibility.\n0296: frac (float, optional): Threshold in [0.0, 1.0]. `1.0` means EM.\n0297: \n0298: Returns:\n0299: bool: True if the match condition holds; otherwise False.\n0300: \n0301: Examples:\n0302: ```python\n0303: import dspy\n0304: \n0305: example = dspy.Example(answer=[\"Eiffel Tower\", \"Louvre\"])\n0306: pred = dspy.Prediction(answer=\"The Eiffel Tower\")\n0307: \n0308: answer_exact_match(example, pred, frac=1.0) # equivalent to EM, True\n0309: answer_exact_match(example, pred, frac=0.5) # True\n0310: ```\n0311: \"\"\"\n0312: if isinstance(example.answer, str):\n0313: return _answer_match(pred.answer, [example.answer], frac=frac)\n0314: elif isinstance(example.answer, list):\n0315: return _answer_match(pred.answer, example.answer, frac=frac)\n0316: \n0317: raise ValueError(f\"Invalid answer type: {type(example.answer)}\")\n0318: \n0319: \n0320: def answer_passage_match(example, pred, trace=None):\n0321: \"\"\"Return True if any passage in `pred.context` contains the answer(s).\n0322: \n0323: Strings are normalized (and passages also use DPR normalization internally).\n0324: \n0325: Args:\n0326: example: `dspy.Example` object with field `answer` (str or list[str]).\n0327: pred: `dspy.Prediction` object with field `context` (list[str]) containing passages.\n0328: trace: Unused; reserved for compatibility.\n0329: \n0330: Returns:\n0331: bool: True if any passage contains any reference answer; otherwise False.\n0332: \n0333: Examples:\n0334: ```python\n0335: import dspy\n0336: \n0337: example = dspy.Example(answer=\"Eiffel Tower\")\n0338: pred = dspy.Prediction(context=[\"The Eiffel Tower is in Paris.\", \"...\"])\n0339: \n0340: answer_passage_match(example, pred) # True\n0341: ```\n0342: \"\"\"\n0343: if isinstance(example.answer, str):\n0344: return _passage_match(pred.context, [example.answer])\n0345: elif isinstance(example.answer, list):\n0346: return _passage_match(pred.context, example.answer)\n0347: \n0348: raise ValueError(f\"Invalid answer type: {type(example.answer)}\")"}, {"span_id": "s4", "path": "tests/examples/test_baleen.py", "start_line": 72, "end_line": 85, "excerpt": "0072: def validate_context_and_answer_and_hops(example, pred, trace=None):\n0073: if not dspy.evaluate.answer_exact_match(example, pred):\n0074: return False\n0075: if not dspy.evaluate.answer_passage_match(example, pred):\n0076: return False\n0077: \n0078: hops = [example.question] + [outputs.query for *_, outputs in trace if \"query\" in outputs]\n0079: \n0080: if max([len(h) for h in hops]) > 100:\n0081: return False\n0082: if any(dspy.evaluate.answer_exact_match_str(hops[idx], hops[:idx], frac=0.8) for idx in range(2, len(hops))):\n0083: return False\n0084: \n0085: return True"}, {"span_id": "s5", "path": "dspy/teleprompt/bootstrap.py", "start_line": 205, "end_line": 223, "excerpt": "0205: if self.metric:\n0206: metric_val = self.metric(example, prediction, trace)\n0207: if self.metric_threshold:\n0208: success = metric_val >= self.metric_threshold\n0209: else:\n0210: success = metric_val\n0211: else:\n0212: success = True\n0213: except Exception as e:\n0214: success = False\n0215: with self.error_lock:\n0216: self.error_count += 1\n0217: current_error_count = self.error_count\n0218: effective_max_errors = self.max_errors if self.max_errors is not None else dspy.settings.max_errors\n0219: if current_error_count >= effective_max_errors:\n0220: raise e\n0221: logger.error(f\"Failed to run or to evaluate example {example} with {self.metric} due to {e}.\")\n0222: \n0223: if success:"}, {"span_id": "s6", "path": "dspy/teleprompt/bootstrap.py", "start_line": 84, "end_line": 94, "excerpt": "0084: def compile(self, student, *, teacher=None, trainset):\n0085: self.trainset = trainset\n0086: \n0087: self._prepare_student_and_teacher(student, teacher)\n0088: self._prepare_predictor_mappings()\n0089: self._bootstrap()\n0090: \n0091: self.student = self._train()\n0092: self.student._compiled = True\n0093: \n0094: return self.student"}, {"span_id": "s7", "path": "dspy/teleprompt/bootstrap.py", "start_line": 259, "end_line": 271, "excerpt": "0259: def _train(self):\n0260: rng = random.Random(0)\n0261: raw_demos = self.validation\n0262: \n0263: for name, predictor in self.student.named_predictors():\n0264: augmented_demos = self.name2traces[name][: self.max_bootstrapped_demos]\n0265: \n0266: sample_size = min(self.max_labeled_demos - len(augmented_demos), len(raw_demos))\n0267: sample_size = max(0, sample_size)\n0268: \n0269: raw_demos = rng.sample(raw_demos, sample_size)\n0270: predictor.demos = augmented_demos + raw_demos\n0271: "}, {"span_id": "s8", "path": "dspy/retrievers/embeddings.py", "start_line": 18, "end_line": 39, "excerpt": "0018: def __init__(\n0019: self,\n0020: corpus: list[str],\n0021: embedder,\n0022: k: int = 5,\n0023: callbacks: list[Any] | None = None,\n0024: cache: bool = False,\n0025: brute_force_threshold: int = 20_000,\n0026: normalize: bool = True,\n0027: ):\n0028: assert cache is False, \"Caching is not supported for embeddings-based retrievers\"\n0029: \n0030: self.embedder = embedder\n0031: self.k = k\n0032: self.corpus = corpus\n0033: self.normalize = normalize\n0034: \n0035: self.corpus_embeddings = self.embedder(self.corpus)\n0036: self.corpus_embeddings = self._normalize(self.corpus_embeddings) if self.normalize else self.corpus_embeddings\n0037: \n0038: self.index = self._build_faiss() if len(corpus) >= brute_force_threshold else None\n0039: self.search_fn = Unbatchify(self._batch_forward)"}, {"span_id": "s9", "path": "dspy/evaluate/evaluate.py", "start_line": 64, "end_line": 82, "excerpt": "0064: class Evaluate:\n0065: \"\"\"DSPy Evaluate class.\n0066: \n0067: This class is used to evaluate the performance of a DSPy program. Users need to provide a evaluation dataset and\n0068: a metric function in order to use this class. This class supports parallel evaluation on the provided dataset.\n0069: \"\"\"\n0070: \n0071: def __init__(\n0072: self,\n0073: *,\n0074: devset: list[\"dspy.Example\"],\n0075: metric: Callable | None = None,\n0076: num_threads: int | None = None,\n0077: display_progress: bool = False,\n0078: display_table: bool | int = False,\n0079: max_errors: int | None = None,\n0080: provide_traceback: bool | None = None,\n0081: failure_score: float = 0.0,\n0082: save_as_csv: str | None = None,"}, {"span_id": "s10", "path": "dspy/evaluate/evaluate.py", "start_line": 117, "end_line": 125, "excerpt": "0117: def __call__(\n0118: self,\n0119: program: \"dspy.Module\",\n0120: metric: Callable | None = None,\n0121: devset: list[\"dspy.Example\"] | None = None,\n0122: num_threads: int | None = None,\n0123: display_progress: bool | None = None,\n0124: display_table: bool | int | None = None,\n0125: callback_metadata: dict[str, Any] | None = None,"}]} {"id": "dspy_0a25b1b505ca", "topic": "signature_schema_and_pydantic_types", "question": "I'm building a reusable ticket-tagging `dspy.Module`. The set of allowed tags grows at runtime as our agents approve new ones, so right now I pass the current tag list in as an input field and spell out in the signature instructions that the model must answer with exactly one tag from that list (or the string `__NEW__` if nothing fits). It mostly works, but every so often the model returns a tag that isn't in the list at all — a near-miss paraphrase, or an old tag we already retired — and that bogus value sails straight into my downstream object with no complaint. I need each individual call to be hard-constrained to whatever the live tag inventory is at that moment, so that an answer outside the inventory fails loudly instead of silently slipping through, and I want the result handed back as a small typed object rather than a raw prediction. Write that `dspy.Module`. It should take the ticket text plus the current tag inventory, allow exactly one existing tag or a `__NEW__` sentinel per call, and normalize the outcome (the chosen tag, and whether a brand-new tag was requested) into that typed object.", "gold_answer": "```python\nfrom typing import Literal\n\nimport dspy\nimport pydantic\nfrom dspy.utils import DummyLM\n\n\nclass LabelDecision(pydantic.BaseModel):\n label: str\n created_new: bool\n\n\nclass BaseTicketLabeler(dspy.Signature):\n 'Choose an existing label or request a new one.'\n\n text: str = dspy.InputField()\n known_labels: list[str] = dspy.InputField(desc='Previously accepted labels.')\n choice: str = dspy.OutputField(desc='Pick one existing label or __NEW__.')\n new_label: str | None = dspy.OutputField(desc='Use None unless choice is __NEW__.')\n\n\nclass TicketLabeler(dspy.Module):\n def forward(self, text: str, known_labels: list[str]) -> LabelDecision:\n dynamic_sig = BaseTicketLabeler.with_updated_fields(\n 'choice',\n type_=Literal[tuple([*known_labels, '__NEW__'])],\n )\n pred = dspy.Predict(dynamic_sig)(text=text, known_labels=known_labels)\n\n if pred.choice == '__NEW__':\n if pred.new_label is None:\n raise ValueError('LM chose __NEW__ without providing new_label')\n return LabelDecision(label=pred.new_label, created_new=True)\n\n return LabelDecision(label=pred.choice, created_new=False)\n\n\ndspy.configure(\n lm=DummyLM(\n [\n {\n 'choice': '__NEW__',\n 'new_label': 'billing_issue',\n }\n ]\n )\n)\n\nresult = TicketLabeler()(\n text='My invoice shows duplicate charges for the same seat.',\n known_labels=['bug_report', 'feature_request', 'access_problem'],\n)\n\nassert result == LabelDecision(label='billing_issue', created_new=True)\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 45, "statement": "The hard per-call constraint is enforced by the CHOICE output field's TYPE: that field is annotated with a runtime `Literal[...]` built from the current inventory (e.g. `Literal[tuple([*known_labels, '__NEW__'])]`), so an out-of-set value is rejected during DSPy value parsing (`parse_value` raising `ValueError` on an invalid literal). It does NOT count if the output field is left as a free `str` (or other open type) and validity is instead enforced by a post-hoc Python membership check / `raise`, by prompt/instruction text describing the allowed values, or by a reward/retry/assertion wrapper.", "span_ids": ["s1", "s2", "s3"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "A FRESH signature is constructed on each call from the live inventory using the snapshot's signature-derivation convention -- e.g. `BaseSig.with_updated_fields('choice', type_=...)` (or an equivalently rebuilt `dspy.Signature` whose output field is set via `type_=Literal[...]`) inside `forward`. A single static signature class defined once (e.g. in `__init__` or at module scope) and reused across calls, with the inventory only flowing in as input data, does NOT satisfy this.", "span_ids": ["s1", "s2"]}, {"claim_id": "c3", "claim_type": "supporting", "weight": 15, "statement": "The reusable component is a `dspy.Module` whose `forward` takes the ticket text and the current label inventory, runs a `dspy.Predict`/predictor over the constrained signature, and returns a normalized typed result object rather than the raw `Prediction`.", "span_ids": ["s1", "s4"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "The normalized result object captures BOTH the chosen label string and whether a brand-new label was requested, e.g. via a small Pydantic `BaseModel` (or comparable typed) result type.", "span_ids": ["s4"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 10, "statement": "When the model selects `__NEW__`, the module adopts the companion new-label field as the returned label and treats missing/None new-label data as invalid (raises), rather than silently returning the literal `__NEW__` sentinel string as the label.", "span_ids": ["s4"]}], "evidence": [{"span_id": "s1", "path": "dspy/signatures/signature.py", "start_line": 299, "end_line": 322, "excerpt": "0299: def with_updated_fields(cls, name: str, type_: type | None = None, **kwargs: dict[str, Any]) -> type[\"Signature\"]:\n0300: \"\"\"Create a new Signature class with the updated field information.\n0301: \n0302: Returns a new Signature class with the field, name, updated\n0303: with fields[name].json_schema_extra[key] = value.\n0304: \n0305: Args:\n0306: name: The name of the field to update.\n0307: type_: The new type of the field.\n0308: kwargs: The new values for the field.\n0309: \n0310: Returns:\n0311: A new Signature class (not an instance) with the updated field information.\n0312: \"\"\"\n0313: fields_copy = deepcopy(cls.fields)\n0314: # Update `fields_copy[name].json_schema_extra` with the new kwargs, on conflicts\n0315: # we use the new value in kwargs.\n0316: fields_copy[name].json_schema_extra = {\n0317: **fields_copy[name].json_schema_extra,\n0318: **kwargs,\n0319: }\n0320: if type_ is not None:\n0321: fields_copy[name].annotation = type_\n0322: return Signature(fields_copy, cls.instructions)"}, {"span_id": "s2", "path": "dspy/predict/react.py", "start_line": 73, "end_line": 79, "excerpt": "0073: react_signature = (\n0074: dspy.Signature({**signature.input_fields}, \"\\n\".join(instr))\n0075: .append(\"trajectory\", dspy.InputField(), type_=str)\n0076: .append(\"next_thought\", dspy.OutputField(), type_=str)\n0077: .append(\"next_tool_name\", dspy.OutputField(), type_=Literal[tuple(tools.keys())])\n0078: .append(\"next_tool_args\", dspy.OutputField(), type_=dict[str, Any])\n0079: )"}, {"span_id": "s3", "path": "tests/adapters/test_adapter_utils.py", "start_line": 64, "end_line": 77, "excerpt": "0064: def test_parse_value_literal():\n0065: # Test Literal type\n0066: assert parse_value(\"option1\", Literal[\"option1\", \"option2\"]) == \"option1\"\n0067: assert parse_value(\"option2\", Literal[\"option1\", \"option2\"]) == \"option2\"\n0068: \n0069: # Test Literal with quotes and prefixes\n0070: assert parse_value(\"'option1'\", Literal[\"option1\", \"option2\"]) == \"option1\"\n0071: assert parse_value('\"option1\"', Literal[\"option1\", \"option2\"]) == \"option1\"\n0072: assert parse_value(\"Literal[option1]\", Literal[\"option1\", \"option2\"]) == \"option1\"\n0073: assert parse_value(\"str[option1]\", Literal[\"option1\", \"option2\"]) == \"option1\"\n0074: \n0075: # Test invalid literal\n0076: with pytest.raises(ValueError):\n0077: parse_value(\"invalid\", Literal[\"option1\", \"option2\"])"}, {"span_id": "s4", "path": "tests/adapters/test_adapter_utils.py", "start_line": 25, "end_line": 43, "excerpt": "0025: def test_parse_value_pydantic_types():\n0026: # Test with pydantic BaseModel - JSON string input\n0027: json_str = '{\"name\": \"John\", \"age\": 30}'\n0028: result = parse_value(json_str, Profile)\n0029: assert isinstance(result, Profile)\n0030: assert result.name == \"John\"\n0031: assert result.age == 30\n0032: \n0033: # Test with pydantic BaseModel - dict input\n0034: dict_input = {\"name\": \"Jane\", \"age\": 25}\n0035: result = parse_value(dict_input, Profile)\n0036: assert isinstance(result, Profile)\n0037: assert result.name == \"Jane\"\n0038: assert result.age == 25\n0039: \n0040: # Test with invalid pydantic data\n0041: with pytest.raises(Exception):\n0042: parse_value('{\"name\": \"John\"}', Profile) # missing required age field\n0043: "}]} {"id": "dspy_37b0aa70071a", "topic": "signature_schema_and_pydantic_types", "question": "I'm building a study-quiz generator with DSPy. A quiz has a title and a list of questions, where each question is one of several kinds — multiple-choice (carries `options` plus the correct option), true/false (a boolean answer), flashcard (a `term` and a `definition`), and so on. They all share the `question` prompt text and a short string tag naming the kind. I want the model to emit one structured quiz object and hand me back real per-kind question objects so downstream code can read `q.options` on a multiple-choice item or `q.definition` on a flashcard.\n\nHere's the shape of what I have:\n\n```python\nimport dspy\nimport pydantic\n\n\nclass BaseQuestion(pydantic.BaseModel):\n kind: str\n question: str\n\n\nclass Quiz(pydantic.BaseModel):\n title: str\n questions: list[BaseQuestion]\n\n\nclass GenerateQuiz(dspy.Signature):\n \"\"\"Generate a quiz from the provided study context.\"\"\"\n\n context: str = dspy.InputField()\n quiz: Quiz = dspy.OutputField()\n\n\ngenerate = dspy.TypedPredictor(GenerateQuiz)\nquiz = generate(context=study_text).quiz\n\nfor q in quiz.questions:\n if q.kind == \"multiple_choice\":\n print(q.options, q.correct_answer)\n```\n\nThe problem: every element of `quiz.questions` comes back as the shared base type, so the kind-specific fields (`options`, `correct_answer`, `term`, `definition`) are simply not there and `q.options` raises. I just get the common `question`/`kind` fields on each item.\n\nRewrite this as a corrected, self-contained runnable program (no network — stub the LM so it returns a fixed quiz) that hands back genuinely typed, per-kind question objects dispatched from the kind tag, built on a typed schema rather than raw dicts. Demonstrate with assertions that a multiple-choice element really is its own concrete question type and that its `options` and `correct_answer` fields are populated.", "gold_answer": "```python\nfrom enum import Enum\nfrom typing import Annotated, Literal\n\nimport dspy\nimport pydantic\nfrom dspy.utils import DummyLM\n\n\nclass QuestionKind(str, Enum):\n MULTIPLE_CHOICE = \"multiple_choice\"\n TRUE_FALSE = \"true_false\"\n FLASH_CARD = \"flash_card\"\n\n\nclass BaseQuestion(pydantic.BaseModel):\n question: str\n\n\nclass MultipleChoiceQuestion(BaseQuestion):\n kind: Literal[QuestionKind.MULTIPLE_CHOICE]\n options: list[str]\n correct_answer: str\n\n\nclass TrueFalseQuestion(BaseQuestion):\n kind: Literal[QuestionKind.TRUE_FALSE]\n correct_answer: bool\n\n\nclass FlashCardQuestion(BaseQuestion):\n kind: Literal[QuestionKind.FLASH_CARD]\n term: str\n definition: str\n\n\nQuestion = Annotated[\n MultipleChoiceQuestion | TrueFalseQuestion | FlashCardQuestion,\n pydantic.Field(discriminator=\"kind\"),\n]\n\n\nclass Quiz(pydantic.BaseModel):\n title: str\n questions: list[Question]\n\n\nclass GenerateQuiz(dspy.Signature):\n \"\"\"Generate a quiz from the provided study context.\"\"\"\n\n context: str = dspy.InputField()\n quiz: Quiz = dspy.OutputField()\n\n\nadapter = dspy.JSONAdapter()\ndspy.configure(\n lm=DummyLM(\n [\n {\n \"quiz\": {\n \"title\": \"Planet Basics\",\n \"questions\": [\n {\n \"kind\": \"multiple_choice\",\n \"question\": \"Which planet is known as the Red Planet?\",\n \"options\": [\"Earth\", \"Mars\", \"Venus\"],\n \"correct_answer\": \"Mars\",\n },\n {\n \"kind\": \"flash_card\",\n \"question\": \"Define 'red planet'.\",\n \"term\": \"Red Planet\",\n \"definition\": \"A common nickname for Mars.\",\n },\n ],\n }\n }\n ],\n adapter=adapter,\n ),\n adapter=adapter,\n)\n\nquiz = dspy.Predict(GenerateQuiz)(context=\"Mars is called the Red Planet.\").quiz\n\nassert isinstance(quiz.questions[0], MultipleChoiceQuestion)\nassert quiz.questions[0].options == [\"Earth\", \"Mars\", \"Venus\"]\nassert quiz.questions[0].correct_answer == \"Mars\"\nassert isinstance(quiz.questions[1], FlashCardQuestion)\nassert quiz.questions[1].definition == \"A common nickname for Mars.\"\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 70, "statement": "The program produces and parses the typed quiz by calling `dspy.Predict(GenerateQuiz)` (equivalently `dspy.ChainOfThought`) over the class-based Signature, and the LM is stubbed offline with `dspy.utils.DummyLM` (no network). It MUST NOT use the decoy `dspy.TypedPredictor(GenerateQuiz)` (nor any `dspy.TypedChainOfThought`/`functional`-style typed-predictor wrapper) copied from the broken starter code: `dspy.TypedPredictor` does not exist in this snapshot, so structured Pydantic parsing of the annotated output runs only through the plain `dspy.Predict` path. (Static: the execution call site is `dspy.Predict(...)`/`dspy.ChainOfThought(...)`, not `dspy.TypedPredictor(...)`.)", "span_ids": ["s1", "s4", "s5"]}, {"claim_id": "c2", "claim_type": "core", "weight": 12, "statement": "`Quiz.questions`' element type is a TAGGED/DISCRIMINATED union of the distinct per-kind Pydantic subtypes keyed on `kind` -- i.e. `Annotated[MultipleChoiceQuestion | TrueFalseQuestion | FlashCardQuestion, pydantic.Field(discriminator=\"kind\")]` (or equivalent tagged-union declaration) -- so each element is parsed into its concrete subtype. It MUST NOT collapse every item to the shared base model nor type the list as a plain undiscriminated `list[Union[...]]`/`list[BaseQuestion]`/list of raw dicts. (Static: read the annotation on `questions`; a `discriminator=`/tagged-union declaration must be present.)", "span_ids": ["s1", "s3"]}, {"claim_id": "c3", "claim_type": "supporting", "weight": 8, "statement": "The output is exposed through a class-based `dspy.Signature` subclass whose `quiz` field is annotated with the Pydantic `Quiz` schema type and declared via `dspy.OutputField()` (with `context` via `dspy.InputField()`), preserving the full structured type annotation on the signature. (Static: a `class ...(dspy.Signature)` with `quiz: Quiz = dspy.OutputField()`.)", "span_ids": ["s4", "s5"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 6, "statement": "Each per-kind subtype constrains its `kind` discriminator with an Enum/Literal value (e.g. `kind: Literal[\"multiple_choice\"]` or a `Literal[QuestionKind.MULTIPLE_CHOICE]`) and gives the kind-specific data typed fields (`options`/`correct_answer`/`term`/`definition`), so the selecting tag is a validated typed value rather than a free-form `str`. (Static: each subtype's `kind` is Literal/Enum-typed.)", "span_ids": ["s2", "s3"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 4, "statement": "The code TEXT contains an `isinstance(...)` assertion checking that an element of `quiz.questions` is one of the concrete per-kind subtypes (e.g. `assert isinstance(quiz.questions[0], MultipleChoiceQuestion)`) AND reads at least one subtype-only attribute off such an element (e.g. `.options`/`.correct_answer`/`.definition`). (Static: presence of the isinstance-against-subtype assertion and a subtype-only attribute access in the source; not graded on any runtime value.)", "span_ids": ["s1"]}], "evidence": [{"span_id": "s1", "path": "dspy/adapters/utils.py", "start_line": 149, "end_line": 190, "excerpt": "0149: def parse_value(value, annotation):\n0150: if annotation is str:\n0151: return str(value)\n0152: \n0153: if isinstance(annotation, enum.EnumMeta):\n0154: return find_enum_member(annotation, value)\n0155: \n0156: origin = get_origin(annotation)\n0157: \n0158: if origin is Literal:\n0159: allowed = get_args(annotation)\n0160: if value in allowed:\n0161: return value\n0162: \n0163: if isinstance(value, str):\n0164: v = value.strip()\n0165: if v.startswith((\"Literal[\", \"str[\")) and v.endswith(\"]\"):\n0166: v = v[v.find(\"[\") + 1 : -1]\n0167: if len(v) > 1 and v[0] == v[-1] and v[0] in \"\\\"'\":\n0168: v = v[1:-1]\n0169: \n0170: if v in allowed:\n0171: return v\n0172: \n0173: raise ValueError(f\"{value!r} is not one of {allowed!r}\")\n0174: \n0175: if not isinstance(value, str):\n0176: return TypeAdapter(annotation).validate_python(value)\n0177: \n0178: if origin in (Union, types.UnionType) and type(None) in get_args(annotation) and str in get_args(annotation):\n0179: # Handle union annotations, e.g., `str | None`, `Optional[str]`, `Union[str, int, None]`, etc.\n0180: return TypeAdapter(annotation).validate_python(value)\n0181: \n0182: candidate = json_repair.loads(value) # json_repair.loads returns \"\" on failure.\n0183: if candidate == \"\" and value != \"\":\n0184: try:\n0185: candidate = ast.literal_eval(value)\n0186: except (ValueError, SyntaxError):\n0187: candidate = value\n0188: \n0189: try:\n0190: return TypeAdapter(annotation).validate_python(candidate)"}, {"span_id": "s2", "path": "tests/reliability/test_pydantic_models.py", "start_line": 46, "end_line": 62, "excerpt": "0046: @pytest.mark.parametrize(\"module\", [dspy.Predict, dspy.ChainOfThought])\n0047: @pytest.mark.reliability\n0048: def test_color_classification_using_enum(module):\n0049: Color = Enum(\"Color\", [\"RED\", \"GREEN\", \"BLUE\"])\n0050: \n0051: class Colorful(dspy.Signature):\n0052: text: str = dspy.InputField()\n0053: color: Color = dspy.OutputField()\n0054: \n0055: program = module(Colorful)\n0056: # Note: The precise text, including the trailing period, is important here for ensuring that\n0057: # the program is correctly extracting the color from the text; previous implementations have\n0058: # produced invalid enum responses for \"The sky is blue.\", but they have produced valid enum\n0059: # responses for \"The sky is blue\" (without the period).\n0060: color = program(text=\"The sky is blue.\").color\n0061: \n0062: assert color == Color.BLUE"}, {"span_id": "s3", "path": "tests/reliability/test_pydantic_models.py", "start_line": 110, "end_line": 190, "excerpt": "0110: @pytest.mark.parametrize(\"module\", [dspy.Predict, dspy.ChainOfThought])\n0111: @pytest.mark.reliability\n0112: def test_tool_calling_with_literals(module):\n0113: next_tool_names = [\n0114: \"get_docs\",\n0115: \"finish\",\n0116: \"search_policy\",\n0117: \"notify_manager\",\n0118: \"calculate_accrual\",\n0119: \"combine_leave\",\n0120: \"review_seniority_rules\",\n0121: \"fetch_calendar\",\n0122: \"verify_compensation\",\n0123: \"check_carryover_policy\",\n0124: ]\n0125: \n0126: class ToolCalling(dspy.Signature):\n0127: \"\"\"\n0128: Given the fields question, produce the fields response.\n0129: You will be given question and your goal is to finish with response.\n0130: To do this, you will interleave Thought, Tool Name, and Tool Args, and receive a resulting Observation.\n0131: \"\"\"\n0132: \n0133: question: str = dspy.InputField()\n0134: trajectory: str = dspy.InputField()\n0135: next_thought: str = dspy.OutputField()\n0136: next_tool_name: Literal[\n0137: \"get_docs\",\n0138: \"finish\",\n0139: \"search_policy\",\n0140: \"notify_manager\",\n0141: \"calculate_accrual\",\n0142: \"combine_leave\",\n0143: \"review_seniority_rules\",\n0144: \"fetch_calendar\",\n0145: \"verify_compensation\",\n0146: \"check_carryover_policy\",\n0147: ] = dspy.OutputField()\n0148: next_tool_args: dict[str, Any] = dspy.OutputField()\n0149: response_status: Literal[\"success\", \"error\", \"pending\"] = dspy.OutputField()\n0150: user_intent: Literal[\"informational\", \"transactional\", \"exploratory\"] = dspy.OutputField()\n0151: \n0152: program = dspy.Predict(ToolCalling)\n0153: prediction = program(\n0154: question=(\n0155: \"Tell me more about the company's internal policy for paid time off (PTO), \"\n0156: \"including as many details as possible. I want to know how PTO is accrued—are \"\n0157: \"there fixed rates, and do they vary by employee seniority or length of service? \"\n0158: \"Are there specific rules about carrying unused PTO into the next calendar year, \"\n0159: \"or is it a 'use it or lose it' system? Additionally, if an employee plans to take \"\n0160: \"extended leave for a vacation or personal reasons, what is the process for submitting \"\n0161: \"a request, and how far in advance should they notify their manager? Is there any overlap \"\n0162: \"or interaction between PTO and other forms of leave, such as sick leave or parental leave? \"\n0163: \"For example, can PTO be combined with those leave types to create a longer absence, or are \"\n0164: \"they strictly separate? I’d also like to know if there are any restrictions on when PTO can \"\n0165: \"be used, such as during critical business periods or holidays. Finally, what is the official \"\n0166: \"policy if an employee resigns or is terminated—are they compensated for unused PTO days, and if \"\n0167: \"so, at what rate?\"\n0168: ),\n0169: trajectory=(\n0170: \"[\"\n0171: \"{'thought': 'Start by understanding PTO accrual rules.', 'tool_name': 'search_policy', 'tool_args': {'topic': 'PTO accrual rates'}}, \"\n0172: \"{'thought': 'Clarify whether PTO accrual rates vary by seniority.', 'tool_name': 'review_seniority_rules', 'tool_args': {}}, \"\n0173: \"{'thought': 'Identify carryover rules for unused PTO.', 'tool_name': 'check_carryover_policy', 'tool_args': {'year': 'current year'}}, \"\n0174: \"{'thought': 'Determine policies on extended leave requests.', 'tool_name': 'search_policy', 'tool_args': {'topic': 'PTO leave request process'}}, \"\n0175: \"{'thought': 'Check the notification requirements for extended PTO.', 'tool_name': 'notify_manager', 'tool_args': {'type': 'extended leave'}}, \"\n0176: \"{'thought': 'Investigate overlap between PTO and sick leave.', 'tool_name': 'combine_leave', 'tool_args': {'types': ['PTO', 'sick leave']}}, \"\n0177: \"{'thought': 'Explore how PTO interacts with parental leave.', 'tool_name': 'combine_leave', 'tool_args': {'types': ['PTO', 'parental leave']}}, \"\n0178: \"{'thought': 'Fetch the company calendar to determine critical business periods.', 'tool_name': 'fetch_calendar', 'tool_args': {'year': 'current year'}}, \"\n0179: \"{'thought': 'Verify restrictions on PTO usage during holidays.', 'tool_name': 'search_policy', 'tool_args': {'topic': 'holiday restrictions on PTO'}}, \"\n0180: \"{'thought': 'Confirm whether unused PTO is compensated upon termination.', 'tool_name': 'verify_compensation', 'tool_args': {'scenario': 'termination'}}, \"\n0181: \"{'thought': 'Check if PTO is compensated differently upon resignation.', 'tool_name': 'verify_compensation', 'tool_args': {'scenario': 'resignation'}}, \"\n0182: \"{'thought': 'Review if accrual caps limit PTO earnings.', 'tool_name': 'calculate_accrual', 'tool_args': {'cap': True}}, \"\n0183: \"{'thought': 'Investigate whether senior employees receive additional PTO benefits.', 'tool_name': 'review_seniority_rules', 'tool_args': {'seniority_level': 'high'}}, \"\n0184: \"{'thought': 'Assess policy transparency in PTO documentation.', 'tool_name': 'search_policy', 'tool_args': {'topic': 'PTO documentation clarity'}}, \"\n0185: \"{'thought': 'Explore how leave types can be optimized together.', 'tool_name': 'combine_leave', 'tool_args': {'types': ['PTO', 'other leave']}}, \"\n0186: \"{'thought': 'Check historical trends in PTO policy changes.', 'tool_name': 'get_docs', 'tool_args': {'document': 'PTO history'}}\"\n0187: \"]\"\n0188: ),\n0189: )\n0190: assert prediction.next_tool_name in next_tool_names"}, {"span_id": "s4", "path": "dspy/signatures/signature.py", "start_line": 138, "end_line": 203, "excerpt": "0138: def __new__(mcs, signature_name, bases, namespace, **kwargs):\n0139: # At this point, the orders have been swapped already.\n0140: field_order = [name for name, value in namespace.items() if isinstance(value, FieldInfo)]\n0141: # Set `str` as the default type for all fields\n0142: if sys.version_info >= (3, 14):\n0143: try:\n0144: import annotationlib\n0145: # Try to get from explicit __annotations__ first (e.g., from __future__ import annotations)\n0146: raw_annotations = namespace.get(\"__annotations__\")\n0147: \n0148: if raw_annotations is None:\n0149: # In 3.14 with PEP 649, get the annotate function and call it\n0150: annotate_func = annotationlib.get_annotate_from_class_namespace(namespace)\n0151: if annotate_func:\n0152: raw_annotations = annotationlib.call_annotate_function(\n0153: annotate_func,\n0154: format=annotationlib.Format.FORWARDREF\n0155: )\n0156: else:\n0157: raw_annotations = {}\n0158: except ImportError:\n0159: raw_annotations = namespace.get(\"__annotations__\", {})\n0160: else:\n0161: # Python 3.13 and earlier\n0162: # Set `str` as the default type for all fields\n0163: raw_annotations = namespace.get(\"__annotations__\", {})\n0164: for name, field in namespace.items():\n0165: if not isinstance(field, FieldInfo):\n0166: continue # Don't add types to non-field attributes\n0167: if not name.startswith(\"__\") and name not in raw_annotations:\n0168: raw_annotations[name] = str\n0169: field.json_schema_extra[IS_TYPE_UNDEFINED] = True # Mark that the type was originally undefined in the signature\n0170: # Create ordered annotations dictionary that preserves field order\n0171: ordered_annotations = {name: raw_annotations[name] for name in field_order if name in raw_annotations}\n0172: # Add any remaining annotations that weren't in field_order\n0173: ordered_annotations.update({k: v for k, v in raw_annotations.items() if k not in ordered_annotations})\n0174: namespace[\"__annotations__\"] = ordered_annotations\n0175: \n0176: # Let Pydantic do its thing\n0177: cls = super().__new__(mcs, signature_name, bases, namespace, **kwargs)\n0178: \n0179: # If we don't have instructions, it might be because we are a derived generic type.\n0180: # In that case, we should inherit the instructions from the base class.\n0181: if cls.__doc__ is None:\n0182: for base in bases:\n0183: if isinstance(base, SignatureMeta):\n0184: doc = getattr(base, \"__doc__\", \"\")\n0185: if doc != \"\":\n0186: cls.__doc__ = doc\n0187: \n0188: # The more likely case is that the user has just not given us a type.\n0189: # In that case, we should default to the input/output format.\n0190: if cls.__doc__ is None:\n0191: cls.__doc__ = _default_instructions(cls)\n0192: \n0193: # Ensure all fields are declared with InputField or OutputField\n0194: cls._validate_fields()\n0195: \n0196: # Ensure all fields have a prefix\n0197: for name, field in cls.model_fields.items():\n0198: if \"prefix\" not in field.json_schema_extra:\n0199: field.json_schema_extra[\"prefix\"] = infer_prefix(name) + \":\"\n0200: if \"desc\" not in field.json_schema_extra:\n0201: field.json_schema_extra[\"desc\"] = f\"${{{name}}}\"\n0202: \n0203: return cls"}, {"span_id": "s5", "path": "tests/reliability/test_pydantic_models.py", "start_line": 10, "end_line": 44, "excerpt": "0010: @pytest.mark.reliability\n0011: def test_qa_with_pydantic_answer_model():\n0012: class Answer(pydantic.BaseModel):\n0013: value: str\n0014: certainty: float = pydantic.Field(\n0015: description=\"A value between 0 and 1 indicating the model's confidence in the answer.\"\n0016: )\n0017: comments: list[str] = pydantic.Field(\n0018: description=\"At least two comments providing additional details about the answer.\"\n0019: )\n0020: \n0021: class QA(dspy.Signature):\n0022: question: str = dspy.InputField()\n0023: answer: Answer = dspy.OutputField()\n0024: \n0025: program = dspy.Predict(QA)\n0026: question = \"What is the capital of France?\"\n0027: answer = program(question=question).answer\n0028: \n0029: assert_program_output_correct(\n0030: program_input=question,\n0031: program_output=answer.value,\n0032: grading_guidelines=\"The answer should be Paris. Answer should not contain extraneous information.\",\n0033: )\n0034: assert_program_output_correct(\n0035: program_input=question,\n0036: program_output=answer.comments,\n0037: grading_guidelines=(\n0038: \"The comments should be relevant to the answer. They don't need to restate the answer explicitly.\"\n0039: ),\n0040: )\n0041: assert answer.certainty >= 0\n0042: assert answer.certainty <= 1\n0043: assert len(answer.comments) >= 2\n0044: "}]} {"id": "dspy_d6683c54b609", "topic": "signature_schema_and_pydantic_types", "question": "I need an intent extractor that reads the latest user question plus the prior conversation turns, using a `dspy.History` input field. Several output fields are legitimately absent on many turns — e.g. a turn may have a primary intent but no secondary intents, no clarification questions, and no resolved glossary terms — so I want those to come back as real Python `None` (not empty strings, not `\"None\"`, not empty lists).\n\nMy current signature declares each optional output as `dspy.OutputField(default=None)` and I let the model just leave those fields out of its answer when they don't apply, expecting DSPy to fill the skipped fields in as `None`. Instead I'm getting an `AdapterParseError` complaining it \"expected to find output fields\" that I deliberately omitted. I also tried typing them as plain `list[str]` and emitting `null`, but then it blows up with a pydantic validation error.\n\nGive me a complete, runnable program (use `dspy.utils.DummyLM` so it runs offline, with `dspy.JSONAdapter`) defining the signature and a `dspy.History`-based call that reliably yields real `None` for the genuinely-absent fields, including at least one optional field that returns a list of structured (Pydantic) terms when present. Show with assertions that the absent fields are `None` and the structured field parses.", "gold_answer": "```python\nimport dspy\nimport pydantic\nfrom dspy.utils import DummyLM\n\n\nclass Term(pydantic.BaseModel):\n term: str\n meaning: str\n\n\nclass ExtractIntent(dspy.Signature):\n \"\"\"Extract the main intent and any optional follow-up needs from the latest user\n question given the prior conversation turns.\"\"\"\n\n question: str = dspy.InputField()\n history: dspy.History = dspy.InputField()\n primary_intent: str = dspy.OutputField()\n secondary_intents: list[str] | None = dspy.OutputField()\n clarification_needed: list[str] | None = dspy.OutputField()\n unresolved_terms: list[str] | None = dspy.OutputField()\n resolved_terms: list[Term] | None = dspy.OutputField()\n\n\nadapter = dspy.JSONAdapter()\ndspy.configure(\n lm=DummyLM(\n [\n {\n \"primary_intent\": \"reset password\",\n \"secondary_intents\": None,\n \"clarification_needed\": [\"Which account is affected?\"],\n \"unresolved_terms\": None,\n \"resolved_terms\": [{\"term\": \"SSO\", \"meaning\": \"single sign-on\"}],\n }\n ],\n adapter=adapter,\n ),\n adapter=adapter,\n)\n\nhistory = dspy.History(\n messages=[\n {\n \"question\": \"What does SSO mean here?\",\n \"primary_intent\": \"understand SSO\",\n \"secondary_intents\": None,\n \"clarification_needed\": None,\n \"unresolved_terms\": [\"SSO\"],\n \"resolved_terms\": None,\n }\n ]\n)\n\npred = dspy.Predict(ExtractIntent)(\n question=\"I need to reset my work account password.\",\n history=history,\n)\n\nassert pred.secondary_intents is None\nassert pred.unresolved_terms is None\nassert pred.clarification_needed == [\"Which account is affected?\"]\nassert pred.resolved_terms[0].meaning == \"single sign-on\"\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 40, "statement": "Absent outputs are produced by typing EACH optional output field as a union with `None` (e.g. `secondary_intents: list[str] | None` or `Optional[list[str]]`) AND having the LM emit an explicit `null` for those fields, so the adapter validates the explicit null down to a real Python `None`. The solution must NOT use `dspy.OutputField(default=...)` for the optional fields, and must NOT rely on the model OMITTING those keys from its response to represent absence — a declared output field that is missing from the JSON raises a parse error rather than defaulting to `None`, and a non-union (plain `list[str]`) field given `null` fails validation. Uses the union+explicit-null convention, NOT the `default=None`/omitted-key decoy.", "span_ids": ["s5"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "At least one optional output is declared on the SIGNATURE with a structured Pydantic type, specifically a union like `list[Term] | None` (or `Optional[list[Term]]`) where `Term` is a `pydantic.BaseModel`, so the adapter returns that field as a list of `BaseModel` instances when present. It must NOT be typed as a plain `list`/`dict` that is post-validated into Pydantic models by hand after the call.", "span_ids": ["s6"]}, {"claim_id": "c3", "claim_type": "supporting", "weight": 15, "statement": "The history is constructed as `dspy.History(messages=[...])` where each prior-turn entry is a dict keyed by THIS signature's own fields (the prior `question` plus its extracted output fields), NOT a generic `{question, answer}`/`{role, content}` shape and NOT built via `.append(role=..., content=...)`.", "span_ids": ["s1", "s4"]}, {"claim_id": "c4", "claim_type": "core", "weight": 15, "statement": "Prior turns are supplied through a `dspy.History` input field on the signature (`history: dspy.History = dspy.InputField()`) and passed as a `dspy.History` object, not via a plain list-typed or string-typed history field.", "span_ids": ["s1", "s2"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 10, "statement": "Because a `dspy.History` input field is used, the adapter expands the prior turns into alternating user/assistant messages placed before the current request, with the history field stripped from the live request.", "span_ids": ["s2", "s3"]}], "evidence": [{"span_id": "s1", "path": "dspy/adapters/types/history.py", "start_line": 6, "end_line": 20, "excerpt": "0006: class History(pydantic.BaseModel):\n0007: \"\"\"Class representing the conversation history.\n0008: \n0009: The conversation history is a list of messages, each message entity should have keys from the associated signature.\n0010: For example, if you have the following signature:\n0011: \n0012: ```\n0013: class MySignature(dspy.Signature):\n0014: question: str = dspy.InputField()\n0015: history: dspy.History = dspy.InputField()\n0016: answer: str = dspy.OutputField()\n0017: ```\n0018: \n0019: Then the history should be a list of dictionaries with keys \"question\" and \"answer\".\n0020: "}, {"span_id": "s2", "path": "dspy/adapters/base.py", "start_line": 267, "end_line": 289, "excerpt": "0267: inputs_copy = dict(inputs)\n0268: \n0269: # If the signature and inputs have conversation history, we need to format the conversation history and\n0270: # remove the history field from the signature.\n0271: history_field_name = self._get_history_field_name(signature)\n0272: if history_field_name:\n0273: # In order to format the conversation history, we need to remove the history field from the signature.\n0274: signature_without_history = signature.delete(history_field_name)\n0275: conversation_history = self.format_conversation_history(\n0276: signature_without_history,\n0277: history_field_name,\n0278: inputs_copy,\n0279: )\n0280: \n0281: messages = []\n0282: system_message = self.format_system_message(signature)\n0283: messages.append({\"role\": \"system\", \"content\": system_message})\n0284: messages.extend(self.format_demos(signature, demos))\n0285: if history_field_name:\n0286: # Conversation history and current input\n0287: content = self.format_user_message_content(signature_without_history, inputs_copy, main_request=True)\n0288: messages.extend(conversation_history)\n0289: messages.append({\"role\": \"user\", \"content\": content})"}, {"span_id": "s3", "path": "dspy/adapters/base.py", "start_line": 480, "end_line": 521, "excerpt": "0480: def format_conversation_history(\n0481: self,\n0482: signature: type[Signature],\n0483: history_field_name: str,\n0484: inputs: dict[str, Any],\n0485: ) -> list[dict[str, Any]]:\n0486: \"\"\"Format the conversation history.\n0487: \n0488: This method formats the conversation history and the current input as multiturn messages.\n0489: \n0490: Args:\n0491: signature: The DSPy signature for which to format the conversation history.\n0492: history_field_name: The name of the history field in the signature.\n0493: inputs: The input arguments to the DSPy module.\n0494: \n0495: Returns:\n0496: A list of multiturn messages.\n0497: \"\"\"\n0498: conversation_history = inputs[history_field_name].messages if history_field_name in inputs else None\n0499: \n0500: if conversation_history is None:\n0501: return []\n0502: \n0503: messages = []\n0504: for message in conversation_history:\n0505: messages.append(\n0506: {\n0507: \"role\": \"user\",\n0508: \"content\": self.format_user_message_content(signature, message),\n0509: }\n0510: )\n0511: messages.append(\n0512: {\n0513: \"role\": \"assistant\",\n0514: \"content\": self.format_assistant_message_content(signature, message),\n0515: }\n0516: )\n0517: \n0518: # Remove the history field from the inputs\n0519: del inputs[history_field_name]\n0520: \n0521: return messages"}, {"span_id": "s4", "path": "tests/adapters/test_json_adapter.py", "start_line": 515, "end_line": 536, "excerpt": "0515: def test_json_adapter_formats_conversation_history():\n0516: class MySignature(dspy.Signature):\n0517: question: str = dspy.InputField()\n0518: history: dspy.History = dspy.InputField()\n0519: answer: str = dspy.OutputField()\n0520: \n0521: history = dspy.History(\n0522: messages=[\n0523: {\"question\": \"What is the capital of France?\", \"answer\": \"Paris\"},\n0524: {\"question\": \"What is the capital of Germany?\", \"answer\": \"Berlin\"},\n0525: ]\n0526: )\n0527: \n0528: adapter = dspy.JSONAdapter()\n0529: messages = adapter.format(MySignature, [], {\"question\": \"What is the capital of France?\", \"history\": history})\n0530: \n0531: assert len(messages) == 6\n0532: assert messages[1][\"content\"] == \"[[ ## question ## ]]\\nWhat is the capital of France?\"\n0533: assert messages[2][\"content\"] == '{\\n \"answer\": \"Paris\"\\n}'\n0534: assert messages[3][\"content\"] == \"[[ ## question ## ]]\\nWhat is the capital of Germany?\"\n0535: assert messages[4][\"content\"] == '{\\n \"answer\": \"Berlin\"\\n}'\n0536: "}, {"span_id": "s5", "path": "tests/adapters/test_adapter_utils.py", "start_line": 80, "end_line": 95, "excerpt": "0080: def test_parse_value_union():\n0081: # Test Union with None (Optional)\n0082: assert parse_value(\"test\", Optional[str]) == \"test\"\n0083: assert parse_value(\"test\", str | None) == \"test\"\n0084: assert parse_value(\"5\", int | None) == 5\n0085: assert parse_value(None, Optional[str]) is None\n0086: assert parse_value(\"text with [placeholder]\", Optional[str]) == \"text with [placeholder]\"\n0087: assert parse_value(\"text with [placeholder]\", str | None) == \"text with [placeholder]\"\n0088: \n0089: # Test Union fallback to str\n0090: assert parse_value(\"fallback\", Union[int, str, None]) == \"fallback\"\n0091: assert parse_value(5, Union[int, str, None]) == 5\n0092: assert parse_value(\"fallback\", int | str | None) == \"fallback\"\n0093: assert parse_value(5, int | str | None) == 5\n0094: assert parse_value(\"text with [placeholder]\", Union[int, str, None]) == \"text with [placeholder]\"\n0095: "}, {"span_id": "s6", "path": "tests/adapters/test_json_adapter.py", "start_line": 128, "end_line": 143, "excerpt": "0128: def test_json_adapter_on_pydantic_model():\n0129: from litellm.utils import Choices, Message, ModelResponse\n0130: \n0131: class User(pydantic.BaseModel):\n0132: id: int\n0133: name: str\n0134: email: str\n0135: \n0136: class Answer(pydantic.BaseModel):\n0137: analysis: str\n0138: result: str\n0139: \n0140: class TestSignature(dspy.Signature):\n0141: user: User = dspy.InputField(desc=\"The user who asks the question\")\n0142: question: str = dspy.InputField(desc=\"Question the user asks\")\n0143: answer: Answer = dspy.OutputField(desc=\"Answer to this question\")"}]} {"id": "dspy_b03a99c316d5", "topic": "signature_schema_and_pydantic_types", "question": "I'm building a small `dspy.Module` and I prefer inline string signatures over class-based ones. My schema types are Pydantic models: one model I define locally, right where I build the predictor, and another lives as a nested class inside a small `Container` class I use to namespace my schemas (so I reference it in the signature string as `Container.Verdict`). I want one predictor whose input is the local model and a second predictor whose output is the nested `Container.Verdict`, and I need both to run together in a single forward pass.\n\nThe local-type predictor is fine. But the nested one keeps blowing up at construction time with `ValueError: Unknown attribute: Verdict on typing.Container` — and weirdly it still happens even after I switched to passing the nested type in explicitly via `custom_types={'Container': Container}` on that signature. Give me a complete, runnable program (use `DummyLM` so it executes offline, e.g. through a `dspy.JSONAdapter`) where both inline-signature predictors resolve their Pydantic types correctly and run together in one forward pass.", "gold_answer": "```python\nimport dspy\nimport pydantic\nfrom dspy.utils import DummyLM\n\n\nclass Container:\n class Verdict(pydantic.BaseModel):\n label: str\n confidence: float\n\n\nclass InlineTypedModule(dspy.Module):\n def __init__(self):\n super().__init__()\n\n class Query(pydantic.BaseModel):\n text: str\n\n self.Query = Query\n\n # Predictor 1: input type `Query` is defined right here in local scope. With no\n # `custom_types` argument, Signature(...) walks the caller frames and auto-resolves\n # `Query` from this scope.\n self.summarize = dspy.Predict(\n dspy.Signature(\"query: Query -> summary: str\")\n )\n\n # Predictor 2: output type is the nested `Container.Verdict`. Three things are\n # needed and all are required:\n # (a) The base name `Container` collides with `typing.Container`, so frame\n # auto-detection skips it and parsing would resolve the wrong class. We must\n # pass `custom_types` to shadow it.\n # (b) Passing `custom_types` disables auto-detection for THIS signature, so every\n # custom name in the string must be supplied -- here both `Query` and `Container`.\n # (c) We pass an explicit instructions string. If instructions are omitted, the\n # signature string is re-parsed WITHOUT `custom_types` to derive a default\n # prompt, which re-triggers the `typing.Container` collision.\n self.classify = dspy.Predict(\n dspy.Signature(\n \"query: Query -> verdict: Container.Verdict\",\n \"Classify the query and return a verdict.\",\n custom_types={\"Query\": Query, \"Container\": Container},\n )\n )\n\n def forward(self, text: str):\n query = self.Query(text=text)\n summary = self.summarize(query=query).summary\n verdict = self.classify(query=query).verdict\n return dspy.Prediction(summary=summary, verdict=verdict)\n\n\nadapter = dspy.JSONAdapter()\ndspy.configure(\n lm=DummyLM(\n [\n {\"summary\": \"Typed inline signatures work.\"},\n {\"verdict\": {\"label\": \"structured\", \"confidence\": 0.93}},\n ],\n adapter=adapter,\n ),\n adapter=adapter,\n)\n\nmodule = InlineTypedModule()\npred = module(text=\"Use inline signatures with custom models.\")\n\nassert pred.summary == \"Typed inline signatures work.\"\nassert pred.verdict.label == \"structured\"\nassert pred.verdict.confidence == 0.93\n# Nested output type resolved to the user's class, not typing.Container.\nassert module.classify.signature.output_fields[\"verdict\"].annotation is Container.Verdict\n# Local input type resolved via frame auto-detection (no custom_types).\nassert module.summarize.signature.input_fields[\"query\"].annotation is module.Query\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 50, "statement": "For the second inline signature whose output is the nested `Container.Verdict`, the type is made to resolve to the user's class by passing a `custom_types` mapping that (i) includes the container name `Container` (to shadow the same-named member of the `typing` module), AND (ii) includes EVERY other custom name used in the signature string (e.g. the input model `Query`), AND (iii) is accompanied by an EXPLICIT instructions string argument. It uses the snapshot's actual convention of `custom_types` + explicit instructions, and does NOT rely on bare dotted-name frame auto-resolution and does NOT pass `custom_types` without an instructions string.", "span_ids": ["s3", "s4", "s7"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "The first predictor uses an inline string signature whose input is a Pydantic model defined in local scope and lets DSPy auto-resolve that local type by frame introspection — i.e. it constructs that signature with NO `custom_types` argument (the snapshot's recommended local-type pattern), NOT by passing `custom_types` for this predictor.", "span_ids": ["s1", "s2"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "Within a single `forward` pass the module constructs the typed input object once, calls BOTH predictors, and returns a `dspy.Prediction(...)` carrying both outputs — NOT a plain dict and NOT only the second predictor's result.", "span_ids": ["s5", "s6"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "Both predictors are built from INLINE string signatures (not class-based `dspy.Signature` subclasses), and the program is wired to run offline via `DummyLM` through a `dspy.JSONAdapter` (DummyLM constructed with response dicts and the adapter, configured via `dspy.configure`), with at least one predictor consuming a Pydantic input object and one producing a structured Pydantic output.", "span_ids": ["s6", "s7"]}], "evidence": [{"span_id": "s1", "path": "dspy/signatures/signature.py", "start_line": 42, "end_line": 50, "excerpt": "0042: def __call__(cls, *args, **kwargs):\n0043: if cls is Signature:\n0044: # We don't create an actual Signature instance, instead, we create a new Signature class.\n0045: custom_types = kwargs.pop(\"custom_types\", None)\n0046: \n0047: if custom_types is None and args and isinstance(args[0], str):\n0048: custom_types = cls._detect_custom_types_from_caller(args[0])\n0049: \n0050: return make_signature(*args, custom_types=custom_types, **kwargs)"}, {"span_id": "s2", "path": "tests/signatures/test_custom_types.py", "start_line": 66, "end_line": 75, "excerpt": "0066: def test_recommended_patterns():\n0067: \"\"\"Test recommended patterns for working with custom types in signatures.\"\"\"\n0068: \n0069: # PATTERN 1: Local type with auto-resolution\n0070: class LocalType(pydantic.BaseModel):\n0071: value: str\n0072: \n0073: sig1 = Signature(\"input: str -> output: LocalType\")\n0074: assert sig1.output_fields[\"output\"].annotation == LocalType\n0075: "}, {"span_id": "s3", "path": "dspy/signatures/signature.py", "start_line": 521, "end_line": 567, "excerpt": "0521: def make_signature(\n0522: signature: str | dict[str, tuple[type, FieldInfo]],\n0523: instructions: str | None = None,\n0524: signature_name: str = \"StringSignature\",\n0525: custom_types: dict[str, type] | None = None,\n0526: ) -> type[Signature]:\n0527: \"\"\"Create a new Signature subclass with the specified fields and instructions.\n0528: \n0529: Args:\n0530: signature: Either a string in the format \"input1, input2 -> output1, output2\"\n0531: or a dictionary mapping field names to tuples of (type, FieldInfo).\n0532: instructions: Optional string containing instructions/prompt for the signature.\n0533: If not provided, defaults to a basic description of inputs and outputs.\n0534: signature_name: Optional string to name the generated Signature subclass.\n0535: Defaults to \"StringSignature\".\n0536: custom_types: Optional dictionary mapping type names to their actual type objects.\n0537: Useful for resolving custom types that aren't built-ins or in the typing module.\n0538: \n0539: Returns:\n0540: A new signature class with the specified fields and instructions.\n0541: \n0542: Examples:\n0543: \n0544: ```\n0545: # Using string format\n0546: sig1 = make_signature(\"question, context -> answer\")\n0547: \n0548: # Using dictionary format\n0549: sig2 = make_signature({\n0550: \"question\": (str, InputField()),\n0551: \"answer\": (str, OutputField())\n0552: })\n0553: \n0554: # Using custom types\n0555: class MyType:\n0556: pass\n0557: \n0558: sig3 = make_signature(\"input: MyType -> output\", custom_types={\"MyType\": MyType})\n0559: ```\n0560: \"\"\"\n0561: # Prepare the names dictionary for type resolution\n0562: names = None\n0563: if custom_types:\n0564: names = dict(typing.__dict__)\n0565: names.update(custom_types)\n0566: \n0567: fields = _parse_signature(signature, names) if isinstance(signature, str) else signature"}, {"span_id": "s4", "path": "tests/signatures/test_custom_types.py", "start_line": 26, "end_line": 44, "excerpt": "0026: def test_type_alias_for_nested_types():\n0027: \"\"\"Test using type aliases for nested types.\"\"\"\n0028: class Container:\n0029: class NestedType(pydantic.BaseModel):\n0030: value: str\n0031: \n0032: NestedType = Container.NestedType\n0033: alias_sig = Signature(\"input: str -> output: NestedType\")\n0034: assert alias_sig.output_fields[\"output\"].annotation == Container.NestedType\n0035: \n0036: class Container2:\n0037: class Query(pydantic.BaseModel):\n0038: text: str\n0039: class Score(pydantic.BaseModel):\n0040: score: float\n0041: \n0042: signature = dspy.Signature(\"query: Container2.Query -> score: Container2.Score\")\n0043: assert signature.output_fields[\"score\"].annotation == Container2.Score\n0044: "}, {"span_id": "s5", "path": "tests/signatures/test_custom_types.py", "start_line": 98, "end_line": 109, "excerpt": "0098: def test_module_type_resolution():\n0099: class TestModule(dspy.Module):\n0100: def __init__(self):\n0101: super().__init__()\n0102: self.predict = dspy.Predict(\"input: str -> output: OuterContainer.InnerType\")\n0103: \n0104: def predict(self, input: str) -> str:\n0105: return input\n0106: \n0107: module = TestModule()\n0108: sig = module.predict.signature\n0109: assert sig.output_fields[\"output\"].annotation == OuterContainer.InnerType"}, {"span_id": "s6", "path": "tests/signatures/test_signature.py", "start_line": 414, "end_line": 430, "excerpt": "0414: def test_basic_custom_type():\n0415: class CustomType(pydantic.BaseModel):\n0416: value: str\n0417: \n0418: test_signature = dspy.Signature(\n0419: \"input: CustomType -> output: str\",\n0420: custom_types={\"CustomType\": CustomType}\n0421: )\n0422: \n0423: assert test_signature.input_fields[\"input\"].annotation == CustomType\n0424: \n0425: lm = DummyLM([{\"output\": \"processed\"}])\n0426: dspy.configure(lm=lm)\n0427: \n0428: custom_obj = CustomType(value=\"test\")\n0429: pred = dspy.Predict(test_signature)(input=custom_obj)\n0430: assert pred.output == \"processed\""}, {"span_id": "s7", "path": "dspy/signatures/signature.py", "start_line": 633, "end_line": 727, "excerpt": "0633: def _parse_field_string(field_string: str, names=None) -> Iterator[tuple[str, type, bool]]:\n0634: \"\"\"Extract the field name and type from field string in the string-based Signature.\n0635: \n0636: It takes a string like \"x: int, y: str\" and returns a dictionary mapping field names to their types.\n0637: For example, \"x: int, y: str\" -> [(\"x\", int), (\"y\", str)]. This function utilizes the Python AST to parse the\n0638: fields and types.\n0639: \"\"\"\n0640: \n0641: args = ast.parse(f\"def f({field_string}): pass\").body[0].args.args\n0642: field_names: list[str] = [arg.arg for arg in args]\n0643: types_list: list[type] = [str if arg.annotation is None else _parse_type_node(arg.annotation, names) for arg in args]\n0644: is_type_undefined: list[bool] = [True if arg.annotation is None else False for arg in args]\n0645: return zip(field_names, types_list, is_type_undefined, strict=False)\n0646: \n0647: \n0648: def _parse_type_node(node, names=None) -> Any:\n0649: \"\"\"Recursively parse an AST node representing a type annotation.\n0650: \n0651: This function converts Python's Abstract Syntax Tree (AST) nodes into actual Python types.\n0652: It's used to parse type annotations in signature strings like \"x: list[int] -> y: str\".\n0653: \n0654: Examples:\n0655: - For \"x: int\", the AST node represents 'int' and returns the int type\n0656: - For \"x: list[str]\", it processes a subscript node to return typing.list[str]\n0657: - For \"x: Optional[int]\", it handles the Union type to return Optional[int]\n0658: - For \"x: MyModule.CustomType\", it processes attribute access to return the actual type\n0659: \n0660: Args:\n0661: node: An AST node from Python's ast module, representing a type annotation.\n0662: Common node types include:\n0663: - ast.Name: Simple types like 'int', 'str'\n0664: - ast.Attribute: Nested types like 'typing.List'\n0665: - ast.Subscript: Generic types like 'list[int]'\n0666: names: Optional dictionary mapping type names to their actual type objects.\n0667: Defaults to Python's typing module contents plus NoneType.\n0668: \n0669: Returns:\n0670: The actual Python type represented by the AST node.\n0671: \n0672: Raises:\n0673: ValueError: If the AST node represents an unknown or invalid type annotation.\n0674: \"\"\"\n0675: \n0676: if names is None:\n0677: names = dict(typing.__dict__)\n0678: names[\"NoneType\"] = type(None)\n0679: \n0680: def resolve_name(type_name: str):\n0681: # Check if it's a built-in known type or in the provided names\n0682: if type_name in names:\n0683: return names[type_name]\n0684: # Common built-in types\n0685: builtin_types = [int, str, float, bool, list, tuple, dict, set, frozenset, complex, bytes, bytearray]\n0686: \n0687: # Check if it matches any known built-in type by name\n0688: for t in builtin_types:\n0689: if t.__name__ == type_name:\n0690: return t\n0691: \n0692: # Attempt to import a module with this name dynamically\n0693: # This allows handling of module-based annotations like `dspy.Image`.\n0694: try:\n0695: mod = importlib.import_module(type_name)\n0696: names[type_name] = mod\n0697: return mod\n0698: except ImportError:\n0699: pass\n0700: \n0701: # If we don't know the type or module, raise an error\n0702: raise ValueError(f\"Unknown name: {type_name}\")\n0703: \n0704: if isinstance(node, ast.Module):\n0705: if len(node.body) != 1:\n0706: raise ValueError(f\"Code is not syntactically valid: {ast.dump(node)}\")\n0707: return _parse_type_node(node.body[0], names)\n0708: \n0709: if isinstance(node, ast.Expr):\n0710: return _parse_type_node(node.value, names)\n0711: \n0712: if isinstance(node, ast.Name):\n0713: return resolve_name(node.id)\n0714: \n0715: if isinstance(node, ast.Attribute):\n0716: base = _parse_type_node(node.value, names)\n0717: attr_name = node.attr\n0718: \n0719: if hasattr(base, attr_name):\n0720: return getattr(base, attr_name)\n0721: \n0722: if isinstance(node.value, ast.Name):\n0723: full_name = f\"{node.value.id}.{attr_name}\"\n0724: if full_name in names:\n0725: return names[full_name]\n0726: \n0727: raise ValueError(f\"Unknown attribute: {attr_name} on {base}\")"}]} {"id": "dspy_ad7223e585ba", "topic": "signature_schema_and_pydantic_types", "question": "I keep changing a typed signature and want a regression check that proves the contract actually reaches the model. The signature has output fields with length and numeric limits (think `min_length`/`max_length` on a short string field and `ge`/`le` on a 0–1 float), a class docstring, and a `desc` on every field. I want a runnable check that proves those three things — the docstring, the per-field descriptions, and those numeric/length limits — actually show up in BOTH the default chat formatting AND when I run the signature through `dspy.JSONAdapter` for structured output.\n\nMy current check builds the structured-output response model the JSON adapter hands the LM as `response_format` and dumps its JSON schema, then asserts the limits come through as `minimum`/`maximum`/`minLength`/`maxLength` and that the docstring and field `desc` strings are in there too. The chat side I was going to check the same way off the response schema. The problem: against the structured-output schema almost none of those assertions pass — the limits and the description text just aren't in it — so my regression test is useless for catching when I break a constraint or a description.\n\nWrite the helper that actually pins this down: a self-contained Python program that constructs such a signature and asserts the docstring, the field descriptions, and the human-readable form of the numeric/length limits are present for both the chat layout and the JSON/structured-output layout, plus the input-field markers and the per-layout output reminders. It should pass on the current codebase.", "gold_answer": "```python\nimport dspy\nimport json\n\n\ndef check_typed_signature_prompt_surface():\n class ScoreCard(dspy.Signature):\n \"\"\"Score a support reply for policy compliance.\"\"\"\n\n ticket_text: str = dspy.InputField(desc=\"Original support ticket body.\")\n allowed_labels: list[str] = dspy.InputField(desc=\"Valid policy tags to use.\")\n verdict: str = dspy.OutputField(min_length=3, max_length=12, desc=\"Short compliance decision.\")\n confidence: float = dspy.OutputField(ge=0, le=1, desc=\"Confidence from 0 to 1.\")\n tags: list[str] = dspy.OutputField(desc=\"Relevant policy tags.\")\n\n chat = dspy.ChatAdapter()\n js = dspy.JSONAdapter()\n\n example_inputs = {\n \"ticket_text\": \"Customer asked for a refund outside policy.\",\n \"allowed_labels\": [\"refund\", \"abuse\"],\n }\n\n chat_system = chat.format_system_message(ScoreCard)\n json_system = js.format_system_message(ScoreCard)\n chat_user = chat.format_user_message_content(ScoreCard, example_inputs, main_request=True)\n json_user = js.format_user_message_content(ScoreCard, example_inputs, main_request=True)\n\n assert \"Score a support reply for policy compliance.\" in chat_system\n assert \"Score a support reply for policy compliance.\" in json_system\n\n assert \"Original support ticket body.\" in chat_system\n assert \"Short compliance decision.\" in chat_system\n assert \"Valid policy tags to use.\" in json_system\n\n assert \"Constraints: minimum length: 3, maximum length: 12\" in chat_system\n assert \"Constraints: greater than or equal to: 0, less than or equal to: 1\" in chat_system\n assert \"Constraints: minimum length: 3, maximum length: 12\" in json_system\n assert \"Constraints: greater than or equal to: 0, less than or equal to: 1\" in json_system\n\n assert \"[[ ## ticket_text ## ]]\" in chat_user\n assert \"Respond with the corresponding output fields\" in chat_user\n\n assert \"[[ ## ticket_text ## ]]\" in json_user\n assert \"Respond with a JSON object in the following order of fields\" in json_user\n assert \"must adhere to the JSON schema\" in json_system\n\n from dspy.adapters.json_adapter import _get_structured_outputs_response_format\n\n structured_schema = json.dumps(_get_structured_outputs_response_format(ScoreCard).model_json_schema())\n assert \"minimum\" not in structured_schema\n assert \"maxLength\" not in structured_schema\n assert \"minLength\" not in structured_schema\n assert \"Short compliance decision.\" not in structured_schema\n assert \"Score a support reply for policy compliance.\" not in structured_schema\n\n return True\n\n\nif __name__ == \"__main__\":\n assert check_typed_signature_prompt_surface()\n print(\"ENHANCED GOLD PASSES\")\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 45, "statement": "ANTI-DECOY GATE. To prove the docstring and per-field descriptions reach the model, the answer's code INSPECTS the human-readable SYSTEM-MESSAGE TEXT produced statically by the adapters -- it calls `ChatAdapter().format_system_message(sig)` (or `.format()`/`.format_field_description`) AND `JSONAdapter().format_system_message(sig)` and checks the class docstring text (= `sig.instructions`) and each `InputField`/`OutputField` `desc` string is contained in BOTH of those system-message strings. It must NOT instead read a JSON SCHEMA for these -- i.e. it must NOT satisfy the docstring/`desc` requirement by dumping `sig.model_json_schema()` (the signature's own pydantic schema, where the docstring lands in `description` and `desc` survives in `json_schema_extra`) or by reading the JSONAdapter `response_format` schema. An answer whose docstring/description checks target a `.model_json_schema()` / `response_format` schema object rather than the `format_system_message` text fails this claim, even if those assertions would have passed.", "span_ids": ["s1", "s2", "s5", "s6"]}, {"claim_id": "c2", "claim_type": "core", "weight": 25, "statement": "ANTI-DECOY NEGATIVE GATE (the crux the question's broken approach gets wrong). The answer builds the SAME structured-output response model the JSONAdapter hands the LM -- `_get_structured_outputs_response_format(sig)` from `dspy.adapters.json_adapter` (or the `response_format`/schema produced by JSONAdapter's structured-output path) -- and its code asserts that the Pydantic limits (`minimum`/`maximum`/`minLength`/`maxLength`), the docstring, and the field `desc` strings are ABSENT from that schema (because it is rebuilt from output annotations with `json_schema_extra` stripped). An answer that asserts those limits/docstring/descriptions are PRESENT in that structured-output schema, or that only checks property names/base types without the absence assertions, fails this claim.", "span_ids": ["s6", "s8"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "For the numeric/length limits specifically, the answer's code checks the TRANSLATED human-readable constraint TEXT inside the system messages -- the literal `minimum length: ` / `maximum length: ` (from `min_length`/`max_length`) and `greater than or equal to: ` / `less than or equal to: ` (from `ge`/`le`) substrings, as emitted via `json_schema_extra['constraints']` by `get_field_description_string` -- and confirms that text appears in BOTH the chat and JSON system messages. Merely confirming `minLength`/`maximum` keys exist in some JSON schema, or asserting only loose paraphrases (e.g. \"between 0 and 1\", \"1-40 character\") that the snapshot does not actually emit, does not satisfy this claim.", "span_ids": ["s4", "s5"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "The answer also INSPECTS the per-layout USER-message/reminder text: for the chat layout it builds the user content via `ChatAdapter().format_user_message_content(sig, inputs, main_request=True)` and checks both the input-section marker form `[[ ## field_name ## ]]` and the chat main-request reminder beginning `Respond with the corresponding output fields`; and it checks the JSON layout's reminder `Respond with a JSON object in the following order of fields`. Loose regexes over an aggregated prompt blob (not the specific user-message string) that miss the exact `[[ ## field ## ]]` markers / exact reminder wording do not satisfy this claim.", "span_ids": ["s7", "s6"]}], "evidence": [{"span_id": "s1", "path": "dspy/adapters/base.py", "start_line": 298, "end_line": 309, "excerpt": "0298: def format_system_message(self, signature: type[Signature]) -> str:\n0299: \"\"\"Format the system message for the LM call.\n0300: \n0301: \n0302: Args:\n0303: signature: The DSPy signature for which to format the system message.\n0304: \"\"\"\n0305: return (\n0306: f\"{self.format_field_description(signature)}\\n\"\n0307: f\"{self.format_field_structure(signature)}\\n\"\n0308: f\"{self.format_task_description(signature)}\"\n0309: )"}, {"span_id": "s2", "path": "dspy/adapters/chat_adapter.py", "start_line": 139, "end_line": 143, "excerpt": "0139: def format_task_description(self, signature: type[Signature]) -> str:\n0140: instructions = textwrap.dedent(signature.instructions)\n0141: objective = (\"\\n\" + \" \" * 8).join([\"\"] + instructions.splitlines())\n0142: return f\"In adhering to this structure, your objective is: {objective}\"\n0143: "}, {"span_id": "s3", "path": "dspy/adapters/json_adapter.py", "start_line": 10, "end_line": 10, "excerpt": "0010: from dspy.adapters.chat_adapter import ChatAdapter, FieldInfoWithName"}, {"span_id": "s4", "path": "dspy/signatures/field.py", "start_line": 39, "end_line": 58, "excerpt": "0039: def move_kwargs(**kwargs):\n0040: # Pydantic doesn't allow arbitrary arguments to be given to fields,\n0041: # but asks that\n0042: # > any extra data you want to add to the JSON schema should be passed\n0043: # > as a dictionary to the json_schema_extra keyword argument.\n0044: # See: https://docs.pydantic.dev/2.6/migration/#changes-to-pydanticfield\n0045: pydantic_kwargs = {}\n0046: json_schema_extra = {}\n0047: for k, v in kwargs.items():\n0048: if k in DSPY_FIELD_ARG_NAMES:\n0049: json_schema_extra[k] = v\n0050: else:\n0051: pydantic_kwargs[k] = v\n0052: # Also copy over the pydantic \"description\" if no dspy \"desc\" is given.\n0053: if \"description\" in kwargs and \"desc\" not in json_schema_extra:\n0054: json_schema_extra[\"desc\"] = kwargs[\"description\"]\n0055: constraints = _translate_pydantic_field_constraints(**kwargs)\n0056: if constraints:\n0057: json_schema_extra[\"constraints\"] = constraints\n0058: pydantic_kwargs[\"json_schema_extra\"] = json_schema_extra"}, {"span_id": "s5", "path": "dspy/adapters/chat_adapter.py", "start_line": 111, "end_line": 115, "excerpt": "0111: def format_field_description(self, signature: type[Signature]) -> str:\n0112: return (\n0113: f\"Your input fields are:\\n{get_field_description_string(signature.input_fields)}\\n\"\n0114: f\"Your output fields are:\\n{get_field_description_string(signature.output_fields)}\"\n0115: )"}, {"span_id": "s6", "path": "dspy/adapters/json_adapter.py", "start_line": 104, "end_line": 134, "excerpt": "0104: def format_field_structure(self, signature: type[Signature]) -> str:\n0105: parts = []\n0106: parts.append(\"All interactions will be structured in the following way, with the appropriate values filled in.\")\n0107: \n0108: def format_signature_fields_for_instructions(fields: dict[str, FieldInfo], role: str):\n0109: return self.format_field_with_value(\n0110: fields_with_values={\n0111: FieldInfoWithName(name=field_name, info=field_info): translate_field_type(field_name, field_info)\n0112: for field_name, field_info in fields.items()\n0113: },\n0114: role=role,\n0115: )\n0116: \n0117: parts.append(\"Inputs will have the following structure:\")\n0118: parts.append(format_signature_fields_for_instructions(signature.input_fields, role=\"user\"))\n0119: parts.append(\"Outputs will be a JSON object with the following fields.\")\n0120: parts.append(format_signature_fields_for_instructions(signature.output_fields, role=\"assistant\"))\n0121: return \"\\n\\n\".join(parts).strip()\n0122: \n0123: def user_message_output_requirements(self, signature: type[Signature]) -> str:\n0124: def type_info(v):\n0125: return (\n0126: f\" (must be formatted as a valid Python {get_annotation_name(v.annotation)})\"\n0127: if v.annotation is not str\n0128: else \"\"\n0129: )\n0130: \n0131: message = \"Respond with a JSON object in the following order of fields: \"\n0132: message += \", then \".join(f\"`{f}`{type_info(v)}\" for f, v in signature.output_fields.items())\n0133: message += \".\"\n0134: return message"}, {"span_id": "s7", "path": "dspy/adapters/chat_adapter.py", "start_line": 144, "end_line": 194, "excerpt": "0144: def format_user_message_content(\n0145: self,\n0146: signature: type[Signature],\n0147: inputs: dict[str, Any],\n0148: prefix: str = \"\",\n0149: suffix: str = \"\",\n0150: main_request: bool = False,\n0151: ) -> str:\n0152: messages = [prefix]\n0153: for k, v in signature.input_fields.items():\n0154: if k in inputs:\n0155: value = inputs.get(k)\n0156: formatted_field_value = format_field_value(field_info=v, value=value)\n0157: messages.append(f\"[[ ## {k} ## ]]\\n{formatted_field_value}\")\n0158: \n0159: if main_request:\n0160: output_requirements = self.user_message_output_requirements(signature)\n0161: if output_requirements is not None:\n0162: messages.append(output_requirements)\n0163: \n0164: messages.append(suffix)\n0165: return \"\\n\\n\".join(messages).strip()\n0166: \n0167: def user_message_output_requirements(self, signature: type[Signature]) -> str:\n0168: \"\"\"Returns a simplified format reminder for the language model.\n0169: \n0170: In chat-based interactions, language models may lose track of the required output format\n0171: as the conversation context grows longer. This method generates a concise reminder of\n0172: the expected output structure that can be included in user messages.\n0173: \n0174: Args:\n0175: signature (Type[Signature]): The DSPy signature defining the expected input/output fields.\n0176: \n0177: Returns:\n0178: str: A simplified description of the required output format.\n0179: \n0180: Note:\n0181: This is a more lightweight version of `format_field_structure` specifically designed\n0182: for inline reminders within chat messages.\n0183: \"\"\"\n0184: \n0185: def type_info(v):\n0186: if v.annotation is not str:\n0187: return f\" (must be formatted as a valid Python {get_annotation_name(v.annotation)})\"\n0188: else:\n0189: return \"\"\n0190: \n0191: message = \"Respond with the corresponding output fields, starting with the field \"\n0192: message += \", then \".join(f\"`[[ ## {f} ## ]]`{type_info(v)}\" for f, v in signature.output_fields.items())\n0193: message += \", and then ending with the marker for `[[ ## completed ## ]]`.\"\n0194: return message"}, {"span_id": "s8", "path": "dspy/adapters/json_adapter.py", "start_line": 212, "end_line": 289, "excerpt": "0212: def _get_structured_outputs_response_format(\n0213: signature: SignatureMeta,\n0214: use_native_function_calling: bool = True,\n0215: ) -> type[pydantic.BaseModel]:\n0216: \"\"\"\n0217: Builds a Pydantic model from a DSPy signature's output_fields and ensures the generated JSON schema\n0218: is compatible with OpenAI Structured Outputs (all objects have a \"required\" key listing every property,\n0219: and additionalProperties is always false).\n0220: \n0221: IMPORTANT: If any field's annotation is an open-ended mapping (e.g. dict[str, Any]), then a structured\n0222: schema cannot be generated since all properties must be explicitly declared. In that case, an exception\n0223: is raised so that the caller can fall back to using a plain \"json_object\" response_format.\n0224: \"\"\"\n0225: # Although we've already performed an early check, we keep this here as a final guard.\n0226: for name, field in signature.output_fields.items():\n0227: annotation = field.annotation\n0228: if get_origin(annotation) is dict:\n0229: raise ValueError(\n0230: f\"Field '{name}' has an open-ended mapping type which is not supported by Structured Outputs.\"\n0231: )\n0232: \n0233: fields = {}\n0234: for name, field in signature.output_fields.items():\n0235: annotation = field.annotation\n0236: if use_native_function_calling and annotation == ToolCalls:\n0237: # Skip ToolCalls field if native function calling is enabled.\n0238: continue\n0239: default = field.default if hasattr(field, \"default\") else ...\n0240: fields[name] = (annotation, default)\n0241: \n0242: # Build the model with extra fields forbidden.\n0243: pydantic_model = pydantic.create_model(\n0244: \"DSPyProgramOutputs\",\n0245: __config__=pydantic.ConfigDict(extra=\"forbid\"),\n0246: **fields,\n0247: )\n0248: \n0249: # Generate the initial schema.\n0250: schema = pydantic_model.model_json_schema()\n0251: \n0252: # Remove any DSPy-specific metadata.\n0253: for prop in schema.get(\"properties\", {}).values():\n0254: prop.pop(\"json_schema_extra\", None)\n0255: \n0256: def enforce_required(schema_part: dict):\n0257: \"\"\"\n0258: Recursively ensure that:\n0259: - for any object schema, a \"required\" key is added with all property names (or [] if no properties)\n0260: - additionalProperties is set to False regardless of the previous value.\n0261: - the same enforcement is run for nested arrays and definitions.\n0262: \"\"\"\n0263: if schema_part.get(\"type\") == \"object\":\n0264: props = schema_part.get(\"properties\")\n0265: if props is not None:\n0266: # For objects with explicitly declared properties:\n0267: schema_part[\"required\"] = list(props.keys())\n0268: schema_part[\"additionalProperties\"] = False\n0269: for sub_schema in props.values():\n0270: if isinstance(sub_schema, dict):\n0271: enforce_required(sub_schema)\n0272: else:\n0273: # For objects with no properties (should not happen normally but a fallback).\n0274: schema_part[\"properties\"] = {}\n0275: schema_part[\"required\"] = []\n0276: schema_part[\"additionalProperties\"] = False\n0277: if schema_part.get(\"type\") == \"array\" and isinstance(schema_part.get(\"items\"), dict):\n0278: enforce_required(schema_part[\"items\"])\n0279: # Also enforce in any nested definitions / $defs.\n0280: for key in (\"$defs\", \"definitions\"):\n0281: if key in schema_part:\n0282: for def_schema in schema_part[key].values():\n0283: enforce_required(def_schema)\n0284: \n0285: enforce_required(schema)\n0286: \n0287: # Override the model's JSON schema generation to return our precomputed schema.\n0288: pydantic_model.model_json_schema = lambda *args, **kwargs: schema\n0289: "}]} {"id": "dspy_2980c79329e9", "topic": "evaluation_metrics_and_custom_eval", "question": "I'm stress-testing a `dspy.Module` over a ~500-example devset where a handful of examples reliably throw exceptions (bad inputs, occasional tool timeouts). I want it to run in parallel, give failed examples a fallback score instead of crashing, compute an overall score, and hand me back the rows that failed so I can inspect them.\n\nI'm already passing `failure_score=0.0` to `Evaluate` and bumping `num_threads` up for speed, but on the full flaky devset the whole evaluation still dies partway through and I lose every result — it never returns. When I tried capturing the bad ones with `program.batch(my_examples, return_failed_examples=True)` instead, it ran but just gave me raw outputs with no scores at all. Lowering `num_threads` didn't help either.\n\nWrite a runnable Python program (use `dspy.utils.dummies.DummyLM` so it runs offline, and a tiny module that raises on certain inputs to simulate the failures) that actually survives a flaky devset, assigns the fallback score to the failures, prints the overall percentage, and collects the failed rows for inspection. Explain why my current setup aborts and what the real fix is.", "gold_answer": "```python\nimport dspy\nfrom dspy.evaluate import Evaluate\nfrom dspy.utils.dummies import DummyLM\n\n\nclass FlakyQA(dspy.Module):\n def __init__(self):\n super().__init__()\n self.qa = dspy.Predict('question -> answer')\n\n def forward(self, question):\n if 'explode' in question:\n raise RuntimeError('synthetic failure')\n return self.qa(question=question)\n\n\ndef exact_metric(example, pred, trace=None):\n return float(example.answer == getattr(pred, 'answer', None))\n\n\ndevset = [\n dspy.Example(question='2+2?', answer='4').with_inputs('question'),\n dspy.Example(question='explode please', answer='n/a').with_inputs('question'),\n dspy.Example(question='3+3?', answer='6').with_inputs('question'),\n]\n\n\ndspy.configure(\n lm=DummyLM(\n {\n '2+2?': {'answer': '4'},\n '3+3?': {'answer': '6'},\n }\n )\n)\n\n\nevaluator = Evaluate(\n devset=devset,\n metric=exact_metric,\n num_threads=4,\n max_errors=len(devset),\n failure_score=0.0,\n display_progress=False,\n)\n\nresult = evaluator(FlakyQA())\n\nfailed_rows = [\n {'question': example.question, 'prediction': prediction.toDict(), 'score': score}\n for example, prediction, score in result.results\n if not prediction.toDict()\n]\n\nprint(\n {\n 'overall_percent': result.score,\n 'num_examples': len(result.results),\n 'num_failures': len(failed_rows),\n 'failed_rows': failed_rows,\n }\n)\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 45, "statement": "Correctly attributes the abort to the executor's error ceiling and applies the matching fix: explains that the run dies because each failing example increments an error counter and, once the failure count reaches `max_errors` (default 10), the parallel executor sets a cancel flag and RAISES at the end so nothing is returned (the threshold is `>=`), and the real fix is to RAISE `max_errors` strictly above the number of failures to tolerate (e.g. `max_errors=len(devset)`) while still using `Evaluate`. This claim is NOT satisfied if the answer instead says the cure is setting `failure_score`, or switching to `program.batch`/`return_failed_examples`/`return_exceptions`, or abandoning `Evaluate` for a hand-rolled try/except loop, or attributes the abort to vaguely 'an exception escaping Evaluate's internal/threaded error handling' without naming the `max_errors` ceiling. Identifying the ceiling mechanism but then prescribing a bypass (custom executor, batch, or merely raising failure_score) does NOT satisfy it — both the diagnosis (error count vs `max_errors`) and the fix (raise `max_errors`) must be present, and the code must actually pass a `max_errors` larger than the failure count to `Evaluate`.", "span_ids": ["s1", "s3"]}, {"claim_id": "c2", "claim_type": "core", "weight": 25, "statement": "Performs the evaluation with the metric-applying `Evaluate` evaluator itself — constructs `Evaluate(devset=..., metric=..., num_threads=<>1, ...)` and CALLS it on the program instance to obtain an `EvaluationResult` carrying an overall percentage score and per-example results. It does NOT replace `Evaluate` with a custom parallel loop (e.g. a hand-rolled `concurrent.futures.ThreadPoolExecutor` that catches exceptions per example and aggregates scores manually), and does NOT route scoring through `program.batch(...)` or `dspy.Parallel(...)` (which run the module but never apply the metric). Building one's own evaluator that happens to produce a percentage does not satisfy this — the snapshot's `Evaluate(...)(program)` must be the thing that runs the devset and applies the metric.", "span_ids": ["s1", "s2"]}, {"claim_id": "c3", "claim_type": "core", "weight": 15, "statement": "Passes `failure_score` (the desired fallback value, e.g. `0.0`) to `Evaluate`, and treats it correctly per this snapshot: once the run is kept alive (via a large enough `max_errors`), each failed example is replaced inside `Evaluate` with an EMPTY `dspy.Prediction()` paired with that fallback score, and the answer notes (or its design makes clear) that `failure_score` alone does NOT keep the run alive / prevent the abort. Merely defining a local `failure_score` variable inside a hand-rolled scorer, or describing `failure_score` as the mechanism that survives the flaky devset, does not satisfy this.", "span_ids": ["s1", "s2"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "Inspects per-example outcomes by reading the `results` attribute of the returned `EvaluationResult`, which is a list of `(example, prediction, score)` tuples covering every devset item in order. Manually re-looping over the devset and re-running the program/metric to reconstruct per-example outcomes, instead of reading `result.results`, does not satisfy this.", "span_ids": ["s2"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 5, "statement": "Recovers the failed rows by filtering `result.results` for the empty predictions that `Evaluate` substituted for failures (e.g. checking that `prediction.toDict()` is empty / the prediction has no fields), and collects the original example fields together with that prediction and its fallback score for inspection.", "span_ids": ["s2"]}], "evidence": [{"span_id": "s1", "path": "dspy/evaluate/evaluate.py", "start_line": 71, "end_line": 82, "excerpt": "0071: def __init__(\n0072: self,\n0073: *,\n0074: devset: list[\"dspy.Example\"],\n0075: metric: Callable | None = None,\n0076: num_threads: int | None = None,\n0077: display_progress: bool = False,\n0078: display_table: bool | int = False,\n0079: max_errors: int | None = None,\n0080: provide_traceback: bool | None = None,\n0081: failure_score: float = 0.0,\n0082: save_as_csv: str | None = None,"}, {"span_id": "s2", "path": "dspy/evaluate/evaluate.py", "start_line": 116, "end_line": 179, "excerpt": "0116: @with_callbacks\n0117: def __call__(\n0118: self,\n0119: program: \"dspy.Module\",\n0120: metric: Callable | None = None,\n0121: devset: list[\"dspy.Example\"] | None = None,\n0122: num_threads: int | None = None,\n0123: display_progress: bool | None = None,\n0124: display_table: bool | int | None = None,\n0125: callback_metadata: dict[str, Any] | None = None,\n0126: save_as_csv: str | None = None,\n0127: save_as_json: str | None = None,\n0128: ) -> EvaluationResult:\n0129: \"\"\"\n0130: Args:\n0131: program (dspy.Module): The DSPy program to evaluate.\n0132: metric (Callable): The metric function to use for evaluation. if not provided, use `self.metric`.\n0133: devset (list[dspy.Example]): the evaluation dataset. if not provided, use `self.devset`.\n0134: num_threads (Optional[int]): The number of threads to use for parallel evaluation. if not provided, use\n0135: `self.num_threads`.\n0136: display_progress (bool): Whether to display progress during evaluation. if not provided, use\n0137: `self.display_progress`.\n0138: display_table (Union[bool, int]): Whether to display the evaluation results in a table. if not provided, use\n0139: `self.display_table`. If a number is passed, the evaluation results will be truncated to that number before displayed.\n0140: callback_metadata (dict): Metadata to be used for evaluate callback handlers.\n0141: \n0142: Returns:\n0143: The evaluation results are returned as a dspy.EvaluationResult object containing the following attributes:\n0144: \n0145: - score: A float percentage score (e.g., 67.30) representing overall performance\n0146: \n0147: - results: a list of (example, prediction, score) tuples for each example in devset\n0148: \"\"\"\n0149: metric = metric if metric is not None else self.metric\n0150: devset = devset if devset is not None else self.devset\n0151: num_threads = num_threads if num_threads is not None else self.num_threads\n0152: display_progress = display_progress if display_progress is not None else self.display_progress\n0153: display_table = display_table if display_table is not None else self.display_table\n0154: save_as_csv = save_as_csv if save_as_csv is not None else self.save_as_csv\n0155: save_as_json = save_as_json if save_as_json is not None else self.save_as_json\n0156: \n0157: if callback_metadata:\n0158: logger.debug(f\"Evaluate is called with callback metadata: {callback_metadata}\")\n0159: \n0160: tqdm.tqdm._instances.clear()\n0161: \n0162: executor = ParallelExecutor(\n0163: num_threads=num_threads,\n0164: disable_progress_bar=not display_progress,\n0165: max_errors=(self.max_errors if self.max_errors is not None else dspy.settings.max_errors),\n0166: provide_traceback=self.provide_traceback,\n0167: compare_results=True,\n0168: )\n0169: \n0170: def process_item(example):\n0171: prediction = program(**example.inputs())\n0172: score = metric(example, prediction)\n0173: return prediction, score\n0174: \n0175: results = executor.execute(process_item, devset)\n0176: assert len(devset) == len(results)\n0177: \n0178: results = [((dspy.Prediction(), self.failure_score) if r is None else r) for r in results]\n0179: results = [(example, prediction, score) for example, (prediction, score) in zip(devset, results, strict=False)]"}, {"span_id": "s3", "path": "dspy/utils/parallelizer.py", "start_line": 54, "end_line": 69, "excerpt": "0054: def _wrap_function(self, user_function):\n0055: def safe_func(item):\n0056: if self.cancel_jobs.is_set():\n0057: return None\n0058: try:\n0059: return user_function(item)\n0060: except Exception as e:\n0061: with self.error_lock:\n0062: self.error_count += 1\n0063: if self.error_count >= self.max_errors:\n0064: self.cancel_jobs.set()\n0065: if self.provide_traceback:\n0066: logger.error(f\"Error for {item}: {e}\\n{traceback.format_exc()}\")\n0067: else:\n0068: logger.error(f\"Error for {item}: {e}. Set `provide_traceback=True` for traceback.\")\n0069: return e"}]} {"id": "dspy_e1bc894a3f32", "topic": "evaluation_metrics_and_custom_eval", "question": "I'm benchmarking a `dspy.Predict('question -> response')` generator on a QA set where the gold answers are long-form and the wording varies a lot — two responses can mean the same thing with almost no shared tokens. Right now my metric is dspy's `HotPotF1` (token-overlap F1) against the gold string, and paraphrased-but-correct answers keep scoring near zero, so the metric is useless to me. I want a built-in dspy metric that instead uses an LM to grade each response against the gold on a graded 0-to-1 scale (so semantically equivalent phrasings score high), and I want the whole thing to be fully deterministic for a regression test (no real API calls). After running `Evaluate(...)(program)`, I also need to pull out the individual 0-to-1 grade for each devset example, not just the aggregate percentage — when I iterate `for ex, pred, score in result.results` and collect `score`, I get objects that don't behave like the floats I expected. Give me a runnable program that builds the deterministic devset + metric, runs the evaluation, and prints both the overall score and the list of per-example numeric grades.", "gold_answer": "```python\nimport dspy\nfrom dspy.evaluate import Evaluate, SemanticF1\nfrom dspy.utils.dummies import DummyLM\n\n\ndevset = [\n dspy.Example(question='What is the capital of France?', response='Paris').with_inputs('question'),\n dspy.Example(question='Which ocean is the largest on Earth?', response='The Pacific Ocean').with_inputs('question'),\n]\n\n\ndspy.configure(\n lm=DummyLM(\n [\n {'response': 'Paris is the capital of France.'},\n {'reasoning': 'The response fully covers the gold answer.', 'precision': 1.0, 'recall': 1.0},\n {'response': 'The Pacific is the largest ocean.'},\n {'reasoning': 'Mostly correct, but slightly less complete.', 'precision': 0.9, 'recall': 0.75},\n ]\n )\n)\n\nprogram = dspy.Predict('question -> response')\nmetric = SemanticF1()\n\nresult = Evaluate(\n devset=devset,\n metric=metric,\n num_threads=1,\n display_progress=False,\n)(program)\n\nper_example = [\n {'question': example.question, 'semantic_f1': metric_output.score}\n for example, _, metric_output in result.results\n]\n\nprint({'overall_percent': result.score, 'per_example': per_example})\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 45, "statement": "The scorer is the built-in LM-based semantic precision/recall metric `SemanticF1` imported from `dspy.evaluate` (instantiated and passed as the `metric`) -- NOT a hand-rolled custom metric (e.g. a user-defined class/function that calls `dspy.Predict`/`dspy.ChainOfThought` to grade) and NOT a token-overlap metric such as `F1`/`HotPotF1`/`EM`. Correspondingly the devset `dspy.Example`s expose `question` as the input (via `.with_inputs('question')`) and place the gold answer in a field named `response` (not `answer`), and the program is `dspy.Predict('question -> response')`, matching how `SemanticF1` reads `example.question`, `example.response`, and `pred.response`.", "span_ids": ["s1", "s2"]}, {"claim_id": "c2", "claim_type": "core", "weight": 20, "statement": "Because `SemanticF1` returns a `dspy.Prediction` (not a bare float), the per-example numeric grade is read from that prediction's `.score` attribute -- i.e. the code accesses `metric_output.score` (the third element of each `result.results` tuple) -- and does NOT instead treat that third element as if it were itself a number (e.g. `float(score)` / appending the raw tuple element as the numeric grade).", "span_ids": ["s1", "s4"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "Determinism with no real API calls is achieved with a `DummyLM` imported from `dspy.utils.dummies` (NOT `dspy.DummyLM`, and NOT a hand-written fake LM subclassing `BaseLM`), constructed from a fixed list of output dicts ordered so that the entries first supply the generator's `response` output and then the judge's `precision`/`recall` outputs that the semantic metric consumes (interleaved per devset example).", "span_ids": ["s3", "s4"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "`Evaluate(...)(program)` is treated as returning an `EvaluationResult` whose `.results` is a list of per-example `(example, prediction, metric_output)` tuples, and per-example grades are obtained by iterating over `result.results`.", "span_ids": ["s5"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 5, "statement": "The code reports the aggregate `result.score` (a single percentage value) separately from, and alongside, the collected list of per-example numeric grades (e.g. they are printed as distinct items).", "span_ids": ["s5", "s6"]}], "evidence": [{"span_id": "s1", "path": "dspy/evaluate/auto_evaluation.py", "start_line": 42, "end_line": 62, "excerpt": "0042: class SemanticF1(Module):\n0043: \"\"\"Computes semantic F1 between a prediction and ground truth via LLM-based precision/recall.\n0044: \n0045: Args:\n0046: threshold: Minimum F1 score to accept during optimization. Defaults to 0.66.\n0047: decompositional: If True, uses DecompositionalSemanticRecallPrecision. Defaults to False.\n0048: \"\"\"\n0049: \n0050: def __init__(self, threshold=0.66, decompositional=False):\n0051: self.threshold = threshold\n0052: \n0053: if decompositional:\n0054: self.module = ChainOfThought(DecompositionalSemanticRecallPrecision)\n0055: else:\n0056: self.module = ChainOfThought(SemanticRecallPrecision)\n0057: \n0058: def forward(self, example, pred, trace=None):\n0059: scores = self.module(question=example.question, ground_truth=example.response, system_response=pred.response)\n0060: score = f1_score(scores.precision, scores.recall)\n0061: \n0062: return Prediction(score=score if trace is None else score >= self.threshold)"}, {"span_id": "s2", "path": "dspy/evaluate/auto_evaluation.py", "start_line": 7, "end_line": 18, "excerpt": "0007: class SemanticRecallPrecision(Signature):\n0008: \"\"\"\n0009: Compare a system's response to the ground truth to compute its recall and precision.\n0010: If asked to reason, enumerate key ideas in each response, and whether they are present in the other response.\n0011: \"\"\"\n0012: \n0013: question: str = InputField()\n0014: ground_truth: str = InputField()\n0015: system_response: str = InputField()\n0016: recall: float = OutputField(desc=\"fraction (out of 1.0) of ground truth covered by the system response\")\n0017: precision: float = OutputField(desc=\"fraction (out of 1.0) of system response covered by the ground truth\")\n0018: "}, {"span_id": "s3", "path": "tests/evaluate/test_auto_evaluation.py", "start_line": 7, "end_line": 33, "excerpt": "0007: def test_semantic_f1_returns_prediction_without_trace():\n0008: # Configure with a dummy LM that returns precision and recall values\n0009: # ChainOfThought adds a \"reasoning\" field to the output\n0010: dspy.configure(\n0011: lm=DummyLM(\n0012: [\n0013: {\n0014: \"reasoning\": \"Comparing the responses\",\n0015: \"precision\": 1.0,\n0016: \"recall\": 1.0,\n0017: }\n0018: ]\n0019: )\n0020: )\n0021: \n0022: # Create example and prediction\n0023: example = dspy.Example(question=\"What is 1+1?\", response=\"2\")\n0024: pred = dspy.Prediction(response=\"2\")\n0025: \n0026: # Test SemanticF1\n0027: metric = SemanticF1()\n0028: result = metric(example, pred)\n0029: \n0030: assert isinstance(result, Prediction)\n0031: assert hasattr(result, \"score\")\n0032: assert isinstance(result.score, (int, float, bool))\n0033: "}, {"span_id": "s4", "path": "tests/evaluate/test_auto_evaluation.py", "start_line": 62, "end_line": 86, "excerpt": "0062: def test_semantic_f1_score_value():\n0063: # Configure with a dummy LM that returns specific precision and recall\n0064: dspy.configure(\n0065: lm=DummyLM(\n0066: [\n0067: {\n0068: \"reasoning\": \"Comparing the responses\",\n0069: \"precision\": 0.8,\n0070: \"recall\": 0.6,\n0071: }\n0072: ]\n0073: )\n0074: )\n0075: \n0076: # Create example and prediction\n0077: example = dspy.Example(question=\"test\", response=\"answer\")\n0078: pred = dspy.Prediction(response=\"response\")\n0079: \n0080: # Test SemanticF1\n0081: metric = SemanticF1()\n0082: result = metric(example, pred)\n0083: \n0084: expected_f1 = 2 * (0.8 * 0.6) / (0.8 + 0.6)\n0085: assert isinstance(result, Prediction)\n0086: assert abs(result.score - expected_f1) < 0.001"}, {"span_id": "s5", "path": "dspy/evaluate/evaluate.py", "start_line": 48, "end_line": 61, "excerpt": "0048: class EvaluationResult(Prediction):\n0049: \"\"\"\n0050: A class that represents the result of an evaluation.\n0051: It is a subclass of `dspy.Prediction` that contains the following fields\n0052: \n0053: - score: An float value (e.g., 67.30) representing the overall performance\n0054: - results: a list of (example, prediction, score) tuples for each example in devset\n0055: \"\"\"\n0056: \n0057: def __init__(self, score: float, results: list[tuple[\"dspy.Example\", \"dspy.Example\", Any]]):\n0058: super().__init__(score=score, results=results)\n0059: \n0060: def __repr__(self):\n0061: return f\"EvaluationResult(score={self.score}, results=)\""}, {"span_id": "s6", "path": "dspy/evaluate/evaluate.py", "start_line": 170, "end_line": 225, "excerpt": "0170: def process_item(example):\n0171: prediction = program(**example.inputs())\n0172: score = metric(example, prediction)\n0173: return prediction, score\n0174: \n0175: results = executor.execute(process_item, devset)\n0176: assert len(devset) == len(results)\n0177: \n0178: results = [((dspy.Prediction(), self.failure_score) if r is None else r) for r in results]\n0179: results = [(example, prediction, score) for example, (prediction, score) in zip(devset, results, strict=False)]\n0180: ncorrect, ntotal = sum(score for *_, score in results), len(devset)\n0181: \n0182: logger.info(f\"Average Metric: {ncorrect} / {ntotal} ({round(100 * ncorrect / ntotal, 1)}%)\")\n0183: \n0184: if display_table:\n0185: if importlib.util.find_spec(\"pandas\") is not None:\n0186: # Rename the 'correct' column to the name of the metric object\n0187: metric_name = metric.__name__ if isinstance(metric, types.FunctionType) else metric.__class__.__name__\n0188: # Construct a pandas DataFrame from the results\n0189: result_df = self._construct_result_table(results, metric_name)\n0190: \n0191: self._display_result_table(result_df, display_table, metric_name)\n0192: else:\n0193: logger.warning(\"Skipping table display since `pandas` is not installed.\")\n0194: \n0195: if save_as_csv:\n0196: metric_name = (\n0197: metric.__name__\n0198: if isinstance(metric, types.FunctionType)\n0199: else metric.__class__.__name__\n0200: )\n0201: data = self._prepare_results_output(results, metric_name)\n0202: \n0203: with open(save_as_csv, \"w\", newline=\"\") as csvfile:\n0204: fieldnames = data[0].keys()\n0205: writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n0206: \n0207: writer.writeheader()\n0208: for row in data:\n0209: writer.writerow(row)\n0210: if save_as_json:\n0211: metric_name = (\n0212: metric.__name__\n0213: if isinstance(metric, types.FunctionType)\n0214: else metric.__class__.__name__\n0215: )\n0216: data = self._prepare_results_output(results, metric_name)\n0217: with open(\n0218: save_as_json,\n0219: \"w\",\n0220: ) as f:\n0221: json.dump(data, f)\n0222: \n0223: return EvaluationResult(\n0224: score=round(100 * ncorrect / ntotal, 2),\n0225: results=results,"}]} {"id": "dspy_9e63ca9046ae", "topic": "evaluation_metrics_and_custom_eval", "question": "I'm tuning a short-answer QA program with BootstrapFewShot and want optimization driven by one number that blends two checks: exactness against the gold answer and brevity (answer is at most 3 words). My metric currently returns a plain dict like {'score': 0.7*exact + 0.3*brief, 'exact': exact, 'brief': brief} so I keep the per-check breakdown, and I pass metric_threshold=0.75 to accept bootstrapped demos. Two things are wrong: bootstrapping accepts almost nothing (0 traces), and when I run Evaluate over my dev set it blows up with \"unsupported operand type(s) for +: 'int' and 'dict'\". I tried switching to Evaluate(..., return_outputs=True) to get the per-example values back instead, but that just raises too. I want the single blended objective to actually drive bootstrapping AND the brevity/exactness split for every dev example available from the eval results afterward. Give me a complete, runnable program (use DummyLM so it runs offline) that does this correctly.", "gold_answer": "```python\nimport dspy\nfrom dspy.evaluate import Evaluate\nfrom dspy.utils.dummies import DummyLM\n\n\nclass ShortAnswerer(dspy.Module):\n def __init__(self):\n super().__init__()\n self.qa = dspy.Predict('question -> answer')\n\n def forward(self, question):\n return self.qa(question=question)\n\n\ndef exact_and_brief(example, pred, trace=None):\n exact = float(example.answer == pred.answer)\n brief = float(len(pred.answer.split()) <= 3)\n return dspy.Prediction(\n score=0.7 * exact + 0.3 * brief,\n exact=exact,\n brief=brief,\n feedback=f'exact={exact}, brief={brief}',\n )\n\n\ntrainset = [\n dspy.Example(question='2+2?', answer='4').with_inputs('question'),\n dspy.Example(question='Capital of France?', answer='Paris').with_inputs('question'),\n]\ndevset = [\n dspy.Example(question='3+3?', answer='6').with_inputs('question'),\n dspy.Example(question='Largest ocean?', answer='Pacific').with_inputs('question'),\n]\n\n\ndspy.configure(\n lm=DummyLM(\n {\n '2+2?': {'answer': '4'},\n 'Capital of France?': {'answer': 'Paris'},\n '3+3?': {'answer': '6'},\n 'Largest ocean?': {'answer': 'Pacific Ocean'},\n }\n )\n)\n\noptimizer = dspy.BootstrapFewShot(\n metric=exact_and_brief,\n metric_threshold=0.75,\n max_bootstrapped_demos=1,\n max_labeled_demos=2,\n)\ncompiled = optimizer.compile(\n student=ShortAnswerer(),\n teacher=ShortAnswerer(),\n trainset=trainset,\n)\n\nresult = Evaluate(\n devset=devset,\n metric=exact_and_brief,\n num_threads=1,\n display_progress=False,\n)(compiled)\n\nbreakdown = [\n {'question': example.question, **metric_output.toDict()}\n for example, _, metric_output in result.results\n]\n\nprint({'overall_percent': result.score, 'per_example': breakdown})\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 35, "statement": "The metric function's return statement constructs and returns a single `dspy.Prediction(...)` whose `score=` kwarg is set to the blended objective (0.7*exact + 0.3*brief) AND that SAME Prediction also carries the per-check sub-scores as extra fields (e.g. `exact=`, `brief=`). It must NOT return a plain dict, tuple, namedtuple, a bare float/number, or any non-dspy framework's result object (e.g. an inspect_ai MetricResult): grade ONLY on the literal return expression's type in the answer's code text.", "span_ids": ["s1"]}, {"claim_id": "c2", "claim_type": "core", "weight": 25, "statement": "The code passes `metric_threshold=0.75` to `dspy.BootstrapFewShot(...)` AND wires that optimizer's `metric=` to the SAME Prediction-returning metric from c1 (not a separate float-returning or dict-returning function). Grade statically on the BootstrapFewShot call's keyword arguments and the identity of the function bound to `metric=`; do not run or assert anything about how many demos are accepted.", "span_ids": ["s1", "s2"]}, {"claim_id": "c3", "claim_type": "core", "weight": 25, "statement": "The SAME Prediction-returning metric from c1 is also the `metric=` passed to `dspy.Evaluate(...)`, and the answer does NOT construct Evaluate (or its call) with `return_outputs=True` and does NOT rely on a `return_all_scores=` argument to Evaluate to obtain the per-example values. Grade statically on the Evaluate construction/call kwargs and on the metric identity in the code text; do not grade on the runtime sum or on any raised/avoided exception.", "span_ids": ["s1", "s3"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 15, "statement": "The per-check breakdown is recovered by iterating `result.results` and unpacking each item as a 3-tuple `(example, prediction, metric_output)`, reading the per-check sub-fields off the third element (the Prediction metric output) via `.toDict()` (or by direct attribute/field access on it). It must NOT read the breakdown from an external dict/log keyed by `id(example)` nor from a removed/ignored Evaluate argument. Grade statically on how `result.results` is unpacked and where the sub-fields are read.", "span_ids": ["s3"]}], "evidence": [{"span_id": "s1", "path": "dspy/primitives/prediction.py", "start_line": 4, "end_line": 16, "excerpt": "0004: class Prediction(Example):\n0005: \"\"\"A prediction object that contains the output of a DSPy module.\n0006: \n0007: Prediction inherits from Example.\n0008: \n0009: To allow feedback-augmented scores, Prediction supports comparison operations\n0010: (<, >, <=, >=) for Predictions with a `score` field. The comparison operations\n0011: compare the 'score' values as floats. For equality comparison, Predictions are equal\n0012: if their underlying data stores are equal (inherited from Example).\n0013: \n0014: Arithmetic operations (+, /, etc.) are also supported for Predictions with a 'score'\n0015: field, operating on the score value.\n0016: \"\"\""}, {"span_id": "s2", "path": "dspy/teleprompt/bootstrap.py", "start_line": 205, "end_line": 210, "excerpt": "0205: if self.metric:\n0206: metric_val = self.metric(example, prediction, trace)\n0207: if self.metric_threshold:\n0208: success = metric_val >= self.metric_threshold\n0209: else:\n0210: success = metric_val"}, {"span_id": "s3", "path": "dspy/evaluate/evaluate.py", "start_line": 170, "end_line": 225, "excerpt": "0170: def process_item(example):\n0171: prediction = program(**example.inputs())\n0172: score = metric(example, prediction)\n0173: return prediction, score\n0174: \n0175: results = executor.execute(process_item, devset)\n0176: assert len(devset) == len(results)\n0177: \n0178: results = [((dspy.Prediction(), self.failure_score) if r is None else r) for r in results]\n0179: results = [(example, prediction, score) for example, (prediction, score) in zip(devset, results, strict=False)]\n0180: ncorrect, ntotal = sum(score for *_, score in results), len(devset)\n0181: \n0182: logger.info(f\"Average Metric: {ncorrect} / {ntotal} ({round(100 * ncorrect / ntotal, 1)}%)\")\n0183: \n0184: if display_table:\n0185: if importlib.util.find_spec(\"pandas\") is not None:\n0186: # Rename the 'correct' column to the name of the metric object\n0187: metric_name = metric.__name__ if isinstance(metric, types.FunctionType) else metric.__class__.__name__\n0188: # Construct a pandas DataFrame from the results\n0189: result_df = self._construct_result_table(results, metric_name)\n0190: \n0191: self._display_result_table(result_df, display_table, metric_name)\n0192: else:\n0193: logger.warning(\"Skipping table display since `pandas` is not installed.\")\n0194: \n0195: if save_as_csv:\n0196: metric_name = (\n0197: metric.__name__\n0198: if isinstance(metric, types.FunctionType)\n0199: else metric.__class__.__name__\n0200: )\n0201: data = self._prepare_results_output(results, metric_name)\n0202: \n0203: with open(save_as_csv, \"w\", newline=\"\") as csvfile:\n0204: fieldnames = data[0].keys()\n0205: writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n0206: \n0207: writer.writeheader()\n0208: for row in data:\n0209: writer.writerow(row)\n0210: if save_as_json:\n0211: metric_name = (\n0212: metric.__name__\n0213: if isinstance(metric, types.FunctionType)\n0214: else metric.__class__.__name__\n0215: )\n0216: data = self._prepare_results_output(results, metric_name)\n0217: with open(\n0218: save_as_json,\n0219: \"w\",\n0220: ) as f:\n0221: json.dump(data, f)\n0222: \n0223: return EvaluationResult(\n0224: score=round(100 * ncorrect / ntotal, 2),\n0225: results=results,"}]} {"id": "dspy_3a5e956e4421", "topic": "evaluation_metrics_and_custom_eval", "question": "I've got a `dspy.ReAct` agent that answers arithmetic word problems and is given a Python `add` function as a tool. I want an evaluation harness that gives an example credit ONLY when the final answer is correct AND the agent genuinely used the calculator to get there. The reason I care: some of these agents just blurt out the right number and immediately finish without ever calling the tool, and those runs must score zero — a correct answer alone is not enough.\n\nMy current metric pulls the tool calls off the prediction (I look at `pred.tool_calls` like I would with native function-calling / `dspy.ToolCalls`) and checks whether `add` is among them, but it never awards credit — even on runs where I can see from the logs that the agent clearly did call `add`. So my whole devset scores 0%.\n\nGive me a small, runnable harness (devset of a couple of arithmetic examples, a custom metric, and a run over the devset that prints an overall percentage plus per-example scores) that scores this correctly. Use `DummyLM` so it runs offline with no API key.", "gold_answer": "```python\nimport dspy\nfrom dspy.evaluate import Evaluate\nfrom dspy.utils.dummies import DummyLM\n\n\ndef add(a: int, b: int) -> int:\n return a + b\n\n\ndef tool_use_metric(example, pred, trace=None):\n # Credit only if the agent actually invoked the `add` tool. Note that ReAct always\n # records a `finish` step in the trajectory, so we must match the specific tool name,\n # not merely \"some tool was called\".\n used_add = any(\n key.startswith('tool_name_') and value == 'add'\n for key, value in pred.trajectory.items()\n )\n correct = str(example.answer) == str(pred.answer)\n return float(used_add and correct)\n\n\ndevset = [\n dspy.Example(question='What is 2 + 2?', answer='4').with_inputs('question'),\n dspy.Example(question='What is 3 + 4?', answer='7').with_inputs('question'),\n]\n\n\ndspy.configure(\n lm=DummyLM(\n [\n {'next_thought': 'I should add the numbers.', 'next_tool_name': 'add', 'next_tool_args': {'a': 2, 'b': 2}},\n {'next_thought': 'I have the result, so I can finish.', 'next_tool_name': 'finish', 'next_tool_args': {}},\n {'reasoning': 'The tool returned 4.', 'answer': '4'},\n {'next_thought': 'I already know the answer, so I can finish.', 'next_tool_name': 'finish', 'next_tool_args': {}},\n {'reasoning': 'It is 7.', 'answer': '7'},\n ]\n )\n)\n\nagent = dspy.ReAct('question -> answer', tools=[add], max_iters=2)\nresult = Evaluate(\n devset=devset,\n metric=tool_use_metric,\n num_threads=1,\n display_progress=False,\n)(agent)\n\nper_example = [\n {'question': example.question, 'tool_use_score': score}\n for example, _, score in result.results\n]\n\nprint({'overall_percent': result.score, 'per_example': per_example})\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 70, "statement": "The custom metric awards credit only when BOTH (a) the prediction's final answer matches the example answer AND (b) the agent actually invoked the arithmetic tool, and it detects (b) by reading the ReAct trajectory: it iterates `pred.trajectory` (the dict ReAct returns) and checks for a `tool_name_*` entry whose VALUE equals the specific tool name `'add'`. It must NOT read tool usage from `pred.tool_calls` / `pred.trace.tool_calls` / any `dspy.ToolCalls`-style native-function-calling field (ReAct does not populate those), and it must NOT pass on the mere presence of any `tool_name_*` entry or a non-empty trajectory — because ReAct ALWAYS records a `finish` step (`tool_name_* == 'finish'`), a correct answer whose trajectory contains only a `finish` step (no `add` call) must score zero.", "span_ids": ["s1", "s2", "s3"]}, {"claim_id": "c2", "claim_type": "core", "weight": 10, "statement": "The evaluated program is a `dspy.ReAct` agent constructed with the arithmetic function passed in `tools=[...]`, so each prediction carries a `trajectory` attribute recording the per-step `tool_name_*`/`tool_args_*`/`observation_*` entries that the metric inspects (rather than an OpenAI-style `tool_calls` field on the prediction).", "span_ids": ["s1", "s2"]}, {"claim_id": "c3", "claim_type": "core", "weight": 12, "statement": "The harness runs `dspy.evaluate.Evaluate` over a devset of `dspy.Example`s (declared runnable, i.e. the input is marked with `.with_inputs('question')`) using the custom metric; `Evaluate` invokes the program per example as `program(**example.inputs())`, scores it via `metric(example, prediction)`, and returns an overall percentage plus per-example `(example, prediction, score)` results.", "span_ids": ["s4"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 8, "statement": "The example reports results by reading from the `Evaluate` return value: it extracts the per-example tool-use scores from `result.results` (the `(example, prediction, score)` tuples) and prints them alongside the overall percentage from `result.score`.", "span_ids": ["s4"]}], "evidence": [{"span_id": "s1", "path": "dspy/predict/react.py", "start_line": 95, "end_line": 118, "excerpt": "0095: def forward(self, **input_args):\n0096: trajectory = {}\n0097: max_iters = input_args.pop(\"max_iters\", self.max_iters)\n0098: for idx in range(max_iters):\n0099: try:\n0100: pred = self._call_with_potential_trajectory_truncation(self.react, trajectory, **input_args)\n0101: except ValueError as err:\n0102: logger.warning(f\"Ending the trajectory: Agent failed to select a valid tool: {_fmt_exc(err)}\")\n0103: break\n0104: \n0105: trajectory[f\"thought_{idx}\"] = pred.next_thought\n0106: trajectory[f\"tool_name_{idx}\"] = pred.next_tool_name\n0107: trajectory[f\"tool_args_{idx}\"] = pred.next_tool_args\n0108: \n0109: try:\n0110: trajectory[f\"observation_{idx}\"] = self.tools[pred.next_tool_name](**pred.next_tool_args)\n0111: except Exception as err:\n0112: trajectory[f\"observation_{idx}\"] = f\"Execution error in {pred.next_tool_name}: {_fmt_exc(err)}\"\n0113: \n0114: if pred.next_tool_name == \"finish\":\n0115: break\n0116: \n0117: extract = self._call_with_potential_trajectory_truncation(self.extract, trajectory, **input_args)\n0118: return dspy.Prediction(trajectory=trajectory, **extract)"}, {"span_id": "s2", "path": "tests/predict/test_react.py", "start_line": 116, "end_line": 133, "excerpt": "0116: expected_trajectory = {\n0117: \"thought_0\": \"I need to write an invitation letter for Alice to the Science Fair event.\",\n0118: \"tool_name_0\": \"write_invitation_letter\",\n0119: \"tool_args_0\": {\n0120: \"participant_name\": \"Alice\",\n0121: \"event_info\": {\n0122: \"name\": \"Science Fair\",\n0123: \"date\": \"Friday\",\n0124: \"participants\": {\"Alice\": \"female\", \"Bob\": \"male\"},\n0125: },\n0126: },\n0127: \"observation_0\": \"It's my honor to invite Alice to event Science Fair on Friday\",\n0128: \"thought_1\": \"I have successfully written the invitation letter for Alice to the Science Fair. Now I can finish the task.\",\n0129: \"tool_name_1\": \"finish\",\n0130: \"tool_args_1\": {},\n0131: \"observation_1\": \"Completed.\",\n0132: }\n0133: assert outputs.trajectory == expected_trajectory"}, {"span_id": "s3", "path": "tests/predict/test_react.py", "start_line": 198, "end_line": 211, "excerpt": "0198: expected_trajectory = {\n0199: \"thought_0\": \"I need to add two numbers.\",\n0200: \"tool_name_0\": \"foo\",\n0201: \"tool_args_0\": {\n0202: \"a\": 1,\n0203: \"b\": 2,\n0204: },\n0205: \"observation_0\": 3,\n0206: \"thought_1\": \"I have the sum, now I can finish.\",\n0207: \"tool_name_1\": \"finish\",\n0208: \"tool_args_1\": {},\n0209: \"observation_1\": \"Completed.\",\n0210: }\n0211: assert outputs.trajectory == expected_trajectory"}, {"span_id": "s4", "path": "dspy/evaluate/evaluate.py", "start_line": 170, "end_line": 225, "excerpt": "0170: def process_item(example):\n0171: prediction = program(**example.inputs())\n0172: score = metric(example, prediction)\n0173: return prediction, score\n0174: \n0175: results = executor.execute(process_item, devset)\n0176: assert len(devset) == len(results)\n0177: \n0178: results = [((dspy.Prediction(), self.failure_score) if r is None else r) for r in results]\n0179: results = [(example, prediction, score) for example, (prediction, score) in zip(devset, results, strict=False)]\n0180: ncorrect, ntotal = sum(score for *_, score in results), len(devset)\n0181: \n0182: logger.info(f\"Average Metric: {ncorrect} / {ntotal} ({round(100 * ncorrect / ntotal, 1)}%)\")\n0183: \n0184: if display_table:\n0185: if importlib.util.find_spec(\"pandas\") is not None:\n0186: # Rename the 'correct' column to the name of the metric object\n0187: metric_name = metric.__name__ if isinstance(metric, types.FunctionType) else metric.__class__.__name__\n0188: # Construct a pandas DataFrame from the results\n0189: result_df = self._construct_result_table(results, metric_name)\n0190: \n0191: self._display_result_table(result_df, display_table, metric_name)\n0192: else:\n0193: logger.warning(\"Skipping table display since `pandas` is not installed.\")\n0194: \n0195: if save_as_csv:\n0196: metric_name = (\n0197: metric.__name__\n0198: if isinstance(metric, types.FunctionType)\n0199: else metric.__class__.__name__\n0200: )\n0201: data = self._prepare_results_output(results, metric_name)\n0202: \n0203: with open(save_as_csv, \"w\", newline=\"\") as csvfile:\n0204: fieldnames = data[0].keys()\n0205: writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n0206: \n0207: writer.writeheader()\n0208: for row in data:\n0209: writer.writerow(row)\n0210: if save_as_json:\n0211: metric_name = (\n0212: metric.__name__\n0213: if isinstance(metric, types.FunctionType)\n0214: else metric.__class__.__name__\n0215: )\n0216: data = self._prepare_results_output(results, metric_name)\n0217: with open(\n0218: save_as_json,\n0219: \"w\",\n0220: ) as f:\n0221: json.dump(data, f)\n0222: \n0223: return EvaluationResult(\n0224: score=round(100 * ncorrect / ntotal, 2),\n0225: results=results,"}]} {"id": "dspy_e98cfa59364f", "topic": "evaluation_metrics_and_custom_eval", "question": "I've got a small retrieval-then-answer DSPy module (each prediction carries the predicted `answer` plus the list of retrieved passages it used as `context`), and I want my dev-set score to reflect a strict bar: an example counts as correct only when the predicted answer matches the gold answer **and** the retrieved passages it returned genuinely contain that answer. Right now I'm wiring `dspy.evaluate.CompleteAndGrounded` in as my metric and bumping its `threshold`, but my numbers come out fuzzy — clearly-wrong answers still land partial credit and I can't get a clean \"both-or-nothing\" pass/fail per example. I want a deterministic, no-extra-LLM-call check, not a judged score. Write a compact, runnable program that defines such a metric and runs it across a tiny dev set with `Evaluate`, printing the overall percentage and the per-example scores.", "gold_answer": "```python\nimport dspy\nfrom dspy.evaluate import Evaluate, answer_exact_match, answer_passage_match\nfrom dspy.utils.dummies import DummyLM\n\n\nclass AnswerFromContext(dspy.Signature):\n question: str = dspy.InputField()\n context: list[str] = dspy.InputField()\n answer: str = dspy.OutputField()\n\n\nclass TinyRAG(dspy.Module):\n def __init__(self):\n super().__init__()\n self.answer = dspy.Predict(AnswerFromContext)\n self.corpus = {\n 'Where is the Eiffel Tower?': ['Paris | The Eiffel Tower is in Paris, France.'],\n 'What is the largest ocean?': ['Pacific | The Pacific Ocean is the largest ocean on Earth.'],\n }\n\n def forward(self, question):\n context = self.corpus[question]\n pred = self.answer(question=question, context=context)\n return dspy.Prediction(answer=pred.answer, context=context)\n\n\ndef answer_and_support(example, pred, trace=None):\n exact = answer_exact_match(example, pred)\n supported = answer_passage_match(example, pred)\n return float(exact and supported)\n\n\ndevset = [\n dspy.Example(question='Where is the Eiffel Tower?', answer='Paris').with_inputs('question'),\n dspy.Example(question='What is the largest ocean?', answer='Pacific Ocean').with_inputs('question'),\n]\n\n\ndspy.configure(\n lm=DummyLM(\n {\n 'Where is the Eiffel Tower?': {'answer': 'Paris'},\n 'What is the largest ocean?': {'answer': 'Pacific Ocean'},\n }\n )\n)\n\nresult = Evaluate(\n devset=devset,\n metric=answer_and_support,\n num_threads=1,\n display_progress=False,\n)(TinyRAG())\n\nper_example = [\n {'question': example.question, 'score': score}\n for example, _, score in result.results\n]\n\nprint({'overall_percent': result.score, 'per_example': per_example})\n```", "rubric": [{"claim_id": "c1", "claim_type": "core", "weight": 50, "statement": "Implements BOTH halves of the metric with the snapshot's built-in deterministic helpers — answer correctness via `answer_exact_match(example, pred)` and passage support via `answer_passage_match(example, pred)` (imported from `dspy.evaluate` or `dspy.evaluate.metrics`; either path acceptable) — and combines their results with a strict boolean AND so credit is given only when both return truthy. It does NOT hand-roll the checks with raw Python equality (`pred.answer == example.answer`) or a substring/`in` scan over the passages, and does NOT use the LLM-judge module `CompleteAndGrounded` (nor `SemanticF1` / any `ChainOfThought`-based grader). The two named helper calls themselves must be present; a custom both-or-nothing metric built from naive string ops or from `CompleteAndGrounded` scores 0 here (the helpers apply normalized EM and normalized token-sequence matching, so a naive decoy is semantically wrong, not merely stylistically different).", "span_ids": ["s1", "s2", "s3", "s4"]}, {"claim_id": "c2", "claim_type": "core", "weight": 10, "statement": "The metric is a plain callable with the `(example, pred, trace=None)` signature that returns a single deterministic per-example verdict (a number/bool such as 1.0/0.0 or True/False) representing a both-or-nothing pass: a failure of EITHER the answer check OR the passage check yields zero, and only their conjunction yields full credit. It makes no extra LLM/judge call and applies no fractional/F1 threshold to decide the per-example result.", "span_ids": ["s1"]}, {"claim_id": "c3", "claim_type": "core", "weight": 20, "statement": "The evaluated module's `forward` returns a `dspy.Prediction` carrying BOTH an `answer` field and a `context` field (the list of retrieved passages), matching what the two helpers consume — `answer_exact_match` reads `pred.answer` and `answer_passage_match` reads `pred.context`. An answer that returns only `answer`, or stores the passages somewhere the passage-helper does not read (not on `pred.context`), does not satisfy this.", "span_ids": ["s5", "s6"]}, {"claim_id": "c4", "claim_type": "supporting", "weight": 10, "statement": "Runs the evaluation by passing the custom metric to `Evaluate(devset=..., metric=...)` and invoking the evaluator on the module instance, so the combined metric is applied across the tiny dev set.", "span_ids": ["s7"]}, {"claim_id": "c5", "claim_type": "supporting", "weight": 10, "statement": "Reads the aggregated outcome off the `Evaluate` return value — the overall percentage from its `score` attribute and the per-example outcomes from its `results` list of `(example, prediction, score)` tuples — and includes a print of both the overall percentage and the per-example scores. Recomputing per-example scores by manually re-looping over the devset and re-calling the metric instead of reading `result.results` does not satisfy this.", "span_ids": ["s8"]}], "evidence": [{"span_id": "s1", "path": "tests/examples/test_baleen.py", "start_line": 72, "end_line": 85, "excerpt": "0072: def validate_context_and_answer_and_hops(example, pred, trace=None):\n0073: if not dspy.evaluate.answer_exact_match(example, pred):\n0074: return False\n0075: if not dspy.evaluate.answer_passage_match(example, pred):\n0076: return False\n0077: \n0078: hops = [example.question] + [outputs.query for *_, outputs in trace if \"query\" in outputs]\n0079: \n0080: if max([len(h) for h in hops]) > 100:\n0081: return False\n0082: if any(dspy.evaluate.answer_exact_match_str(hops[idx], hops[:idx], frac=0.8) for idx in range(2, len(hops))):\n0083: return False\n0084: \n0085: return True"}, {"span_id": "s2", "path": "dspy/evaluate/metrics.py", "start_line": 285, "end_line": 348, "excerpt": "0285: def answer_exact_match(example, pred, trace=None, frac=1.0):\n0286: \"\"\"Evaluate exact match or F1-thresholded match for an example/prediction pair.\n0287: \n0288: If `example.answer` is a string, compare `pred.answer` against it. If it's a list,\n0289: compare against any of the references. When `frac >= 1.0` (default), use EM;\n0290: otherwise require that the maximum F1 across references is at least `frac`.\n0291: \n0292: Args:\n0293: example: `dspy.Example` object with field `answer` (str or list[str]).\n0294: pred: `dspy.Prediction` object with field `answer` (str).\n0295: trace: Unused; reserved for compatibility.\n0296: frac (float, optional): Threshold in [0.0, 1.0]. `1.0` means EM.\n0297: \n0298: Returns:\n0299: bool: True if the match condition holds; otherwise False.\n0300: \n0301: Examples:\n0302: ```python\n0303: import dspy\n0304: \n0305: example = dspy.Example(answer=[\"Eiffel Tower\", \"Louvre\"])\n0306: pred = dspy.Prediction(answer=\"The Eiffel Tower\")\n0307: \n0308: answer_exact_match(example, pred, frac=1.0) # equivalent to EM, True\n0309: answer_exact_match(example, pred, frac=0.5) # True\n0310: ```\n0311: \"\"\"\n0312: if isinstance(example.answer, str):\n0313: return _answer_match(pred.answer, [example.answer], frac=frac)\n0314: elif isinstance(example.answer, list):\n0315: return _answer_match(pred.answer, example.answer, frac=frac)\n0316: \n0317: raise ValueError(f\"Invalid answer type: {type(example.answer)}\")\n0318: \n0319: \n0320: def answer_passage_match(example, pred, trace=None):\n0321: \"\"\"Return True if any passage in `pred.context` contains the answer(s).\n0322: \n0323: Strings are normalized (and passages also use DPR normalization internally).\n0324: \n0325: Args:\n0326: example: `dspy.Example` object with field `answer` (str or list[str]).\n0327: pred: `dspy.Prediction` object with field `context` (list[str]) containing passages.\n0328: trace: Unused; reserved for compatibility.\n0329: \n0330: Returns:\n0331: bool: True if any passage contains any reference answer; otherwise False.\n0332: \n0333: Examples:\n0334: ```python\n0335: import dspy\n0336: \n0337: example = dspy.Example(answer=\"Eiffel Tower\")\n0338: pred = dspy.Prediction(context=[\"The Eiffel Tower is in Paris.\", \"...\"])\n0339: \n0340: answer_passage_match(example, pred) # True\n0341: ```\n0342: \"\"\"\n0343: if isinstance(example.answer, str):\n0344: return _passage_match(pred.context, [example.answer])\n0345: elif isinstance(example.answer, list):\n0346: return _passage_match(pred.context, example.answer)\n0347: \n0348: raise ValueError(f\"Invalid answer type: {type(example.answer)}\")"}, {"span_id": "s3", "path": "dspy/evaluate/metrics.py", "start_line": 285, "end_line": 317, "excerpt": "0285: def answer_exact_match(example, pred, trace=None, frac=1.0):\n0286: \"\"\"Evaluate exact match or F1-thresholded match for an example/prediction pair.\n0287: \n0288: If `example.answer` is a string, compare `pred.answer` against it. If it's a list,\n0289: compare against any of the references. When `frac >= 1.0` (default), use EM;\n0290: otherwise require that the maximum F1 across references is at least `frac`.\n0291: \n0292: Args:\n0293: example: `dspy.Example` object with field `answer` (str or list[str]).\n0294: pred: `dspy.Prediction` object with field `answer` (str).\n0295: trace: Unused; reserved for compatibility.\n0296: frac (float, optional): Threshold in [0.0, 1.0]. `1.0` means EM.\n0297: \n0298: Returns:\n0299: bool: True if the match condition holds; otherwise False.\n0300: \n0301: Examples:\n0302: ```python\n0303: import dspy\n0304: \n0305: example = dspy.Example(answer=[\"Eiffel Tower\", \"Louvre\"])\n0306: pred = dspy.Prediction(answer=\"The Eiffel Tower\")\n0307: \n0308: answer_exact_match(example, pred, frac=1.0) # equivalent to EM, True\n0309: answer_exact_match(example, pred, frac=0.5) # True\n0310: ```\n0311: \"\"\"\n0312: if isinstance(example.answer, str):\n0313: return _answer_match(pred.answer, [example.answer], frac=frac)\n0314: elif isinstance(example.answer, list):\n0315: return _answer_match(pred.answer, example.answer, frac=frac)\n0316: \n0317: raise ValueError(f\"Invalid answer type: {type(example.answer)}\")"}, {"span_id": "s4", "path": "dspy/evaluate/metrics.py", "start_line": 320, "end_line": 348, "excerpt": "0320: def answer_passage_match(example, pred, trace=None):\n0321: \"\"\"Return True if any passage in `pred.context` contains the answer(s).\n0322: \n0323: Strings are normalized (and passages also use DPR normalization internally).\n0324: \n0325: Args:\n0326: example: `dspy.Example` object with field `answer` (str or list[str]).\n0327: pred: `dspy.Prediction` object with field `context` (list[str]) containing passages.\n0328: trace: Unused; reserved for compatibility.\n0329: \n0330: Returns:\n0331: bool: True if any passage contains any reference answer; otherwise False.\n0332: \n0333: Examples:\n0334: ```python\n0335: import dspy\n0336: \n0337: example = dspy.Example(answer=\"Eiffel Tower\")\n0338: pred = dspy.Prediction(context=[\"The Eiffel Tower is in Paris.\", \"...\"])\n0339: \n0340: answer_passage_match(example, pred) # True\n0341: ```\n0342: \"\"\"\n0343: if isinstance(example.answer, str):\n0344: return _passage_match(pred.context, [example.answer])\n0345: elif isinstance(example.answer, list):\n0346: return _passage_match(pred.context, example.answer)\n0347: \n0348: raise ValueError(f\"Invalid answer type: {type(example.answer)}\")"}, {"span_id": "s5", "path": "tests/examples/test_baleen.py", "start_line": 34, "end_line": 43, "excerpt": "0034: def forward(self, question):\n0035: context = []\n0036: \n0037: for hop in range(self.max_hops):\n0038: query = self.generate_query[hop](context=context, question=question).query\n0039: passages = self.retrieve(query).passages\n0040: context = deduplicate(context + passages)\n0041: \n0042: pred = self.generate_answer(context=context, question=question)\n0043: return dspy.Prediction(context=context, answer=pred.answer)"}, {"span_id": "s6", "path": "dspy/evaluate/metrics.py", "start_line": 285, "end_line": 348, "excerpt": "0285: def answer_exact_match(example, pred, trace=None, frac=1.0):\n0286: \"\"\"Evaluate exact match or F1-thresholded match for an example/prediction pair.\n0287: \n0288: If `example.answer` is a string, compare `pred.answer` against it. If it's a list,\n0289: compare against any of the references. When `frac >= 1.0` (default), use EM;\n0290: otherwise require that the maximum F1 across references is at least `frac`.\n0291: \n0292: Args:\n0293: example: `dspy.Example` object with field `answer` (str or list[str]).\n0294: pred: `dspy.Prediction` object with field `answer` (str).\n0295: trace: Unused; reserved for compatibility.\n0296: frac (float, optional): Threshold in [0.0, 1.0]. `1.0` means EM.\n0297: \n0298: Returns:\n0299: bool: True if the match condition holds; otherwise False.\n0300: \n0301: Examples:\n0302: ```python\n0303: import dspy\n0304: \n0305: example = dspy.Example(answer=[\"Eiffel Tower\", \"Louvre\"])\n0306: pred = dspy.Prediction(answer=\"The Eiffel Tower\")\n0307: \n0308: answer_exact_match(example, pred, frac=1.0) # equivalent to EM, True\n0309: answer_exact_match(example, pred, frac=0.5) # True\n0310: ```\n0311: \"\"\"\n0312: if isinstance(example.answer, str):\n0313: return _answer_match(pred.answer, [example.answer], frac=frac)\n0314: elif isinstance(example.answer, list):\n0315: return _answer_match(pred.answer, example.answer, frac=frac)\n0316: \n0317: raise ValueError(f\"Invalid answer type: {type(example.answer)}\")\n0318: \n0319: \n0320: def answer_passage_match(example, pred, trace=None):\n0321: \"\"\"Return True if any passage in `pred.context` contains the answer(s).\n0322: \n0323: Strings are normalized (and passages also use DPR normalization internally).\n0324: \n0325: Args:\n0326: example: `dspy.Example` object with field `answer` (str or list[str]).\n0327: pred: `dspy.Prediction` object with field `context` (list[str]) containing passages.\n0328: trace: Unused; reserved for compatibility.\n0329: \n0330: Returns:\n0331: bool: True if any passage contains any reference answer; otherwise False.\n0332: \n0333: Examples:\n0334: ```python\n0335: import dspy\n0336: \n0337: example = dspy.Example(answer=\"Eiffel Tower\")\n0338: pred = dspy.Prediction(context=[\"The Eiffel Tower is in Paris.\", \"...\"])\n0339: \n0340: answer_passage_match(example, pred) # True\n0341: ```\n0342: \"\"\"\n0343: if isinstance(example.answer, str):\n0344: return _passage_match(pred.context, [example.answer])\n0345: elif isinstance(example.answer, list):\n0346: return _passage_match(pred.context, example.answer)\n0347: \n0348: raise ValueError(f\"Invalid answer type: {type(example.answer)}\")"}, {"span_id": "s7", "path": "dspy/evaluate/evaluate.py", "start_line": 71, "end_line": 75, "excerpt": "0071: def __init__(\n0072: self,\n0073: *,\n0074: devset: list[\"dspy.Example\"],\n0075: metric: Callable | None = None,"}, {"span_id": "s8", "path": "dspy/evaluate/evaluate.py", "start_line": 170, "end_line": 225, "excerpt": "0170: def process_item(example):\n0171: prediction = program(**example.inputs())\n0172: score = metric(example, prediction)\n0173: return prediction, score\n0174: \n0175: results = executor.execute(process_item, devset)\n0176: assert len(devset) == len(results)\n0177: \n0178: results = [((dspy.Prediction(), self.failure_score) if r is None else r) for r in results]\n0179: results = [(example, prediction, score) for example, (prediction, score) in zip(devset, results, strict=False)]\n0180: ncorrect, ntotal = sum(score for *_, score in results), len(devset)\n0181: \n0182: logger.info(f\"Average Metric: {ncorrect} / {ntotal} ({round(100 * ncorrect / ntotal, 1)}%)\")\n0183: \n0184: if display_table:\n0185: if importlib.util.find_spec(\"pandas\") is not None:\n0186: # Rename the 'correct' column to the name of the metric object\n0187: metric_name = metric.__name__ if isinstance(metric, types.FunctionType) else metric.__class__.__name__\n0188: # Construct a pandas DataFrame from the results\n0189: result_df = self._construct_result_table(results, metric_name)\n0190: \n0191: self._display_result_table(result_df, display_table, metric_name)\n0192: else:\n0193: logger.warning(\"Skipping table display since `pandas` is not installed.\")\n0194: \n0195: if save_as_csv:\n0196: metric_name = (\n0197: metric.__name__\n0198: if isinstance(metric, types.FunctionType)\n0199: else metric.__class__.__name__\n0200: )\n0201: data = self._prepare_results_output(results, metric_name)\n0202: \n0203: with open(save_as_csv, \"w\", newline=\"\") as csvfile:\n0204: fieldnames = data[0].keys()\n0205: writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n0206: \n0207: writer.writeheader()\n0208: for row in data:\n0209: writer.writerow(row)\n0210: if save_as_json:\n0211: metric_name = (\n0212: metric.__name__\n0213: if isinstance(metric, types.FunctionType)\n0214: else metric.__class__.__name__\n0215: )\n0216: data = self._prepare_results_output(results, metric_name)\n0217: with open(\n0218: save_as_json,\n0219: \"w\",\n0220: ) as f:\n0221: json.dump(data, f)\n0222: \n0223: return EvaluationResult(\n0224: score=round(100 * ncorrect / ntotal, 2),\n0225: results=results,"}]}