litellm/litellm-rust/crates/host-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

8.5 KiB

  • Target invariants. Implementation and runtime validation may lag these rules

Boundary with Python consumers

This crate owns CPython execution mechanics for generic litellm-host machines and hooks. Consumers supply domain bindings, host operations, public result construction and callback policy. Neither Rust dependencies nor Python imports may require LiteLLM route modules or legacy Logging

src/native.rs belongs here: it runs a generic machine through the Python runtime and owns its pending execution and abort handle. Keep provider selection, request projection and public exception policy out of it. A rename to machine_runner.rs is optional and must not change behavior

The execution handle receives its Python lifecycle binding from its consumer through PythonLifecycle rather than import a fixed litellm.rust_bridge module. Generic suspension and execution state validation belong here. Public stream wrappers and _hidden_params conventions belong to the consumer

Creating a resolved asyncio Future from an already constructed Python value belongs here, alongside runtime waiting, interpreter detachment and panic containment. Choosing which callable exceptions become a public RuntimeError belongs to the consumer. python-bridge::callable::wrap_failure owns that policy

The driver owns ordering: start, argument preparation, prepared-argument hooks, binding decode and machine start. Fallible per-call resource setup supplied by the consumer runs after all argument hooks, using the prepared argument view, and before provider work. Setup failure follows the existing terminal failure path. Creating or discarding an unstarted coroutine must not initialize clients, acquire credentials or capture execution context

Boundary tests exercise behavior with a supplied lifecycle binding without importing the LiteLLM Python package. Pin inline awaiting, awaitable final values, exception identity, cancellation, re-entry and release of retained objects, rather than module names or source layout

HookChain composes Python runtime hooks as layers. The argument, request and wire-request transformations walk inbound in append order and each feeds its result to the next hook. The response transformation walks outbound, so the last hook appended transforms the response first. The driver runs every hook's prepare_arguments, then every hook's prepare_request, then calls arguments_prepared on every hook in order with the view the request stage produced. Retained callback views must adopt that dictionary before later policy hooks can mutate or reject it. SDK policy is supplied by bridge composition as a hook, never a separate driver phase or parameter. Hooks implement only the stages they need. Default stages preserve the supplied values

After arguments_prepared the driver asks the chain for a StreamPolicy, the most demanding answer any hook gives. Relay hands chunks to the consumer as they arrive and runs no response transformation. HoldBack opens the consumer's stream at once, swallows the provider's chunks, and at stream end has the binding assemble them into the route's response, runs the response transformation on it, and delivers the binding's replay of the result chunk by chunk; the stream hooks see only what the consumer got. Synthesize does the same replay for a complete response whose caller asked for a stream. While a held-back call waits on the runtime it suspends with Keepalive, and the Python Stream hands its consumer the binding's keepalive chunk whenever that wait outlasts the interval. Hooks that await Python are never wrapped in a task for that, so no ping is sent while a hook itself runs

Terminal notifications share the selected response or exception. An ordinary notification error is reported as unraisable and does not skip the next hook or replace the selected outcome. Preparation, interception and transformation errors stop the chain. Cancellation stops all further hook dispatch

Hooks and host calls are async fns that receive the PythonTask. A Python call's result goes through PythonTask::settle, which awaits an awaitable on the caller's task when the call is asynchronous and returns a cancellation as the outer error. No hook returns a continuation or keeps pending state between steps: whatever a suspended hook holds lives on its own future, and dropping the future releases it

Existing runtime invariants

  • Keep this crate the CPython runtime adapter and nothing more: Serde marshalling, interpreter detachment, tokio/asyncio glue, the Execution handle, the PythonTask, the call driver and the PythonBinding, PythonHostCalls and PythonOwned traits, and the PythonRuntime specialization of host::hooks::CallHooks
    • No LiteLLM domain dependencies beyond litellm-host: no route types, no Logging policy, no public API registration, no cdylib build features
    • PythonCallHooks only constrains the shared call-stage interface to PythonRuntime and Python ownership. It must not redeclare the stages
    • PythonCallEvent is a specialization of the shared CallEvent, never a separately defined lifecycle. The driver emits Succeeded or Failed exactly once and never dispatches callbacks after a cancellation. Which Python objects consume those events is the legacy adapter's business
    • CallOptions can publish snapshots independently of callback delivery. Terminal snapshots follow completed hook dispatch, and cancellation never calls a Python callback. For Python-driven calls, leave the machine's observation publisher unset so the driver is the sole publisher of intercepted provider-response snapshots
    • PythonBinding::decode_request receives the keyword view returned by prepare_arguments and updated by arguments_prepared, not the caller's dict. A binding that decodes from it inherits all composed argument rewrites
    • A native failure, including one a host op returns as InvokeError::Native, is classified exactly once through the binding's map_error. A Python exception raised inside the call, and a failure in prepare_arguments or transform_response, is raised as is
    • A failing map_error is raised with the native error's text as its __context__, never swallowed
  • Use standard PyO3 ownership and conversion APIs
    • Prefer Bound<'py, T> for attached operations/results, Py<T> for retention. Binding/unbinding does not copy payloads
    • Use pythonize for selected Serde data, never a JSON-text round trip. Share conversion with Pythonized<T>
    • Preserve PythonizeError's standard conversion into PyErr. Do not stringify original Python exceptions into new ValueErrors
    • Keep serializer-panic containment in Pythonized<T>: async output conversion can run in an unjoined blocking task and otherwise strand delivery
  • Use Python::detach for Rust-only work. Python operations require attachment
    • Keep diagnostic counters in the consumer. Wrapper invocations do not measure every interpreter release
    • Release exclusive class borrows/locks before Python calls or decrements that can invoke finalizers. Expose retained Python edges to GC without calling Python during traversal
  • Keep coroutine driving in the shared Python driver and the native handle
    • Shared driver implementation: litellm/rust_bridge/lifecycle.py, handle: src/handle.rs, task: src/task.rs, call driver: src/driver.rs, native-backed behavior tests: tests/lifecycle.py. The consumer supplies the lifecycle binding
    • The call is one async body polled only from Execution.resume_* through PythonTask::resume, with a noop waker. Nothing in that body may await tokio I/O directly: the native machine is polled inline and otherwise becomes a Python awaitable, and every other await goes through PythonTask::suspend
    • Every lifecycle suspension is awaited inline in the caller's task. into_future creates a separate task and cannot satisfy this contract
    • The body shares the binding, hooks and keyword view with the handle through a lock it releases around every native step and stream boundary, so GC traversal sees them while the call waits on the runtime or its consumer. Traversal is blind only while a hook's own awaitable is in flight
  • References: ownership, conversions, pythonize errors