Skip to main content

trusty_code/provider/
fireworks.rs

1//! Fireworks provider — request-shaping normalisation for `fireworks/*` slugs
2//! (#2406, epic #2400).
3//!
4//! Why: enabling Fireworks in tcode (#2406) is not only a transport concern —
5//! `AgentLoop::build_request` consults `crate::provider::provider_for` to decide
6//! whether to request OpenRouter's detailed-usage directive, whether to attach
7//! prompt-cache breakpoints, and whether to send a native `tools` array. Routing
8//! a `fireworks/*` slug to the default `OpenRouterProvider` would (wrongly)
9//! request `usage:{include:true}` — a directive Fireworks doesn't understand —
10//! so Fireworks needs its own normalisation profile, mirroring the shared
11//! capability registry's Fireworks seed (`detailed_usage_accounting = false`,
12//! `prompt_caching = false`, native OpenAI-style function calling).
13//! What: [`FireworksProvider`] implements [`Provider`] with the OpenAI-dialect
14//! `tool_choice` mapping (identical to OpenRouter's), the standard usage
15//! extraction, native tool support, NO prompt caching, and NO detailed-usage
16//! request. The transport (`crate::llm::client::OpenAiCompatClient`) is what
17//! actually reaches `api.fireworks.ai`; this type only shapes the request.
18//! Test: `fireworks::tests::*`.
19
20use serde_json::{Value, json};
21
22use super::traits::{Provider, ToolChoice};
23use crate::llm::ChatResponse;
24use crate::perf::TokenUsage;
25
26/// Provider for Fireworks-hosted models (`fireworks/*` slugs), served behind the
27/// OpenAI-compatible `/chat/completions` schema.
28///
29/// Why: gives `build_request` a Fireworks-correct normalisation profile so the
30/// wire payload matches what Fireworks accepts (no OpenRouter-only directives).
31/// What: zero-sized marker type implementing [`Provider`].
32/// Test: `fireworks::tests::*`.
33#[derive(Debug, Clone, Default)]
34pub struct FireworksProvider;
35
36impl FireworksProvider {
37    /// Construct a `FireworksProvider`.
38    ///
39    /// Why: gives the factory a uniform constructor call site.
40    /// What: returns the zero-sized marker.
41    /// Test: `fireworks::tests::name_is_fireworks`.
42    pub fn new() -> Self {
43        Self
44    }
45}
46
47impl Provider for FireworksProvider {
48    fn name(&self) -> &str {
49        "fireworks"
50    }
51
52    /// Translate a neutral [`ToolChoice`] into OpenAI-dialect wire JSON.
53    ///
54    /// Why: Fireworks uses the OpenAI `tool_choice` spelling (string policies +
55    /// `{type:function, function:{name}}` object), identical to OpenRouter.
56    /// What: the OpenAI mapping.
57    /// Test: `fireworks::tests::map_tool_choice_scalars`.
58    fn map_tool_choice(&self, choice: ToolChoice) -> Value {
59        match choice {
60            ToolChoice::None => json!("none"),
61            ToolChoice::Auto => json!("auto"),
62            ToolChoice::Required => json!("required"),
63            ToolChoice::Function(name) => json!({
64                "type": "function",
65                "function": { "name": name },
66            }),
67        }
68    }
69
70    /// Extract canonical token usage from a Fireworks response.
71    ///
72    /// Why: Fireworks returns the standard OpenAI `usage` block, already
73    /// normalised into `ChatResponse.usage` by the shared adapter's parse.
74    /// What: delegates to `ChatResponse::token_usage` (identical to the other
75    /// OpenAI-dialect providers).
76    /// Test: `fireworks::tests::extract_usage_maps_fields`.
77    fn extract_usage(&self, response: &ChatResponse) -> TokenUsage {
78        response.clone().token_usage()
79    }
80
81    fn supports_native_tools(&self) -> bool {
82        // Fireworks' tool-capable models accept the native OpenAI `tools` array;
83        // mirrors the shared registry's Fireworks `native_tool_calling = true`.
84        true
85    }
86
87    fn supports_prompt_caching(&self) -> bool {
88        // Fireworks does not honour Anthropic-style `cache_control` breakpoints;
89        // mirrors the shared registry's Fireworks `prompt_caching = false`.
90        false
91    }
92
93    fn wants_detailed_usage(&self) -> bool {
94        // `usage:{include:true}` is an OpenRouter-only directive; Fireworks would
95        // not understand it. Mirrors the shared registry's Fireworks
96        // `detailed_usage_accounting = false`.
97        false
98    }
99}
100
101// ── Tests ─────────────────────────────────────────────────────────────────────
102
103#[cfg(test)]
104mod tests {
105    use super::*;
106
107    /// `name()` returns `"fireworks"`.
108    ///
109    /// Why: routing and telemetry distinguish Fireworks by name; the transport's
110    /// `provider_for_slug` and `dispatch`'s bedrock check both key off it.
111    /// What: assert the name.
112    /// Test: this test.
113    #[test]
114    fn name_is_fireworks() {
115        assert_eq!(FireworksProvider::new().name(), "fireworks");
116    }
117
118    /// Fireworks reports native-tool support.
119    ///
120    /// Why: `build_request` sends the native `tools` array for tool-capable
121    /// Fireworks models.
122    /// What: assert `supports_native_tools()` is `true`.
123    /// Test: this test.
124    #[test]
125    fn fireworks_supports_native_tools() {
126        assert!(FireworksProvider::new().supports_native_tools());
127    }
128
129    /// Fireworks does NOT request OpenRouter's detailed usage accounting.
130    ///
131    /// Why: this is the exact gate that would otherwise attach the
132    /// OpenRouter-only `usage:{include:true}` directive to a Fireworks request —
133    /// the core reason a Fireworks-specific provider is needed.
134    /// What: assert `wants_detailed_usage()` is `false`.
135    /// Test: this test.
136    #[test]
137    fn fireworks_does_not_want_detailed_usage() {
138        assert!(!FireworksProvider::new().wants_detailed_usage());
139    }
140
141    /// Fireworks does NOT advertise prompt caching.
142    ///
143    /// Why: `build_request` must never mark a Fireworks request with an
144    /// Anthropic-style `cache_control` breakpoint it cannot honour.
145    /// What: assert `supports_prompt_caching()` is `false`.
146    /// Test: this test.
147    #[test]
148    fn fireworks_does_not_support_prompt_caching() {
149        assert!(!FireworksProvider::new().supports_prompt_caching());
150    }
151
152    /// `map_tool_choice` maps the scalar policies to the OpenAI wire strings.
153    ///
154    /// Why: Fireworks expects the OpenAI spelling; a wrong shape breaks
155    /// tool routing.
156    /// What: map each scalar variant, assert the JSON value.
157    /// Test: this test.
158    #[test]
159    fn map_tool_choice_scalars() {
160        let p = FireworksProvider::new();
161        assert_eq!(p.map_tool_choice(ToolChoice::None), json!("none"));
162        assert_eq!(p.map_tool_choice(ToolChoice::Auto), json!("auto"));
163        assert_eq!(p.map_tool_choice(ToolChoice::Required), json!("required"));
164        assert_eq!(
165            p.map_tool_choice(ToolChoice::Function("search".into())),
166            json!({"type": "function", "function": {"name": "search"}})
167        );
168    }
169
170    /// `extract_usage` maps a normalised usage block into `TokenUsage`.
171    ///
172    /// Why: pins that Fireworks performs no extra (inconsistent) usage transform.
173    /// What: deserialise a response fixture, extract usage, assert fields.
174    /// Test: this test.
175    #[test]
176    fn extract_usage_maps_fields() {
177        let fixture = r#"{
178          "id": "fw-1",
179          "choices": [{"message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
180          "usage": {"prompt_tokens": 40, "completion_tokens": 8, "total_tokens": 48}
181        }"#;
182        let resp: ChatResponse = serde_json::from_str(fixture).expect("deserialise");
183        let usage = FireworksProvider::new().extract_usage(&resp);
184        assert_eq!(usage.prompt_tokens, 40);
185        assert_eq!(usage.completion_tokens, 8);
186    }
187}