Skip to main content

trusty_code/provider/
traits.rs

1//! Provider trait and tool-choice abstraction.
2//!
3//! Why: Different LLM backends (OpenRouter, AWS Bedrock, …) normalise
4//! `tool_choice` and token-usage differently on the wire. The agent loop should
5//! not branch on the provider; instead it asks a `Provider` to translate a
6//! provider-neutral [`ToolChoice`] into the backend's wire format and to extract
7//! a canonical [`TokenUsage`] from the response. This keeps per-backend quirks
8//! behind one seam (#1021) and feeds fallback-guidance selection in #1032/#1023.
9//! What: Defines [`ToolChoice`] (the neutral policy enum) and the [`Provider`]
10//! trait with `name`, `map_tool_choice`, `extract_usage`, and
11//! `supports_native_tools`.
12//! Test: `provider::tests::*` plus per-impl tests in `openrouter` and `bedrock`.
13
14use serde_json::Value;
15
16use crate::llm::ChatResponse;
17use crate::perf::TokenUsage;
18
19/// Provider-neutral tool-choice policy.
20///
21/// Why: Callers (the agent loop) want to express intent — "don't call tools",
22/// "you may call tools", "you must call a tool", or "call this specific
23/// function" — without knowing how each backend spells it on the wire. The
24/// `Provider` translates this enum via [`Provider::map_tool_choice`].
25/// What: `None` disables tools, `Auto` lets the model decide, `Required` forces
26/// some tool call, and `Function(name)` forces a specific named function.
27/// Test: `openrouter::tests::map_tool_choice_*` cover every variant.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum ToolChoice {
30    /// The model must not call any tool (`"none"`).
31    None,
32    /// The model may call a tool if it decides to (`"auto"`).
33    Auto,
34    /// The model must call some tool this turn (`"required"`).
35    Required,
36    /// The model must call the named function.
37    Function(String),
38}
39
40/// A backend that normalises tool-choice and usage for one family of models.
41///
42/// Why: The agent loop must stay backend-agnostic. By depending on `dyn
43/// Provider` it can drive OpenRouter today and Bedrock later without changing
44/// the loop — the factory ([`crate::provider::provider_for`]) picks the impl
45/// from the model slug.
46/// What: Object-safe (`Send + Sync`) trait with the four normalisation hooks the
47/// loop needs. Implementations live in `openrouter` and `bedrock`.
48/// Test: `openrouter::tests::*`, `bedrock::tests::*`.
49pub trait Provider: Send + Sync {
50    /// Stable provider name for logging and diagnostics.
51    ///
52    /// Why: Telemetry and error messages need a human-readable backend label
53    /// that does not change across releases.
54    /// What: Returns a short identifier such as `"openrouter"` or `"bedrock"`.
55    /// Test: `openrouter::tests::name_is_stable`, `bedrock::tests::name_is_bedrock`.
56    fn name(&self) -> &str;
57
58    /// Translate a neutral [`ToolChoice`] into this backend's wire JSON.
59    ///
60    /// Why: OpenAI-style backends use `"none"`/`"auto"`/`"required"` strings and
61    /// a `{type:function, function:{name}}` object for a specific call; other
62    /// backends differ. Centralising the mapping keeps the loop clean.
63    /// What: Returns the `serde_json::Value` to place in
64    /// `ChatRequest.tool_choice`.
65    /// Test: `openrouter::tests::map_tool_choice_*`.
66    fn map_tool_choice(&self, choice: ToolChoice) -> Value;
67
68    /// Extract canonical token usage from a chat response.
69    ///
70    /// Why: Cost accounting needs a single `TokenUsage` shape regardless of how
71    /// the backend reports prompt/completion/cache tokens.
72    /// What: Reads the provider-specific usage block out of `response` and maps
73    /// it to [`TokenUsage`].
74    /// Test: `openrouter::tests::extract_usage_maps_fields`.
75    fn extract_usage(&self, response: &ChatResponse) -> TokenUsage;
76
77    /// Whether the backend/model supports native function-calling.
78    ///
79    /// Why: Models without native tool support need prompt-injected fallback
80    /// guidance instead of the `tools` array; this flag drives that selection in
81    /// #1032/#1023.
82    /// What: Returns `true` when the model can be sent the native `tools` array,
83    /// `false` when the loop must fall back to prompt-based tool emulation.
84    /// Test: `openrouter::tests::supports_native_tools_*`,
85    /// `bedrock::tests::bedrock_supports_native_tools`.
86    fn supports_native_tools(&self) -> bool;
87
88    /// Whether this backend/model honours Anthropic-style `cache_control`
89    /// prompt-cache breakpoints (#2156).
90    ///
91    /// Why: Emitting a `cache_control` marker to a backend/model that ignores
92    /// it is harmless (the field is simply dropped), but gating on this flag
93    /// keeps the wire payload minimal for models that can never benefit and
94    /// documents, in one place, exactly which backends this has been
95    /// verified against — rather than scattering `model.starts_with(...)`
96    /// checks at every call site.
97    /// What: Returns `true` when `agent_loop::build_request` should mark the
98    /// static tools+system-prompt prefix with an ephemeral cache breakpoint;
99    /// `false` otherwise.
100    /// Test: `openrouter::tests::supports_prompt_caching_*`,
101    /// `bedrock::tests::bedrock_does_not_support_prompt_caching`.
102    fn supports_prompt_caching(&self) -> bool;
103
104    /// Whether this backend should be asked for detailed usage accounting
105    /// (response-side cache-usage fix).
106    ///
107    /// Why: OpenRouter's detailed-usage directive
108    /// (`RequestUsageConfig::detailed`, `usage: {"include": true}`) is what
109    /// makes OpenRouter return its authoritative, cache-discount-aware
110    /// `usage.cost` and the nested `prompt_tokens_details` cache counters —
111    /// without it only the bare prompt/completion/total counts are
112    /// guaranteed. This is an OpenRouter-specific wire directive with no
113    /// equivalent on the direct/Bedrock path, so it must stay gated per
114    /// backend rather than sent unconditionally.
115    /// What: Returns `true` when `agent_loop::build_request` should attach
116    /// `ChatRequest.usage = Some(RequestUsageConfig::detailed())`; `false`
117    /// otherwise.
118    /// Test: `openrouter::tests::wants_detailed_usage_is_true`,
119    /// `bedrock::tests::bedrock_does_not_want_detailed_usage`.
120    fn wants_detailed_usage(&self) -> bool;
121}