Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Consolidate Jev on dspy.LM via bundled lm15 (#10648)

Isaac Miller2872410cef53
diff --git a/docs/docs/api/experimental/DecisionTypes.md b/docs/docs/api/experimental/DecisionTypes.md
index c6d7d243f..be7428a32 100644
--- a/docs/docs/api/experimental/DecisionTypes.md
+++ b/docs/docs/api/experimental/DecisionTypes.md
@@ -1,7 +1,7 @@
# Decision types and System One models
!!! warning "Experimental API"
- `Noul`, `Score`, `Choice`, `TypeSafe`, and Predict's per-field decision
+ `Noul`, `Score`, `Choice`, and Predict's per-field decision
configuration are experimental and may change without warning.
Use one signature with a generative LM or a System One model. `Predict` owns
@@ -10,7 +10,7 @@ request format and derives results from probability evidence.
```python
import dspy
-from dspy.experimental import Noul, Score, Choice, TypeSafe
+from dspy.experimental import Noul, Score, Choice
Availability = Noul[(True, "Service unavailable"), (False, "Workaround available")]
Severity = Score["Minor", "Disruptive", "Blocking"]
@@ -24,9 +24,9 @@ class Assess(dspy.Signature):
severity: Severity = dspy.OutputField(desc="Rate impact.")
category: Category = dspy.OutputField(desc="Classify the issue.")
-# pip install "dspy[typesafe]"; set TYPESAFE_API_KEY
+# pip install dspy; set TYPESAFE_API_KEY
assess = dspy.Predict(Assess)
-assess.set_lm(TypeSafe("jev-latest"))
+assess.set_lm(dspy.LM("typesafe:jev-latest"))
assess.demos = [dspy.Example(
ticket="Incorrect invoice", urgent=False, severity=0.0, category="billing",
)]
@@ -47,20 +47,22 @@ Use `set_lm()` to bind a client to the predictor, supply `lm=` per call, or conf
`dspy.configure(lm=...)` / `dspy.context(lm=...)`.
```python
-dspy.configure(lm=TypeSafe("jev-latest"))
+dspy.configure(lm=dspy.LM("typesafe:jev-latest"))
assess = dspy.Predict(Assess)
```
-Predict selects the request format using the client's
-`supports_decision_requests` capability. TypeSafe receives decision requests;
-generative LMs use the configured ChatAdapter or JSONAdapter and return
-probability evidence for rich outputs.
+The default `engine="auto"` routes Jev to lm15; no explicit engine is needed.
+For Jev, `DecisionAdapter` builds a typed lm15 `Request` and decodes
+`response.provider_data['typesafe']['answers']`. Generative LMs use the configured
+ChatAdapter or JSONAdapter and return probability evidence for rich outputs.
+Thresholds, cuts, and weights are still applied locally.
-Decision clients accept `state` and `questions` keyword arguments and return a
-field-to-evidence mapping; async calls use `acall` with the same contract.
-TypeSafe supports DSPy caching, usage tracking, LM callbacks, history, copying,
-and save/load. Generation controls such as temperature and fine-tuning are
-unsupported.
+**API break:** `dspy.experimental.TypeSafe` has been removed, with no compatibility
+shim or migration of legacy saved LM state. Use ordinary `dspy.LM` with
+`TYPESAFE_API_KEY`; specify `model` and `api_base` as ordinary
+LM settings when needed. There are no Jev-specific LM defaults. Normal LM caching,
+history, usage tracking, persistence, retry, and lifecycle semantics apply;
+synchronous and asynchronous response caches are separate.
## Annotations and evidence
@@ -116,7 +118,7 @@ the candidate content in the inputs:
```python
import dspy
-from dspy.experimental import Choice, Noul, TypeSafe
+from dspy.experimental import Choice, Noul
passages = {
"p0": "Standard delivery takes three to five business days.",
@@ -137,7 +139,7 @@ select = dspy.Predict(signature)
result = select(
query="How long do I have to return an unused item?",
passages=passages,
- lm=TypeSafe("jev-latest"),
+ lm=dspy.LM("typesafe:jev-latest"),
)
if result.answer_exists.probability >= 0.7: # Illustrative; tune on your own examples.
print(passages[result.best.value])
@@ -245,7 +247,7 @@ Use ordinary `Predict.save()` / `load()` with the same signature architecture.
| `signature` | Global instructions and field descriptions/prefixes |
| `demos` | Demonstration inputs and answers, including rich JSON values |
| `fields` | Explicit per-output overrides only; omitted when empty |
-| `lm` | Provider class, model, endpoint, cache setting and timeout; no API key |
+| `lm` | Ordinary LM state, including model, engine, endpoint and cache settings |
| `traces`, `train` | Existing Predict bookkeeping |
| `metadata` | DSPy's dependency versions |
@@ -257,8 +259,8 @@ Predict participates in ordinary predictor discovery, callbacks, tracing,
batching and async calls. Numeric settings survive `reset()`; demos follow normal
Predict reset behavior. Trace/training records are not sent as task context.
-TypeSafe accepts closed-set decision outputs, not free-form text generation.
-Unsupported generation options and decision streaming raise explicitly.
+Jev accepts closed-set decision outputs, not free-form text generation.
+Call-time generation settings and decision streaming remain unsupported and raise explicitly.
**Nested LM decision outputs do not use evidence decoding.** Predict warns
when called with output containers such as `list[Noul]`, `list[Score[...]]`,
@@ -276,15 +278,17 @@ does not prevent execution; ordinary native RLM outputs are unaffected.
Unsupported output annotations (such as `str`, `int`, bare `float`, lists,
arbitrary Pydantic models, or optional decision types) raise `ValueError` when
-Predict is called with TypeSafe, before any provider request. Every output must
+Predict is called with Jev, before any provider request. Every output must
be supported; there is no automatic fallback to a generative LM. The same
signature can still be used with an ordinary LM when its adapter supports those
annotations. This restriction applies to outputs, not structured input data.
-Use TypeSafe through `Predict`, rather than calling chat adapters directly.
+Jev also rejects empty-string labels in `Choice` or `Literal` outputs before any
+provider request. Use a nonempty label such as `"no_match"` instead. Empty-string
+labels remain supported with generative LMs.
+
+Use Jev through `Predict`, rather than calling chat adapters directly.
Generation-specific wrappers such as `BestOfN` and `Refine`, generative optimizers,
-and fine-tuning are unsupported with TypeSafe.
-[ReAnchor](ReAnchor.md) calibrates decision outputs with TypeSafe or a
+and fine-tuning are unsupported with Jev.
+[ReAnchor](ReAnchor.md) calibrates decision outputs with Jev or a
generative LM, and it sends no generation settings.
-Wrappers that assume LM generation settings can currently raise `AttributeError`
-rather than a capability-specific error.
diff --git a/docs/docs/api/experimental/ReAnchor.md b/docs/docs/api/experimental/ReAnchor.md
index f31139ee3..e00d18477 100644
--- a/docs/docs/api/experimental/ReAnchor.md
+++ b/docs/docs/api/experimental/ReAnchor.md
@@ -16,7 +16,7 @@ does not support RLM programs either.
```python
import dspy
-from dspy.experimental import ReAnchor, TypeSafe
+from dspy.experimental import ReAnchor
class Match(dspy.Signature):
@@ -30,7 +30,8 @@ def metric(example, prediction, trace=None):
return float(prediction.match == example.match)
-dspy.configure(lm=TypeSafe("jev-latest"))
+# Set TYPESAFE_API_KEY in the environment.
+dspy.configure(lm=dspy.LM("typesafe:jev-latest"))
optimizer = ReAnchor(metric)
tuned = optimizer.compile(dspy.Predict(Match), trainset=trainset, valset=valset)
print(optimizer.report)
@@ -82,6 +83,9 @@ The numeric settings are not part of the request. Repeated identical requests
reuse cached answers. In a composed program, changing an upstream decision can
change downstream inputs or which predictors run, producing new requests and
additional backend calls. Native-output promotion also changes the request.
+Jev uses ordinary `dspy.LM` caching; synchronous and asynchronous response caches
+are separate. Local calibration is unchanged by the removal of
+`dspy.experimental.TypeSafe` (see the [migration note](DecisionTypes.md)).
`compile` requires caching by default to avoid repeating identical backend
calls; it does not guarantee a fixed request count. Pass `require_cache=False`
diff --git a/docs/docs/tutorials/jev_decisions/index.md b/docs/docs/tutorials/jev_decisions/index.md
index 5bcdb1101..1bdcc4c0c 100644
--- a/docs/docs/tutorials/jev_decisions/index.md
+++ b/docs/docs/tutorials/jev_decisions/index.md
@@ -1,7 +1,7 @@
# Decision-Making with Jev Types
!!! warning "Experimental API"
- `Noul`, `Score`, `Choice`, `TypeSafe`, and `ReAnchor` are experimental and may change
+ `Noul`, `Score`, `Choice`, and `ReAnchor` are experimental and may change
without warning. See the [API reference](../../api/experimental/DecisionTypes.md) for details.
In this tutorial, we will walk you through building **structured decision-making programs** in DSPy
@@ -19,11 +19,8 @@ you can adjust. This is the core idea behind DSPy's Jev integration.
pip install dspy
```
-If you want to use the TypeSafe System One backend (optional):
-
-```shell
-pip install "dspy[typesafe]"
-```
+For the optional Jev System One backend, set `TYPESAFE_API_KEY`. No
+`dspy[typesafe]` extra is needed; Jev uses ordinary `dspy.LM`.
## Define Decision Types
@@ -198,18 +195,16 @@ loaded_triage.load("triage_calibrated.json")
print(loaded_triage.fields) # Fitted parameters restored
```
-## Use the TypeSafe Backend (Optional)
+## Use Jev (Optional)
If you have a TypeSafe API key, you can switch the same predictor to the System One backend for
probability-native inference:
```python
-from dspy.experimental import TypeSafe
-
os.environ["TYPESAFE_API_KEY"] = "your-api-key"
-jev_client = TypeSafe("jev-latest")
-triage.set_lm(jev_client)
+jev_lm = dspy.LM("typesafe:jev-latest")
+triage.set_lm(jev_lm)
result = triage(ticket="My dashboard is blank after the update")
```
@@ -218,7 +213,15 @@ The same signature, demos, and field parameters work with both backends. The dif
probabilities are produced:
- **Generative LMs**: DSPy asks the LM to generate probability evidence as structured JSON, then decodes it locally.
-- **TypeSafe System One**: The API returns calibrated probabilities directly. No generation settings (temperature, etc.) are supported.
+- **Jev System One**: `DecisionAdapter` builds a typed lm15 `Request` and decodes
+ `response.provider_data['typesafe']['answers']`. Thresholds, cuts, and weights
+ still apply locally, and ReAnchor calibration is unchanged.
+
+**API break:** `dspy.experimental.TypeSafe` has been removed without a compatibility
+shim or legacy saved-state migration. Replace it with the `dspy.LM` above. Model
+and `api_base` are ordinary LM settings, with no Jev-specific LM defaults. Normal
+LM caching, history, usage tracking, persistence, retry, and lifecycle semantics
+apply; synchronous and asynchronous response caches are separate.
You can even mix backends within a single program — use Jev for critical decisions and a generative
LM for free-text outputs.
@@ -327,7 +330,7 @@ optional, probability-native alternative.
**Q: Can I mix decision outputs with regular string outputs?**
Yes. You can have `summary: str` alongside `urgent: Noul[...]` in the same signature. The generative
-LM handles both; TypeSafe requires all outputs to be decision types.
+LM handles both; Jev requires all outputs to be supported decision types.
**Q: What's the difference between `Noul` and just returning a `bool`?**
A bare `bool` output uses direct generation — the LM picks True or False. A `Noul` output asks
@@ -341,5 +344,5 @@ smaller sets). More data gives more reliable calibration. Since it reuses cached
adding more examples is cheap after the first pass.
**Q: Can I use this with async?**
-Yes. `TypeSafe` supports `acall()` for async inference. Decision types work with DSPy's async
-support.
+Yes. Jev uses ordinary `dspy.LM` async inference, and decision types work with
+DSPy's async support. Synchronous and asynchronous response caches are separate.
diff --git a/dspy/adapters/decision.py b/dspy/adapters/decision.py
index b8dc80526..b1af846b2 100644
--- a/dspy/adapters/decision.py
+++ b/dspy/adapters/decision.py
@@ -12,6 +12,7 @@ from pydantic import BaseModel, ConfigDict, Field, create_model
from dspy.adapters.decision_state import DecisionState
from dspy.adapters.types.decision import Choice, Noul, Probability, Score
from dspy.dsp.utils.settings import settings
+from dspy.lm15 import Config, DataPart, Message, Request, choice, score, yes_no
@contextmanager
@@ -73,7 +74,7 @@ class DecisionAdapter:
self.state = state
self.system_one = system_one
- def _prepare(self, signature, demos, inputs, lm_kwargs):
+ def _prepare(self, lm, signature, demos, inputs, lm_kwargs):
from dspy.adapters.utils import get_field_description_string
from dspy.predict.predict import serialize_object
@@ -95,7 +96,26 @@ class DecisionAdapter:
state["demos"] = [
serialize_object({k: v for k, v in demo.items() if k in signature.fields}) for demo in demos
]
- return {"state": state, "questions": questions}
+ properties = {}
+ for name, kind in types.items():
+ if issubclass(kind, Noul):
+ properties[name] = yes_no(name)
+ elif issubclass(kind, Score):
+ properties[name] = score(name, [str(i) for i in range(len(kind.criteria()))])
+ else:
+ criteria = questions[name]["criteria"]
+ if "" in criteria:
+ raise ValueError(
+ f"Jev output {name!r} cannot contain an empty choice label; "
+ "use a nonempty label such as 'no_match'."
+ )
+ properties[name] = choice(name, list(criteria))
+ # The schema declares answer spaces; native questions retain structured instructions and criteria.
+ response_format = {"type": "json_schema", "schema": {"type": "object", "properties": properties}}
+ return Request(
+ model=lm.model, messages=(Message.user(DataPart(value=state)),),
+ config=Config(response_format=response_format, extensions={"questions": questions}),
+ )
for name, kind in types.items():
signature = signature.with_updated_fields(
name, type_=evidence_type(kind), desc="\n" + json.dumps(questions[name], ensure_ascii=False, indent=2)
@@ -136,11 +156,13 @@ class DecisionAdapter:
return results
def __call__(self, lm, lm_kwargs, signature, demos, inputs):
- request = self._prepare(signature, demos, inputs, lm_kwargs)
- completions = [lm(**request)] if self.system_one else self.adapter(lm, **request)
+ request = self._prepare(lm, signature, demos, inputs, lm_kwargs)
+ completions = ([lm(request).provider_data["typesafe"]["answers"]] if self.system_one
+ else self.adapter(lm, **request))
return self._decode(completions)
async def acall(self, lm, lm_kwargs, signature, demos, inputs):
- request = self._prepare(signature, demos, inputs, lm_kwargs)
- completions = [await lm.acall(**request)] if self.system_one else await self.adapter.acall(lm, **request)
+ request = self._prepare(lm, signature, demos, inputs, lm_kwargs)
+ completions = ([(await lm.acall(request)).provider_data["typesafe"]["answers"]] if self.system_one
+ else await self.adapter.acall(lm, **request))
return self._decode(completions)
diff --git a/dspy/clients/base_lm.py b/dspy/clients/base_lm.py
index 44e74f5d6..7901e7128 100644
--- a/dspy/clients/base_lm.py
+++ b/dspy/clients/base_lm.py
@@ -262,10 +262,6 @@ class BaseLM:
class_path = state.pop(LM_CLASS_STATE_KEY, None)
if cls is BaseLM:
- if class_path == "dspy.clients.typesafe.TypeSafe":
- from dspy.clients.typesafe import TypeSafe
-
- return TypeSafe.load_state(state)
if class_path is None:
# Legacy saved programs did not record the concrete LM class.
from dspy.clients.lm import LM
diff --git a/dspy/clients/lm.py b/dspy/clients/lm.py
index c38c5d3ff..2bf35809c 100644
--- a/dspy/clients/lm.py
+++ b/dspy/clients/lm.py
@@ -341,6 +341,21 @@ class LM(BaseLM):
return capabilities(self).response_schema
+ @property
+ def supports_decision_requests(self) -> bool:
+ """Whether the engine accepts typed System One judgments instead of chat prompts."""
+ from dspy.clients.capabilities import resolve
+ from dspy.lm15 import UnknownModelError, UnsupportedFeatureError
+
+ if not isinstance(self.engine, str):
+ return getattr(self.engine, "supports_decision_requests", False) is True
+ if self.engine == "litellm":
+ return False
+ try:
+ return resolve(self).provider == "typesafe"
+ except (UnknownModelError, UnsupportedFeatureError):
+ return False
+
@property
def supported_params(self) -> set[str]:
from dspy.clients.capabilities import capabilities
@@ -834,4 +849,3 @@ def _add_dspy_identifier_to_headers(headers: dict[str, Any] | None = None):
"User-Agent": f"DSPy/{dspy.__version__}",
**headers,
}
-
diff --git a/dspy/clients/typesafe.py b/dspy/clients/typesafe.py
deleted file mode 100644
index 3dde1852d..000000000
--- a/dspy/clients/typesafe.py
+++ /dev/null
@@ -1,154 +0,0 @@
-"""System One client for the non-generative TypeSafe API."""
-
-import copy
-import json
-import os
-
-import dspy
-from dspy.clients.base_lm import LM_CLASS_STATE_KEY, record_history
-from dspy.dsp.utils.settings import settings
-from dspy.utils.annotation import experimental
-from dspy.utils.callback import with_callbacks
-from dspy.utils.inspect_history import pretty_print_history
-
-
-@experimental
-class TypeSafe:
- """Call TypeSafe's System One API with DSPy's shared request cache.
-
- Install ``dspy[typesafe]`` to use this client. Model, API key, and endpoint
- default to TYPESAFE_DEFAULT_MODEL, TYPESAFE_API_KEY, and TYPESAFE_BASE_URL.
- Configure with ``dspy.configure(lm=dspy.experimental.TypeSafe(...))`` or pass
- ``lm=`` when calling a predictor. Predict selects System One translation automatically.
-
- Args:
- model: Model name (defaults to ``jev-latest``).
- api_key: Credential; omitted from saved state and history.
- base_url: Endpoint (defaults to ``https://api.typesafe.ai``).
- cache: Whether to use DSPy's cache.
- timeout: Per-operation timeout in seconds.
- """
-
- supports_decision_requests = True
-
- def __init__(
- self,
- model: str | None = None,
- *,
- api_key: str | None = None,
- base_url: str | None = None,
- cache: bool = True,
- timeout: float = 10.0,
- callbacks=None,
- ):
- self.model = model or os.getenv("TYPESAFE_DEFAULT_MODEL") or "jev-latest"
- self.callbacks = list(callbacks or [])
- self.base_url = (base_url or os.getenv("TYPESAFE_BASE_URL") or "https://api.typesafe.ai").rstrip("/")
- self.api_key = api_key
- self.cache = cache
- self.timeout = timeout
- self.history = []
-
- def copy(self, **kwargs):
- """Copy connection settings and callbacks, starting with empty history."""
- state = self.dump_state()
- state.pop(LM_CLASS_STATE_KEY)
- return type(self)(**{**state, "api_key": self.api_key, "callbacks": self.callbacks, **kwargs})
-
- def inspect_history(self, n=1, file=None):
- pretty_print_history(self.history, n, file=file)
-
- @classmethod
- def load_state(cls, state):
- state = dict(state)
- state.pop(LM_CLASS_STATE_KEY, None)
- return cls(**state)
-
- def dump_state(self):
- """Return reconstruction settings, without credentials or runtime history."""
- return {
- LM_CLASS_STATE_KEY: "dspy.clients.typesafe.TypeSafe",
- "model": self.model,
- "base_url": self.base_url,
- "cache": self.cache,
- "timeout": self.timeout,
- }
-
- def _request(self, state, questions):
- return {
- "provider": "typesafe",
- "model": self.model,
- "base_url": self.base_url,
- "state": state,
- "questions": questions,
- }
-
- def _finish(self, request, response, cache_hit):
- if self.cache and not cache_hit:
- dspy.cache.put(request, response)
- usage = {} if cache_hit else response["usage"]
- if settings.usage_tracker and usage:
- settings.usage_tracker.add_usage(response["model"], usage)
- if not settings.disable_history:
- record_history(
- self,
- {
- "request": copy.deepcopy(request),
- "response": copy.deepcopy(response),
- "usage": usage,
- "cache_hit": cache_hit,
- "messages": None,
- "prompt": json.dumps({"state": request["state"], "questions": request["questions"]}),
- "outputs": [json.dumps(response["answers"])],
- }
- )
- del self.history[: -settings.max_history_size]
- return copy.deepcopy(response["answers"])
-
- def _sdk_kwargs(self):
- return {"model": self.model, "api_key": self.api_key, "base_url": self.base_url, "timeout": self.timeout}
-
- @staticmethod
- def _response(response):
- # Both SDK 0.6's dataclasses and 0.7's Pydantic models expose these attributes.
- return {
- "model": response.model,
- "usage": {"prompt_tokens": response.usage.input_tokens, "completion_tokens": response.usage.output_tokens},
- "answers": {
- name: {
- key: getattr(answer, key)
- for key in ("noul", "score", "choice", "confidence", "probabilities")
- if hasattr(answer, key)
- }
- for name, answer in response.answers.items()
- },
- }
-
- @with_callbacks
- def __call__(self, state, questions):
- request = self._request(state, questions)
- response = dspy.cache.get(request) if self.cache else None
- cache_hit = response is not None
- if not cache_hit:
- try:
- from typesafe_sdk import TypeSafeClient
- except ImportError:
- raise ImportError('Install TypeSafe support with `pip install "dspy[typesafe]"`.') from None
- with TypeSafeClient(**self._sdk_kwargs()) as client:
- response = self._response(client.system_one(state=state, questions=questions))
- return self._finish(request, response, cache_hit)
-
- @with_callbacks
- async def acall(self, state, questions):
- """Async equivalent using the SDK's native asynchronous client."""
- request = self._request(state, questions)
- response = dspy.cache.get(request) if self.cache else None
- cache_hit = response is not None
- if not cache_hit:
- try:
- from typesafe_sdk import AsyncTypeSafeClient
- except ImportError:
- raise ImportError('Install TypeSafe support with `pip install "dspy[typesafe]"`.') from None
- async with AsyncTypeSafeClient(**self._sdk_kwargs()) as client:
- response = self._response(await client.system_one(state=state, questions=questions))
- return self._finish(request, response, cache_hit)
diff --git a/dspy/experimental/__init__.py b/dspy/experimental/__init__.py
index e99c24437..fd9cf1d66 100644
--- a/dspy/experimental/__init__.py
+++ b/dspy/experimental/__init__.py
@@ -1,7 +1,6 @@
from dspy.adapters.types.citation import Citations
from dspy.adapters.types.decision import Choice, Noul, Score
from dspy.adapters.types.document import Document
-from dspy.clients.typesafe import TypeSafe
from dspy.teleprompt.reanchor import ReAnchor
__all__ = [
@@ -10,6 +9,5 @@ __all__ = [
"Choice",
"Noul",
"Score",
- "TypeSafe",
"ReAnchor",
]
diff --git a/dspy/predict/predict.py b/dspy/predict/predict.py
index 36b9652ad..5c0910115 100644
--- a/dspy/predict/predict.py
+++ b/dspy/predict/predict.py
@@ -173,11 +173,11 @@ class Predict(Module, Parameter):
f"LM must be an instance of `dspy.BaseLM`, not a string. Instead of using a string like "
f"'dspy.configure(lm=\"{lm}\")', please configure the LM like 'dspy.configure(lm=dspy.LM(\"{lm}\"))'"
)
- elif not isinstance(lm, BaseLM) and getattr(lm, "supports_decision_requests", False) is not True:
- raise ValueError(f"LM must be a dspy.BaseLM or a decision-request client, not {type(lm)}.")
+ elif not isinstance(lm, BaseLM):
+ raise ValueError(f"LM must be a dspy.BaseLM, not {type(lm)}.")
# If temperature is unset or <=0.15, and n > 1, set temperature to 0.7 to keep randomness.
- defaults = getattr(lm, "kwargs", {})
+ defaults = lm.kwargs
temperature = config.get("temperature") or defaults.get("temperature")
num_generations = config.get("n") or defaults.get("n") or defaults.get("num_generations") or 1
diff --git a/dspy/utils/callback.py b/dspy/utils/callback.py
index 803f07043..901b20bcf 100644
--- a/dspy/utils/callback.py
+++ b/dspy/utils/callback.py
@@ -403,7 +403,7 @@ def _get_on_start_handler(callback: BaseCallback, instance: Any, fn: Callable) -
"""Selects the appropriate on_start handler of the callback based on the instance and function name."""
from dspy.teleprompt.teleprompt import Teleprompter
- if isinstance(instance, dspy.BaseLM) or getattr(instance, "supports_decision_requests", False) is True:
+ if isinstance(instance, dspy.BaseLM):
return callback.on_lm_start
elif isinstance(instance, dspy.Evaluate):
return callback.on_evaluate_start
@@ -431,7 +431,7 @@ def _get_on_end_handler(callback: BaseCallback, instance: Any, fn: Callable) ->
"""Selects the appropriate on_end handler of the callback based on the instance and function name."""
from dspy.teleprompt.teleprompt import Teleprompter
- if isinstance(instance, dspy.BaseLM) or getattr(instance, "supports_decision_requests", False) is True:
+ if isinstance(instance, dspy.BaseLM):
return callback.on_lm_end
elif isinstance(instance, dspy.Evaluate):
return callback.on_evaluate_end
diff --git a/pyproject.toml b/pyproject.toml
index 4d3c42478..89b210951 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -43,7 +43,6 @@ dependencies = [
[project.optional-dependencies]
anthropic = ["anthropic>=0.18.0,<1.0.0"]
-typesafe = ["typesafe-sdk>=0.6.0,<1.0.0"]
weaviate = ["weaviate-client>=4.5.4,<4.22.0"]
mcp = ["mcp; python_version >= '3.10'"]
deno = ["deno>=2.4.5,<3.0.0"]
diff --git a/tests/adapters/test_decision_types.py b/tests/adapters/test_decision_types.py
index b3b449b35..ae1de14b8 100644
--- a/tests/adapters/test_decision_types.py
+++ b/tests/adapters/test_decision_types.py
@@ -54,9 +54,7 @@ def test_ordinary_annotated_fields_keep_existing_parsing_and_schema(adapter):
def test_decision_apis_are_experimental_only():
- from dspy.experimental import TypeSafe
-
- for api in (Choice, Noul, Score, TypeSafe):
+ for api in (Choice, Noul, Score):
assert getattr(dspy.experimental, api.__name__) is api
assert not hasattr(dspy, api.__name__)
assert "Experimental:" in api.__doc__
@@ -123,7 +121,7 @@ def test_predict_outputs_and_generated_schema(adapter, rich):
else:
assert result[name] == value
assert type(result[name]) is type(value)
- prepared = resolve_adapter(None, adapter, signature, {})._prepare(signature, [], {"ticket": "Payment failed."}, {})
+ prepared = resolve_adapter(None, adapter, signature, {})._prepare(None, signature, [], {"ticket": "Payment failed."}, {})
rendered = prepared["signature"]
messages = adapter.format(rendered, [], prepared["inputs"])
assert "Minor" in messages[0]["content"]
@@ -306,7 +304,7 @@ def test_structured_criteria_reach_both_backends_and_survive_save_load(adapter,
assert (chat.urgent.value if rich else chat.urgent) is True
assert (chat.category.value if rich else chat.category) == "technical"
assert chat.severity.value == pytest.approx(1.6)
- translated = resolve_adapter(lm, adapter, sig, module.fields)._prepare(sig, [], {"ticket": "Login fails"}, {})
+ translated = resolve_adapter(lm, adapter, sig, module.fields)._prepare(lm, sig, [], {"ticket": "Login fails"}, {})
for name, criteria in expected.items():
assert json.loads(translated["signature"].output_fields[name].json_schema_extra["desc"])["criteria"] == criteria
module.save(tmp_path / "defaults.json")
diff --git a/tests/clients/test_typesafe.py b/tests/clients/test_typesafe.py
index 61fc2e010..8de4852e7 100644
--- a/tests/clients/test_typesafe.py
+++ b/tests/clients/test_typesafe.py
@@ -1,187 +1,152 @@
-import copy
-import io
import json
+from typing import Literal
import pytest
import dspy
-from dspy.experimental import TypeSafe
+from dspy._vendor.lm15.transports import StdlibAsyncTransport, StdlibTransport
+from dspy.experimental import Choice, Noul, Score
+from dspy.utils.dummies import DummyLM
+from tests.clients.test_lm_engine_execution import DualResponse
from tests.predict.test_decision_parameters import predict, signature
-sdk = pytest.importorskip("typesafe_sdk")
-httpx = pytest.importorskip("httpx2")
-
@pytest.fixture
def transport(monkeypatch):
calls = []
+ monkeypatch.setenv("TYPESAFE_API_KEY", "test-default-key")
def respond(request):
- body = json.loads(request.content)
- calls.append((str(request.url), body))
+ body = json.loads(request.body)
+ calls.append((str(request.url), body, dict(request.headers)))
answers = {}
- for name, q in body["questions"].items():
- if q["type"] == "noul":
+ for name, question in body["questions"].items():
+ if question["type"] == "noul":
answers[name] = {"type": "noul", "noul": 0.8}
- elif q["type"] == "score":
+ elif question["type"] == "score":
answers[name] = {
- "type": "score",
- "score": 1.5,
- "confidence": 0.61,
+ "type": "score", "score": 1.5, "confidence": 0.61,
"probabilities": {"0": 0.1, "1": 0.3, "2": 0.6},
- "legend": {"0": "bad", "1": "fair", "2": "great"},
}
else:
answers[name] = {
- "type": "choice",
- "choice": "2",
- "confidence": 0.73,
+ "type": "choice", "choice": "2", "confidence": 0.73,
"probabilities": {"2": 0.8, "other": 0.2},
}
- return httpx.Response(
- 200, json={"model": body["model"], "answers": answers, "usage": {"input_tokens": 10, "output_tokens": 2}}
- )
-
- sync, asynchronous = sdk.TypeSafeClient, sdk.AsyncTypeSafeClient
- monkeypatch.setattr(sdk, "TypeSafeClient", lambda **kwargs: sync(**kwargs, transport=httpx.MockTransport(respond)))
- monkeypatch.setattr(
- sdk, "AsyncTypeSafeClient", lambda **kwargs: asynchronous(**kwargs, transport=httpx.MockTransport(respond))
- )
- return calls
-
+ return DualResponse(200, json.dumps({
+ "model": body["model"], "answers": answers, "usage": {"input_tokens": 10, "output_tokens": 2},
+ }).encode())
-def test_real_sdk_request_cache_usage_and_local_parameters(transport):
- client = TypeSafe("jev-test", api_key="test-only", base_url="https://example.test")
- module = predict(True, client)
- with dspy.context(track_usage=True):
- first = module(text="x")
- module.fields["flag"]["threshold"] = 0.9
- module.fields["rating"]["cuts"] = [0.5, 1.6]
- module.fields["label"]["weights"] = {"2": 0.1}
- second = module(text="x")
- assert first.flag.value is True
- assert second.flag.value is False
- assert first.flag.confidence == pytest.approx(0.6)
- assert second.flag.confidence == pytest.approx(1 / 9)
- assert first.rating.value == pytest.approx(1.5)
- assert second.rating.value == first.rating.value
- assert first.rating.level == 2
- assert second.rating.level == 1
- assert first.label.value == 2
- assert second.label.value == "other"
- assert second.label.probabilities == first.label.probabilities == {"2": 0.8, "other": 0.2}
- assert second.label.confidence == first.label.confidence == 0.73
- assert first.get_lm_usage() == {"jev-test": {"prompt_tokens": 10, "completion_tokens": 2}}
- assert second.get_lm_usage() == {}
- assert len(transport) == 1
- url, body = transport[0]
- assert url == "https://example.test/v1/systemone"
- assert body["state"] == {
- "instructions": "Assess the document.",
- "input_fields": "1. `text` (str):",
- "inputs": {"text": "x"},
- }
- assert body["questions"]["rating"]["criteria"] == ["bad", "fair", "great"]
- assert "thresholds" not in json.dumps(body)
- assert "weights" not in json.dumps(body)
- assert "cuts" not in json.dumps(body)
- assert "test-only" not in json.dumps(client.history)
- assert [h["cache_hit"] for h in client.history] == [False, True]
- first.rating.probabilities[0] = 0.99
- assert module(text="x").rating.probabilities[0] == 0.1
+ monkeypatch.setattr(StdlibTransport, "stream", lambda self, request: respond(request))
+ monkeypatch.setattr(StdlibAsyncTransport, "stream", lambda self, request: respond(request))
+ return calls
@pytest.mark.asyncio
-async def test_async_sdk_and_shared_cache(transport):
- module = predict(client=TypeSafe("jev-test", api_key="test-only"))
- asynchronous = await module.acall(text="x")
- synchronous = module(text="x")
- assert asynchronous.toDict() == synchronous.toDict()
- module.fields["label"]["weights"] = {"2": 0.1}
- assert (await module.acall(text="x")).label == "other"
- assert len(transport) == 1
- assert synchronous.rating.value == pytest.approx(1.5)
-
-
-def test_cache_identity_and_controls(transport):
- client = TypeSafe("jev-test", api_key="test-only", base_url="https://a.test")
- module = predict(client=client)
- module(text="x")
- client.base_url = "https://b.test"
- module(text="x")
- client.model = "jev-other"
- module(text="x")
- module(text="changed")
- client.cache = False
- module(text="changed")
- assert len(transport) == 5
- with dspy.context(disable_history=True):
- module(text="changed")
- assert len(client.history) == 5
- with dspy.context(max_history_size=1):
- module(text="changed")
- assert len(client.history) == 1
-
-
[email protected]("disabled", [False, True])
-async def test_zero_local_history_limit_preserves_global_history(transport, monkeypatch, disabled):
- from dspy.clients import base_lm
-
- history = []
- monkeypatch.setattr(base_lm, "GLOBAL_HISTORY", history)
- client = TypeSafe("jev-test", api_key="test-only")
- module = predict(client=client)
- with dspy.context(max_history_size=0, disable_history=disabled):
- module(text="x")
- await module.acall(text="x")
- assert client.history == module.history == []
- assert len(history) == (0 if disabled else 2)
- if not disabled:
- assert [entry["cache_hit"] for entry in history] == [False, True]
-
-
-def test_client_copy_and_environment(monkeypatch, transport):
- monkeypatch.setenv("TYPESAFE_DEFAULT_MODEL", "jev-environment")
- monkeypatch.setenv("TYPESAFE_BASE_URL", "https://environment.test/")
- monkeypatch.setenv("TYPESAFE_API_KEY", "test-environment-key")
- client = TypeSafe()
- module = predict(client=client)
- assert module(text="x").flag is True
- assert transport[0][0] == "https://environment.test/v1/systemone"
- assert transport[0][1]["model"] == "jev-environment"
- duplicate = copy.deepcopy(client)
- duplicate.history.clear()
- assert len(client.history) == 1
- assert "api_key" not in client.dump_state()
[email protected]("engine", ["auto", "lm15"])
[email protected]("asynchronous", [False, True])
+async def test_predict_uses_lm15_and_reinterprets_cached_evidence(transport, engine, asynchronous):
+ model = "typesafe:jev-test"
+ lm = dspy.LM(model, engine=engine, api_key="test-explicit-key", api_base="https://example.test", num_retries=0)
+ module = predict(True, lm)
+ try:
+ with dspy.context(track_usage=True):
+ first = await module.acall(text="x") if asynchronous else module(text="x")
+ module.fields["flag"]["threshold"] = 0.9
+ module.fields["rating"]["cuts"] = [0.5, 1.6]
+ module.fields["label"]["weights"] = {"2": 0.1}
+ second = await module.acall(text="x") if asynchronous else module(text="x")
+ assert first.flag.value is True and second.flag.value is False
+ assert first.flag.confidence == pytest.approx(0.6)
+ assert second.flag.confidence == pytest.approx(1 / 9)
+ assert first.rating.value == second.rating.value == pytest.approx(1.5)
+ assert first.rating.level == 2 and second.rating.level == 1
+ assert first.label.value == 2 and second.label.value == "other"
+ assert second.label.probabilities == first.label.probabilities == {"2": 0.8, "other": 0.2}
+ assert second.label.confidence == first.label.confidence == 0.73
+ assert first.get_lm_usage()[model]["prompt_tokens"] == 10
+ assert first.get_lm_usage()[model]["completion_tokens"] == 2
+ assert second.get_lm_usage() == {}
+ assert len(transport) == 1
+ url, body, headers = transport[0]
+ assert url == "https://example.test/v1/systemone"
+ assert headers["Authorization"] == "Bearer test-explicit-key"
+ assert body["model"] == "jev-test"
+ assert body["state"] == {
+ "instructions": "Assess the document.", "input_fields": "1. `text` (str):", "inputs": {"text": "x"},
+ }
+ assert body["questions"]["rating"]["criteria"] == ["bad", "fair", "great"]
+ assert not {"threshold", "weights", "cuts"} & body["questions"]["flag"].keys()
+ assert isinstance(lm.history[-1]["request"], dspy.lm15.Request)
+ assert lm.history[-1]["response"].provider_data["typesafe"]["answers"]["rating"]["score"] == 1.5
+ first.rating.probabilities[0] = 0.99
+ third = await module.acall(text="x") if asynchronous else module(text="x")
+ assert third.rating.probabilities[0] == 0.1
+ finally:
+ await lm.aclose()
@pytest.mark.asyncio
-async def test_predict_demos_sdk_cache_history_and_usage(transport, monkeypatch):
- monkeypatch.setenv("TYPESAFE_API_KEY", "test-sdk-key")
- module = dspy.Predict(signature(True))
- module.set_lm(TypeSafe("jev-test"))
- module.demos = [dspy.Example(text="labeled document", flag=False, rating=0.0, label="other")]
- with dspy.context(track_usage=True):
- first = module(text="query")
- second = await module.acall(text="query")
- await module.acall(text="query", demos=[])
- assert len(transport) == 2
- assert transport[0][1]["state"]["demos"] == [module.demos[0].toDict()]
- assert "demos" not in transport[1][1]["state"]
- assert module.demos == [dspy.Example(text="labeled document", flag=False, rating=0.0, label="other")]
- assert first.toDict() == second.toDict()
- assert first.get_lm_usage() == {"jev-test": {"prompt_tokens": 10, "completion_tokens": 2}}
- assert second.get_lm_usage() == {}
- assert len(module.history) == 3
- stream = io.StringIO()
- module.inspect_history(file=stream)
- assert "query" in stream.getvalue()
- assert "probabilities" in stream.getvalue()
[email protected]("asynchronous", [False, True])
[email protected]("rich", [False, True])
+async def test_empty_choice_labels_are_rejected_only_by_jev(transport, asynchronous, rich):
+ annotation = Choice[("", "No match"), ("match", "Match")] if rich else Literal["", "match"]
+ module = dspy.Predict(dspy.Signature({
+ "text": (str, dspy.InputField()), "label": (annotation, dspy.OutputField(desc="Select a match.")),
+ }))
+ lm = dspy.LM("typesafe:jev-test")
+ module.set_lm(lm)
+ try:
+ with pytest.raises(ValueError, match="Jev output 'label'.*empty choice label.*no_match"):
+ await module.acall(text="x") if asynchronous else module(text="x")
+ assert transport == []
+ finally:
+ await lm.aclose()
+
+ evidence = {"probabilities": {"": 0.8, "match": 0.2}, "confidence": 0.6}
+ module.set_lm(DummyLM([{"label": evidence if rich else ""}]))
+ result = await module.acall(text="x") if asynchronous else module(text="x")
+ assert (result.label.value if rich else result.label) == ""
@pytest.mark.asyncio
-async def test_standalone_client_callbacks_copy_and_reload(transport, tmp_path):
[email protected]("asynchronous", [False, True])
+async def test_structured_questions_and_raw_evidence(transport, asynchronous):
+ sig = dspy.Signature({
+ "text": (str, dspy.InputField()),
+ "name": (Noul, dspy.OutputField()),
+ "rating": (Score["bad", "fair", "great"], dspy.OutputField()),
+ "strict": (Choice[(2, ""), ("other", "")], dspy.OutputField()),
+ }, "Assess the document.")
+ lm = dspy.LM("typesafe:jev-test", engine="lm15")
+ module = dspy.Predict(sig)
+ module.set_lm(lm)
+ module.demos = [dspy.Example(text="example", name=False)]
+ module.fields = {
+ "name": {"instructions": {"focus": ["impact"]}, "criteria": {"true": {"examples": ["Outage"]}, "false": None}},
+ "rating": {"instructions": ["Assess severity.", {"ignore": "tone"}], "criteria": [{"what": "bad"}, "fair", {"examples": ["Resolved"]}]},
+ "strict": {"instructions": None, "criteria": {"2": {"what": "Known"}, "other": None}},
+ }
+ try:
+ result = await module.acall(text="query") if asynchronous else module(text="query")
+ _, body, headers = transport[0]
+ assert headers["Authorization"] == "Bearer test-default-key"
+ assert body["state"]["inputs"] == {"text": "query"}
+ assert body["state"]["demos"] == [{"text": "example", "name": False}]
+ assert body["questions"] == {
+ name: {"type": kind, **module.fields[name]}
+ for name, kind in [("name", "noul"), ("rating", "score"), ("strict", "choice")]
+ }
+ assert result.name.probability == 0.8
+ assert result.rating.value == pytest.approx(1.5)
+ assert result.rating.confidence == 0.61
+ assert result.strict.value == 2
+ assert result.strict.confidence == 0.73
+ finally:
+ await lm.aclose()
+
+
+def test_jev_predict_uses_normal_lm_persistence_and_callbacks(transport, tmp_path):
from dspy.utils.callback import BaseCallback
class Calls(BaseCallback):
@@ -195,27 +160,21 @@ async def test_standalone_client_callbacks_copy_and_reload(transport, tmp_path):
self.events.append("end")
callbacks = Calls()
- client = TypeSafe("jev-test", base_url="https://original.test", callbacks=[callbacks])
- assert not isinstance(client, dspy.BaseLM)
- module = dspy.Predict(signature(True))
- module.set_lm(client)
- first = module(text="x")
- assert (await module.acall(text="x")).toDict() == first.toDict()
- assert callbacks.events == ["start", "end", "start", "end"]
- duplicate = client.copy(base_url="https://copy.test")
- assert duplicate.history == []
- duplicate.callbacks.clear()
- assert client.callbacks == [callbacks]
- assert len(client.history) == len(module.history) == 2
- module(text="x", lm=duplicate)
- assert len(transport) == 2 # Different endpoints must not share cached evidence.
- path = tmp_path / "standalone.json"
- module.save(path)
+ lm = dspy.LM("typesafe:jev-test", engine="lm15", callbacks=[callbacks])
+ module = predict(True, lm)
restored = dspy.Predict(signature(True))
- restored.load(path, allow_unsafe_lm_state=True)
- assert type(restored.lm) is TypeSafe
- assert restored.lm.base_url == client.base_url
- assert restored(text="x").toDict() == first.toDict()
- assert len(transport) == 2
- with pytest.raises(TypeError):
- client.copy(temperature=0.7)
+ try:
+ first = module(text="x")
+ assert module(text="x").toDict() == first.toDict()
+ assert callbacks.events == ["start", "end", "start", "end"]
+ path = tmp_path / "jev.json"
+ module.save(path)
+ restored.load(path)
+ assert type(restored.lm) is dspy.LM
+ assert restored.lm.engine == "lm15"
+ assert restored(text="x").toDict() == first.toDict()
+ assert len(transport) == 1
+ finally:
+ lm.close()
+ if restored.lm is not None:
+ restored.lm.close()
diff --git a/tests/predict/test_decision_live.py b/tests/predict/test_decision_live.py
index 6c5e227df..08ea39327 100644
--- a/tests/predict/test_decision_live.py
+++ b/tests/predict/test_decision_live.py
@@ -12,7 +12,7 @@ from typing import Literal
import pytest
import dspy
-from dspy.experimental import Choice, Noul, Score, TypeSafe
+from dspy.experimental import Choice, Noul, Score
from tests.predict.test_decision_parameters import FakeClient
pytestmark = pytest.mark.llm_call
@@ -81,10 +81,9 @@ def lm(lm_for_test):
@pytest.fixture(scope="module")
def client():
- pytest.importorskip("typesafe_sdk")
if not os.getenv("TYPESAFE_API_KEY"):
pytest.skip("TYPESAFE_API_KEY is required for the live Jev integration checks")
- return TypeSafe(cache=False, timeout=60)
+ return dspy.LM("typesafe:jev-latest", engine="lm15", cache=False, timeout=60)
def invoke(backend, sig, inputs, lm, client):
@@ -169,7 +168,7 @@ def test_live_distribution_reinterpretation(client):
module = dspy.Predict(signature(True))
module.set_lm(client)
initial = module(ticket=CASES[2][1])
- raw = client.history[-1]["response"]["answers"]
+ raw = client.history[-1]["response"].provider_data["typesafe"]["answers"]
# Replay the actual live evidence to isolate local interpretation from model variability.
module.lm = FakeClient(answers=raw)
module.fields["urgent"] = {"threshold": initial.urgent.probability}
@@ -194,7 +193,7 @@ def test_live_choice_weighted_reinterpretation(client):
module.set_lm(client)
ticket = "Checkout rejected a payment. It might be an incorrect charge or a software fault; neither is confirmed."
initial = module(ticket=ticket).category
- raw = client.history[-1]["response"]["answers"]
+ raw = client.history[-1]["response"].provider_data["typesafe"]["answers"]
other = "technical" if initial.value == "billing" else "billing"
assert initial.probabilities[other] > 0, "Live evidence must assign mass to the alternative to test reweighting"
weights = {initial.value: 0.0, other: 1.0}
diff --git a/tests/predict/test_decision_parameters.py b/tests/predict/test_decision_parameters.py
index 874abedab..a18f933e7 100644
--- a/tests/predict/test_decision_parameters.py
+++ b/tests/predict/test_decision_parameters.py
@@ -7,23 +7,43 @@ from typing import Annotated, Literal, get_args
import pytest
import dspy
-from dspy.experimental import Choice, Noul, Score, TypeSafe
+from dspy.clients.engines.dummy_engine import AsyncDummyEngine
+from dspy.experimental import Choice, Noul, Score
+from dspy.lm15 import Message, Request, Response, Usage
Rating = Score["bad", "fair", "great"]
Label = Choice[(2, ""), ("other", "")]
-class FakeClient:
+class DecisionEngine:
supports_decision_requests = True
+ def __init__(self, owner):
+ self.owner = owner
+
+ def complete(self, request):
+ assert isinstance(request, Request)
+ state = request.messages[0].parts[0].value
+ questions = request.config.extensions["questions"]
+ self.owner.calls.append(copy.deepcopy((state, questions)))
+ response = Response(id=None, model=request.model, message=Message.assistant(""), finish_reason="stop", usage=Usage(),
+ provider_data={"typesafe": {}})
+ # Inject raw evidence after construction so malformed-evidence tests reach DSPy's decoder,
+ # including non-JSON keys and nonfinite values rejected by Response's generic JSON validation.
+ response.provider_data["typesafe"]["answers"] = self.owner.evidence(state, questions)
+ return response
+
+
+class FakeClient(dspy.LM):
def __init__(self, probability=0.8, choice="2", answers=None):
+ engine = DecisionEngine(self)
+ super().__init__("typesafe:jev-test", engine=engine, async_engine=AsyncDummyEngine(engine), cache=False)
self.probability = probability
self.choice = choice
self.answers = answers
self.calls = []
- def __call__(self, state, questions):
- self.calls.append(copy.deepcopy((state, questions)))
+ def evidence(self, state, questions):
if self.answers is not None:
return copy.deepcopy(self.answers)
answers = {}
@@ -40,9 +60,6 @@ class FakeClient:
}
return answers
- async def acall(self, **kwargs):
- return self(**kwargs)
-
def signature(rich=False):
return dspy.Signature(
@@ -161,7 +178,7 @@ def test_score_cuts_normalization_and_snapshot(cuts, level):
assert before.level == 2 and after.level == level
assert before.confidence == after.confidence == 0.61
assert client.calls[0] == client.calls[1]
- answers = client(*client.calls[0])
+ answers = client.evidence(*client.calls[0])
answers["rating"]["probabilities"] = {0: 0.099, 1: 0.297, 2: 0.594}
result = module(text="x", lm=FakeClient(answers=answers)).rating
assert result.value == pytest.approx(1.5)
@@ -286,7 +303,7 @@ def test_malformed_evidence_is_rejected(field, update):
client = FakeClient()
module = predict(True, client)
module(text="x")
- answers = client(*client.calls[0])
+ answers = client.evidence(*client.calls[0])
answers[field].update(update)
with pytest.raises(ValueError):
module(text="x", lm=FakeClient(answers=answers))
@@ -349,11 +366,11 @@ def test_nested_mutations_are_revalidated(setting):
def test_inflight_decoding_uses_configuration_snapshot():
class UpdatingClient(FakeClient):
- def __call__(self, state, questions):
+ def evidence(self, state, questions):
module.fields["flag"]["threshold"] = 0.9
module.fields["rating"]["cuts"][1] = 1.6
module.fields["label"]["weights"]["2"] = 0.1
- return super().__call__(state, questions)
+ return super().evidence(state, questions)
module = predict(True, UpdatingClient())
module.fields["rating"] = {"cuts": [0.5, 1.5]}
@@ -469,7 +486,7 @@ def test_null_instructions_and_criteria_survive_reload(tmp_path):
def test_reset_copy_and_endpoint_state(tmp_path):
- module = predict(True, TypeSafe("jev-test", api_key="test-credential", base_url="https://example.test"))
+ module = predict(True, dspy.LM("typesafe:jev-test", engine="lm15", api_key="test-credential", api_base="https://example.test"))
module.fields["flag"]["threshold"] = 0.9
module.demos = [{"text": "example", "flag": False}]
duplicate = module.reset_copy()
@@ -481,9 +498,10 @@ def test_reset_copy_and_endpoint_state(tmp_path):
assert "test-credential" not in path.read_text()
restored = predict(True)
restored.load(path)
- assert restored.lm.base_url != "https://example.test"
+ assert restored.lm.kwargs.get("api_base") != "https://example.test"
restored.load(path, allow_unsafe_lm_state=True)
- assert restored.lm.base_url == "https://example.test" and restored.lm.api_key is None
+ assert restored.lm.kwargs["api_base"] == "https://example.test"
+ assert restored.lm.kwargs.get("api_key") is None
@pytest.mark.asyncio
diff --git a/tests/predict/test_predict.py b/tests/predict/test_predict.py
index ca5b21965..c79e9f6a1 100644
--- a/tests/predict/test_predict.py
+++ b/tests/predict/test_predict.py
@@ -899,7 +899,7 @@ def test_error_message_on_invalid_lm_setup():
dspy.configure(lm=dummy_lm)
with pytest.raises(ValueError) as e:
Predict("question -> answer")(question="Why did a chicken cross the kitchen?")
- assert "LM must be a dspy.BaseLM or a decision-request client, not <class 'function'>." in str(e.value)
+ assert "LM must be a dspy.BaseLM, not <class 'function'>." in str(e.value)
@pytest.mark.parametrize("adapter_type", ["chat", "json"])
diff --git a/tests/predict/test_predict_decisions.py b/tests/predict/test_predict_decisions.py
index 42691e435..60fc82498 100644
--- a/tests/predict/test_predict_decisions.py
+++ b/tests/predict/test_predict_decisions.py
@@ -6,8 +6,9 @@ from typing import Annotated, Literal
import pytest
import dspy
-from dspy.experimental import Choice, Noul, Score, TypeSafe
+from dspy.experimental import Choice, Noul, Score
from dspy.utils.dummies import DummyLM
+from tests.predict.test_decision_parameters import FakeClient
Rating = Score["bad", "fair", "great"]
Label = Choice[(2, "primary"), ("other", "secondary")]
@@ -29,17 +30,9 @@ EVIDENCE = {
}
-class FakeTypeSafe(TypeSafe):
+class FakeTypeSafe(FakeClient):
def __init__(self):
- super().__init__("jev-test")
- self.calls = []
-
- def __call__(self, state, questions):
- self.calls.append(copy.deepcopy({"state": state, "questions": questions}))
- return copy.deepcopy(EVIDENCE)
-
- async def acall(self, **kwargs):
- return self(**kwargs)
+ super().__init__(answers=EVIDENCE)
def configured_predict(lm):
@@ -72,7 +65,7 @@ def test_backend_equivalence(adapter):
prompt = json.dumps(lm.lm.history[-1]["messages"])
assert "relevance" in prompt and "examples" in prompt
system = lm.lm.history[-1]["messages"][0]["content"]
- for name, question in jev.lm.calls[-1]["questions"].items():
+ for name, question in jev.lm.calls[-1][1].items():
# Decision descriptions are real multiline JSON in both adapter prompts.
description = system.split(f"`{name}` (", 1)[1].split("): \n", 1)[1]
assert description.startswith('{\n "instructions": ')
@@ -98,25 +91,25 @@ async def test_demos_overrides_trace_and_save_load(tmp_path):
assert dspy.settings.trace[0][0] is module
assert dspy.settings.trace[0][1] == {"text": "new"}
assert dspy.settings.trace[0][2].flag == result.flag
- request = client.calls[-1]
- assert request["state"]["instructions"] == "Override instructions."
- assert request["state"]["inputs"] == {"text": "new"}
- assert request["state"]["demos"] == [{"text": "override", "flag": False}]
+ state, questions = client.calls[-1]
+ assert state["instructions"] == "Override instructions."
+ assert state["inputs"] == {"text": "new"}
+ assert state["demos"] == [{"text": "override", "flag": False}]
assert override == snapshot
assert module.demos[0].text == "saved"
assert module.signature is Assess
# Save a reconstructible provider, never a fixture class or credentials.
- module.lm = TypeSafe("jev-test", api_key="do-not-save")
+ module.lm = dspy.LM("typesafe:jev-test", engine="lm15", api_key="do-not-save", cache=False)
path = tmp_path / "predict.json"
module.save(path)
restored = dspy.Predict(Assess)
restored.load(path)
assert restored.fields == module.fields
assert restored.demos == [{"text": "saved", "flag": True, "rating": 1.0, "label": 2}]
- assert isinstance(restored.lm, TypeSafe)
+ assert isinstance(restored.lm, dspy.LM)
assert "api_key" not in path.read_text()
restored(text="new", lm=client)
- assert client.calls[-1]["state"]["demos"] == restored.demos
+ assert client.calls[-1][0]["demos"] == restored.demos
copied = restored.deepcopy()
copied.fields["flag"]["threshold"] = 0.9
assert restored.fields["flag"]["threshold"] == 0.7
@@ -171,7 +164,10 @@ async def test_native_decision_state_does_not_depend_on_client_binding(binding):
assert result.flag is True
assert result.label == 2 and type(result.label) is int
assert module.fields == {}
+ bound_lm = module.lm
+ module.lm = None # Scripted custom engines deliberately have no persistence protocol.
assert "fields" not in module.dump_state()
+ module.lm = bound_lm
# A previous decision-client call must not silently opt native LM outputs into evidence schemas.
lm = DummyLM([{"flag": False, "label": "other"}] * 2)
@@ -181,7 +177,7 @@ async def test_native_decision_state_does_not_depend_on_client_binding(binding):
def test_invalid_criteria_load_does_not_mutate_predict():
- module = configured_predict(TypeSafe("jev-test"))
+ module = configured_predict(dspy.LM("typesafe:jev-test", engine="lm15", cache=False))
before = module.dump_state()
invalid = copy.deepcopy(before)
invalid["fields"]["rating"]["criteria"] = {"wrong": "shape"}
@@ -199,7 +195,7 @@ def test_rich_demos_remain_json_serializable_after_reload(tmp_path):
module.load(path)
client = FakeTypeSafe()
module(text="x", lm=client)
- assert client.calls[-1]["state"]["demos"] == [
+ assert client.calls[-1][0]["demos"] == [
{"text": "rich label", "flag": {"value": False, "probability": 0.2, "confidence": 0.6}}
]
assert flag.probability == 0.2
@@ -225,8 +221,8 @@ def test_native_literal_not_supported_by_jev_still_works_with_llm():
def test_choice_uses_distribution_not_provider_choice_or_key_order():
class Fixed(FakeTypeSafe):
- def __call__(self, **kwargs):
- result = super().__call__(**kwargs)
+ def evidence(self, state, questions):
+ result = super().evidence(state, questions)
result["label"] = {"choice": "other", "probabilities": {"other": 0.5, "2": 0.5}, "confidence": 0.4}
return result
@@ -283,17 +279,12 @@ def test_unsupported_options_and_streaming_fail_explicitly():
@pytest.mark.asyncio
async def test_decision_capability_dispatches_before_chat_checks():
- class DecisionClient:
- supports_decision_requests = True
-
- def __call__(self, state, questions):
+ class DecisionClient(FakeTypeSafe):
+ def evidence(self, state, questions):
assert state["inputs"] == {"text": "document"}
assert questions["rating"]["type"] == "score"
return copy.deepcopy(EVIDENCE)
- async def acall(self, **kwargs):
- return self(**kwargs)
-
class ForbiddenAdapter(dspy.ChatAdapter):
def __call__(self, *args, **kwargs):
pytest.fail("Decision requests must bypass chat adapters")
@@ -308,9 +299,6 @@ async def test_decision_capability_dispatches_before_chat_checks():
assert (await module.acall(text="document")).toDict() == result.toDict()
assert result.flag.value is True
assert result.rating.value == pytest.approx(1.5)
- client.supports_decision_requests = False
- with pytest.raises(ValueError, match="decision-request client"):
- module(text="document")
@pytest.mark.parametrize("desc", [None, "", " "])
diff --git a/tests/teleprompt/reanchor/fakes.py b/tests/teleprompt/reanchor/fakes.py
index 6f325cb5e..bf7d07dbd 100644
--- a/tests/teleprompt/reanchor/fakes.py
+++ b/tests/teleprompt/reanchor/fakes.py
@@ -1,32 +1,26 @@
"""Stand-in decision clients and generative LMs for the ReAnchor tests."""
-import copy
import re
import threading
+import dspy
from dspy.clients.engines.dummy_engine import AsyncDummyEngine, DummyEngine
from dspy.utils.dummies import DummyLM
+from tests.predict.test_decision_parameters import DecisionEngine
-class FakeClient:
+class FakeClient(dspy.LM):
"""A System One client. Answers each question with `answer(state, name, question)`, and records every request."""
- supports_decision_requests = True
-
- def __init__(self, answer, cache=True):
+ def __init__(self, answer, cache=False):
+ engine = DecisionEngine(self)
+ super().__init__("typesafe:jev-test", engine=engine, async_engine=AsyncDummyEngine(engine), cache=cache)
self.answer = answer
- self.cache = cache
self.calls = []
- self.history = []
- self.callbacks = []
- def __call__(self, state, questions):
- self.calls.append(copy.deepcopy((state, questions)))
+ def evidence(self, state, questions):
return {name: self.answer(state, name, q) for name, q in questions.items()}
- async def acall(self, state, questions):
- return self(state, questions)
-
class _ComputedEngine(DummyEngine):
_lock = threading.Lock()
@@ -61,7 +55,7 @@ def noul(p: float) -> dict:
def score(probabilities: dict[int, float], confidence: float = 0.8) -> dict:
- return {"score": 0.0, "confidence": confidence, "probabilities": probabilities}
+ return {"score": 0.0, "confidence": confidence, "probabilities": {str(k): v for k, v in probabilities.items()}}
def choice(probabilities: dict[str, float], confidence: float = 0.7) -> dict:
diff --git a/uv.lock b/uv.lock
index 5c519913b..70df8afae 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1,5 +1,5 @@
version = 1
-revision = 5
+revision = 3
requires-python = ">=3.10, <3.16"
resolution-markers = [
"python_full_version >= '3.15' and sys_platform != 'win32'",
@@ -894,7 +894,7 @@ wheels = [
[[package]]
name = "dspy"
-version = "3.4.0"
+version = "3.4.1"
source = { editable = "." }
dependencies = [
{ name = "anyio" },
@@ -968,9 +968,6 @@ test-extras = [
{ name = "pandas", version = "2.3.3", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
{ name = "pandas", version = "3.0.5", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
]
-typesafe = [
- { name = "typesafe-sdk" },
-]
weaviate = [
{ name = "weaviate-client" },
]
@@ -1025,10 +1022,9 @@ requires-dist = [
{ name = "ruff", marker = "extra == 'dev'", specifier = ">=0.3.0" },
{ name = "tenacity", specifier = ">=8.2.3" },
{ name = "tqdm", specifier = ">=4.66.1" },
- { name = "typesafe-sdk", marker = "extra == 'typesafe'", specifier = ">=0.6.0,<1.0.0" },
{ name = "weaviate-client", marker = "extra == 'weaviate'", specifier = ">=4.5.4,<4.22.0" },
]
-provides-extras = ["anthropic", "typesafe", "weaviate", "mcp", "deno", "langchain", "optuna", "numpy", "litellm", "dev", "test-extras"]
+provides-extras = ["anthropic", "weaviate", "mcp", "deno", "langchain", "optuna", "numpy", "litellm", "dev", "test-extras"]
[package.metadata.requires-dev]
dev = [{ name = "dspy-interpreters", git = "https://github.com/cmpnd-ai/dspy-interpreters" }]
@@ -1623,19 +1619,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
]
-[[package]]
-name = "httpcore2"
-version = "2.13.0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "h11" },
- { name = "truststore" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/15/8c/e925b1c92018abb3a1863ce1549d76d2381e334d21d65d4ac8f65dabd78a/httpcore2-2.13.0.tar.gz", hash = "sha256:2adc8be4fb285fbcd6d894298db3b52c177e74b6674eda3a76bd36be3292a3db", size = 67740, upload-time = "2026-09-14T14:18:04.717Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/7e/0d/117a771a2bb91df334b66bf4da14cd02f21aefbcfe53180f336ce55e8f90/httpcore2-2.13.0-py3-none-any.whl", hash = "sha256:35ae5be347aa40467b4a5dc032ac67ebb6d27189fc97e8cebcf99616f6a1bb9e", size = 83162, upload-time = "2026-09-14T14:18:02.529Z" },
-]
-
[[package]]
name = "httpx"
version = "0.28.1"
@@ -1660,32 +1643,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/d2/fd/6668e5aec43ab844de6fc74927e155a3b37bf40d7c3790e49fc0406b6578/httpx_sse-0.4.3-py3-none-any.whl", hash = "sha256:0ac1c9fe3c0afad2e0ebb25a934a59f4c7823b60792691f779fad2c5568830fc", size = 8960, upload-time = "2025-10-10T21:48:21.158Z" },
]
-[[package]]
-name = "httpx2"
-version = "2.13.0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "anyio", marker = "sys_platform != 'emscripten'" },
- { name = "httpcore2", marker = "sys_platform != 'emscripten'" },
- { name = "httpx2-jsfetch", marker = "python_full_version >= '3.12' and sys_platform == 'emscripten'" },
- { name = "idna" },
- { name = "truststore", marker = "sys_platform != 'emscripten'" },
- { name = "typing-extensions", marker = "python_full_version < '3.13'" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/b9/a0/e9deef4654132857b5a5dbe4eddd0ac59c2814500e11f2f5044cd81103ee/httpx2-2.13.0.tar.gz", hash = "sha256:81bd07dc67a3701729ef1f777a3c00c915d4539604fdb5afd327f8682f6b7b44", size = 100290, upload-time = "2026-09-14T14:18:05.486Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/fe/d1/a0c72b0e006df654709fbc366cc5bcb53e5aee13e1e3395152c6dd293376/httpx2-2.13.0-py3-none-any.whl", hash = "sha256:fc12720cedf72faa26cca6b4ca394e05c894e7d7933fc45cafe767960804e49a", size = 95565, upload-time = "2026-09-14T14:18:03.553Z" },
-]
-
-[[package]]
-name = "httpx2-jsfetch"
-version = "1.0"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" },
-]
-
[[package]]
name = "huggingface-hub"
version = "1.27.0"
@@ -4734,15 +4691,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/f9/1c/01bfd571a64e7f270e6bab5e33777debe0edc56759233ce84f27dec92d14/tqdm-4.70.0-py3-none-any.whl", hash = "sha256:7f585706bfddbdebf89daac705b2dfcc16890130727d3197ca62c732b4310953", size = 80184, upload-time = "2026-07-27T11:33:13.167Z" },
]
-[[package]]
-name = "truststore"
-version = "0.10.4"
-source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/53/a3/1585216310e344e8102c22482f6060c7a6ea0322b63e026372e6dcefcfd6/truststore-0.10.4.tar.gz", hash = "sha256:9d91bd436463ad5e4ee4aba766628dd6cd7010cf3e2461756b3303710eebc301", size = 26169, upload-time = "2025-08-12T18:49:02.73Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/19/97/56608b2249fe206a67cd573bc93cd9896e1efb9e98bce9c163bcdc704b88/truststore-0.10.4-py3-none-any.whl", hash = "sha256:adaeaecf1cbb5f4de3b1959b42d41f6fab57b2b1666adb59e89cb0b53361d981", size = 18660, upload-time = "2025-08-12T18:49:01.46Z" },
-]
-
[[package]]
name = "typeguard"
version = "4.6.0"
@@ -4755,22 +4703,6 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/8f/eb/461d5f167b6f5c7d97696f397c82f82e3480e003fce3f0a1cd1dd26e2eb2/typeguard-4.6.0-py3-none-any.whl", hash = "sha256:79878165bb86f2cf5d41d159a0ff1792a796cf496882d2fe1b1c6c7049b9cdd7", size = 36884, upload-time = "2026-07-26T08:40:21.868Z" },
]
-[[package]]
-name = "typesafe-sdk"
-version = "0.7.0"
-source = { registry = "https://pypi.org/simple" }
-dependencies = [
- { name = "httpx2" },
- { name = "pydantic" },
- { name = "pydantic-core" },
- { name = "tenacity" },
- { name = "typing-extensions" },
-]
-sdist = { url = "https://files.pythonhosted.org/packages/28/e2/ac317772d4d5cfabf3cecdeacd83cc838523e240bb4e1cf256837e6005bb/typesafe_sdk-0.7.0.tar.gz", hash = "sha256:930d42fd73cfed6f25bccae488ce0f30f6043eaedd8682ef59734e79ab94a876", size = 22235, upload-time = "2026-09-18T09:12:30.846Z" }
-wheels = [
- { url = "https://files.pythonhosted.org/packages/d3/2a/16f4163e6d8827ef80b2ed7a400c80688e1ebf571c10f143f792bdafc654/typesafe_sdk-0.7.0-py3-none-any.whl", hash = "sha256:c6d2257c4b04b8d4d81cff2b55489b4188795fd44fb40b9cef26ff243b2d1080", size = 35352, upload-time = "2026-09-18T09:12:29.625Z" },
-]
-
[[package]]
name = "typing-extensions"
version = "4.16.0"