dspy.Example¶
dspy.Example(base=None, **kwargs)
¶
A flexible data container for DSPy examples and training data with named fields.
An Example is roughly one row from a HuggingFace dataset or pandas
DataFrame. It behaves a lot like a dictionary or dot-access record: you
can read fields with example["question"] or example.question.
In DSPy, lists of Example objects are your trainset, devset, and testset.
Most examples are built from keyword arguments or an existing record, then
tagged with with_inputs(...) to say which fields should be fed into a
module. The remaining fields are labels or metadata.
When you write evaluation code, custom optimizers, or training loops, use
example.inputs() for the fields you want to pass to a module, and use
example.labels() for the fields you want to compare against the module's
output.
Examples:
Build one from keyword arguments:
>>> import dspy
>>> example = dspy.Example(
... question="What is the capital of France?",
... answer="Paris",
... ).with_inputs("question")
>>> example.question
'What is the capital of France?'
>>> example.answer
'Paris'
>>> example.inputs().toDict()
{'question': 'What is the capital of France?'}
Build one from an existing record:
>>> record = {"question": "What is 2+2?", "answer": "4"}
>>> example = dspy.Example(**record).with_inputs("question")
>>> example["question"]
'What is 2+2?'
>>> example.labels().answer
'4'
Mark which fields are inputs:
>>> example = dspy.Example(
... question="What is the weather?",
... answer="It's sunny",
... ).with_inputs("question")
>>> example.inputs().question
'What is the weather?'
>>> example.labels().answer
"It's sunny"
Use examples in a trainset:
>>> trainset = [
... dspy.Example(question="What is 2+2?", answer="4").with_inputs("question"),
... dspy.Example(question="What is 3+3?", answer="6").with_inputs("question"),
... ]
>>> trainset[0].inputs().toDict()
{'question': 'What is 2+2?'}
Use an example in a metric:
>>> def exact_match_metric(example, pred, trace=None):
... return example.answer.lower() == pred.answer.lower()
>>> gold = dspy.Example(question="What is 1+1?", answer="2").with_inputs("question")
>>> pred = dspy.Prediction(answer="2")
>>> exact_match_metric(gold, pred)
True
Use it like a dictionary:
>>> example = dspy.Example(name="Alice", age=30).with_inputs("name")
>>> "name" in example
True
>>> example.get("city", "Unknown")
'Unknown'
See Also
dspy.Evaluate: Evaluate a program on a list of
Examples.
Metrics: Write metric functions
that compare an Example with a prediction.
Create an Example from fields or from an existing record.
In the common case, pass fields as keyword arguments, like
dspy.Example(question="...", answer="..."). Use base when you
already have a dictionary or another Example and want to copy its
fields before adding or overriding a few values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
A dictionary or |
None
|
|
**kwargs
|
Field names and values to store on the example. If a field
appears in both |
{}
|
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
Functions¶
copy(**kwargs)
¶
Return a shallow copy, optionally overriding fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Fields to add or override in the copy. |
{}
|
Examples:
>>> import dspy
>>> ex = dspy.Example(question="Why?", answer="Because.")
>>> ex.copy(answer="No reason.")
Example({'question': 'Why?', 'answer': 'No reason.'}) (input_keys=None)
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
get(key, default=None)
¶
Return the value for key, or default if the field doesn't exist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
Field name to look up. |
required | |
default
|
Value to return when |
None
|
Examples:
>>> import dspy
>>> ex = dspy.Example(name="Alice")
>>> ex.get("name")
'Alice'
>>> ex.get("city", "Unknown")
'Unknown'
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
inputs()
¶
Return a new Example containing only the input fields.
Requires with_inputs to have been called first.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import dspy
>>> ex = dspy.Example(question="Why?", answer="Because.").with_inputs("question")
>>> ex.inputs()
Example({'question': 'Why?'}) (input_keys={'question'})
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
items(include_dspy=False)
¶
Return (field_name, value) pairs, like dict.items().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_dspy
|
If |
False
|
Examples:
>>> import dspy
>>> dspy.Example(question="Why?", answer="Because.").items()
[('question', 'Why?'), ('answer', 'Because.')]
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
keys(include_dspy=False)
¶
Return field names, like dict.keys().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_dspy
|
If |
False
|
Examples:
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
labels()
¶
Return a new Example containing only the label (non-input) fields.
Requires with_inputs to have been called first, since labels are
everything that is not an input.
Examples:
>>> import dspy
>>> ex = dspy.Example(question="Why?", answer="Because.").with_inputs("question")
>>> ex.labels()
Example({'answer': 'Because.'}) (input_keys=None)
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
toDict()
¶
Convert to a plain dictionary, recursively serializing nested objects.
Nested Example objects, Pydantic models, lists, and dicts are
converted so the result is JSON-friendly.
Examples:
>>> import dspy
>>> dspy.Example(question="Why?", answer="Because.").toDict()
{'question': 'Why?', 'answer': 'Because.'}
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
values(include_dspy=False)
¶
Return field values, like dict.values().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_dspy
|
If |
False
|
Examples:
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
with_inputs(*keys)
¶
Mark which fields are inputs and return a new Example.
Fields not listed here are treated as labels (expected outputs).
DSPy optimizers and evaluators use this split: they pass
example.inputs() to your program and compare the output against
example.labels().
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*keys
|
Names of the input fields. |
()
|
Returns:
| Type | Description |
|---|---|
|
A copy of this |
Examples:
>>> import dspy
>>> ex = dspy.Example(question="Why?", answer="Because.").with_inputs("question")
>>> ex.inputs().keys()
['question']
>>> ex.labels().keys()
['answer']
Source code in .venv/lib/python3.14/site-packages/dspy/primitives/example.py
without(*keys)
¶
Return a copy with the specified fields removed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*keys
|
Field names to drop. |
()
|
Examples:
>>> import dspy
>>> ex = dspy.Example(question="Why?", answer="Because.", source="web")
>>> ex.without("source")
Example({'question': 'Why?', 'answer': 'Because.'}) (input_keys=None)