Skip to content
Merged
41 changes: 41 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,47 @@ and this project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html)

### Fixed

- `CostRoutingCoordinator._cheapest_capability_candidate` now performs
price-aware selection: resolving an unspecified embedding batch member
out of several capability-matched candidates (e.g. operator-managed
model-group members) now picks the cheapest one by the configured price
table instead of an arbitrary first/ranked pick. It plays a role similar
to `cheapest_upstream` (`batch_routing.py`) but does not call it — see
below for how the two diverged. `cheapest_upstream` itself remains a
headline-documented, `__all__`-exported utility with no production caller
anywhere in the router.
- `CostRoutingCoordinator._cheapest_capability_candidate` no longer treats an
unpriced or invalid `PriceBook` entry as a free (zero-cost) winner, no
longer compares prices across mismatched currencies at face value against
`PriceBook.default_currency`, and prices embedding candidates with
`assumed_completion_tokens=0` (embeddings never consume completion
tokens). Candidates with no comparable known-currency price keep the
orchestrator's existing ranked order instead of being silently selected.
- `_cheapest_capability_candidate`'s currency-comparability check now reuses
`model_discovery._currency_is_comparable`'s normalization (non-empty,
trimmed, case-insensitive) instead of an exact string match, so a
lowercase or whitespace-padded same-currency code (e.g. `"usd"` vs
`"USD"`) is recognized as comparable rather than losing to a costlier
candidate. `_resolve_embedding_target` now runs this cheapest-comparable-
member selection for ordinary (non-ZDR) unspecified embedding requests
too, not only ZDR ones — previously those returned before the selection
ever ran, so only ZDR embedding batches were price-aware. Explicit
`agent_id` choices and explicit-model passthrough (a model outside the
configured pool) are unchanged. This upstream-selection mechanism is
the `cheapest_upstream` table-driven load balancing already covered by
[ADR 0003](docs/adr/0003-cost-aware-sync-batch-routing.md#consequences);
no new research grounding applies to this bugfix.
- `_cheapest_capability_candidate` no longer ranks comparable embedding
candidates through `cheapest_upstream`'s ledger-rounded (six-decimal-place)
`PriceBook.compute_cost` output. Two genuinely different low per-1K prices
(e.g. `0.00000049` and `0.00000001`) can both round to the same `0.0`
ledger cost for the assumed request size, which collapsed a real price
difference into a tie and let the ranked-first (possibly costlier)
candidate win. Ranking now compares each candidate's raw, unrounded
`PriceEntry.prompt_price_per_1k` directly (embedding requests carry zero
completion tokens, so completion price stays out of the comparison).
`cheapest_upstream` itself, currency filtering, the unpriced-exclusion
behavior, and ranked-order tie-breaking on a true price tie are unchanged.
- OpenRouter discovery no longer marks the entire credential account
evidence-only. Authenticated catalog rows may serve ordinary requests, while
ZDR-only requests still require explicit route-level ZDR evidence.
Expand Down
14 changes: 14 additions & 0 deletions contextual_orchestrator/batch_routing.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,20 @@ def cheapest_upstream(
representative request shape and return the cheapest. Unpriced candidates
cost ``0`` and are treated as free (explicit, so a missing price is visible
rather than silently expensive). Ties keep input order.

:class:`~contextual_orchestrator.cost_router.CostRoutingCoordinator`'s
``_cheapest_capability_candidate`` helper plays a similar upstream
cost-based selection role — resolving one embedding member out of
several capability-matched candidates — but does not call this
function. It looks up each candidate's price directly via
:meth:`~contextual_orchestrator.cost_ledger.PriceBook.get_price` and
compares raw, unrounded
:attr:`~contextual_orchestrator.cost_ledger.PriceEntry.prompt_price_per_1k`
values, rather than this function's ledger-rounded
:meth:`~contextual_orchestrator.cost_ledger.PriceBook.compute_cost`
output (see that helper's docstring for why). This function remains a
standalone, table-driven upstream selector used elsewhere for load
balancing.
"""
if not candidates:
return None
Expand Down
95 changes: 86 additions & 9 deletions contextual_orchestrator/cost_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,9 @@
RoutingPolicy,
)
from .batch_job_registry import JobRegistryFactory, build_job_registry
from .cost_ledger import CostLedger, PriceBook
from .cost_ledger import CostLedger, PriceBook, PriceEntry
from .kv_config import InMemoryConfigStore
from .model_discovery import _currency_is_comparable
from .token_counting import HeuristicTokenCounter, build_token_counter


Expand Down Expand Up @@ -138,6 +139,67 @@ def _agent_provider_model(agent: Any, fallback_model: str) -> tuple[str, str]:
provider = agent.provider_name or _provider_from_base_url(agent.base_url)
return provider or "unknown", agent.model or fallback_model

def _cheapest_capability_candidate(self, candidates: List[Any]) -> Any:
"""Pick the lowest-priced member of a capability candidate list.

Plays the same cost-optimising role as
:func:`~contextual_orchestrator.batch_routing.cheapest_upstream` — the
module's general upstream selector — for a real routing decision:
among several capability-matched members (e.g. operator-managed
model-group members) that could all serve one request, prefer the
cheapest by the configured price table rather than an arbitrary first
pick.

Only candidates with a *known* price in the price book's own
``default_currency`` are comparable: a missing/invalid price entry
stays unknown rather than becoming a false zero-cost winner, and an
entry priced in a different currency is left out of the comparison
rather than compared to a same-currency price by face value (this
repo has no exchange-rate conversion source). Currency comparability
uses :func:`~contextual_orchestrator.model_discovery._currency_is_comparable`
— the same non-empty/trimmed/case-insensitive normalization the
discovery price book applies — so a lowercase or whitespace-padded
same-currency code (e.g. ``"usd"`` or ``" USD "`` against ``"USD"``)
is still recognized as comparable rather than silently excluded.

Ranking compares each comparable candidate's raw, unrounded
:attr:`~contextual_orchestrator.cost_ledger.PriceEntry.prompt_price_per_1k`
directly rather than delegating to ``cheapest_upstream``'s
:meth:`~contextual_orchestrator.cost_ledger.PriceBook.compute_cost`,
which quantizes to six decimal places for ledger reporting: two
genuinely different low per-1K embedding prices (e.g. ``0.00000049``
and ``0.00000001``) can both round to the same ``0.0`` ledger cost for
an assumed request size, which would collapse a real price
difference into a tie and let the more expensive candidate win by
rank order alone. Comparing the raw prompt price is equivalent to
comparing the full-precision cost for embeddings, which is why
``completion_price_per_1k`` is not part of the comparison at all
(embedding requests never consume completion tokens). ``cheapest_upstream``
itself is untouched — its rounded cost remains correct for its own
ledger-reporting callers. Candidates with no comparable price —
including an all-unpriced or all-mismatched-currency pool — keep the
original (ranked) order, so behavior is unchanged whenever the price
table has nothing to optimise; a true tie in raw price also keeps the
first-ranked candidate, matching ``cheapest_upstream``'s own
input-order tie-breaking.
"""
comparable: list[tuple[Any, PriceEntry]] = []
for candidate in candidates:
provider, model = self._agent_provider_model(candidate, candidate.model)
entry = self.price_book.get_price(provider, model)
if entry is None or not _currency_is_comparable(
entry.currency_code, self.price_book.default_currency
):
continue
comparable.append((candidate, entry))
if not comparable:
return candidates[0]
best_candidate, best_entry = comparable[0]
for candidate, entry in comparable[1:]:
if entry.prompt_price_per_1k < best_entry.prompt_price_per_1k:
best_candidate, best_entry = candidate, entry
return best_candidate
Comment on lines +219 to +234

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📝 Info: Unknown prices preserve prior ranking

_cheapest_capability_candidate excludes unknown and cross-currency prices. Empty comparable sets and true price ties preserve the orchestrator’s existing order.

Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.


def _served_provider_model(self, result: Dict[str, Any], fallback_model: str) -> tuple[str, str]:
"""Derive ``(provider, model)`` from the served agent in the trace."""
trace = result.get("trace") or []
Expand Down Expand Up @@ -801,18 +863,33 @@ def submit_embeddings_batch(
def _resolve_embedding_target(
self, model: str, zdr_only: bool, agent_id: Optional[str]
) -> tuple[str, Optional[str]]:
"""Resolve one embedding member without losing a caller's member choice."""
if agent_id is None and not zdr_only:
"""Resolve one embedding member without losing a caller's member choice.

An explicit caller-supplied ``agent_id`` always wins, and an explicit
caller-supplied ``model`` outside the configured pool always passes
through unresolved (no ``_capability_agents`` lookup, so it cannot
raise on an upstream model this repo has no matching agent for) —
both regardless of ``zdr_only``. The only case that now runs
cheapest-comparable-member selection is an *unspecified* model
(the ``contextual-orchestrator``/``AUTO_MODEL`` placeholder) with no
explicit ``agent_id``: previously this short-circuited to plain
passthrough for ordinary (non-ZDR) requests, so cost-aware routing
only ever reached ZDR embedding batches. ZDR requests already ran
this selection unconditionally (an explicit ZDR model still needs
pool-membership + privacy-tag validation), so that behavior is
unchanged here.
"""
unspecified_model = model in {
"contextual-orchestrator", getattr(self.orchestrator, "AUTO_MODEL", "")
}
if agent_id is None and not zdr_only and not unspecified_model:
return model, None
selection_model = (
None
if model in {"contextual-orchestrator", getattr(self.orchestrator, "AUTO_MODEL", "")}
else model
)
selection_model = None if unspecified_model else model
with self.orchestrator.request_policy(zdr_only):
candidates = self.orchestrator._capability_agents("embedding", selection_model)
if agent_id is None:
return candidates[0].model, candidates[0].id
chosen = self._cheapest_capability_candidate(candidates)
return chosen.model, chosen.id
Comment thread
seonghobae marked this conversation as resolved.
Resolved
for candidate in candidates:
if candidate.id == agent_id:
return candidate.model, candidate.id
Expand Down
Loading
Loading