litellm/litellm-rust/crates/inference/AGENTS.md
Nate Armstrong 59538ff1d9
feat(messages): serve anthropic messages on rust only (#51119)
* feat(messages): apply modify_params rewrites on rust

* feat(messages): mint anthropic workload identity tokens on rust

* feat(messages): apply prompt caching injection on rust

* feat(messages): serve the easy python-only detectors on rust

* feat(messages): retry rejected thinking signatures on rust

* feat(messages): serve response cache reads on rust

* feat(messages): retry rejected strict tools on rust

* refactor(messages): delete the python path for anthropic messages

Provider anthropic on /v1/messages is now RUST_REQUIRED, so it runs on Rust
without LITELLM_RUST or litellm.rust(True) and never falls back to Python.
A call the rules would send to Python (a MESSAGES_PYTHON_FEATURES feature or a
detector that raises) gets UnsupportedParamsError naming the feature, raised
from one place in litellm/messages/dispatch.py. Other providers keep the
Python fallback. A call whose arguments the handler signature rejects still
gets Python's TypeError.

Deleted Python code that only served anthropic Messages:
- workload identity in AnthropicMessagesConfig.validate/avalidate (subclasses
  were never eligible; the Rust host mints the token itself)
- the anthropic Foundry beta-row and affinity-base branch in
  async_anthropic_messages_handler, and the "forward" mode of the beta filter
  that only that branch used

The proxy MCP tools detector now uses the light tool precheck so a function
tool never imports the gateway handler, since a raising detector now refuses.

* feat(messages): forward message threads on rust

The Rust path for anthropic /v1/messages dropped the thread body field, so
a create or continue turn reached Anthropic without its thread or the
message-threads-2026-08-12 beta. It now matches the Python handler from
#50976:

- the host forwards thread with the other body params
- a non-null thread adds the message-threads beta
- a well-formed continue turn keeps advisor blocks in history and derives
  no compaction, per-turn-control or tool-change beta from its messages
- the recorded httpx_response carries the request that was sent, for JSON
  and streamed calls, so the proxy's thread ownership hook resends the
  create turn's betas on a continue as it does for Python

Upstream error.details already reached the exception message unchanged, so
thread_not_found relays and keeps the deployment out of cooldown on both
paths. Parity cases cover create, continue, streaming, sync, retries,
thread_not_found and the ownership hook round trip.

* feat(messages): serve mock responses on rust

* feat(messages): send caller clients and unsupported tls through python on rust

* feat(messages): run pre-request hooks on rust

* feat(messages): run agentic loop hooks on rust

* feat(messages): run the safeguards classifier on rust

* feat(messages): run registered interceptors on rust

* fix(messages): match python stream cache gate, logging and interceptor order on rust

Store a streamed Messages response in the cache only when Python would: a
message_stop event line, no provider error frame and at least one frame with
output. Leave dict results untouched by mark_rust_response so hidden params
never reach result dicts, logging objects or hook digests. Ask interceptors
whether they handle the call after the cache lookup, not at decode time, so a
cache hit never calls can_handle. Emit the track_llm_api_timing service event
for the provider exchange. Bill and log a stream superseded by a router
fallback as the failure of its error frame, with the partial usage warning.
Hand litellm_logging_obj to deployment pre-call hooks as @client does, so the
autorouter baseline cache sees retried requests.

* fix(messages): forward python-only json values to anthropic as python does

Accept any max_tokens, sampling scalar and messages collection that
Python main accepts, and carry values serde_json cannot hold (ints beyond
64 bits, NaN and infinities, strings with lone surrogates) as validated
raw JSON leaves written back verbatim on the wire, so the upstream body
matches Python's json.dumps

* fix(messages): match python's body reads, error bodies, encoded heads and tls warnings on rust

* fix(messages): log python's plain provider header names on rust streams

* fix(messages): match python's request params, logged params and validation on rust

Read a non-bool stream by Python truthiness and send it as given, log the
caller's stream flag as Python's handler does, raise the raw Python errors
main raises for malformed messages, tools, model_info and hook-set
litellm_params or providers, read the tool custom-field drop from
drops_unsupported_params, log the caller's nested fields that
additional_drop_params strips and the Python values of raw JSON leaves,
keep a missing stop_reason absent, and map provider-config rejections
(missing max_tokens, unknown reasoning effort) as Python's HTTP handler
maps them, with Python's text, effort order, model and provider

* fix(messages): match python's tls curve names, redirects, auth token, header encoding and timeouts on rust

* fix(messages): match python on hooked streams, empty cache writes and mcp cache hits

* fix(messages): join already buffered stream reads and trim the env api key as python does on rust

* fix(messages): deliver stream bytes read before a cut, keep wide reply numbers and follow python's redirect limit on rust

A stream cut by a transport error now hands the caller the bytes already
buffered before raising, as aiohttp does for a caller that reads them before
the event loop sees the cut, so the frames and their usage reach the caller and
the failure log. Provider replies keep integers wider than 64 bits exactly and
read numbers that overflow a float as infinity, through the response, the
response cache and the logged result. The provider client follows up to 20
redirects as httpx does, and running out raises Python's text. A
provider_specific_header value the ascii codec cannot encode fails before the
send like a caller extra header. The deployment success hook gets the stream as
AnthropicMessagesStreamingResponse, as Python's handler hands it.

* feat(messages): serve proxy mcp tools on rust

* test(messages): cover hook, agentic and interceptor edge cases in the parity suite

* fix(messages): keep provider raw-json marked strings, drop non-string tool_result texts and key clamped streams as python does on rust

* fix(messages): match python's api key encoding, malformed api_base and string provider header errors on rust

A header value Python's client cannot encode as ASCII now fails before the send
whichever header carries it, so a caller api_key with a non-ASCII character
raises Python's InternalServerError instead of a raw UnicodeEncodeError after
the reply. A caller api_base without an http(s) scheme, or with whitespace,
control or non-ASCII characters, is sent through Python's client at the URL
Python builds, so its relative-URL and invalid-URL errors match, and a base
urlsplit cannot split raises Python's bare ValueError before the send. A
provider_specific_header of the wrong shape is scoped through Python's
ProviderSpecificHeaderUtils first, so a plain string raises Python's
AttributeError.

* fix(messages): keep integer temperature and top_p digits a float cannot hold and raise python's typeerror for a string max_tokens while capping the thinking budget on rust

temperature and top_p now deserialize through recognized::exact_float, which keeps an integer
where float(n) != n (beyond 2**53) as an unrecognized value with its exact digits, so it is sent
upstream and logged as the integer python forwards, and comparisons still go through scalar.rs

cap_thinking_budget_to_max_tokens compares max_tokens <= 1024 first, so a max_tokens python
cannot order against an int (a string, list or dict) raises TypeError "'<=' not supported between
instances of 'str' and 'int'" in both the reasoning effort translation and the adaptive effort
reshape. rust now returns ErrorDetail::UnorderableTypes there, the bridge raises it as a python
TypeError marked as a late rejection, and map_failure hands it to the caller unmapped

* test(messages): format the non-string tool_result parity helper

* fix(messages): flag and log the call before python's pre-send raises on rust

The bridge now hands settings() and map_failure() whether the call is async.
A provider_specific_header of the wrong shape sets the aanthropic_messages
flag before re-raising, as Python's handler has already flagged the call. A
base urlsplit cannot split also logs the resolved model, provider and optional
params first, as Python raises it only after its logger is updated. The
TypeError raised while capping the thinking budget for a string max_tokens
sets the flag too

* feat(messages): serve the web search short-circuit override on rust through the intercept host call

* fix(messages): give the web search entry kwargs its mutable-ok reason

* test(messages): drop the body hook gap the rust short-circuit closes

* fix(messages): name the partially unknown handler types on the short-circuit host call
2026-11-12 00:07:20 +00:00

8.5 KiB

Layering

  • gateway-inference (serving) -> inference-<fmt> (one API's call) -> inference (shared base)
  • This crate is the shared base every format crate builds on
    • Error (src/error.rs), CallOptions (src/lib.rs), CallContext (src/context.rs)
    • diagnostic spans (src/diagnostic.rs), outbound send and signing (src/outbound.rs), provider resolution (src/provider.rs), CoreResources (src/resources.rs)
    • response caching (src/caching.rs): Cachable, StreamCachable, CacheRequest, CallCache, execute_unary, execute_streaming, stream capture
    • Shared test helpers belong in litellm-inference-testing, used only as a dev dependency
  • Nothing here names an API format. Format-specific code, constants, tests and test builders live in their inference-<fmt> crate
  • Never depend on an inference-* crate from here

Format crates

  • inference-chat, inference-messages, inference-responses, inference-ocr, inference-transcription, one per API
  • Each owns its entrypoint, route request types (*Request<'a>), credential fallback, provider dispatch, and the handler glue that runs a provider config
  • Each owns its Protocol, its Cachable / StreamCachable impl, its constants, and its tests
  • inference-* is orchestration only
    • shared API data contracts belong in litellm-llms-types
    • adapter contracts and shared transformation machinery in llms/src/base_llm/<format>/
    • provider policy in llms/src/<provider>/<format>/
  • Select concrete adapters, then invoke their contracts instead of applying one provider's policy to every call
  • Route types describe call envelopes and execution state, not duplicate public payload schemas
  • Format-specific rules go in that crate's AGENTS.md

Routes

  • Hosts assemble route objects from shared CoreResources, HTTP settings, and secret sources
    • each route owns its provider client and authentication dependencies
    • gateway routes live for the gateway lifetime. Python assembles routes per call from its settings snapshot
  • Calls pass Interceptors and an optional ObservationSender separately
    • use &() for no hooks and None for no observer
    • handlers accept Interceptors, never a concrete ChannelInterceptors
  • Construction does no work. Preparation and lifecycle observation begin when the future is polled
  • Native observers receive start and terminal events through the shared call runner. A stream retains its lifecycle until exhaustion, error, or drop. Hosted routes leave terminal observation to their driver
  • A hosted format's route.rs declares the concrete Protocol and a route method that takes a typed request and builds a litellm_host::call::HostedMachine with hosted_call. Audio transcription has no hosted machine and returns its response directly
    • the shared call plumbing owns stream opening, delivery, backpressure, and detachment
    • request decoding belongs to the boundary before the machine starts
    • route closures only supply execution dependencies and route-specific host capabilities
    • Python uses its own shared driver and preserves caller-task callback execution
  • Not here: serving HTTP (axum routes, extractors), config file reading, rollout state, databases, or callback execution of any kind. Routes run as machines that yield host operations and call events. Which integrations consume those events is the host's business

Crate boundaries

  • Dependencies only point down. Python package names identify counterparts, not ownership
  • litellm-llms-types owns shared inference API contracts, grouped by format: pure serde data and shape validation, no I/O
  • litellm-core-utils mirrors litellm/litellm_core_utils/: pure helpers (provider resolution, prompt factory, call arguments, settings lookup and layer merge), no network I/O
  • litellm-http is Rust-only and route-neutral: settings resolution, pooled reqwest clients, TLS, proxies, the SSRF-safe media fetcher, request and header helpers, and transport errors
  • litellm-llms mirrors litellm/llms/: base_llm/<api>/transformation.rs, <provider>/<api>/transformation.rs, and base_llm/ocr/handler.rs
  • litellm-inference-<fmt> mirrors the route packages (litellm/ocr/, litellm/messages/, ...)
  • Provider code never imports from inference or inference-*
  • Handlers belong in inference-* or llms, never in a host crate
  • Import every item from its canonical path. Never re-export another crate's items or give an item a second public path. The only allowed re-exports are a private submodule surfacing its item at its module root (mod error; pub use error::Error;) and each format crate's pub use litellm_inference::Error;, which keeps the pre-split <fmt>::Error name

Error placement

  • The rust-error skill shapes each crate's error. This section decides which crate and module a failure belongs to
  • A failure is declared once, by the lowest crate that raises it
    • every crate above nests it in one variant and delegates its predicates, as Error::Llm, Error::Auth and Error::Http do, or translates it once in the shared From when its meaning changes, as From<litellm_llms::Error> does for Unsupported and From<litellm_http::Error> does for a header the signer computes
    • Error collects route failures for every format crate and never re-declares a variant a lower crate raises. Routes build transformation failures with Error::invalid_request and Error::invalid_response and collapse anything raised after the send with Error::after_send, and callers ask declined(), is_request(), is_response(), is_missing_credential(), dispatched(), upstream_response() and rejected_request() instead of matching nested variants
  • Scope follows the concept, not the first caller
    • an error type under litellm-llms's <provider>/ is private to that provider: no other provider and nothing in base_llm may import it
    • a failure two providers or two routes can hit (wire framing, stream event decoding, a malformed provider response) belongs to the crate that owns the concept: litellm-framer for framing, litellm_llms::Error for the transformation layer
  • litellm_llms::Error (crates/llms/src/error.rs) is the one transformation error for every provider and API. base_llm/ocr/error.rs is the recorded exception until OCR folds into it

Response caching and accounting

  • Attach a litellm_cache_response::ScopedCache with route.with_cache(cache). Cached and uncached routes use the same execute and machine methods
  • CallOptions carries a scope-free CachePolicy and observation. Per-call policy never replaces the attached scope or service
  • Provider transport does not own cache orchestration. Stream capture stays in src/caching.rs
  • This crate and the format crates own request identity, typed response reconstruction, and stream capture and replay
  • cache-response owns cache policy, namespacing, scope encoding, versioned envelopes, and freshness
  • The SDK explicitly chooses shared scope. The gateway derives isolated scope from authenticated identity before attaching its service
  • ExecutionFacts are delivered through the awaited ResultReady host operation for both provider and cached results, before public response processing or stream opening
    • facts carry resolved model/provider and result source, including the hit key
    • usage remains in the typed response or delivered stream, where completion and cancellation determine what was actually reported
    • passive observation is not an accounting delivery mechanism
  • Inference does not calculate prices, charge budgets, or update rate-limit counters
    • the legacy Python callback adapter translates execution facts into the existing Python logging contract. Python remains the accounting owner on that path
    • native gateway accounting belongs to gateway dependencies, independently of host-python
    • response-cache services expose no coordination counters or reservation APIs. A shared Redis deployment does not make response storage and accounting coordination the same dependency
  • Cache lookup follows provider preparation, credential resolution, and the request interceptor
    • keys describe the effective provider URL, authenticated headers, and rewritten body
    • signed requests bypass caching until the signing identity has a stable cache representation
  • A service that keys entries by the caller's arguments (keyed_by_caller, the Python host's legacy cache) is looked up before provider preparation, as Python's @client wrapper does, and a hit skips request building and the request interceptor