litellm/litellm-rust/crates/callbacks-legacy-python/AGENTS.md
Yujong Lee 2c08938d78 feat(rust): run body hooks on native streams
Python's Messages handler holds a provider stream back when the request
carries a tool a registered callback fulfils server-side, runs the
agentic hooks on the assembled message, and streams what came out, so
the tool call never reaches a client that cannot run it. It also turns
a complete response back into a stream when a pre-request hook made the
provider call complete for a caller who asked to stream. The native
route relayed every stream live and ran no response hooks on it

Add a route-neutral StreamPolicy stage to the host hook contract. The
driver opens the caller's stream at once under HoldBack, swallows the
provider's chunks, assembles them through the binding at stream end,
runs transform_response, and replays the result chunk by chunk, and
Synthesize replays a complete response the same way. While a held-back
call waits on the runtime it suspends with Keepalive, and the Python
stream wrapper sends the route's ping whenever that wait outlasts the
interval. The Anthropic Messages SSE codec that assembles and replays a
message lives next to the existing SSE helpers, and the Messages binding
exposes it

HandlerBody answers the policy from the shim, which applies the
handler's own server-fulfilled tool rule, and synthesizes when the
pre-request fan-out turned the stream off. A held-back response that
still carries a server-fulfilled tool call nobody fulfilled is raised
instead of leaked. Live streams run no response-stage body hooks: Python
appends the loop's answer as a second message on the same stream, which
no SSE client can consume, so that mode is not ported

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-11 19:14:50 -07:00

4.7 KiB

  • Target invariants, not completion claims
  • This crate owns compatibility for all existing Python callbacks and loggers, including CustomLogger. mapping.rs owns the executable call bindings and the inventory of Python-owned hooks. A Python-owned entry records an existing path, never permission to invoke it a second time. The native call adapter preserves the Logging contract (function_setup, the deployment hooks, pre_call/post_call, the sync and async success and failure fan-out, the deferred proxy release, the argument sharing those callbacks rely on)
    • Smell test: if a future callback host (callbacks-v1-python, WASM, in-process Rust) could share a piece of this crate, it does not belong here
    • SDK request policy (credential inheritance, the budget and retry-count limits) is a separate hook supplied by python-bridge. Compose it after this adapter so logging adopts the final keyword view before policy mutates or rejects it
    • HandlerBody is the Python handler body a route runs around the provider call, keyed by LoggingOperation: for async Messages the async_pre_request_hook fan-out at the request stage and the agentic-loop orchestration at the response stage, for Responses (sync and async) the agentic-loop orchestration only. A sync call runs the fan-out to completion through the shim's run_sync, as Python's sync handler does. The body also answers the driver's stream policy: a streaming request is held back when the shim finds a requested tool a registered callback fulfils server-side, and a request whose stream the pre-request fan-out turned off is synthesized back into one. The response fan-out learns whether the stream was held back, and a held-back response that still carries a server-fulfilled tool call nobody fulfilled is raised as an error instead of leaking to the client. legacy_hooks composes it inside LegacyLogging so the body's response replaces the one the wrapper's success hook and Logging see, as on the Python path. Both fan-outs stay in callbacks_legacy_python.py, dispatch on the operation name and borrow the handler's own functions; the body hook only hands them the resolved request and lays their changed keys over the keyword layer. Adding a route's body means a new operation arm in those two functions and its rows in mapping.rs, never a second hook type
    • The driver in litellm-host-python, the routes and core see one PythonCallHooks using the shared CallEvent. They never learn which Python objects consume a call
  • Every litellm Python internal Rust still borrows is a variant of LegacyPython, grouped by subsystem, with its signature pinned in python_contract.json
    • The enum only shrinks: when Rust owns a subsystem, delete its group rather than adding a Rust path beside it
    • Calling a user's own callback directly is permanent Python surface and gets its own type outside LegacyPython
  • PublicCall is the caller's call as Logging sees it: the positional arguments, the keyword view as the call rewrites it (setup, deployment hook, preflight) and the bound request object backing omitted keywords. Shared bridge composition hands it to LegacyLogging. Routes use the neutral call boundary
  • LoggingOperation selects legacy logging entrypoints and response handling. It belongs here rather than in shared inference data contracts
  • setup reuses a Logging passed as litellm_logging_obj (the proxy and Router) and otherwise builds one through function_setup. Which callbacks run is Logging's decision, never this crate's
  • Callbacks receive the caller's own objects and may mutate them. This crate alone carries that obligation
    • Retain complete boundary arguments, opaque values, aliases, omitted/default distinctions and deliberate copies. Preserve the deployment-hook kwargs view
    • Before pre_call, re-alias every body key whose value equals the caller's argument to the caller's own object, resolved through litellm_host_python::lookup
    • Retain body/header roots from pre_call to post_call. In-place mutation reaches the wire, envelope field replacement is visible to later callbacks only
  • Success and failure handlers receive the exact selected public response or exception
    • A failure-handler error cannot suppress the other eligible family or replace the mapped provider error. A cancellation ends the call with no further dispatch
    • Dispatch errors never replay provider work or trigger the opposite outcome. The proxy releases deferred success at most once
    • Delivery follows the registry, not the callable's type: direct, awaited, executor-submitted, logging-worker and deferred paths stay distinct
  • Traverse every retained Python edge. close is idempotent and restores the correlation context once