id stringlengths 17 17 | topic stringclasses 6
values | question stringlengths 856 1.85k | gold_answer stringlengths 1.1k 3.56k | rubric listlengths 4 6 | evidence listlengths 3 10 |
|---|---|---|---|---|---|
dspy_db6c58a4b861 | gepa_optimizer_usage | I'm debugging a tiny GEPA run on a one-step QA module (a single `dspy.Predict('question -> answer')`). My harness wires up two separate `DummyLM`s — one configured as the default task LM and one passed to GEPA as the `reflection_lm` — runs a small optimization with a single budget cap, and a feedback metric so reflecti... | ```python
import json
import dspy
from dspy.utils.dummies import DummyLM
class QAProgram(dspy.Module):
def __init__(self):
super().__init__()
self.predictor = dspy.Predict('question -> answer')
def forward(self, question):
return self.predictor(question=question)
def metric(gold, pr... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 52,
"statement": "To surface the exact reflection request, the code recovers it from the `prompt` field of `reflection_lm.history[-1]` (e.g. `last['messages'] or [{'role':'user','content': last['prompt']}]`, or by reading `last['prompt']` directly)... | [
{
"span_id": "s1",
"path": "dspy/teleprompt/gepa/gepa.py",
"start_line": 330,
"end_line": 365,
"excerpt": "0330: def __init__(\n0331: self,\n0332: metric: GEPAFeedbackMetric,\n0333: *,\n0334: # Budget configuration\n0335: auto: Literal[\"light\", \"med... |
dspy_024049972dfc | gepa_optimizer_usage | I have a hand-written instruction for a customer-support `dspy.Predict` and I want GEPA to refine *that* wording, not invent one from scratch. My module builds the predictor like this:
```python
self.reply = dspy.Predict('question -> answer', instructions=BASE_INSTRUCTION)
```
It runs without complaint, but when I co... | ```python
import dspy
from dspy.utils.dummies import DummyLM
BASE_INSTRUCTION = (
'Answer support questions in one sentence. '
'For returns questions, mention the 30-day refund window.'
)
class SupportProgram(dspy.Module):
def __init__(self):
super().__init__()
self.reply = dspy.Predict('... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 42,
"statement": "The hand-written instruction is attached to the predictor's SIGNATURE so that `predictor.signature.instructions` returns the user's text — via `predictor.signature = predictor.signature.with_instructions(BASE_INSTRUCTION)`, or by ... | [
{
"span_id": "s1",
"path": "dspy/signatures/signature.py",
"start_line": 269,
"end_line": 297,
"excerpt": "0269: @classmethod\n0270: def with_instructions(cls, instructions: str) -> type[\"Signature\"]:\n0271: \"\"\"Return a new Signature class with identical fields and new instr... |
dspy_89c0e8c85588 | gepa_optimizer_usage | I'm optimizing a single-`Predict` question-answering program with `dspy.GEPA`, and I have no reference/gold answers in my trainset. What I do have is a stronger model I trust as an LLM judge: it reads a `(question, response)` pair, decides pass/fail, and writes a short critique explaining *why* it failed. I want GEPA t... | ```python
import dspy
from dspy.utils.dummies import DummyLM
class AnswerProgram(dspy.Module):
def __init__(self):
super().__init__()
self.predictor = dspy.Predict('question -> answer')
def forward(self, question):
return self.predictor(question=question)
class JudgeSignature(dspy.S... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 28,
"statement": "The metric handed to dspy.GEPA is a PLAIN Python callable whose parameter list is GEPA's five-argument signature `(gold, pred, trace=None, pred_name=None, pred_trace=None)` (a def or lambda accepting these five positional params; ... | [
{
"span_id": "s1",
"path": "dspy/teleprompt/gepa/gepa.py",
"start_line": 27,
"end_line": 35,
"excerpt": "0027: class GEPAFeedbackMetric(Protocol):\n0028: def __call__(\n0029: self,\n0030: gold: Example,\n0031: pred: Prediction,\n0032: trace: Optional[\"DSPyTra... |
dspy_52b34e22e3eb | gepa_optimizer_usage | I'm using `dspy.GEPA` and I want my own prompt-improvement step to rewrite predictor instructions using a dedicated rewrite model that is completely separate from the model my program uses to answer tasks. I deliberately don't want GEPA to own or manage that rewrite model, so I construct GEPA without giving it any refl... | ```python
import dspy
from dspy.utils.dummies import DummyLM
class RewriteInstruction(dspy.Signature):
current_instruction: str = dspy.InputField()
feedback_blob: str = dspy.InputField()
improved_instruction: str = dspy.OutputField()
class ExternalReflectionProposer:
def __init__(self):
self... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 35,
"statement": "GEPA is constructed with NO separate-prompt-LM constructor argument: the answer relies ONLY on `reflection_lm=None` together with a custom `instruction_proposer=...` (the constructor's `assert reflection_lm is not None or instruct... | [
{
"span_id": "span_1",
"path": "dspy/teleprompt/gepa/gepa.py",
"start_line": 392,
"end_line": 398,
"excerpt": "0392: assert reflection_lm is not None or instruction_proposer is not None, (\n0393: \"GEPA requires a reflection language model, or custom instruction proposer to b... |
dspy_9e8d3c68af73 | gepa_optimizer_usage | I'm setting up a GEPA run with `auto="light"` and a small QA program (one `Predict`), and I keep mixing up the three example collections: the trainset, the validation set, and the per-step reflection minibatch. Before I launch, I want a helper that prints what each of those three is actually used for, and that estimate... | ```python
import json
import dspy
from dspy.utils.dummies import DummyLM
# GEPA's "light" / "medium" / "heavy" auto presets resolve to these candidate counts.
AUTO_CANDIDATE_COUNTS = {'light': 6, 'medium': 12, 'heavy': 18}
class QAProgram(dspy.Module):
def __init__(self):
super().__init__()
self.... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 50,
"statement": "DOMINANT ANTI-DECOY GATE: the light metric-call budget must be estimated via the snapshot's auto_budget estimator computed from only the student predictor count and the scoring valset size with the light-preset candidate count — i... | [
{
"span_id": "s1",
"path": "dspy/teleprompt/gepa/gepa.py",
"start_line": 465,
"end_line": 480,
"excerpt": "0465: def compile(\n0466: self,\n0467: student: Module,\n0468: *,\n0469: trainset: list[Example],\n0470: teacher: Module | None = None,\n0471: ... |
dspy_064741a8777f | prompt_optimization_workflows | I'm building a support-ticket classifier and I want prompt optimization to rewrite my own seed instruction (not invent one from scratch), while keeping the deployed program completely demo-free — just the one optimized instruction, no few-shot examples baked in.
Right now I'm running `dspy.COPRO`: I attach my seed wor... | ```python
import dspy
def build_compiled_classifier():
seed_instruction = (
"Classify each support ticket as billing, account, or technical. "
"Return only the label."
)
program = dspy.Predict(dspy.Signature("ticket -> label").with_instructions(seed_instruction))
dataset = [
d... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 30,
"statement": "The workflow seeds the predictor with the user's own instruction by building a signature like `\"ticket -> label\"` and calling `with_instructions(seed_instruction)` on it before wrapping in `dspy.Predict`, rather than letting the... | [
{
"span_id": "s1",
"path": "dspy/signatures/signature.py",
"start_line": 269,
"end_line": 297,
"excerpt": "0269: @classmethod\n0270: def with_instructions(cls, instructions: str) -> type[\"Signature\"]:\n0271: \"\"\"Return a new Signature class with identical fields and new instr... |
dspy_9f98ea7f1ef5 | prompt_optimization_workflows | I'm building a customer-support classifier in DSPy. There's a fixed policy block of musts/nevers (e.g. "MUST ask for an order ID before refunds; NEVER request a full card number") that has to reach the model **word-for-word at runtime** and must NOT be paraphrased or absorbed into anything the optimizer rewrites — only... | ```python
import dspy
from typing import Literal
POLICY = """MUST request an order ID before discussing refunds.
NEVER ask for a full card number."""
class SafeDecision(dspy.Signature):
policy: str = dspy.InputField()
message: str = dspy.InputField()
decision: Literal["ask_order_id", "decline_sensitive",... | [
{
"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 N... | [
{
"span_id": "s1",
"path": "dspy/signatures/signature.py",
"start_line": 193,
"end_line": 245,
"excerpt": "0193: # Ensure all fields are declared with InputField or OutputField\n0194: cls._validate_fields()\n0195: \n0196: # Ensure all fields have a prefix\n0197: f... |
dspy_962f53473587 | prompt_optimization_workflows | I have a two-step support agent: it first picks a route (billing / account / technical) for an incoming request, then drafts the reply conditioned on that route. I'm compiling the whole thing with `MIPROv2` against a metric that returns a single 0-1 score, and it plateaus quickly — the proposer never seems to figure ou... | ```python
import dspy
class SupportAgent(dspy.Module):
def __init__(self):
super().__init__()
self.route = dspy.Predict("question -> route")
self.reply = dspy.Predict("question, route -> answer")
def forward(self, question: str):
route = self.route(question=question).route
... | [
{
"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... | [
{
"span_id": "s1",
"path": "tests/teleprompt/test_gepa.py",
"start_line": 271,
"end_line": 282,
"excerpt": "0271: class MultiComponentModule(dspy.Module):\n0272: \"\"\"Test module with multiple predictors.\"\"\"\n0273: \n0274: def __init__(self):\n0275: super().__init__()\n0276: ... |
dspy_81c16cac1a88 | prompt_optimization_workflows | I'm prototyping a tiny retrieval-augmented QA program in DSPy and I need it to run fully offline — no calls to any hosted service. Right now my module retrieves by instantiating `dspy.retrievers.Embeddings` over my list of passages and calling it directly inside `forward`, but that forces me to stand up an embedding mo... | ```python
import dspy
from dspy.utils import dummy_rm
corpus = [
"Paris | Paris is the capital of France.",
"Berlin | Berlin is the capital of Germany.",
"Madrid | Madrid is the capital of Spain.",
"Rome | Rome is the capital of Italy.",
]
class WriteQuery(dspy.Signature):
question: str = dspy.In... | [
{
"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 (positional... | [
{
"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 passag... |
dspy_898cf1643d8a | prompt_optimization_workflows | I'm building an inference-time guardrail for one stage of a DSPy program. There's no labeled data for this stage, but for every individual request I can score the model's output with a plain Python function that returns a float (higher = better), and I know the score I need to clear.
Right now I wrap that stage in `ds... | ```python
import dspy
# One stage of a larger program; no trainset for it, only a per-request scorer.
stage = dspy.Predict(
dspy.Signature("question -> answer").with_instructions(
"Answer in one short, direct sentence. Do not hedge."
)
)
# Per-request Python reward: higher is better, with a known pas... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 55,
"statement": "The guarded stage is built by wrapping the base prediction module in this snapshot's `dspy.Refine(module=..., N=..., reward_fn=..., threshold=...)` -- the answer must actually instantiate `dspy.Refine` (the snapshot exposes it wit... | [
{
"span_id": "s1",
"path": "dspy/predict/refine.py",
"start_line": 41,
"end_line": 57,
"excerpt": "0041: class Refine(Module):\n0042: def __init__(\n0043: self,\n0044: module: Module,\n0045: N: int, # noqa: N803\n0046: reward_fn: Callable[[dict, Prediction], ... |
dspy_2de37073e8e4 | react_agents_and_tools | I'm building a customer-facing support chatbot on a `dspy.ReAct` agent. Each user should have their own ongoing conversation, and the agent also needs a tool to look up our internal support notes. Today I keep a per-user dict of past turns and I've registered a `recall_history(user_id)` tool on the agent so the model c... | ```python
from collections import defaultdict
import dspy
from dspy.utils import DummyLM
class SupportTurn(dspy.Signature):
user_message: str = dspy.InputField()
history: dspy.History = dspy.InputField()
reply: str = dspy.OutputField()
class StatefulSupportBot(dspy.Module):
def __init__(self):
... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 40,
"statement": "Per-user prior turns are surfaced to the model by declaring an input field of type `dspy.History` on the signature (e.g. `history: dspy.History = dspy.InputField()`) and passing it `dspy.History(messages=[...])` built from that us... | [
{
"span_id": "s1",
"path": "dspy/adapters/types/history.py",
"start_line": 6,
"end_line": 19,
"excerpt": "0006: class History(pydantic.BaseModel):\n0007: \"\"\"Class representing the conversation history.\n0008: \n0009: The conversation history is a list of messages, each message entity ... |
dspy_7329144ef1e9 | react_agents_and_tools | I'm building a carpool assistant and I want my tools to pass real ride objects around — a search step, a "pick cheapest" step, and a booking step — instead of stringly-typed blobs. Right now I expose the tools through a `dspy.Signature` with a `tool_calls: dspy.ToolCalls` output field and let native function calling dr... | ```python
from pydantic import BaseModel
import dspy
from dspy.utils import DummyLM
class RideOffer(BaseModel):
driver: str
origin: str
destination: str
seats: int
price: float
class RiderProfile(BaseModel):
name: str
seats_needed: int
class Booking(BaseModel):
driver: str
rid... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 28,
"statement": "The assistant is a single `dspy.ReAct` agent: it constructs `dspy.ReAct(signature, tools=[search, pick_best, confirm], ...)` (one agent driving the whole search -> choose-best -> confirm-booking flow) and does NOT hand-roll a mult... | [
{
"span_id": "s1",
"path": "dspy/predict/react.py",
"start_line": 16,
"end_line": 18,
"excerpt": "0016: class ReAct(Module):\n0017: def __init__(self, signature: type[\"Signature\"], tools: list[Callable], max_iters: int = 20):\n0018: \"\"\""
},
{
"span_id": "s3",
"path":... |
dspy_a5b116f00083 | react_agents_and_tools | I've got a mostly chat-style DSPy app and one step that needs to be different: a single planning call that's handed a tool inventory and has to emit machine-readable tool calls so my own Python code can run them afterward (no agent loop, no iterative tool execution inside DSPy — just one call that returns the plan).
R... | ```python
import dspy
from dspy.utils import DummyLM
class PlanStep(dspy.Signature):
request: str = dspy.InputField()
tools: list[dspy.Tool] = dspy.InputField()
plan_summary: str = dspy.OutputField()
tool_calls: dspy.ToolCalls = dspy.OutputField()
def lookup_balance(user_id: str) -> str:
return ... | [
{
"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 emit... | [
{
"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 ... |
dspy_e175093485fd | react_agents_and_tools | I'm building a two-layer support bot in DSPy: a top-level `dspy.ReAct` router decides which specialist to hand a request to, and the chosen specialist is itself a module that runs its own `dspy.ReAct` to pick a concrete business tool (search/book a trip, look up/refund an invoice, etc.). Delegation and business-tool us... | ```python
import dspy
from dspy.utils import DummyLM
class TravelSpecialist(dspy.Module):
def __init__(self):
super().__init__()
# Built ONCE. No max_iters fixed here; the budget is chosen per call.
self.agent = dspy.ReAct('request -> reply', tools=[self.search_trips, self.book_trip])
... | [
{
"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... | [
{
"span_id": "s1",
"path": "dspy/primitives/module.py",
"start_line": 40,
"end_line": 49,
"excerpt": "0040: class Module(BaseModule, metaclass=ProgramMeta):\n0041: \"\"\"Base class for all DSPy modules (programs).\n0042: \n0043: A Module is a building block for DSPy programs that can con... |
dspy_0b4b420ebeb4 | react_agents_and_tools | I'm building a small DSPy program that plays a text adventure. The world exposes three operations the player can perform — `ask(question)` to query an NPC, `move(direction)` to change rooms, and `take(item)` to pick something up — and each one takes its own differently-named argument. I want a single language model to ... | ```python
import dspy
from dspy.utils import DummyLM
class TinyWorld:
def __init__(self):
self.room = 'hall'
self.inventory: list[str] = []
def ask(self, question: str) -> str:
return 'The brass key is in the attic.' if 'key' in question.lower() else 'I only know about the key.'
... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 45,
"statement": "The agent is a single `dspy.ReAct(...)` module so the language model itself selects which operation to invoke at each step from ReAct's accumulated trajectory. It must NOT use the decoy of a developer-written `while`/`for` loop th... | [
{
"span_id": "s1",
"path": "dspy/predict/react.py",
"start_line": 16,
"end_line": 18,
"excerpt": "0016: class ReAct(Module):\n0017: def __init__(self, signature: type[\"Signature\"], tools: list[Callable], max_iters: int = 20):\n0018: \"\"\""
},
{
"span_id": "s2",
"path":... |
dspy_188039f2a0d6 | rag_and_retrieval_pipelines | Our policy corpus is ~30k documents and encoding it takes minutes, so I want to pay that cost exactly once: encode at build time, write everything needed for retrieval to disk, and have a separate serving process start up and answer questions without ever touching the embedding model for the corpus again.
I built a `d... | ```python
from pathlib import Path
import dspy
from dspy.utils import DummyVectorizer
INDEX_DIR = Path('saved_policy_index')
corpus = [
'Finance keeps invoices for seven years.',
'Security incidents must be reported within one hour.',
'Customer data exports require director approval.',
]
embedder = dspy.... | [
{
"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 RETRIEVE... | [
{
"span_id": "s1",
"path": "dspy/retrievers/embeddings.py",
"start_line": 18,
"end_line": 39,
"excerpt": "0018: def __init__(\n0019: self,\n0020: corpus: list[str],\n0021: embedder,\n0022: k: int = 5,\n0023: callbacks: list[Any] | None = None,\n0024: ... |
dspy_0ab31a81ea0b | rag_and_retrieval_pipelines | I have an in-memory list of strings (an internal knowledge base) and I'm standing up a lightweight DSPy search service over it — no answer generation yet, just retrieval. I'm building it on `dspy.Embeddings`, and it does return the right top-k passages with their corpus positions. The problem: for each hit I also need ... | ```python
import dspy
from dspy.utils import DummyVectorizer
class SearchService(dspy.Module):
def __init__(self, corpus: list[str], top_k: int = 3):
super().__init__()
self.search = dspy.EmbeddingsWithScores(
corpus=corpus,
embedder=dspy.Embedder(DummyVectorizer(max_length... | [
{
"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 `d... | [
{
"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... |
dspy_aa7467f4bdc2 | rag_and_retrieval_pipelines | 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 di... | ```python
from types import SimpleNamespace
import dspy
class ExistingVectorClient:
def __init__(self, namespaces: dict[str, list[str]]):
self.namespaces = namespaces
def search(self, query: str, limit: int, namespace: str) -> list[str]:
docs = self.namespaces[namespace]
scored = sor... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 40,
"statement": "Registers the existing client ONCE as the program-wide retrieval backend by setting the global `rm` slot via `dspy.configure(rm=...)` (or `dspy.settings.configure(rm=...)`), AND performs retrieval through `dspy.Retrieve` (e.g. `se... | [
{
"span_id": "s1",
"path": "dspy/retrievers/retrieve.py",
"start_line": 43,
"end_line": 65,
"excerpt": "0043: def forward(\n0044: self,\n0045: query: str,\n0046: k: int | None = None,\n0047: **kwargs,\n0048: ) -> list[str] | Prediction | list[Prediction]:\... |
dspy_136c0583928c | rag_and_retrieval_pipelines | 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 wh... | ```python
from types import SimpleNamespace
import dspy
from dspy.dsp.utils import deduplicate
from dspy.utils import DummyVectorizer
class GenerateSearchQuery(dspy.Signature):
context = dspy.InputField(desc="may contain relevant facts")
question = dspy.InputField()
query = dspy.OutputField()
class Gen... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 50,
"statement": "Retrieval each round goes through `dspy.Retrieve` (constructed with `k=`), and the configured retrieval model is a THIN RM ADAPTER wrapping `dspy.Embeddings` that accepts a `k` argument and returns items exposing `.long_text`, reg... | [
{
"span_id": "s1",
"path": "tests/examples/test_baleen.py",
"start_line": 25,
"end_line": 43,
"excerpt": "0025: class SimplifiedBaleen(dspy.Module):\n0026: def __init__(self, passages_per_hop=3, max_hops=2):\n0027: super().__init__()\n0028: \n0029: self.generate_query = [dspy... |
dspy_0f329f8e4a71 | rag_and_retrieval_pipelines | I have a fixed corpus plus labeled question/answer pairs and a retrieval-backed DSPy module (an embeddings retriever feeding a ChainOfThought answer step). I want `BootstrapFewShot` to tune the prompting around the answer step while leaving retrieval untouched, and I only want it to keep a bootstrapped trajectory when ... | ```python
import dspy
from dspy.evaluate import Evaluate, answer_exact_match, answer_passage_match
from dspy.utils import DummyVectorizer
class AnswerFromContext(dspy.Signature):
context = dspy.InputField()
question = dspy.InputField()
answer = dspy.OutputField()
class RetrievalQA(dspy.Module):
def ... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 45,
"statement": "The metric passed to BootstrapFewShot is deterministic and label-based with NO model/judge call: it returns a boolean that is true only when the predicted answer matches the labeled answer AND the labeled answer is present in the ... | [
{
"span_id": "s1",
"path": "dspy/retrievers/embeddings.py",
"start_line": 41,
"end_line": 56,
"excerpt": "0041: def __call__(self, query: str):\n0042: return self.forward(query)\n0043: \n0044: def forward(self, query: str):\n0045: \"\"\"Search for the top-k passages most ... |
dspy_0a25b1b505ca | signature_schema_and_pydantic_types | 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__`... | ```python
from typing import Literal
import dspy
import pydantic
from dspy.utils import DummyLM
class LabelDecision(pydantic.BaseModel):
label: str
created_new: bool
class BaseTicketLabeler(dspy.Signature):
'Choose an existing label or request a new one.'
text: str = dspy.InputField()
known_la... | [
{
"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-s... | [
{
"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 upd... |
dspy_37b0aa70071a | signature_schema_and_pydantic_types | 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 te... | ```python
from enum import Enum
from typing import Annotated, Literal
import dspy
import pydantic
from dspy.utils import DummyLM
class QuestionKind(str, Enum):
MULTIPLE_CHOICE = "multiple_choice"
TRUE_FALSE = "true_false"
FLASH_CARD = "flash_card"
class BaseQuestion(pydantic.BaseModel):
question: s... | [
{
"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 M... | [
{
"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... |
dspy_d6683c54b609 | signature_schema_and_pydantic_types | I need an intent extractor that reads the latest user question plus the prior conversation turns, using a `dspy.History` input field. Several output fields are legitimately absent on many turns — e.g. a turn may have a primary intent but no secondary intents, no clarification questions, and no resolved glossary terms —... | ```python
import dspy
import pydantic
from dspy.utils import DummyLM
class Term(pydantic.BaseModel):
term: str
meaning: str
class ExtractIntent(dspy.Signature):
"""Extract the main intent and any optional follow-up needs from the latest user
question given the prior conversation turns."""
quest... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 40,
"statement": "Absent outputs are produced by typing EACH optional output field as a union with `None` (e.g. `secondary_intents: list[str] | None` or `Optional[list[str]]`) AND having the LM emit an explicit `null` for those fields, so the adapt... | [
{
"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 ... |
dspy_b03a99c316d5 | signature_schema_and_pydantic_types | 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... | ```python
import dspy
import pydantic
from dspy.utils import DummyLM
class Container:
class Verdict(pydantic.BaseModel):
label: str
confidence: float
class InlineTypedModule(dspy.Module):
def __init__(self):
super().__init__()
class Query(pydantic.BaseModel):
tex... | [
{
"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 sa... | [
{
"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.\... |
dspy_ad7223e585ba | signature_schema_and_pydantic_types | I keep changing a typed signature and want a regression check that proves the contract actually reaches the model. The signature has output fields with length and numeric limits (think `min_length`/`max_length` on a short string field and `ge`/`le` on a 0–1 float), a class docstring, and a `desc` on every field. I want... | ```python
import dspy
import json
def check_typed_signature_prompt_surface():
class ScoreCard(dspy.Signature):
"""Score a support reply for policy compliance."""
ticket_text: str = dspy.InputField(desc="Original support ticket body.")
allowed_labels: list[str] = dspy.InputField(desc="Vali... | [
{
"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_mes... | [
{
"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: ... |
dspy_2980c79329e9 | evaluation_metrics_and_custom_eval | I'm stress-testing a `dspy.Module` over a ~500-example devset where a handful of examples reliably throw exceptions (bad inputs, occasional tool timeouts). I want it to run in parallel, give failed examples a fallback score instead of crashing, compute an overall score, and hand me back the rows that failed so I can in... | ```python
import dspy
from dspy.evaluate import Evaluate
from dspy.utils.dummies import DummyLM
class FlakyQA(dspy.Module):
def __init__(self):
super().__init__()
self.qa = dspy.Predict('question -> answer')
def forward(self, question):
if 'explode' in question:
raise Runt... | [
{
"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` (def... | [
{
"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 | Non... |
dspy_e1bc894a3f32 | evaluation_metrics_and_custom_eval | 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... | ```python
import dspy
from dspy.evaluate import Evaluate, SemanticF1
from dspy.utils.dummies import DummyLM
devset = [
dspy.Example(question='What is the capital of France?', response='Paris').with_inputs('question'),
dspy.Example(question='Which ocean is the largest on Earth?', response='The Pacific Ocean').... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 45,
"statement": "The scorer is the built-in LM-based semantic precision/recall metric `SemanticF1` imported from `dspy.evaluate` (instantiated and passed as the `metric`) -- NOT a hand-rolled custom metric (e.g. a user-defined class/function that ... | [
{
"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: thresho... |
dspy_9e63ca9046ae | evaluation_metrics_and_custom_eval | I'm tuning a short-answer QA program with BootstrapFewShot and want optimization driven by one number that blends two checks: exactness against the gold answer and brevity (answer is at most 3 words). My metric currently returns a plain dict like {'score': 0.7*exact + 0.3*brief, 'exact': exact, 'brief': brief} so I kee... | ```python
import dspy
from dspy.evaluate import Evaluate
from dspy.utils.dummies import DummyLM
class ShortAnswerer(dspy.Module):
def __init__(self):
super().__init__()
self.qa = dspy.Predict('question -> answer')
def forward(self, question):
return self.qa(question=question)
def ex... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 35,
"statement": "The metric function's return statement constructs and returns a single `dspy.Prediction(...)` whose `score=` kwarg is set to the blended objective (0.7*exact + 0.3*brief) AND that SAME Prediction also carries the per-check sub-sco... | [
{
"span_id": "s1",
"path": "dspy/primitives/prediction.py",
"start_line": 4,
"end_line": 16,
"excerpt": "0004: class Prediction(Example):\n0005: \"\"\"A prediction object that contains the output of a DSPy module.\n0006: \n0007: Prediction inherits from Example.\n0008: \n0009: ... |
dspy_3a5e956e4421 | evaluation_metrics_and_custom_eval | I've got a `dspy.ReAct` agent that answers arithmetic word problems and is given a Python `add` function as a tool. I want an evaluation harness that gives an example credit ONLY when the final answer is correct AND the agent genuinely used the calculator to get there. The reason I care: some of these agents just blurt... | ```python
import dspy
from dspy.evaluate import Evaluate
from dspy.utils.dummies import DummyLM
def add(a: int, b: int) -> int:
return a + b
def tool_use_metric(example, pred, trace=None):
# Credit only if the agent actually invoked the `add` tool. Note that ReAct always
# records a `finish` step in the... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 70,
"statement": "The custom metric awards credit only when BOTH (a) the prediction's final answer matches the example answer AND (b) the agent actually invoked the arithmetic tool, and it detects (b) by reading the ReAct trajectory: it iterates `p... | [
{
"span_id": "s1",
"path": "dspy/predict/react.py",
"start_line": 95,
"end_line": 118,
"excerpt": "0095: def forward(self, **input_args):\n0096: trajectory = {}\n0097: max_iters = input_args.pop(\"max_iters\", self.max_iters)\n0098: for idx in range(max_iters):\n0099:... |
dspy_e98cfa59364f | evaluation_metrics_and_custom_eval | 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 pas... | ```python
import dspy
from dspy.evaluate import Evaluate, answer_exact_match, answer_passage_match
from dspy.utils.dummies import DummyLM
class AnswerFromContext(dspy.Signature):
question: str = dspy.InputField()
context: list[str] = dspy.InputField()
answer: str = dspy.OutputField()
class TinyRAG(dspy.... | [
{
"claim_id": "c1",
"claim_type": "core",
"weight": 50,
"statement": "Implements BOTH halves of the metric with the snapshot's built-in deterministic helpers — answer correctness via `answer_exact_match(example, pred)` and passage support via `answer_passage_match(example, pred)` (imported from `dsp... | [
{
"span_id": "s1",
"path": "tests/examples/test_baleen.py",
"start_line": 72,
"end_line": 85,
"excerpt": "0072: def validate_context_and_answer_and_hops(example, pred, trace=None):\n0073: if not dspy.evaluate.answer_exact_match(example, pred):\n0074: return False\n0075: if not ds... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.