Skip to main content

InferenceAdapter

Trait InferenceAdapter 

Source
pub trait InferenceAdapter: Send + Sync {
    // Required methods
    fn name(&self) -> &str;
    fn capabilities(&self) -> &ProviderCapabilities;
    fn chat<'life0, 'life1, 'async_trait>(
        &'life0 self,
        request: &'life1 ChatRequest,
    ) -> Pin<Box<dyn Future<Output = Result<ChatResponse, InferenceError>> + Send + 'async_trait>>
       where 'life0: 'async_trait,
             'life1: 'async_trait,
             Self: 'async_trait;

    // Provided methods
    fn capabilities_for(&self, model: &str) -> &ProviderCapabilities { ... }
    fn chat_stream<'life0, 'life1, 'async_trait>(
        &'life0 self,
        request: &'life1 ChatRequest,
    ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<ChatStreamEvent, InferenceError>> + Send>>, InferenceError>> + Send + 'async_trait>>
       where 'life0: 'async_trait,
             'life1: 'async_trait,
             Self: 'async_trait { ... }
    fn map_tool_choice(&self, choice: ToolChoice) -> Value { ... }
    fn supports_native_tools(&self) -> bool { ... }
    fn supports_prompt_caching(&self) -> bool { ... }
    fn supports_structured_output(&self) -> bool { ... }
    fn wants_detailed_usage(&self) -> bool { ... }
    fn context_window(&self, model: &str) -> usize { ... }
}
Expand description

The async inference surface every provider implements.

Why: one seam lets the agent loop, trusty-review, and tga issue a chat call against any provider identically; the concrete HTTP mechanics live in each adapter, not in the caller. Send + Sync are required because callers share adapters across tokio tasks. What: implementors MUST provide Self::name, Self::capabilities, and Self::chat. The remaining methods have capability-derived defaults an implementor overrides only when its wire behaviour differs (e.g. an Anthropic-dialect adapter overriding Self::map_tool_choice). Object-safe: async_trait boxes the chat future so Box<dyn InferenceAdapter> works. Test: ScriptedAdapter (test_support) implements it; the configurator drives it as a trait object.

Required Methods§

Source

fn name(&self) -> &str

Stable provider name for logging and diagnostics.

Why: telemetry and error messages need a human-readable backend label. What: a short identifier such as "openrouter" or "scripted". Test: configurator round-trip asserts the built adapter’s name.

Source

fn capabilities(&self) -> &ProviderCapabilities

The capability descriptor for this adapter’s provider.

Why: the introspection defaults below read from it, and consumers query it directly to decide per-model behaviour before issuing a call. What: returns a borrowed ProviderCapabilities (typically a &'static from crate::inference::registry::capabilities, but an adapter may own a customised copy). Test: supports_* defaults are derived from it.

Source

fn chat<'life0, 'life1, 'async_trait>( &'life0 self, request: &'life1 ChatRequest, ) -> Pin<Box<dyn Future<Output = Result<ChatResponse, InferenceError>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait,

Issue one chat/completions call.

Why: the single method the whole agent loop depends on; a one-call surface keeps test doubles trivial and the caller’s dependency minimal. What: sends request to the provider and yields a ChatResponse (which carries the normalized crate::inference::Usage) or an InferenceError the caller classifies via InferenceError::is_retryable/InferenceError::is_alarm. Test: ScriptedAdapter::chat returns queued scripted responses.

Provided Methods§

Source

fn capabilities_for(&self, model: &str) -> &ProviderCapabilities

The capability descriptor for the provider that would actually serve model.

Why (#4425): Self::capabilities assumes one adapter serves one provider, but a ROUTING adapter picks its backend per request from the model slug (trusty-code’s OpenAiCompatClient spans OpenRouter / Fireworks / Together / AtlasCloud; its DispatchingLlmClient adds Bedrock). Answering such an adapter’s capability question with one fixed provider’s profile is silently wrong for every other backend it serves — e.g. reporting OpenRouter’s detailed_usage_accounting: true for a Fireworks turn, which no other provider accepts on the wire. This is the model-aware form callers should prefer whenever a slug is in hand; Self::context_window already established that shape. What: defaults to Self::capabilities — correct for every single-provider adapter, which is most of them. A routing adapter overrides it to resolve model through the same routing gate its chat/chat_stream use, so capabilities can never disagree with where the request is actually sent. Test: adapter_capabilities_for_defaults_to_capabilities; trusty-code’s client::tests::capabilities_for_follows_slug_routing and dispatch::tests::capabilities_for_follows_slug_routing.

Source

fn chat_stream<'life0, 'life1, 'async_trait>( &'life0 self, request: &'life1 ChatRequest, ) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<ChatStreamEvent, InferenceError>> + Send>>, InferenceError>> + Send + 'async_trait>>
where 'life0: 'async_trait, 'life1: 'async_trait, Self: 'async_trait,

Issue one chat/completions call as an incremental token stream.

Why: consumers that render tokens as they arrive (the trusty-agents chat UI first) need deltas incrementally, not one buffered ChatResponse. Making this a trait method with a working default means every adapter is stream-callable immediately: OpenAI-dialect providers override it with a real SSE transport (#3696 Gap B), while adapters without native streaming keep the default. Returning Result<ChatStream, _> (rather than a stream whose first item is the error) lets a stream=true handshake failure surface synchronously so the caller can choose to retry non-streaming — the adapter never silently degrades to buffered on its own. What: yields ordered crate::inference::ChatStreamEvents — text/tool deltas followed by exactly one terminal Done carrying the finish reason and usage. The default buffers via Self::chat and replays the finished response through buffered_stream; dropping the returned stream cancels the underlying request in a real streaming override. Test: crates/trusty-common/tests/inference_adapters.rs streaming round-trip; super::streaming::tests::buffered_stream_replays_response covers the default’s replay shape.

Source

fn map_tool_choice(&self, choice: ToolChoice) -> Value

Translate a neutral ToolChoice into this provider’s wire JSON.

Why: OpenAI-dialect and Anthropic-dialect providers spell tool-choice differently; centralising the mapping keeps the caller dialect-agnostic. What: defaults to the OpenAI spelling (openai_tool_choice); an Anthropic-dialect adapter overrides this. Test: default asserted via the OpenAI mapper’s own tests.

Source

fn supports_native_tools(&self) -> bool

Whether the provider supports native function-calling.

Why: models without native tool support need prompt-emulated guidance instead of a tools array; this flag drives that selection. What: defaults to capabilities().native_tool_calling. Test: registry seed assertions.

Source

fn supports_prompt_caching(&self) -> bool

Whether the provider honours Anthropic-style prompt-cache breakpoints.

Why: gating the cache_control marker to caching-capable providers keeps the wire payload minimal for models that can never benefit. What: defaults to capabilities().prompt_caching. Test: registry seed assertions.

Source

fn supports_structured_output(&self) -> bool

Whether the provider supports structured / JSON-schema output.

Why: the capability trusty-review needs to request schema-constrained responses; folded into the trait so every consumer shares one answer. What: defaults to capabilities().structured_output. Test: registry seed assertions.

Source

fn wants_detailed_usage(&self) -> bool

Whether to request detailed usage accounting (OpenRouter’s usage: {"include": true} directive).

Why: only OpenRouter returns its authoritative cache-aware cost when asked; other providers must never see the directive. What: defaults to capabilities().detailed_usage_accounting. Test: registry seed assertions.

Source

fn context_window(&self, model: &str) -> usize

The context window (in tokens) for a model slug served by this provider.

Why: compaction/budget code asks the adapter for the real window rather than hard-coding one; the answer is model-specific (incl. the #2330 haiku fix) with the provider default as a fallback. What: defaults to context_window with the capabilities of the provider that would actually serve model (Self::capabilities_for) as the provider-default tier — #4425: on a routing adapter this is the only way the fallback tier can match the backend the slug reaches. Test: context submodule tests (haiku_resolves_to_200k); context_window_default_follows_capabilities_for.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl InferenceAdapter for AnthropicAdapter

Source§

impl InferenceAdapter for BedrockAdapter

Source§

impl InferenceAdapter for BedrockChatClient

Delegating InferenceAdapter impl (#4425).

Why: DispatchingLlmClient routes bedrock/* slugs here through the SHARED trait, so this wrapper must satisfy that trait rather than expose a look-alike inherent chat. Every method delegates — including the capability and tool-choice hooks, which Bedrock overrides with the Anthropic dialect: forwarding them (instead of inheriting the trait’s OpenAI-dialect defaults) is what keeps a bedrock/* turn wire-identical to calling the shared adapter directly. What: name/capabilities/chat/chat_stream/map_tool_choice all forward to BedrockAdapter. The capability-derived supports_* defaults need no override because they read capabilities(), which is forwarded. Test: bedrock::tests::*; wire behaviour is covered by the shared adapter’s own tests.

Source§

impl InferenceAdapter for DispatchingLlmClient

Source§

impl InferenceAdapter for EchoLlmClient

Source§

impl InferenceAdapter for FanoutEchoLlmClient

Source§

impl InferenceAdapter for OpenAiCompatAdapter

Source§

impl InferenceAdapter for OpenAiCompatClient

Delegating InferenceAdapter impl (#4425).

Why: this transport IS a shared-trait implementation, not a private abstraction — DispatchingLlmClient and every trusty-code call site reach it through dyn InferenceAdapter. It routes per REQUEST across four OpenAI-dialect providers, so the trait’s per-adapter identity methods are answered for the routing default rather than for one fixed backend. What: chat and chat_stream both go through Self::route, so they can never disagree about provider selection; chat_stream reaches the shared OpenAI-compat adapter’s NATIVE SSE transport (#3696 Gap B), which is what makes trusty-code’s OpenRouter path stream token-by-token. Test: client::tests::*, tests/inference_shared_adapter_e2e.rs.

Source§

impl InferenceAdapter for RecallEchoLlmClient

Source§

impl InferenceAdapter for RecordingLlmClient

Source§

impl InferenceAdapter for ScriptedAdapter

Source§

impl InferenceAdapter for SearchEchoLlmClient

Source§

impl InferenceAdapter for SoakEchoLlmClient

Source§

impl InferenceAdapter for SoakLoadEchoLlmClient