mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-28 00:00:38 +00:00
* fix(anthropic): keep thinking disabled, display, between_tools, and effort on /v1/messages to OpenAI The Messages to Responses bridge only built reasoning for adaptive and enabled thinking, so disabled, between_tools, and output_config.effort alone reached OpenAI as nothing, and display never asked for a summary. Disabled now maps to effort none, between_tools thinks only after tool results, effort alone maps to reasoning.effort, and display shares the chat route's summary rule * fix(anthropic): drop an unconfirmed reasoning off switch under drop_params and read the whole final user turn between_tools now treats every user message after the last assistant message as the final turn, so a tool_result followed by a separate text message still counts as between tool calls, and it asks for a reasoning summary there the way Anthropic returns progress updates. thinking disabled or a first-turn between_tools on a reasoning model whose cost map row does not set supports_none_reasoning_effort (o3, o4-mini) no longer sends effort none under drop_params, which OpenAI refused with a 400. * fix(anthropic): keep reasoning off for a bare effort on models that reason only when asked A request with output_config.effort and no thinking now leaves reasoning off on a model whose cost map row sets default_reasoning_effort none (gpt-5.1, gpt-5.2, the gpt-5.4 family). Turning it on there made Claude Code with thinking off pay for reasoning, and made a temperature the model accepts at none answer 400. Models that reason by default still get the effort. between_tools now honors thinking.summary and display omitted before falling back to summary auto, and the new helpers lose their docstrings. * fix(anthropic): let a bare effort yield to reasoning_effort and unmapped models, drop an undefined effort under drop_params * fix(anthropic): retry an unverified org without the reasoning summary, keep disabled reasoning off at the lowest tier, and match between_tools on the chat route Under drop_params, the Responses bridge now retries once without reasoning.summary when OpenAI refuses summaries to an unverified organization. It drops an effort the model's own levels exclude unless the deployment rounds efforts itself. It sends minimal or low for disabled when the model lists no none. The chat-completions route now maps between_tools and a bare output_config.effort for non-Claude targets the same way the bridge does, through a shared tool-turn check * fix(anthropic): limit the chat route's between_tools and bare effort mapping to OpenAI, keep reasoning off at the lowest level the model takes, and ignore a bare effort on a model that cannot reason * fix(anthropic): drop an unconfirmed reasoning off switch under drop_params on the OpenAI chat route too, through one helper both routes share * fix(anthropic): keep sending reasoning_effort none on the chat route to an openai/ deployment the cost map does not list The router registers an unlisted deployment as a stub row with no mode, which made its reasoning levels read as known-empty, so thinking disabled stopped sending none on the chat-completions route. The levels now read as unknown for such a row. The Responses bridge keeps sending no reasoning there, since the Responses transformation answers 400 to reasoning.effort on a row without supports_reasoning. * fix(anthropic): send reasoning effort none wherever the Responses transformation accepts it An openai/ deployment the cost map does not list now gets effort none for disabled thinking on the chat route even when its model_info sets a mode, since the off level now asks whether the loaded cost map lists the model instead of reading the row the router registers. On the Responses bridge the off switch is dropped only where the Responses transformation itself would refuse reasoning.effort, so a slash-named model it accepts gets none again for adaptive effort none and disabled thinking. * fix(anthropic): leave reasoning to the model on a first-turn between_tools when its levels are unlisted A first-turn between_tools request sent reasoning effort none to every openai/ deployment whose cost map row lists no effort levels, so a backend that requires reasoning answered 400 where main answered 200. That turn now sends no reasoning unless the row or the deployment's model_info lists the model's levels. The OpenAI integration fixture now expects the summary that display summarized asks for. * fix(anthropic): read each deployment's own model_info for the off switch and guard a non-object thinking * fix(anthropic): keep a client's effort none on the unsupported-value path and send minimal as the off level only where confirmed * fix(anthropic): drop a client's unconfirmed effort none under drop_params and keep the pin out Under drop_params, a client's own effort none, bare or adaptive or after a tool result, on a reasoning deployment that lists no levels and does not set supports_none_reasoning_effort (o3) is now dropped on both routes instead of going to OpenAI, which answers 400. A client effort the bridge drops also keeps a deployment's pinned reasoning_effort out, as the chat route and main do * fix(anthropic): keep a pinned effort out when drop_params drops disabled Under drop_params, disabled on a reasoning deployment that does not confirm effort none (o3) is dropped on both routes. The deployment's pinned reasoning_effort no longer comes back in its place, so the model answers at its default effort instead of the pinned one the client turned off * fix(anthropic): keep the refused summary attempt out of failure logs and drop unknown efforts on the chat route Under drop_params the refused summary attempt is marked as sent again, so it is not logged as the turn failing and num_retries does not resend it. A name only a model-family rule matches counts as unlisted. The chat route drops an effort no reasoning API defines, and a bare effort skips a model whose chat config takes no reasoning_effort * fix(anthropic): keep family-rule info when normalizing a client's effort The listed-effort check now skips info that only the OpenAI reasoning family rule supplies, but effort normalization still reads it, so a name only that rule matches normalizes its effort as before. Adds a test for a summary refused while replayed reasoning is resent. * refactor(anthropic): move the client effort drop check into one helper and refresh dashboard API types --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
217 lines
7.6 KiB
Python
217 lines
7.6 KiB
Python
"""
|
|
Internal request context for LiteLLM.
|
|
|
|
Provides a ContextVar-based mechanism for internal signals that must not
|
|
be settable from user input. Context variables are scoped to the current
|
|
asyncio task and cannot be injected via HTTP request bodies.
|
|
"""
|
|
|
|
import inspect
|
|
from collections.abc import Awaitable, Callable, Generator
|
|
from contextlib import contextmanager, suppress
|
|
from contextvars import ContextVar, Token
|
|
from datetime import datetime, timezone
|
|
from functools import wraps
|
|
from typing import TYPE_CHECKING, Final, ParamSpec, TypeVar, cast
|
|
|
|
if TYPE_CHECKING:
|
|
from opentelemetry.trace import Span
|
|
else:
|
|
Span: Final = object
|
|
|
|
_P = ParamSpec("_P")
|
|
_R = TypeVar("_R")
|
|
_T = TypeVar("_T")
|
|
|
|
# When True, suppresses async logging and billing for internal sub-calls
|
|
# (e.g., emulated file-search steps that make nested LLM calls).
|
|
is_internal_call: Final[ContextVar[bool]] = ContextVar("is_internal_call", default=False)
|
|
internal_parent_request_id: Final[ContextVar[str | None]] = ContextVar("internal_parent_request_id", default=None)
|
|
|
|
# One request prices its totals, its per-token-type lines and the rates it reports on
|
|
# separate code paths. Each reads the clock for off-peak pricing, so without a pinned
|
|
# moment they can land on either side of a window boundary and disagree with each other.
|
|
_billing_time: Final[ContextVar[datetime | None]] = ContextVar("billing_time", default=None)
|
|
|
|
_post_response: Final[ContextVar[bool]] = ContextVar("post_response", default=False)
|
|
|
|
_service_target: Final[ContextVar[str | None]] = ContextVar("service_target", default=None)
|
|
|
|
_mirrored_call: Final[ContextVar[bool]] = ContextVar("mirrored_call", default=False)
|
|
|
|
_resent_on: Final[ContextVar[Callable[[Exception], bool] | None]] = ContextVar("resent_on", default=None)
|
|
|
|
_request_parent_otel_span: Final[ContextVar[Span | None]] = ContextVar("request_parent_otel_span", default=None)
|
|
|
|
|
|
@contextmanager
|
|
def internal_sub_call(parent_request_id: str | None = None) -> Generator[None]:
|
|
"""A nested call the parent call logs and bills, so the parent must fold this call's cost into its own."""
|
|
token: Final = is_internal_call.set(True)
|
|
parent_token: Final = internal_parent_request_id.set(parent_request_id or internal_parent_request_id.get())
|
|
try:
|
|
yield
|
|
finally:
|
|
is_internal_call.reset(token)
|
|
internal_parent_request_id.reset(parent_token)
|
|
|
|
|
|
@contextmanager
|
|
def billed_separately() -> Generator[None]:
|
|
"""A call that writes its own spend row even inside a sub-call whose parent bills the model response."""
|
|
token: Final = is_internal_call.set(False)
|
|
parent_token: Final = internal_parent_request_id.set(None)
|
|
try:
|
|
yield
|
|
finally:
|
|
is_internal_call.reset(token)
|
|
internal_parent_request_id.reset(parent_token)
|
|
|
|
|
|
@contextmanager
|
|
def post_response_phase() -> Generator[None]:
|
|
"""Work the caller no longer waits for (success callbacks, response-cache writes), including tasks it spawns."""
|
|
token: Final = _post_response.set(True)
|
|
try:
|
|
yield
|
|
finally:
|
|
_post_response.reset(token)
|
|
|
|
|
|
def in_post_response_phase() -> bool:
|
|
return _post_response.get()
|
|
|
|
|
|
def _restore(var: ContextVar[_T], token: Token[_T]) -> None:
|
|
"""Reset ``var``; a coroutine the GC closes from another context has no value left to restore."""
|
|
with suppress(ValueError):
|
|
var.reset(token)
|
|
|
|
|
|
@contextmanager
|
|
def service_target(target: str | None) -> Generator[None]:
|
|
"""Name what the datastore calls inside this block are for; ``None`` clears an inherited target."""
|
|
token: Final = _service_target.set(target)
|
|
try:
|
|
yield
|
|
finally:
|
|
_restore(_service_target, token)
|
|
|
|
|
|
def current_service_target() -> str | None:
|
|
return _service_target.get()
|
|
|
|
|
|
def with_service_target(
|
|
target: str, *, preserve_existing: bool = False
|
|
) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]:
|
|
"""Run calls under the target, or the inherited target when ``preserve_existing`` is true."""
|
|
|
|
def call_target() -> str:
|
|
if preserve_existing:
|
|
return current_service_target() or target
|
|
return target
|
|
|
|
def decorate(fn: Callable[_P, _R]) -> Callable[_P, _R]:
|
|
if inspect.iscoroutinefunction(fn):
|
|
awaitable_fn: Final[Callable[_P, Awaitable[object]]] = cast( # cast-ok: checked by iscoroutinefunction
|
|
"Callable[_P, Awaitable[object]]", fn
|
|
)
|
|
|
|
@wraps(fn)
|
|
async def run_async(*args: _P.args, **kwargs: _P.kwargs) -> object:
|
|
with service_target(call_target()):
|
|
return await awaitable_fn(*args, **kwargs)
|
|
|
|
return cast("Callable[_P, _R]", run_async) # cast-ok: same coroutine-returning signature as ``fn``
|
|
|
|
@wraps(fn)
|
|
def run(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
|
with service_target(call_target()):
|
|
return fn(*args, **kwargs)
|
|
|
|
return run
|
|
|
|
return decorate
|
|
|
|
|
|
@contextmanager
|
|
def mirrored_call() -> Generator[None]:
|
|
"""A silent_model mirror of a request: every litellm call inside, its retries and fallbacks included."""
|
|
token: Final = _mirrored_call.set(True)
|
|
try:
|
|
yield
|
|
finally:
|
|
_restore(_mirrored_call, token)
|
|
|
|
|
|
def in_mirrored_call() -> bool:
|
|
return _mirrored_call.get()
|
|
|
|
|
|
@contextmanager
|
|
def resent_on(rejection: Callable[[Exception], bool]) -> Generator[None]:
|
|
"""An attempt its caller sends again when it fails with ``rejection``. That failure is not the request's
|
|
outcome, so it is neither logged as the request's failure nor retried, and its budget reservation and rate-limit
|
|
slot stay with the attempt sent again."""
|
|
outer: Final = _resent_on.get()
|
|
token: Final = _resent_on.set(rejection if outer is None else lambda error: outer(error) or rejection(error))
|
|
try:
|
|
yield
|
|
finally:
|
|
_restore(_resent_on, token)
|
|
|
|
|
|
def is_resent_failure(error: Exception) -> bool:
|
|
rejection: Final = _resent_on.get()
|
|
return rejection is not None and rejection(error)
|
|
|
|
|
|
def set_request_parent_otel_span(span: Span) -> None:
|
|
"""Anchor the proxy request's OTEL span for datastore service spans that no call site passes a parent to.
|
|
Never reset: it dies with the request task and rides the tasks it spawns, like ``request.state``."""
|
|
_request_parent_otel_span.set(span)
|
|
|
|
|
|
def current_request_parent_otel_span() -> Span | None:
|
|
return _request_parent_otel_span.get()
|
|
|
|
|
|
@contextmanager
|
|
def request_parent_otel_span(span: Span | None) -> Generator[None]:
|
|
"""Anchor the datastore service spans made inside this block, and by the tasks it starts, under the span an SDK
|
|
caller passed. A request that already anchored its own, as the proxy does at auth, keeps it."""
|
|
if span is None or _request_parent_otel_span.get() is not None:
|
|
yield
|
|
return
|
|
token: Final = _request_parent_otel_span.set(span)
|
|
try:
|
|
yield
|
|
finally:
|
|
_restore(_request_parent_otel_span, token)
|
|
|
|
|
|
@contextmanager
|
|
def outside_mirrored_call() -> Generator[None]:
|
|
"""Logging a mirrored call: the calls its callbacks start are not mirrors themselves."""
|
|
token: Final = _mirrored_call.set(False)
|
|
try:
|
|
yield
|
|
finally:
|
|
_restore(_mirrored_call, token)
|
|
|
|
|
|
@contextmanager
|
|
def pinned_billing_time(moment: datetime) -> Generator[None]:
|
|
"""Price every rate lookup inside this block at ``moment`` rather than at each one's own clock read."""
|
|
token: Final = _billing_time.set(moment)
|
|
try:
|
|
yield
|
|
finally:
|
|
_billing_time.reset(token)
|
|
|
|
|
|
def current_billing_time() -> datetime:
|
|
"""The pinned billing moment, or now in UTC outside a pinned block."""
|
|
pinned: Final = _billing_time.get()
|
|
return pinned if pinned is not None else datetime.now(timezone.utc)
|