| {: , : , : messages\, : , : [{: , : , : 52, : , : [, , , ]}, {: , : , : 20, : , : []}, {: , : , : 12, : , : [, ]}, {: , : , : 9, : , : [, ]}, {: , : , : 7, : , : []}], : [{: , : , : 330, : 365, : light\medium\heavy\pareto\current_best\pareto\ProposalFn | None\ReflectionComponentSelector | str\round_robin\}, {: , : , : 377, : 399, : Exactly one of max_metric_calls, max_full_evals, auto must be set. \You set max_metric_calls={max_metric_calls}, \max_full_evals={max_full_evals}, \auto={auto}.\GEPA requires a reflection language model, or custom instruction proposer to be provided. \Typically, you can use `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)` to get a good reflection model. \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. \}, {: , : , : 27, : 55, : DSPyTrace\DSPyTrace\ScoreWithFeedback\\\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\\n0054: \\}, {: , : , : 90, : 120, : responses\api_\prompt\messages\kwargs\response\outputs\usage\cost\_hidden_params\response_cost\timestamp\uuid\model\response_model\model_type\}, {: , : , : 122, : 132, : }, {: , : , : 69, : 87, : dummy\chat\}, {: , : , : 548, : 599, : }, {: , : , : 570, : 572, : }, {: , : , : 321, : 336, : text\reasoning\text\Missing 'text' field in the output from the base LM!\text\Unexpected output type from the base LM! Expected str or dict\}, {: , : , : 36, : 41, : messages\role\user\content\prompt\outputs\timestamp\Unknown time\}]} |
| {: , : , : , : , : [{: , : , : 42, : , : [, , ]}, {: , : , : 28, : , : [, ]}, {: , : , : 18, : , : [, ]}, {: , : , : 12, : , : [, ]}], : [{: , : , : 269, : 297, : Signature\\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=\)\n0289: output_text: str = dspy.OutputField(desc=\)\n0290: \n0291: NewSig = MySig.with_instructions(\)\n0292: assert NewSig is not MySig\n0293: assert NewSig.instructions == \\n0294: ```\n0295: \\}, {: , : , : 215, : 221, : __doc__\\}, {: , : , : 554, : 565, : }, {: , : , : 465, : 509, : \\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: \\Trainset must be provided and non-empty\Teacher is not supported in DspyGEPA yet.\n\Either auto, max_full_evals, or max_metric_calls must be set.\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.\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.\}, {: , : , : 366, : 397, : GEPA metric must accept five arguments: (gold, pred, trace, pred_name, pred_trace). \See https://dspy.ai/api/optimizers/GEPA for details.\Exactly one of max_metric_calls, max_full_evals, auto must be set. \You set max_metric_calls={max_metric_calls}, \max_full_evals={max_full_evals}, \auto={auto}.\GEPA requires a reflection language model, or custom instruction proposer to be provided. \Typically, you can use `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)` to get a good reflection model. \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. \}, {: , : , : 598, : 604, : }]} |
| {: , : , : , : , : [{: , : , : 28, : , : []}, {: , : , : 26, : This trajectory got a score of {score}.\, : []}, {: , : , : 20, : , : []}, {: , : , : 18, : , : []}, {: , : , : 8, : , : []}], : [{: , : , : 27, : 35, : DSPyTrace\DSPyTrace\ScoreWithFeedback\}, {: , : , : 45, : 54, : This trajectory got a score of {score}.\\span_ids3pathdspy/predict/predict.pystart_lineend_lineexcerpt0143: config = {**self.config, **kwargs.pop(\, {})}\n0144: \n0145: # Get the right LM to use.\n0146: lm = kwargs.pop(\, self.lm) or settings.lm\n0147: span_ids4pathdspy/teleprompt/gepa/gepa.pystart_lineend_lineexcerpt0389: 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: \\n0394: \\n0395: \\n0396: )span_ids5pathdspy/primitives/example.pystart_lineend_lineexcerpt0223: def with_inputs(self, *keys):\n0224: \\}]} |
| {: , : , : , : , : [{: , : , : 35, : , : [, ]}, {: , : , : 20, : , : [, ]}, {: , : , : 25, : , : [, ]}, {: , : , : 10, : , : [, ]}, {: , : , : 10, : , : [, ]}], : [{: , : , : 392, : 398, : GEPA requires a reflection language model, or custom instruction proposer to be provided. \Typically, you can use `dspy.LM(model='gpt-5', temperature=1.0, max_tokens=32000)` to get a good reflection model. \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. \}, {: , : , : 104, : 118, : }, {: , : , : 120, : 134, : current_instruction_doc\dataset_with_feedback\new_instruction\}, {: , : , : 244, : 247, : }, {: , : , : 147, : 153, : role\user\content\Improve this instruction\Externally-improved: {candidate[name]}\}, {: , : , : 180, : 189, : }, {: , : , : 155, : 179, : text -> label\test input\test\text\label\test\label\result\label\output\label\response\label\classification\label\prediction\label\category\label\type\label\class\label\group\label\kind\label\variant\label\form\label\style\label\mode\}]} |
| {: , : , : light\, : light\medium\heavy\, : [{: , : , : 50, : , : [, , , ]}, {: , : , : 12, : , : []}, {: , : , : 20, : , : [, ]}, {: , : , : 10, : , : []}, {: , : , : 8, : , : [, ]}], : [{: , : , : 465, : 480, : \\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_ids2pathdspy/teleprompt/gepa/gepa.pystart_lineend_lineexcerpt0520: \n0521: def feedback_fn_creator(pred_name: str, predictor) -> \:\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: \,\n0528: ) -> \:\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, \):\n0538: if o[\] is None:\n0539: o[\] = f\\n0540: return o\n0541: else:\n0542: return dict(score=o, feedback=f\)\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_ids3pathdspy/teleprompt/gepa/gepa.pystart_lineend_lineexcerpt0019: AUTO_RUN_SETTINGS = {\n0020: \: {\: 6},\n0021: \: {\: 12},\n0022: \: {\: 18},\n0023: }span_ids4pathdspy/teleprompt/gepa/gepa.pystart_lineend_lineexcerpt0431: 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(\)\n0439: if full_eval_steps < 1:\n0440: raise ValueError(\)\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 totalspan_ids5pathtests/teleprompt/test_gepa.pystart_lineend_lineexcerpt0046: @pytest.mark.parametrize(\, [\n0047: (None, [], {\: \}),\n0048: (None, [Example(input=\, output=\)], {\: \}),\n0049: (1, [], {\: True}),\n0050: (1, [\n0051: Example(input=\, output=\),\n0052: Example(input=\, output=\),\n0053: ], {\: \}),\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(\),\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, \, dummy_bootstrap_trace_data)\n0079: monkeypatch.setattr(\n0080: gepa_utils.DspyAdapter,\n0081: \,\n0082: lambda self, candidate: DummyModule(),\n0083: )\n0084: \n0085: adapter.evaluate(batch=batch, candidate={}, capture_traces=True)\n0086: \n0087: assert captured_kwargs[\] == expected_callback_metadata\n0088: span_ids6pathdspy/primitives/module.pystart_lineend_lineexcerpt0160: def predictors(self):\n0161: \\question -> answer\\\n0177: return [param for _, param in self.named_predictors()]span_ids7pathdspy/teleprompt/gepa/gepa.pystart_lineend_lineexcerpt0489: 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][\],\n0493: valset_size=len(valset) if valset is not None else len(trainset),\n0494: ) |
| iddspy_064741a8777ftopicprompt_optimization_workflowsquestionI'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 \ 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 \\n \\n )\n program = dspy.Predict(dspy.Signature(\).with_instructions(seed_instruction))\n\n dataset = [\n dspy.Example(ticket=\, label=\).with_inputs(\),\n dspy.Example(ticket=\, label=\).with_inputs(\),\n dspy.Example(ticket=\, label=\).with_inputs(\),\n dspy.Example(ticket=\, label=\).with_inputs(\),\n dspy.Example(ticket=\, label=\).with_inputs(\),\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(\, cache=False)\n prompt_lm = dspy.LM(\, 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=\,\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```rubricclaim_idc1claim_typecoreweightstatementThe 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_idss2claim_idc3claim_typecoreweightstatementThe 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_idss3s4claim_idc4claim_typecoreweightstatementThe 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_idss6evidencespan_ids1pathdspy/signatures/signature.pystart_lineend_lineexcerpt0269: @classmethod\n0270: def with_instructions(cls, instructions: str) -> type[\]:\n0271: \\Input text\Output text\Translate to French.\Translate to French.\\\n0296: return Signature(cls.fields, instructions)\n0297: span_ids2pathdspy/teleprompt/mipro_optimizer_v2.pystart_lineend_lineexcerpt0111: 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_ids3pathdspy/teleprompt/mipro_optimizer_v2.pystart_lineend_lineexcerpt0145: 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_ids4pathdspy/teleprompt/mipro_optimizer_v2.pystart_lineend_lineexcerpt0257: # If zero-shot, discard demos\n0258: if zeroshot_opt:\n0259: demo_candidates = None\n0260: span_ids5pathdspy/predict/predict.pystart_lineend_lineexcerpt0058: 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_ids6pathdspy/predict/predict.pystart_lineend_lineexcerpt0088: state[\] = self.signature.dump_state()\n0089: state[\] = self.lm.dump_state() if self.lm else None\n0090: return state |
| iddspy_9f98ea7f1ef5topicprompt_optimization_workflowsquestionI'm building a customer-support classifier in DSPy. There's a fixed policy block of musts/nevers (e.g. \) 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_idss5s6claim_idc4claim_typesupportingweightstatementFinal scoring is performed on a separate held-out split via dspy.Evaluate(devset=<heldout>, 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_idss9evidencespan_ids1pathdspy/signatures/signature.pystart_lineend_lineexcerpt0193: # 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 \ not in field.json_schema_extra:\n0199: field.json_schema_extra[\] = infer_prefix(name) + \\n0200: if \ not in field.json_schema_extra:\n0201: field.json_schema_extra[\] = f\\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(\)\n0209: if field_type not in [\, \]:\n0210: raise TypeError(\n0211: f\\n0212: f\,\n0213: )\n0214: \n0215: @property\n0216: def instructions(cls) -> str:\n0217: return inspect.cleandoc(getattr(cls, \, \))\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(\)\n0226: \n0227: @property\n0228: def output_fields(cls) -> dict[str, FieldInfo]:\n0229: return cls._get_fields_with_type(\)\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: \\\\n0239: input_fields = \.join(cls.input_fields.keys())\n0240: output_fields = \.join(cls.output_fields.keys())\n0241: return f\\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[\] == field_type}\n0245: span_ids2pathdspy/teleprompt/mipro_optimizer_v2.pystart_lineend_lineexcerpt0754: 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: \,\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\, 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\] = instruction_idx\n0775: chosen_params.append(f\)\n0776: raw_chosen_params[f\] = instruction_idx\n0777: # Select demos if available\n0778: if demo_candidates:\n0779: demos_idx = trial.suggest_categorical(f\, range(len(demo_candidates[i])))\n0780: predictor.demos = demo_candidates[i][demos_idx]\n0781: trial_logs[trial_num][f\] = demos_idx\n0782: chosen_params.append(f\)\n0783: raw_chosen_params[f\] = instruction_idx\n0784: \n0785: return chosen_params, raw_chosen_paramsspan_ids3pathdspy/primitives/module.pystart_lineend_lineexcerpt0040: class Module(BaseModule, metaclass=ProgramMeta):\n0041: \\question -> answer\\span_ids4pathdspy/primitives/module.pystart_lineend_lineexcerpt0093: @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(\) 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_ids5pathdspy/signatures/signature.pystart_lineend_lineexcerpt0269: @classmethod\n0270: def with_instructions(cls, instructions: str) -> type[\]:\n0271: \\Input text\Output text\Translate to French.\Translate to French.\\\n0296: return Signature(cls.fields, instructions)\n0297: span_ids6pathdspy/teleprompt/mipro_optimizer_v2.pystart_lineend_lineexcerpt0766: for i, predictor in enumerate(candidate_program.predictors()):\n0767: # Select instruction\n0768: instruction_idx = trial.suggest_categorical(\n0769: f\, 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\] = instruction_idxspan_ids7pathdspy/teleprompt/mipro_optimizer_v2.pystart_lineend_lineexcerpt0110: 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: \\n0135: )\n0136: elif requires_permission_to_run == True:\n0137: raise ValueError(\)\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\\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(\)\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: \\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_ids8pathdspy/teleprompt/mipro_optimizer_v2.pystart_lineend_lineexcerpt0145: 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_ids9pathdspy/evaluate/evaluate.pystart_lineend_lineexcerpt0064: class Evaluate:\n0065: \\\\n0070: \n0071: def __init__(\n0072: self,\n0073: *,\n0074: devset: list[\],\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: \\\\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 \ in kwargs:\n0114: raise ValueError(\)\n0115: \n0116: @with_callbacks\n0117: def __call__(\n0118: self,\n0119: program: \,\n0120: metric: Callable | None = None,\n0121: devset: list[\] | 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: |
| iddspy_962f53473587topicprompt_optimization_workflowsquestionI 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_idss8s9evidencespan_ids1pathtests/teleprompt/test_gepa.pystart_lineend_lineexcerpt0271: class MultiComponentModule(dspy.Module):\n0272: \\\\n0273: \n0274: def __init__(self):\n0275: super().__init__()\n0276: self.classifier = Predict(\)\n0277: self.generator = Predict(\)\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_ids2pathdspy/primitives/module.pystart_lineend_lineexcerpt0131: def named_predictors(self):\n0132: \\question -> answer\text -> summary\\\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_ids3pathdspy/teleprompt/gepa/gepa.pystart_lineend_lineexcerpt0465: 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: \\\\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, \\n0487: assert teacher is None, \\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][\],\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, \\n0499: \n0500: logger.info(\n0501: f\\n0502: )\n0503: \n0504: if valset is None:\n0505: logger.warning(\n0506: \\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\\n0515: )\n0516: else:\n0517: logger.info(f\)\n0518: \n0519: rng = random.Random(self.seed)\n0520: \n0521: def feedback_fn_creator(pred_name: str, predictor) -> \:\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: \,\n0528: ) -> \:\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, \):\n0538: if o[\] is None:\n0539: o[\] = f\\n0540: return o\n0541: else:\n0542: return dict(score=o, feedback=f\)\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_ids4pathtests/teleprompt/test_gepa.pystart_lineend_lineexcerpt0099: def test_basic_workflow(use_mlflow, mock_mlflow):\n0100: \\\\n0101: student = SimpleModule(\)\n0102: \n0103: with open(\) as f:\n0104: data = json.load(f)\n0105: lm_history = data[\]\n0106: reflection_lm_history = data[\]\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=\, output=\).with_inputs(\),\n0122: Example(input=\, output=\).with_inputs(\),\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_ids5pathdspy/teleprompt/gepa/gepa.pystart_lineend_lineexcerpt0330: def __init__(\n0331: self,\n0332: metric: GEPAFeedbackMetric,\n0333: *,\n0334: # Budget configuration\n0335: auto: Literal[\, \, \] | 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[\, \] = \,\n0341: reflection_lm: LM | None = None,\n0342: skip_perfect_score: bool = True,\n0343: add_format_failure_as_feedback: bool = False,\n0344: instruction_proposer: \ = None,\n0345: component_selector: \ = \,\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: \\n0372: \\n0373: ) from espan_ids6pathdspy/teleprompt/gepa/gepa.pystart_lineend_lineexcerpt0027: class GEPAFeedbackMetric(Protocol):\n0028: def __call__(\n0029: self,\n0030: gold: Example,\n0031: pred: Prediction,\n0032: trace: Optional[\],\n0033: pred_name: str | None,\n0034: pred_trace: Optional[\],\n0035: ) -> Union[float, \]:\n0036: \\This trajectory got a score of {score}.\\\n0055: ...span_ids7pathtests/teleprompt/test_gepa.pystart_lineend_lineexcerpt0038: def simple_metric(example, prediction, trace=None, pred_name=None, pred_trace=None):\n0039: return dspy.Prediction(score=example.output == prediction.output, feedback=\)\n0040: \n0041: \n0042: def bad_metric(example, prediction):\n0043: return 0.0span_ids8pathdspy/primitives/module.pystart_lineend_lineexcerpt0131: def named_predictors(self):\n0132: \\question -> answer\text -> summary\\\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_ids9pathdspy/teleprompt/gepa/gepa.pystart_lineend_lineexcerpt0563: # 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: |
| iddspy_81c16cac1a88topicprompt_optimization_workflowsquestionI'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(<module instance>, 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_ids3pathtests/examples/test_baleen.pystart_lineend_lineexcerpt0025: 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_ids4pathdspy/utils/dummies.pystart_lineend_lineexcerpt0157: def dummy_rm(passages=()) -> callable:\n0158: if not passages:\n0159: \n0160: def inner(query: str, *, k: int, **kwargs):\n0161: raise ValueError(\)\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 innerspan_ids5pathtests/examples/test_baleen.pystart_lineend_lineexcerpt0103: 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_ids6pathtests/examples/test_baleen.pystart_lineend_lineexcerpt0112: 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 |
| iddspy_898cf1643d8atopicprompt_optimization_workflowsquestionI'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=\)\nbest_answer = result.answer\n```rubricclaim_idc1claim_typecoreweightstatementThe 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_idss1s2claim_idc2claim_typecoreweightstatementThe 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_idss3s2claim_idc4claim_typesupportingweightstatementA 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_idss5evidencespan_ids1pathdspy/predict/refine.pystart_lineend_lineexcerpt0041: 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: \\}, {: , : , : 31, : 39, : question -> answer\What is the capital of Belgium?\}, {: , : , : 87, : 89, : }, {: , : , : 115, : 167, : hint_\N/A\hint_\A hint to the module from an earlier run\program_code\modules_defn\module_name\inputs\outputs\program_inputs\program_trajectory\program_outputs\reward_code\target_threshold\reward_value\}, {: , : , : 137, : 145, : }]} |
| {: , : , : , : , : [{: , : , : 40, : , : [, ]}, {: , : , : 20, : , : [, ]}, {: , : , : 20, : , : []}, {: , : , : 12, : , : []}, {: , : , : 8, : , : []}], : [{: , : , : 6, : 19, : \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 \ and \.span_ids2pathtests/predict/test_predict.pystart_lineend_lineexcerpt0683: @pytest.mark.parametrize(\, [\, \])\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, \: messages, \: kwargs})\n0693: if self.return_json:\n0694: return [\]\n0695: return [\]\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 == \:\n0705: lm = SpyLM(\)\n0706: dspy.configure(adapter=dspy.ChatAdapter(), lm=lm)\n0707: else:\n0708: lm = SpyLM(\, return_json=True)\n0709: dspy.configure(adapter=dspy.JSONAdapter(), lm=lm)\n0710: \n0711: program(\n0712: question=\,\n0713: history=dspy.History(messages=[{\: \, \: \}]),\n0714: )\n0715: \n0716: # Verify the LM was called with correct messages\n0717: assert len(lm.calls) == 1\n0718: messages = lm.calls[0][\]\n0719: \n0720: assert len(messages) == 4\n0721: \n0722: assert \ in messages[1][\]\n0723: assert \ in messages[2][\]\n0724: assert \ in messages[3][\]\n0725: span_ids3pathdspy/predict/react.pystart_lineend_lineexcerpt0016: class ReAct(Module):\n0017: def __init__(self, signature: type[\], tools: list[Callable], max_iters: int = 20):\n0018: \\Reasoning and Acting,\}, {: , : , : 73, : 88, : \\n\trajectory\next_thought\next_tool_name\next_tool_args\trajectory\}]} |
| {: , : , : pick cheapest\, : , : [{: , : , : 28, : , : [, , ]}, {: , : , : 32, : , : [, , ]}, {: , : , : 15, : , : [, ]}, {: , : , : 10, : , : []}, {: , : , : 10, : , : []}, {: , : , : 5, : , : [, ]}], : [{: , : , : 16, : 18, : Signature\\span_ids3pathdspy/adapters/types/tool.pystart_lineend_lineexcerpt0095: # 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_values[k]\n0110: if arg_desc and k in arg_desc:\n0111: args[k][\] = 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\)\n0127: try:\n0128: instance = v.model_dump() if hasattr(v, \) else v\n0129: type_str = self.args[k].get(\)\n0130: if type_str is not None and type_str != \:\n0131: validate(instance=instance, schema=self.args[k])\n0132: except ValidationError as e:\n0133: raise ValueError(f\)\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(\, value=(self.arg_types[k], ...))\n0142: parsed = pydantic_wrapper.model_validate({\: v})\n0143: parsed_kwargs[k] = parsed.value\n0144: else:\n0145: parsed_kwargs[k] = v\n0146: return parsed_kwargsspan_ids4pathtests/predict/test_react.pystart_lineend_lineexcerpt0058: 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\\n0068: \n0069: class InvitationSignature(dspy.Signature):\n0070: participant_name: str = dspy.InputField(desc=\)\n0071: event_info: CalendarEvent = dspy.InputField(desc=\)\n0072: invitation_letter: str = dspy.OutputField(desc=\)\n0073: \n0074: react = dspy.ReAct(InvitationSignature, tools=[write_invitation_letter])\n0075: \n0076: lm = DummyLM(\n0077: [\n0078: {\n0079: \: \,\n0080: \: \,\n0081: \: {\n0082: \: \,\n0083: \: {\n0084: \: \,\n0085: \: \,\n0086: \: {\: \, \: \},\n0087: },\n0088: },\n0089: },\n0090: {\n0091: \: (\n0092: \\n0093: \\n0094: ),\n0095: \: \,\n0096: \: {},\n0097: },\n0098: {\n0099: \: \,\n0100: \: \,\n0101: },\n0102: ]\n0103: )\n0104: dspy.configure(lm=lm)\n0105: \n0106: outputs = react(\n0107: participant_name=\,\n0108: event_info=CalendarEvent(\n0109: name=\,\n0110: date=\,\n0111: participants={\: \, \: \},\n0112: ),\n0113: )\n0114: assert outputs.invitation_letter == \span_ids5pathdspy/predict/react.pystart_lineend_lineexcerpt0044: 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\ for k in signature.input_fields.keys()])\n0048: outputs = \.join([f\ for k in signature.output_fields.keys()])\n0049: instr = [f\] if signature.instructions else []\n0050: \n0051: instr.extend(\n0052: [\n0053: f\,\n0054: f\,\n0055: \,\n0056: \,\n0057: \,\n0058: \,\n0059: ]\n0060: )\n0061: \n0062: tools[\] = Tool(\n0063: func=lambda: \,\n0064: name=\,\n0065: desc=f\,\n0066: args={},\n0067: )\n0068: \n0069: for idx, tool in enumerate(tools.values()):\n0070: instr.append(f\)\n0071: instr.append(\)\n0072: \n0073: react_signature = (\n0074: dspy.Signature({**signature.input_fields}, \.join(instr))\n0075: .append(\, dspy.InputField(), type_=str)\n0076: .append(\, dspy.OutputField(), type_=str)\n0077: .append(\, dspy.OutputField(), type_=Literal[tuple(tools.keys())])\n0078: .append(\, 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(\, dspy.InputField(), type_=str)\n0085: \n0086: self.tools = tools\n0087: self.react = dspy.Predict(react_signature)\n0088: self.extract = dspy.ChainOfThought(fallback_signature)span_ids6pathtests/predict/test_react.pystart_lineend_lineexcerpt0116: expected_trajectory = {\n0117: \: \,\n0118: \: \,\n0119: \: {\n0120: \: \,\n0121: \: {\n0122: \: \,\n0123: \: \,\n0124: \: {\: \, \: \},\n0125: },\n0126: },\n0127: \: \,\n0128: \: \,\n0129: \: \,\n0130: \: {},\n0131: \: \,\n0132: }\n0133: assert outputs.trajectory == expected_trajectory |
| iddspy_a5b116f00083topicreact_agents_and_toolsquestionI'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: \\}, {: , : , : 40, : 79, : \Common call logic to be used for both sync and async calls.\\response_format\response_format\type\json_object\response_format\Failed to use structured output format, falling back to JSON mode.\response_format\type\json_object\}, {: , : , : 212, : 240, : \\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 \ response_format.\n0224: \\Field '{name}' has an open-ended mapping type which is not supported by Structured Outputs.\default\}, {: , : , : 262, : 319, : type\function\function\name\arguments\\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: {\: 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\)\n0314: \n0315: try:\n0316: args = self.args or {}\n0317: return func(**args)\n0318: except Exception as e:\n0319: raise RuntimeError(f\) from espan_ids7pathdspy/adapters/types/tool.pystart_lineend_lineexcerpt0321: tool_calls: list[ToolCall]\n0322: \n0323: @classmethod\n0324: def from_dict_list(cls, tool_calls_dicts: list[dict[str, Any]]) -> \:\n0325: \\name\search\args\query\hello\name\translate\args\text\world\\\n0343: tool_calls = [cls.ToolCall(**item) for item in tool_calls_dicts]\n0344: return cls(tool_calls=tool_calls)\n0345: |
| iddspy_e175093485fdtopicreact_agents_and_toolsquestionI'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_idss2s3claim_idc2claim_typecoreweightstatementThe 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_idss2s3claim_idc4claim_typesupportingweightstatementPlain 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_idss1s5evidencespan_ids1pathdspy/primitives/module.pystart_lineend_lineexcerpt0040: class Module(BaseModule, metaclass=ProgramMeta):\n0041: \\}, {: , : , : 16, : 89, : Signature\\\n0019: ReAct stands for \ 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\\n0035: \n0036: react = dspy.ReAct(signature=\, tools=[get_weather])\n0037: pred = react(question=\)\n0038: ```\n0039: \\, \`{k}`\, \`{k}`\{signature.instructions}\\n\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.\Your goal is to use one or more of the supplied tools to collect any necessary information for producing {outputs}.\\n\To do this, you will interleave next_thought, next_tool_name, and next_tool_args in each turn, and also when finishing the task.\After each tool call, you receive a resulting observation, which gets appended to your trajectory.\\n\When writing next_thought, you may reason about the current situation and plan for future steps.\When selecting the next_tool_name and its next_tool_args, the tool must be one of:\\n\finish\Completed.\finish\Marks the task as complete. That is, signals that all information for producing the outputs, i.e. {outputs}, are now available to be extracted.\({idx + 1}) {tool}\When providing `next_tool_args`, the value inside the field must be in JSON format\\\n\trajectory\next_thought\next_tool_name\next_tool_args\trajectory\}, {: , : , : 95, : 118, : max_iters\Ending the trajectory: Agent failed to select a valid tool: {_fmt_exc(err)}\thought_{idx}\tool_name_{idx}\tool_args_{idx}\observation_{idx}\observation_{idx}\Execution error in {pred.next_tool_name}: {_fmt_exc(err)}\finish\}, {: , : , : 75, : 117, : \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: \\__name__\__doc__\__doc__\\return\default\description\}, {: , : , : 93, : 110, : usage_tracker\}]} |
| {: , : , : find the brass key and pick it up\state -> next_action\ask\move\, : , : [{: , : , : 45, : , : [, ]}, {: , : , : 20, : , : [, ]}, {: , : , : 15, : , : [, ]}, {: , : , : 10, : , : [, ]}, {: , : , : 10, : , : [, ]}], : [{: , : , : 16, : 18, : Signature\\span_ids2pathdspy/predict/react.pystart_lineend_lineexcerpt0095: def forward(self, **input_args):\n0096: trajectory = {}\n0097: max_iters = input_args.pop(\, 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\)\n0103: break\n0104: \n0105: trajectory[f\] = pred.next_thought\n0106: trajectory[f\] = pred.next_tool_name\n0107: trajectory[f\] = pred.next_tool_args\n0108: \n0109: try:\n0110: trajectory[f\] = self.tools[pred.next_tool_name](**pred.next_tool_args)\n0111: except Exception as err:\n0112: trajectory[f\] = f\\n0113: \n0114: if pred.next_tool_name == \:\n0115: break\n0116: \n0117: extract = self._call_with_potential_trajectory_truncation(self.extract, trajectory, **input_args)\n0118: return dspy.Prediction(trajectory=trajectory, **extract)span_ids3pathdspy/adapters/types/tool.pystart_lineend_lineexcerpt0035: 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: \\hello\\\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_ids4pathtests/predict/test_react.pystart_lineend_lineexcerpt0058: 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\\n0068: \n0069: class InvitationSignature(dspy.Signature):\n0070: participant_name: str = dspy.InputField(desc=\)\n0071: event_info: CalendarEvent = dspy.InputField(desc=\)\n0072: invitation_letter: str = dspy.OutputField(desc=\)\n0073: \n0074: react = dspy.ReAct(InvitationSignature, tools=[write_invitation_letter])\n0075: \n0076: lm = DummyLM(\n0077: [\n0078: {\n0079: \: \,\n0080: \: \,\n0081: \: {\n0082: \: \,\n0083: \: {\n0084: \: \,\n0085: \: \,\n0086: \: {\: \, \: \},\n0087: },\n0088: },\n0089: },\n0090: {\n0091: \: (\n0092: \\n0093: \\n0094: ),\n0095: \: \,\n0096: \: {},\n0097: },\n0098: {\n0099: \: \,\n0100: \: \,\n0101: },\n0102: ]\n0103: )\n0104: dspy.configure(lm=lm)\n0105: \n0106: outputs = react(\n0107: participant_name=\,\n0108: event_info=CalendarEvent(\n0109: name=\,\n0110: date=\,\n0111: participants={\: \, \: \},\n0112: ),\n0113: )\n0114: assert outputs.invitation_letter == \ |
| iddspy_188039f2a0d6topicrag_and_retrieval_pipelinesquestionOur 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(\)` 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_idss1s2s3claim_idc2claim_typecoreweightstatementIn 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_idss4s5claim_idc3claim_typesupportingweightstatementUses 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_idss6s7s8claim_idc4claim_typesupportingweightstatementFor 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_idss9evidencespan_ids1pathdspy/retrievers/embeddings.pystart_lineend_lineexcerpt0018: 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, \\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_ids2pathtests/retrievers/test_embeddings.pystart_lineend_lineexcerpt0078: 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, \)\n0086: \n0087: # Save original\n0088: original_retriever.save(save_path)span_ids3pathdspy/retrievers/embeddings.pystart_lineend_lineexcerpt0111: def save(self, path: str):\n0112: \\\\n0121: os.makedirs(path, exist_ok=True)\n0122: \n0123: # Save configuration and corpus\n0124: config = {\n0125: \: self.k,\n0126: \: self.normalize,\n0127: \: self.corpus,\n0128: \: self.index is not None,\n0129: }\n0130: \n0131: with open(os.path.join(path, \), \) as f:\n0132: json.dump(config, f, indent=2)\n0133: \n0134: # Save embeddings\n0135: np.save(os.path.join(path, \), 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, \))\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: \\Save directory not found: {path}\config.json\corpus_embeddings.npy\Config file not found: {config_path}\Embeddings file not found: {embeddings_path}\k\normalize\corpus\has_faiss_index\Invalid config: missing required field '{field}'\k\normalize\corpus\faiss_index.bin\has_faiss_index\\\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(\)\n0226: \n0227: # Load embeddings later\n0228: loaded_embeddings = Embeddings.from_saved(\, embedder)\n0229: ```\n0230: \\}, {: , : , : 114, : 135, : test_embeddings\/nonexistent/path\}, {: , : , : 40, : 49, : \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_ids7pathdspy/primitives/module.pystart_lineend_lineexcerpt0093: @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(\) 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_ids8pathdspy/predict/chain_of_thought.pystart_lineend_lineexcerpt0012: 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: \\\\n0029: super().__init__()\n0030: signature = ensure_signature(signature)\n0031: desc = \\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=\, 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_ids9pathdspy/utils/dummies.pystart_lineend_lineexcerpt0179: class DummyVectorizer:\n0180: \\\\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: \\\\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 |
| iddspy_0ab31a81ea0btopicrag_and_retrieval_pipelinesquestionI 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 \ 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```rubricclaim_idc1claim_typecoreweightstatementRegisters 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_idss1claim_idc4claim_typecoreweightstatementThe 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_idss3claim_idc5claim_typesupportingweightstatementAnswers 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_idss4s1evidencespan_ids1pathdspy/retrievers/retrieve.pystart_lineend_lineexcerpt0043: 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(\)\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.\The incident handbook names platform reliability as the escalation owner.\openai/gpt-4o-mini\Who owns the status page for the vendor mentioned in the outage memo?\, : [{: , : , : 50, : , : [, , ]}, {: , : , : 22, : , : [, ]}, {: , : , : 10, : , : [, ]}, {: , : , : 10, : , : [, ]}, {: , : , : 8, : , : [, ]}], : [{: , : , : 25, : 43, : }, {: , : , : 29, : 40, : }, {: , : , : 43, : 65, : No RM is loaded.\}, {: , : , : 72, : 79, : \\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: \\}, {: , : , : 12, : 38, : \\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: \\${reasoning}\reasoning\}, {: , : , : 41, : 56, : \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: \\}]} |
| {: , : , : correct and grounded in the passages.\, : , : [{: , : , : 45, : , : [, , ]}, {: , : , : 25, : , : [, ]}, {: , : , : 5, : , : [, ]}, {: , : , : 15, : , : [, ]}, {: , : , : 10, : , : [, ]}], : [{: , : , : 41, : 56, : \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: \\}, {: , : , : 25, : 43, : }, {: , : , : 285, : 348, : \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_idss1s2s3claim_idc2claim_typecoreweightstatementA 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('\', 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 = '{\: \, \: 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('{\: \}', 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=\)]` (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_idss1s3claim_idc3claim_typesupportingweightstatementThe 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_idss4s5claim_idc4claim_typesupportingweightstatementEach per-kind subtype constrains its `kind` discriminator with an Enum/Literal value (e.g. `kind: Literal[\]` 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 \"\\\"'\{value!r} is not one of {allowed!r}\\\\}, {: , : , : 46, : 62, : module\Color\RED\GREEN\BLUE\The sky is blue.\The sky is blue\The sky is blue.\}, {: , : , : 110, : 190, : module\get_docs\finish\search_policy\notify_manager\calculate_accrual\combine_leave\review_seniority_rules\fetch_calendar\verify_compensation\check_carryover_policy\\\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: \\get_docs\finish\search_policy\notify_manager\calculate_accrual\combine_leave\review_seniority_rules\fetch_calendar\verify_compensation\check_carryover_policy\success\error\pending\informational\transactional\exploratory\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, \, \)\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 \ not in field.json_schema_extra:\n0199: field.json_schema_extra[\] = infer_prefix(name) + \\n0200: if \ not in field.json_schema_extra:\n0201: field.json_schema_extra[\] = f\\n0202: \n0203: return clsspan_ids5pathtests/reliability/test_pydantic_models.pystart_lineend_lineexcerpt0010: @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=\\n0016: )\n0017: comments: list[str] = pydantic.Field(\n0018: description=\\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 = \\n0027: answer = program(question=question).answer\n0028: \n0029: assert_program_output_correct(\n0030: program_input=question,\n0031: program_output=answer.value,\n0032: grading_guidelines=\,\n0033: )\n0034: assert_program_output_correct(\n0035: program_input=question,\n0036: program_output=answer.comments,\n0037: grading_guidelines=(\n0038: \\n0039: ),\n0040: )\n0041: assert answer.certainty >= 0\n0042: assert answer.certainty <= 1\n0043: assert len(answer.comments) >= 2\n0044: |
| iddspy_d6683c54b609topicsignature_schema_and_pydantic_typesquestionI 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 `\`, 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 \ 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 \\\\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 \: \,\n \: None,\n \: [\],\n \: None,\n \: [{\: \, \: \}],\n }\n ],\n adapter=adapter,\n ),\n adapter=adapter,\n)\n\nhistory = dspy.History(\n messages=[\n {\n \: \,\n \: \,\n \: None,\n \: None,\n \: [\],\n \: None,\n }\n ]\n)\n\npred = dspy.Predict(ExtractIntent)(\n question=\,\n history=history,\n)\n\nassert pred.secondary_intents is None\nassert pred.unresolved_terms is None\nassert pred.clarification_needed == [\]\nassert pred.resolved_terms[0].meaning == \\n```rubricclaim_idc1claim_typecoreweightstatementAbsent 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_idss5claim_idc2claim_typecoreweightstatementAt 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_idss6claim_idc3claim_typesupportingweightstatementThe 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 \: \\\n}'\n0534: assert messages[3][\"content\"] == \"[[ ## question ## ]]\\nWhat is the capital of Germany?\"\n0535: assert messages[4][\"content\"] == '{\\n \: \\\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(\)\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 \,\n \,\n custom_types={\: Query, \: 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 {\: \},\n {\: {\: \, \: 0.93}},\n ],\n adapter=adapter,\n ),\n adapter=adapter,\n)\n\nmodule = InlineTypedModule()\npred = module(text=\)\n\nassert pred.summary == \\nassert pred.verdict.label == \\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_idss1s2claim_idc3claim_typecoreweightstatementWithin 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(\, 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_ids2pathtests/signatures/test_custom_types.pystart_lineend_lineexcerpt0066: def test_recommended_patterns():\n0067: \\\\n0068: \n0069: # PATTERN 1: Local type with auto-resolution\n0070: class LocalType(pydantic.BaseModel):\n0071: value: str\n0072: \n0073: sig1 = Signature(\)\n0074: assert sig1.output_fields[\].annotation == LocalType\n0075: span_ids3pathdspy/signatures/signature.pystart_lineend_lineexcerpt0521: def make_signature(\n0522: signature: str | dict[str, tuple[type, FieldInfo]],\n0523: instructions: str | None = None,\n0524: signature_name: str = \,\n0525: custom_types: dict[str, type] | None = None,\n0526: ) -> type[Signature]:\n0527: \\input1, input2 -> output1, output2\StringSignature\question, context -> answer\question\answer\input: MyType -> output\MyType\\\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 signaturespan_ids4pathtests/signatures/test_custom_types.pystart_lineend_lineexcerpt0026: def test_type_alias_for_nested_types():\n0027: \\\\n0028: class Container:\n0029: class NestedType(pydantic.BaseModel):\n0030: value: str\n0031: \n0032: NestedType = Container.NestedType\n0033: alias_sig = Signature(\)\n0034: assert alias_sig.output_fields[\].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(\)\n0043: assert signature.output_fields[\].annotation == Container2.Score\n0044: span_ids5pathtests/signatures/test_custom_types.pystart_lineend_lineexcerpt0098: def test_module_type_resolution():\n0099: class TestModule(dspy.Module):\n0100: def __init__(self):\n0101: super().__init__()\n0102: self.predict = dspy.Predict(\)\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[\].annotation == OuterContainer.InnerTypespan_ids6pathtests/signatures/test_signature.pystart_lineend_lineexcerpt0414: def test_basic_custom_type():\n0415: class CustomType(pydantic.BaseModel):\n0416: value: str\n0417: \n0418: test_signature = dspy.Signature(\n0419: \,\n0420: custom_types={\: CustomType}\n0421: )\n0422: \n0423: assert test_signature.input_fields[\].annotation == CustomType\n0424: \n0425: lm = DummyLM([{\: \}])\n0426: dspy.configure(lm=lm)\n0427: \n0428: custom_obj = CustomType(value=\)\n0429: pred = dspy.Predict(test_signature)(input=custom_obj)\n0430: assert pred.output == \span_ids7pathdspy/signatures/signature.pystart_lineend_lineexcerpt0633: def _parse_field_string(field_string: str, names=None) -> Iterator[tuple[str, type, bool]]:\n0634: \\x: int, y: str\x: int, y: str\x\y\\\n0640: \n0641: args = ast.parse(f\).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: \\x: list[int] -> y: str\x: int\x: list[str]\x: Optional[int]\x: MyModule.CustomType\\\n0675: \n0676: if names is None:\n0677: names = dict(typing.__dict__)\n0678: names[\] = 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\)\n0703: \n0704: if isinstance(node, ast.Module):\n0705: if len(node.body) != 1:\n0706: raise ValueError(f\)\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\\n0724: if full_name in names:\n0725: return names[full_name]\n0726: \n0727: raise ValueError(f\) |
| iddspy_ad7223e585batopicsignature_schema_and_pydantic_typesquestionI 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. \, \) that the snapshot does not actually emit, does not satisfy this claim.span_idss4s5claim_idc4claim_typesupportingweightstatementThe 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 \ if no dspy \ is given.\n0053: if \ in kwargs and \ not in json_schema_extra:\n0054: json_schema_extra[\] = kwargs[\]\n0055: constraints = _translate_pydantic_field_constraints(**kwargs)\n0056: if constraints:\n0057: json_schema_extra[\] = constraints\n0058: pydantic_kwargs[\] = json_schema_extraspan_ids5pathdspy/adapters/chat_adapter.pystart_lineend_lineexcerpt0111: def format_field_description(self, signature: type[Signature]) -> str:\n0112: return (\n0113: f\\n0114: f\\n0115: )span_ids6pathdspy/adapters/json_adapter.pystart_lineend_lineexcerpt0104: def format_field_structure(self, signature: type[Signature]) -> str:\n0105: parts = []\n0106: parts.append(\)\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(\)\n0118: parts.append(format_signature_fields_for_instructions(signature.input_fields, role=\))\n0119: parts.append(\)\n0120: parts.append(format_signature_fields_for_instructions(signature.output_fields, role=\))\n0121: return \.join(parts).strip()\n0122: \n0123: def user_message_output_requirements(self, signature: type[Signature]) -> str:\n0124: def type_info(v):\n0125: return (\n0126: f\\n0127: if v.annotation is not str\n0128: else \\n0129: )\n0130: \n0131: message = \\n0132: message += \.join(f\ for f, v in signature.output_fields.items())\n0133: message += \\n0134: return messagespan_ids7pathdspy/adapters/chat_adapter.pystart_lineend_lineexcerpt0144: 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\)\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 \.join(messages).strip()\n0166: \n0167: def user_message_output_requirements(self, signature: type[Signature]) -> str:\n0168: \\\\n0184: \n0185: def type_info(v):\n0186: if v.annotation is not str:\n0187: return f\\n0188: else:\n0189: return \\n0190: \n0191: message = \\n0192: message += \.join(f\ for f, v in signature.output_fields.items())\n0193: message += \\n0194: return messagespan_ids8pathdspy/adapters/json_adapter.pystart_lineend_lineexcerpt0212: def _get_structured_outputs_response_format(\n0213: signature: SignatureMeta,\n0214: use_native_function_calling: bool = True,\n0215: ) -> type[pydantic.BaseModel]:\n0216: \\required\json_object\\\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: |
| iddspy_2980c79329e9topicevaluation_metrics_and_custom_evalquestionI'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```rubricclaim_idc1claim_typecoreweightstatementThe 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_idss1s2claim_idc2claim_typecoreweightstatementBecause `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: \\fraction (out of 1.0) of ground truth covered by the system response\fraction (out of 1.0) of system response covered by the ground truth\}, {: , : , : 7, : 33, : reasoning\reasoning\Comparing the responses\precision\recall\What is 1+1?\2\2\score\}, {: , : , : 62, : 86, : reasoning\Comparing the responses\precision\recall\test\answer\response\}, {: , : , : 48, : 61, : \\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: \\dspy.Example\dspy.Example\EvaluationResult(score={self.score}, results=<list of {len(self.results)} results>)\}, {: , : , : 170, : 225, : Average Metric: {ncorrect} / {ntotal} ({round(100 * ncorrect / ntotal, 1)}%)\pandas\Skipping table display since `pandas` is not installed.\w\\w\}]} |
| {: , : , : unsupported operand type(s) for +: 'int' and 'dict'\, : , : [{: , : , : 35, : , : []}, {: , : , : 25, : , : [, ]}, {: , : , : 25, : , : [, ]}, {: , : , : 15, : , : []}], : [{: , : , : 4, : 16, : \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: \\}, {: , : , : 205, : 210, : }, {: , : , : 170, : 225, : Average Metric: {ncorrect} / {ntotal} ({round(100 * ncorrect / ntotal, 1)}%)\pandas\Skipping table display since `pandas` is not installed.\w\\w\}]} |
| {: , : , : , : some tool was called\, : [{: , : , : 70, : , : [, , ]}, {: , : , : 10, : , : [, ]}, {: , : , : 12, : , : []}, {: , : , : 8, : , : []}], : [{: , : , : 95, : 118, : max_iters\Ending the trajectory: Agent failed to select a valid tool: {_fmt_exc(err)}\thought_{idx}\tool_name_{idx}\tool_args_{idx}\observation_{idx}\observation_{idx}\Execution error in {pred.next_tool_name}: {_fmt_exc(err)}\finish\}, {: , : , : 116, : 133, : thought_0\I need to write an invitation letter for Alice to the Science Fair event.\tool_name_0\write_invitation_letter\tool_args_0\participant_name\Alice\event_info\name\Science Fair\date\Friday\participants\Alice\female\Bob\male\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 \ 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```rubricclaim_idc1claim_typecoreweightstatementImplements 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_idss5s6claim_idc4claim_typesupportingweightstatementRuns 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_idss7claim_idc5claim_typesupportingweightstatementReads 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_idss8evidencespan_ids1pathtests/examples/test_baleen.pystart_lineend_lineexcerpt0072: 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 \ 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 Truespan_ids2pathdspy/evaluate/metrics.pystart_lineend_lineexcerpt0285: def answer_exact_match(example, pred, trace=None, frac=1.0):\n0286: \\Eiffel Tower\Louvre\The Eiffel Tower\\\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\)\n0318: \n0319: \n0320: def answer_passage_match(example, pred, trace=None):\n0321: \\Eiffel Tower\The Eiffel Tower is in Paris.\...\\\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\)span_ids3pathdspy/evaluate/metrics.pystart_lineend_lineexcerpt0285: def answer_exact_match(example, pred, trace=None, frac=1.0):\n0286: \\Eiffel Tower\Louvre\The Eiffel Tower\\\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\)span_ids4pathdspy/evaluate/metrics.pystart_lineend_lineexcerpt0320: def answer_passage_match(example, pred, trace=None):\n0321: \\Eiffel Tower\The Eiffel Tower is in Paris.\...\\\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\)span_ids5pathtests/examples/test_baleen.pystart_lineend_lineexcerpt0034: 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_ids6pathdspy/evaluate/metrics.pystart_lineend_lineexcerpt0285: def answer_exact_match(example, pred, trace=None, frac=1.0):\n0286: \\Eiffel Tower\Louvre\The Eiffel Tower\\\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\)\n0318: \n0319: \n0320: def answer_passage_match(example, pred, trace=None):\n0321: \\Eiffel Tower\The Eiffel Tower is in Paris.\...\\\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\)span_ids7pathdspy/evaluate/evaluate.pystart_lineend_lineexcerpt0071: def __init__(\n0072: self,\n0073: *,\n0074: devset: list[\],\n0075: metric: Callable | None = None,span_ids8pathdspy/evaluate/evaluate.pystart_lineend_lineexcerpt0170: 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\)\n0183: \n0184: if display_table:\n0185: if importlib.util.find_spec(\) 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(\)\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, \, 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: \,\n0220: ) as f:\n0221: json.dump(data, f)\n0222: \n0223: return EvaluationResult(\n0224: score=round(100 * ncorrect / ntotal, 2),\n0225: results=results, |
| |