Skip to main content

trusty_code/provider/
together.rs

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