Skip to content

armgit / dspy

Public Imported from GitHub
0

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

Python

Update bundled lm15 to 1.5.0 with reviewed source patches (#10660)

Isaac Miller634fa0197449
diff --git a/dspy/_vendor/lm15-provenance.txt b/dspy/_vendor/lm15-provenance.txt
index e4a9aa767..26e0d012a 100644
--- a/dspy/_vendor/lm15-provenance.txt
+++ b/dspy/_vendor/lm15-provenance.txt
@@ -1,8 +1,8 @@
source=https://github.com/cmpnd-ai/lm15-python.git
-version=1.4.0
-commit=05acf78594fe82df81d9cc37b1c88c5ffc99760b
-contract=10645e5f6a69d9d7a365bdb62de9abac1f4dcffc
-split=39ec7880f77e9452e19a69ccb2f2c3e2d31166be
-upstream_tag=v1.4.0
-upstream_commit=48ab49d84257873e63329c62712973cd0c838363
-patches=2d3730fb1de1b501a08cb457e5a3242da77ca141,1e04a5a2edd6d81e9d2940f08b7ce87d11caa013,f6a7f8bb8bc13c247053a5a42728bbd9c008fe13,7d344a10ee0db3cec5516dbdffe496f1d36760a8,5211b7df922247c82a6639a1c1fe013e9a0491c6,3e9269f199a450b105637b4db6764a04920b454e,a91003b66b64fea90d1fd104429dee1585889007,5c4770348454193b9a6abfba69d1a3419faf5652,a3a526edffb18ca2f8818e9dc14da31c356e4da6,359f90953dd90089c306ceb5a69fe10bbb14c483
+version=1.5.0
+commit=1c6a5c7a9a87482db2b61817847f4ece04339df2
+contract=6dc1c5ccfe8e2e3b0e8b2eece74b5aa3546bb567
+split=57787543fdb848cf74e5699ecd66a1339c4fcc5a
+upstream_tag=v1.5.0
+upstream_commit=6a1814a04565bcabe2a82d7c729b696a102d14ae
+patches=cc8a5b20763718faf4a70a1f8c5bd902eccb7827,b0f32a1cb566c9cf0559051e66333fa3115e5f7e,2f0d9b7fe7158778b4a3edc1a3087b13142bb29d,dfb1e390073fbb6a2ff668996f9d2bb7e394dd0a,37ebcfbc66899e18633663034bd27788ed8f8c5f,89df856db40f0a4f2b9926e20b7184f21de6033b,ff3f297ed5795f02d203c32bf1e26c204bfa4d71,07816eca2bda2d7ee149266b48a92c430377293c,d8dab6150caf86e0328385c89475d8255ac3fd88,d2c73eb1e5099f9ddd53e638ccd8071a907d55f3
diff --git a/dspy/_vendor/lm15/__init__.py b/dspy/_vendor/lm15/__init__.py
index 55c0b8ed2..3fac3f28c 100644
--- a/dspy/_vendor/lm15/__init__.py
+++ b/dspy/_vendor/lm15/__init__.py
@@ -226,7 +226,7 @@ from .transports import Timeouts
from .adaptation import Adaptation, AdaptationPolicy
# ── Judgments (changes/2026-09-17-judgments.md) ─────────────────────
-from .judgments import choice, judgments, score, yes_no
+from .judgments import bounding_box, choice, judgments, score, yes_no
from .types import data
__all__ = [
@@ -269,7 +269,7 @@ __all__ = [
"Auth", "AsyncAuth", "BoundClient", "TerminalUI", "login_providers", "connect",
# providers
"providers",
- "choice", "judgments", "score", "yes_no", "data",
+ "bounding_box", "choice", "judgments", "score", "yes_no", "data",
"OpenAILM", "OpenAIChatLM", "AnthropicLM", "GeminiLM", "ClaudeCodeLM", "OpenAICodexLM", "XaiLM", "TypeSafeLM", "AsyncTypeSafeLM",
"ProviderLM",
# the Chat Completions dialect read in: a request body -> Request (MAP-12), a response body -> Response
diff --git a/dspy/_vendor/lm15/_version.py b/dspy/_vendor/lm15/_version.py
index 7931e2bbd..6b5b57238 100644
--- a/dspy/_vendor/lm15/_version.py
+++ b/dspy/_vendor/lm15/_version.py
@@ -1,3 +1,3 @@
"""The version of this source package, also used when building distributions."""
-__version__ = "1.4.0"
+__version__ = "1.5.0"
diff --git a/dspy/_vendor/lm15/_vet_managed.py b/dspy/_vendor/lm15/_vet_managed.py
index b914c9878..578c05a8e 100644
--- a/dspy/_vendor/lm15/_vet_managed.py
+++ b/dspy/_vendor/lm15/_vet_managed.py
@@ -288,6 +288,13 @@ def _step(auth: Auth, step: JsonObject, clock: _Clock, ui: _UI, env: dict[str, s
report = explain_auth(step["provider"], env=env, api_keys=api_keys or None,
config=RouterConfig(auth=auth, env=env, api_keys=api_keys or None))
return {"configured": report.configured, "steps": [{"kind": s.kind, "state": s.state} for s in report.steps]}
+ if do == "route":
+ from .router import LMRouter, RouterConfig
+
+ api_keys = {p: f"{sentinel}-explicit" for p in step.get("api_keys", [])}
+ router = LMRouter(RouterConfig(auth=auth, env=env, api_keys=api_keys or None, settings=step.get("settings")))
+ lm = router.lm(step["model"])
+ return {"settings": dict(getattr(lm, "settings", None) or {})}
raise ValueError(f"unknown managed step {do!r}")
diff --git a/dspy/_vendor/lm15/doctor.py b/dspy/_vendor/lm15/doctor.py
index 5e97bb0dd..8b4024303 100644
--- a/dspy/_vendor/lm15/doctor.py
+++ b/dspy/_vendor/lm15/doctor.py
@@ -252,8 +252,10 @@ def explain_auth(
env = config.env
if api_keys is None:
api_keys = config.api_keys
- if settings is None and config.settings is not None:
- settings = config.settings.get(canonical) or config.settings.get(provider)
+ if settings is None:
+ from .router import _settings_entry
+
+ settings = _settings_entry(config, canonical)
if credential is None:
from .router import _credentials_entry
diff --git a/dspy/_vendor/lm15/judgments.py b/dspy/_vendor/lm15/judgments.py
index 830fa3503..ac40f4cba 100644
--- a/dspy/_vendor/lm15/judgments.py
+++ b/dspy/_vendor/lm15/judgments.py
@@ -3,11 +3,16 @@
changes/2026-09-17-judgments.md. A judgment is a top-level property of a
``json_schema`` ``response_format`` that declares its answer set: a
boolean, a string ``enum``/``anyOf``-of-``const``, or an ordered integer
-``enum``/``anyOf``-of-``const`` ``0..n-1``. This module reads that
-convention off a schema (§1), rewrites judgment properties for the two
-wires that need it (§2), folds a model's JSON text into a ``DataPart``
-(§3), and offers the sugar that EMITS the convention (``choice``,
-``yes_no``, ``score``, ``judgments``) so it need not be written by hand. Nothing here touches the network.
+``enum``/``anyOf``-of-``const`` ``0..n-1`` — or, since
+changes/2026-10-15-bounding-box.md, a **bounding box**: an object of the
+four numbers ``top``, ``bottom``, ``left``, ``right`` (fractions of the
+image's height and width). A box declares no keys, so it is answered,
+never scored. This module reads that convention off a schema (§1),
+rewrites judgment properties for the two wires that need it (§2), folds a
+model's JSON text into a ``DataPart`` (§3), and offers the sugar that
+EMITS the convention (``choice``, ``yes_no``, ``score``,
+``bounding_box``, ``judgments``) so it need not be written by hand.
+Nothing here touches the network.
"""
from __future__ import annotations
@@ -21,11 +26,23 @@ from .adaptation import adapt
from .errors import UnsupportedFeatureError
from .types import DataPart, JsonObject, JsonValue, Request, TextPart
-JudgmentKind = Literal["boolean", "choice", "ordered"]
+JudgmentKind = Literal["boolean", "choice", "ordered", "box"]
MAX_ORDERED_LEVELS = 10 # Jev's Score ceiling (docs.typesafe.ai/primitives/score)
MAX_CHOICE_KEYS = 255 # Jev's Choice ceiling (docs.typesafe.ai/primitives/choice)
+# changes/2026-10-15-bounding-box.md D1: a box is these four numbers, each a
+# fraction of the image measured from its top-left corner — ``top`` and
+# ``bottom`` of its height, ``left`` and ``right`` of its width (Jev's Box,
+# docs.typesafe.ai/primitives/box). The order is Jev's.
+BOX_EDGES: tuple[str, ...] = ("top", "bottom", "left", "right")
+BOX_EDGE_DESCRIPTIONS: dict[str, str] = {
+ "top": "Top edge, as a fraction of the image's height from the top, from 0 to 1",
+ "bottom": "Bottom edge, as a fraction of the image's height from the top, from 0 to 1",
+ "left": "Left edge, as a fraction of the image's width from the left, from 0 to 1",
+ "right": "Right edge, as a fraction of the image's width from the left, from 0 to 1",
+}
+
@dataclass(frozen=True, slots=True)
class Judgment:
@@ -42,6 +59,12 @@ class Judgment:
def ordered(self) -> bool:
return self.kind == "ordered"
+ @property
+ def measurable(self) -> bool:
+ """Whether a distribution over declared keys exists to measure. A
+ box declares no keys: it is answered, never scored (MAP-14 §1)."""
+ return self.kind != "box"
+
# ─── §1 reading the convention ────────────────────────────────────────
@@ -55,10 +78,25 @@ def _const_branches(prop: Mapping[str, Any]) -> list[Mapping[str, Any]] | None:
return branches
+def _is_box(prop: Mapping[str, Any]) -> bool:
+ """An object whose properties are exactly the four edges, each a
+ ``number`` (changes/2026-10-15-bounding-box.md D1). Other keywords
+ (descriptions, ``required``, ``additionalProperties``) are the caller's
+ and travel verbatim."""
+ if prop.get("type", "object") != "object":
+ return False
+ props = prop.get("properties")
+ if not isinstance(props, dict) or set(props) != set(BOX_EDGES):
+ return False
+ return all(isinstance(edge, dict) and edge.get("type") == "number" for edge in props.values())
+
+
def _judgment_of(name: str, prop: Any) -> Judgment | None:
if not isinstance(prop, dict):
return None
instruction = prop.get("description") if isinstance(prop.get("description"), str) and prop.get("description") else None
+ if _is_box(prop):
+ return Judgment(name, "box", (), instruction, {}, {})
if prop.get("type") == "boolean":
return Judgment(name, "boolean", ("true", "false"), instruction, {"true": None, "false": None}, {})
enum = prop.get("enum")
@@ -118,6 +156,16 @@ def request_judgments(request: Request) -> dict[str, Judgment]:
return judgments_in_schema(fmt.get("schema"))
+def measurable_judgments(found: Mapping[str, Judgment]) -> dict[str, Judgment]:
+ """The judgments with declared keys — the ones a distribution can be
+ measured for. Boxes are left out: they are answered, never scored."""
+ return {name: j for name, j in found.items() if j.measurable}
+
+
+def request_measurable_judgments(request: Request) -> dict[str, Judgment]:
+ return measurable_judgments(request_judgments(request))
+
+
def non_judgment_properties(schema: Any, found: Mapping[str, Judgment]) -> tuple[str, ...]:
props = schema.get("properties") if isinstance(schema, dict) else None
if not isinstance(props, dict):
@@ -130,9 +178,11 @@ def non_judgment_properties(schema: Any, found: Mapping[str, Judgment]) -> tuple
def note_unmeasurable_probabilities(request: Request, provider: str) -> None:
"""MAP-14 §3 on a wire with no distribution: ``if_available`` records
- ``dropped``; ``required`` refuses before the wire (MAP-13 b)."""
+ ``dropped``; ``required`` refuses before the wire (MAP-13 b). A request
+ whose judgments are all boxes asked for nothing measurable: nothing is
+ recorded and nothing refused."""
policy = request.config.probabilities
- if policy in (None, "off") or not request_judgments(request):
+ if policy in (None, "off") or not request_measurable_judgments(request):
return
if policy == "required":
raise UnsupportedFeatureError(
@@ -179,7 +229,7 @@ def gemini_schema(schema: JsonObject, found: Mapping[str, Judgment]) -> JsonObje
out = copy.deepcopy(schema)
for name, j in found.items():
prop = out["properties"][name]
- if j.kind == "boolean" or "anyOf" not in prop:
+ if j.kind in ("boolean", "box") or "anyOf" not in prop:
continue
prop.pop("anyOf")
prop["type"] = "integer" if j.ordered else "string"
@@ -290,6 +340,31 @@ def score(instruction: str, levels: Mapping[str, str] | Sequence[str]) -> JsonOb
return {"type": "integer", "description": instruction, "anyOf": branches}
+def bounding_box(instruction: str) -> JsonObject:
+ """A bounding-box judgment: where in the request's image is what
+ ``instruction`` describes (changes/2026-10-15-bounding-box.md).
+
+ The answer is ``{"top", "bottom", "left", "right"}``, each a fraction
+ from 0 to 1 of the image's height (``top``, ``bottom``) or width
+ (``left``, ``right``), measured from the top-left corner; multiply by
+ the image's size in pixels to draw or crop. There is no "not found"
+ answer: ask a ``yes_no`` beside it. On ``typesafe`` this is Jev's Box
+ question and needs Jev 1.14 (``model="jev-preview"`` or
+ ``"jev-1.14.0"``); elsewhere it is ordinary structured output.
+
+ The edges carry no ``minimum``/``maximum``: Anthropic refuses both on a
+ number (HTTP 400, receipted 2026-10-15); the range is in each edge's
+ description, which every wire passes to the model.
+ """
+ return {
+ "type": "object",
+ "description": instruction,
+ "properties": {edge: {"type": "number", "description": BOX_EDGE_DESCRIPTIONS[edge]} for edge in BOX_EDGES},
+ "required": list(BOX_EDGES),
+ "additionalProperties": False,
+ }
+
+
def judgments(*, name: str = "judgments", strict: bool = True, **properties: JsonObject) -> JsonObject:
"""A ``response_format`` declaring the given judgment properties."""
if not properties:
@@ -304,8 +379,9 @@ def judgments(*, name: str = "judgments", strict: bool = True, **properties: Jso
__all__ = [
- "Judgment", "judgments_in_schema", "request_judgments", "non_judgment_properties",
+ "Judgment", "BOX_EDGES", "judgments_in_schema", "request_judgments", "measurable_judgments",
+ "request_measurable_judgments", "non_judgment_properties",
"note_unmeasurable_probabilities", "anthropic_schema", "gemini_schema",
"data_part_from_text", "replace_text_with_data", "normalize_logprobs", "expected_level",
- "choice", "yes_no", "score", "judgments",
+ "choice", "yes_no", "score", "bounding_box", "judgments",
]
diff --git a/dspy/_vendor/lm15/providers/async_base.py b/dspy/_vendor/lm15/providers/async_base.py
index 5105675ef..3bc154c55 100644
--- a/dspy/_vendor/lm15/providers/async_base.py
+++ b/dspy/_vendor/lm15/providers/async_base.py
@@ -22,7 +22,7 @@ from dataclasses import dataclass, field
from typing import Any, AsyncIterator, Callable, ClassVar, Mapping, Protocol, TypeVar
from ..adaptation import AdaptationPolicy, adapt, check_policy, collecting
-from ..judgments import request_judgments
+from ..judgments import request_measurable_judgments
from ..errors import (
ProviderError,
TransportError as LM15TransportError,
@@ -777,7 +777,7 @@ class AsyncOpenAIChatLM(AsyncBaseProviderLM):
if not inner._judgments_via_token_scoring(wire_request):
return await AsyncBaseProviderLM.complete(self, request)
adaptations = inner._judgment_adaptations(wire_request, policy=self.adaptations)
- found = request_judgments(request)
+ found = request_measurable_judgments(request)
plan = await self._build(inner._judgment_plan, wire_request)
async def tokens(req):
diff --git a/dspy/_vendor/lm15/providers/openai_chat.py b/dspy/_vendor/lm15/providers/openai_chat.py
index 4c8227a1a..c438b12f1 100644
--- a/dspy/_vendor/lm15/providers/openai_chat.py
+++ b/dspy/_vendor/lm15/providers/openai_chat.py
@@ -31,7 +31,7 @@ from ..errors import ProviderError, ServerError, UnsupportedFeatureError
from ..access import OPENAI_CHAT_API
from ..features import ProviderManifest
from ._managed import operation
-from ..judgments import Judgment, judgments_in_schema, non_judgment_properties, normalize_logprobs, note_unmeasurable_probabilities, replace_text_with_data, request_judgments
+from ..judgments import Judgment, judgments_in_schema, non_judgment_properties, normalize_logprobs, note_unmeasurable_probabilities, replace_text_with_data, request_measurable_judgments
from ..sse import SSEEvent
from ..transports import TransportRequest
from ..types import (
@@ -1769,7 +1769,7 @@ class OpenAIChatLM(BaseProviderLM):
def _judgment_plan(self, request: Request) -> "list[dict[str, Any]]":
"""One entry per judgment: the tokenize requests it needs. Pure."""
plan = []
- for name, j in request_judgments(request).items():
+ for name, j in request_measurable_judgments(request).items():
plan.append({
"judgment": j,
"prefill": self._judgment_tokenize_request(request.model, self._judgment_messages(request, j, self._JUDGMENT_PREFILL), continue_final=True),
@@ -1837,7 +1837,7 @@ class OpenAIChatLM(BaseProviderLM):
def _judgments_via_token_scoring(self, request: Request) -> bool:
return (self._scores_named_tokens(request.model) and request.config.probabilities in ("if_available", "required")
- and bool(request_judgments(request)))
+ and bool(request_measurable_judgments(request)))
def _validate_judgment_scoring(self, request: Request) -> None:
"""Harmful omissions are refusals, not silent scoring adaptations."""
@@ -1875,7 +1875,7 @@ class OpenAIChatLM(BaseProviderLM):
@staticmethod
def _judgment_mixed(request: Request) -> bool:
- return bool(non_judgment_properties(request.config.response_format["schema"], request_judgments(request)))
+ return bool(non_judgment_properties(request.config.response_format["schema"], request_measurable_judgments(request)))
@staticmethod
def _judgment_generated_request(request: Request) -> Request:
@@ -1929,7 +1929,7 @@ class OpenAIChatLM(BaseProviderLM):
if not self._judgments_via_token_scoring(wire_request):
return BaseProviderLM.complete(self, request)
adaptations = self._judgment_adaptations(wire_request)
- found = request_judgments(request)
+ found = request_measurable_judgments(request)
plan = self._judgment_plan(wire_request)
tokenized: list[tuple["Judgment", dict[str, tuple[int, ...]], list[int]]] = []
calls = 0
@@ -2031,7 +2031,7 @@ class OpenAIChatLM(BaseProviderLM):
if not isinstance(value, dict):
raise ValueError("generated judgment answer needs a JSON object")
schema = request.config.response_format["schema"]
- measured_fields = request_judgments(request)
+ measured_fields = request_measurable_judgments(request)
for name in schema.get("required", ()):
if (unmeasured or name not in measured_fields) and name not in value:
raise ValueError(f"generated answer is missing required property {name!r}")
diff --git a/dspy/_vendor/lm15/providers/typesafe.py b/dspy/_vendor/lm15/providers/typesafe.py
index 785cb6e1d..082e73438 100644
--- a/dspy/_vendor/lm15/providers/typesafe.py
+++ b/dspy/_vendor/lm15/providers/typesafe.py
@@ -9,8 +9,11 @@ request without judgments or with tools is refused before the wire (D8).
Images reach Jev as top-level ``assets`` named by a reference string
written where the image belongs in the state
(changes/2026-10-14-jev-images.md); audio, video and documents are
-refused (MAP-10). Wire facts: receipts/2026-09-17-judgments/,
-receipts/2026-10-14-typesafe/.
+refused (MAP-10). A bounding-box judgment is Jev's Box question; its
+answer is the box verbatim, with no distribution
+(changes/2026-10-15-bounding-box.md). Wire facts:
+receipts/2026-09-17-judgments/, receipts/2026-10-14-typesafe/,
+receipts/2026-10-15-typesafe/.
"""
from __future__ import annotations
@@ -34,7 +37,7 @@ from ..errors import (
map_http_error,
)
from ..features import ProviderManifest
-from ..judgments import MAX_CHOICE_KEYS, MAX_ORDERED_LEVELS, Judgment, non_judgment_properties, request_judgments
+from ..judgments import BOX_EDGES, MAX_CHOICE_KEYS, MAX_ORDERED_LEVELS, Judgment, non_judgment_properties, request_judgments
from ..transports import TransportRequest
from ..types import DataPart, ImagePart, Message, Part, Request, Response, StreamEvent, TextPart, Usage
from .base import BaseProviderLM, Credential, HttpResponse, SyncTransport, default_transport, _attach_error_metadata
@@ -52,9 +55,10 @@ _DROPPED_KNOBS: tuple[str, ...] = (
# changes/2026-10-14-jev-images.md. The asset formats systemone reads
# (docs.typesafe.ai/images "Asset fields"): PNG and JPEG, nothing else.
_IMAGE_FORMATS: dict[str, str] = {"image/png": "png", "image/jpeg": "jpg", "image/jpg": "jpg"}
-# Images are off unless each request that carries one sends this header
-# (live 400 without it, 2026-10-14: "Images are experimental. Send the header
-# TypeSafe-Danger-Zone-Images: true to use them.").
+# Images and Box questions are off unless each request that carries one
+# sends this header (live 400 without it, 2026-10-14 for an image,
+# 2026-10-15 for a Box question with no image: "Images are experimental.
+# Send the header TypeSafe-Danger-Zone-Images: true to use them.").
_IMAGES_HEADER = "TypeSafe-Danger-Zone-Images"
@@ -202,6 +206,9 @@ class TypeSafeLM(BaseProviderLM):
instruction = name
if j.kind == "boolean":
questions[name] = {"type": "noul", "instructions": instruction}
+ elif j.kind == "box":
+ # Jev's Box takes no criteria (docs.typesafe.ai/primitives/box).
+ questions[name] = {"type": "box", "instructions": instruction}
elif j.kind == "choice":
if len(j.keys) > MAX_CHOICE_KEYS:
raise self._refuse(f"config.response_format.schema.properties.{name}",
@@ -247,9 +254,10 @@ class TypeSafeLM(BaseProviderLM):
raise self._refuse("stream", "systemone answers in one piece; there is no stream to wrap")
payload = self._payload(request)
headers = {"Content-Type": "application/json"}
- if "assets" in payload:
- # The caller put an image in the request: that is the opt-in the
- # header exists for (changes/2026-10-14-jev-images.md D3).
+ if "assets" in payload or any(q["type"] == "box" for q in payload["questions"].values()):
+ # The caller put an image or a box in the request: that is the
+ # opt-in the header exists for (changes/2026-10-14-jev-images.md
+ # D3; changes/2026-10-15-bounding-box.md D2).
headers[_IMAGES_HEADER] = "true"
return self._emit(
method="POST",
@@ -298,9 +306,20 @@ class TypeSafeLM(BaseProviderLM):
path = f"answers.{name}"
if not isinstance(answer, dict):
raise invalid(path, "expected an answer object")
- expected = {"boolean": "noul", "choice": "choice", "ordered": "score"}[j.kind]
+ expected = {"boolean": "noul", "choice": "choice", "ordered": "score", "box": "box"}[j.kind]
if answer.get("type") != expected:
raise invalid(f"{path}.type", f"expected {expected!r}")
+ if j.kind == "box":
+ # The four edges verbatim, in Jev's order; a box has no
+ # distribution, and its `confidence` stays in provider_data.
+ edges = answer.get("box")
+ if not isinstance(edges, dict) or set(edges) != set(BOX_EDGES):
+ raise invalid(f"{path}.box", "expected exactly top, bottom, left and right")
+ for edge in BOX_EDGES:
+ probability(edges[edge], f"{path}.box.{edge}") # a fraction: finite, in [0, 1]
+ # Numbers as written (an opaque value, serde number rule 4).
+ value[name] = {edge: edges[edge] for edge in BOX_EDGES}
+ continue
if j.kind == "boolean":
p = probability(answer.get("noul"), f"{path}.noul")
value[name] = p >= 0.5
diff --git a/dspy/_vendor/lm15/router.py b/dspy/_vendor/lm15/router.py
index 865952557..dd5e7e453 100644
--- a/dspy/_vendor/lm15/router.py
+++ b/dspy/_vendor/lm15/router.py
@@ -988,7 +988,7 @@ def _build_lm(resolution: Resolution, config: RouterConfig, adapters: Mapping[st
from .cloud.chains import profile_settings
env = config.env if config.env is not None else os.environ
- given = (config.settings or {}).get(resolution.provider)
+ given = _settings_entry(config, resolution.provider)
ctx = ChainContext.online(env)
settings = resolve_settings(definition.access.host, given, env, provider=resolution.provider,
profile=profile_settings(definition.access, ctx), endpoint=base_url)
@@ -1090,16 +1090,17 @@ def _build_managed_lm(resolution: Resolution, config: RouterConfig, adapters: Ma
a keyless local server's placeholder. Never an environment key, a
foreign CLI file or the machine's cloud chain."""
from .login.manager import Auth, _RequestSnapshot
+ from .login.types import Connection
auth: Auth = config.auth # type: ignore[assignment]
provider = resolution.provider
original_definition, original_extra, original_url = definition, dict(extra), base_url
saved = None
- connection = None
api_key, explicit = _api_keys_entry(config, provider, adapters)
named = _credentials_entry(config, provider)
origin: str | None = None
account_id: str | None = None
+ connection: Connection | None = None
if not explicit and named is None:
try:
saved = snapshot if snapshot is not None else auth.request_auth(provider)
@@ -1224,7 +1225,7 @@ def _build_planning_lm(resolution: Resolution, config: RouterConfig, adapters: M
from .cloud.hosts import resolve_settings
env = config.env if config.env is not None else os.environ
- given = dict((config.settings or {}).get(resolution.provider) or {})
+ given = dict(_settings_entry(config, resolution.provider) or {})
try:
settings = resolve_settings(definition.access.host, given, env, provider=resolution.provider, endpoint=base_url)
except NotConfiguredError:
diff --git a/tests/clients/test_lm15_rc3_integration.py b/tests/clients/test_lm15_rc3_integration.py
index 9ba2aa10a..d093e6689 100644
--- a/tests/clients/test_lm15_rc3_integration.py
+++ b/tests/clients/test_lm15_rc3_integration.py
@@ -219,7 +219,8 @@ async def test_judgment_response_preserves_json_prediction_and_typed_value(async
@pytest.mark.asyncio
@pytest.mark.parametrize("asynchronous", [False, True])
-async def test_typesafe_image_judgments_preserve_media_and_cached_answers(asynchronous, monkeypatch, tmp_path):
[email protected]("with_box", [False, True])
+async def test_typesafe_image_judgments_preserve_media_and_cached_answers(asynchronous, with_box, monkeypatch, tmp_path):
import json
import dspy.clients.execution as execution
@@ -228,18 +229,25 @@ async def test_typesafe_image_judgments_preserve_media_and_cached_answers(asynch
path = tmp_path / "first.png"
path.write_bytes(b"\x89PNG\r\n\x1a\n")
+ answers = {"same": {"type": "noul", "noul": 0.2}}
+ fields = {"same": lm15.yes_no("Are they the same?")}
+ box = {"top": 0.15, "bottom": 0.8, "left": 0.32, "right": 1}
+ if with_box:
+ fields["mug"] = lm15.bounding_box("Locate the mug.")
+ answers["mug"] = {"type": "box", "box": box, "confidence": 0.91}
transport = FakeTransport([DualResponse(200, json.dumps({
- "model": "jev-1.13.0", "answers": {"same": {"type": "noul", "noul": 0.2}},
+ "model": "jev-1.14.0" if with_box else "jev-1.13.0", "answers": answers,
"usage": {"input_tokens": 42, "output_tokens": 3},
}).encode())])
monkeypatch.setattr(execution, "RouterConfig", lambda **kwargs: lm15.RouterConfig(
**{**kwargs, "transport": transport},
))
- lm = dspy.LM("typesafe:jev-latest", engine="lm15", api_key="fake", num_retries=0)
+ model = "typesafe:jev-preview" if with_box else "typesafe:jev-latest"
+ lm = dspy.LM(model, engine="lm15", api_key="fake", num_retries=0)
request = lm15.Request(model=lm.model, messages=(lm15.Message.user([
"Compare these pictures.", lm15.ImagePart(path=path), lm15.data({"label": "second"}),
lm15.ImagePart(data="/9j/4AAQ", media_type="image/jpeg"),
- ]),), config=lm15.Config(response_format=lm15.judgments(same=lm15.yes_no("Are they the same?"))))
+ ]),), config=lm15.Config(response_format=lm15.judgments(**fields), probabilities="required"))
try:
response = await invoke(lm, asynchronous, request)
cached = await invoke(lm, asynchronous, request)
@@ -252,11 +260,84 @@ async def test_typesafe_image_judgments_preserve_media_and_cached_answers(asynch
"<lm15-image-2>": {"type": "image", "format": "jpg", "data_base64": "/9j/4AAQ"},
}
assert dict(sent.headers)["TypeSafe-Danger-Zone-Images"] == "true"
+ if with_box:
+ assert wire["questions"]["mug"] == {"type": "box", "instructions": "Locate the mug."}
for result in (response, cached):
assert isinstance(result.message.parts[0], lm15.DataPart)
- assert result.data == {"same": False}
+ assert result.data == ({"same": False, "mug": box} if with_box else {"same": False})
assert result.probabilities == {"same": {"true": 0.2, "false": 0.8}}
assert result.method == "provider_classification"
+ if with_box:
+ assert result.provider_data["typesafe"]["answers"]["mug"]["confidence"] == 0.91
+ assert lm.history[-1]["usage"] == {}
+ finally:
+ await lm.aclose()
+
+
[email protected]("asynchronous", [False, True])
+async def test_token_scored_judgments_preserve_generated_boxes_and_cache(asynchronous, monkeypatch):
+ import json
+ import math
+
+ import dspy.clients.execution as execution
+ from dspy._vendor.lm15.testing import FakeTransport
+ from tests.clients.test_lm_engine_execution import DualResponse
+
+ class ScoringTransport(FakeTransport):
+ def stream(self, request):
+ self.requests.append(request)
+ payload = json.loads(request.body)
+ if request.url.endswith("/tokenize"):
+ # Boxes must never enter the candidate-scoring protocol.
+ assert "Locate the mug." not in json.dumps(payload["messages"])
+ answer = payload["messages"][-1]["content"]
+ tokens = {"Answer:": [1], "Answer: true": [1, 10], "Answer: false": [1, 11]}[answer]
+ if not payload["continue_final_message"]:
+ tokens = [*tokens, 99]
+ body = {"tokens": tokens}
+ elif request.url.endswith("/chat/completions"):
+ # Generation deliberately disagrees with the measured yes/no answer.
+ body = {"model": "m", "choices": [{"index": 0, "message": {
+ "role": "assistant", "content": json.dumps({
+ "mug": {"top": 0.2, "bottom": 0.6, "left": 0.55, "right": 0.85},
+ "mug_visible": False,
+ }),
+ }, "finish_reason": "stop"}]}
+ else:
+ assert request.url.endswith("/completions")
+ scores = {f"token_id:{token}": (-0.1 if token == 10 else -3.0)
+ for token in payload["logprob_token_ids"]}
+ body = {"model": "m", "choices": [
+ {"index": i, "logprobs": {"top_logprobs": [scores]}}
+ for i in range(len(payload["prompt"]))
+ ]}
+ return DualResponse(200, json.dumps(body).encode())
+
+ transport = ScoringTransport()
+ monkeypatch.setattr(execution, "RouterConfig", lambda **kwargs: lm15.RouterConfig(
+ **{**kwargs, "transport": transport},
+ ))
+ lm = dspy.LM("vllm:m", engine="lm15", api_base="http://scoring/v1", api_key="fake", num_retries=0)
+ request = lm15.Request(model=lm.model, messages=(lm15.Message.user("a kitchen"),), config=lm15.Config(
+ response_format=lm15.judgments(mug=lm15.bounding_box("Locate the mug."),
+ mug_visible=lm15.yes_no("Is the mug visible?")),
+ probabilities="required",
+ ))
+ try:
+ response = await invoke(lm, asynchronous, request)
+ sent = len(transport.requests)
+ cached = await invoke(lm, asynchronous, request)
+ assert len(transport.requests) == sent
+ for result in (response, cached):
+ assert result.data == {
+ "mug": {"top": 0.2, "bottom": 0.6, "left": 0.55, "right": 0.85}, "mug_visible": True,
+ }
+ assert set(result.probabilities) == {"mug_visible"}
+ # Both paths have the same terminator score; normalize -0.1 versus -3.0.
+ p_true = 1 / (1 + math.exp(-2.9))
+ assert result.probabilities["mug_visible"] == pytest.approx({"true": p_true, "false": 1 - p_true})
+ assert result.method == "candidate_sequence_likelihood"
assert lm.history[-1]["usage"] == {}
finally:
await lm.aclose()