Skip to main content

recursive/llm/
openai.rs

1//! OpenAI-compatible chat-completions adapter.
2//!
3//! Targets the `/chat/completions` shape that OpenAI, Azure (via gateway),
4//! GLM (Zhipu), DeepSeek, Moonshot, Together, Ollama and many others speak.
5//! The only thing that varies is the base URL + model name + API key, which
6//! is all driven by config.
7
8use async_trait::async_trait;
9use reqwest::Client;
10use serde::{Deserialize, Serialize};
11use serde_json::Value;
12use std::time::Duration;
13
14use super::StructuredRequest;
15use super::{Completion, LlmProvider, StreamSender, TokenUsage, ToolCall, ToolSpec};
16use crate::error::{Error, Result};
17use crate::message::{Message, Role};
18
19/// Retry policy for transient failures (network timeouts, 5xx errors).
20#[derive(Debug, Clone)]
21pub struct RetryPolicy {
22    pub max_retries: usize,
23    pub initial_backoff: Duration,
24    pub max_backoff: Duration,
25}
26
27impl Default for RetryPolicy {
28    fn default() -> Self {
29        Self {
30            max_retries: 2,
31            initial_backoff: Duration::from_secs(1),
32            max_backoff: Duration::from_secs(8),
33        }
34    }
35}
36
37impl RetryPolicy {
38    /// Decide whether the caller should wait and try again.
39    /// `attempt` is 0-indexed (0 = the first retry decision after the
40    /// initial try has failed). Returns `Some(backoff)` to retry,
41    /// `None` to give up and propagate the error.
42    pub fn backoff_for(
43        &self,
44        attempt: usize,
45        status: Option<u16>,
46        is_network_error: bool,
47    ) -> Option<Duration> {
48        if attempt >= self.max_retries {
49            return None;
50        }
51
52        let is_transient = is_network_error || status.is_some_and(|s| (500..600).contains(&s));
53
54        if !is_transient {
55            return None;
56        }
57
58        let backoff = self.initial_backoff * 2u32.pow(attempt as u32);
59        Some(backoff.min(self.max_backoff))
60    }
61}
62
63#[derive(Debug, Clone)]
64pub struct OpenAiProvider {
65    base_url: String,
66    api_key: String,
67    model: String,
68    client: Client,
69    temperature: f64,
70    max_tokens: u32,
71    retry: RetryPolicy,
72    stream_tx: Option<StreamSender>,
73}
74
75impl OpenAiProvider {
76    pub fn new(
77        base_url: impl Into<String>,
78        api_key: impl Into<String>,
79        model: impl Into<String>,
80    ) -> Self {
81        Self {
82            base_url: base_url.into().trim_end_matches('/').to_string(),
83            api_key: api_key.into(),
84            model: model.into(),
85            client: Client::builder()
86                .timeout(Duration::from_secs(180))
87                .build()
88                .expect("reqwest client build"),
89            temperature: 0.2,
90            // DeepSeek defaults to a per-response cap of 4096 tokens; any
91            // tool call whose `arguments` string holds more than that — e.g.
92            // a `write_file` with a multi-kilobyte `contents` field — gets
93            // truncated server-side and arrives as malformed JSON. 16384 is
94            // both within DeepSeek's hard ceiling (8192 for v3, 32K-64K for
95            // newer models) and big enough for whole-file writes. Callers
96            // can override with `with_max_tokens` if their provider supports
97            // more or needs less.
98            max_tokens: 16384,
99            retry: RetryPolicy::default(),
100            stream_tx: None,
101        }
102    }
103
104    /// Enable streaming by providing a channel sender for partial tokens.
105    pub fn with_stream_tx(mut self, tx: StreamSender) -> Self {
106        self.stream_tx = Some(tx);
107        self
108    }
109
110    /// Build an `Error::Llm` with the model name prefixed.
111    fn make_err(&self, ctx: impl Into<String>) -> Error {
112        Error::Llm {
113            provider: self.model.clone(),
114            message: ctx.into(),
115        }
116    }
117
118    pub fn with_temperature(mut self, t: f64) -> Self {
119        self.temperature = t;
120        self
121    }
122
123    pub fn with_max_tokens(mut self, n: u32) -> Self {
124        self.max_tokens = n;
125        self
126    }
127
128    pub fn with_retry_policy(mut self, policy: RetryPolicy) -> Self {
129        self.retry = policy;
130        self
131    }
132}
133
134#[async_trait]
135impl LlmProvider for OpenAiProvider {
136    #[tracing::instrument(skip(self, messages, tools), fields(
137        provider = %self.base_url.split('/').next_back().unwrap_or("unknown"),
138        model = %self.model
139    ))]
140    async fn complete(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Completion> {
141        let body = build_request(
142            &self.model,
143            self.temperature,
144            self.max_tokens,
145            messages,
146            tools,
147        );
148        let url = format!("{}/chat/completions", self.base_url);
149
150        let mut attempt = 0;
151        loop {
152            tracing::debug!(target: "recursive::llm", request = %body, "POST {}", url);
153            let result = self
154                .client
155                .post(&url)
156                .bearer_auth(&self.api_key)
157                .json(&body)
158                .send()
159                .await;
160
161            match result {
162                Ok(resp) => {
163                    let status = resp.status();
164                    let is_network_error = false;
165
166                    if status.is_success() {
167                        let text = resp.text().await?;
168                        let parsed: ChatResponse = serde_json::from_str(&text).map_err(|e| {
169                            self.make_err(format!("failed to parse response: {e}; body: {text}"))
170                        })?;
171                        let choice = parsed
172                            .choices
173                            .into_iter()
174                            .next()
175                            .ok_or_else(|| self.make_err("response had no choices"))?;
176                        return Ok(parse_completion(choice, parsed.usage));
177                    }
178
179                    // Non-2xx response: check if it's transient (5xx)
180                    let text = resp.text().await?;
181                    tracing::debug!(target: "recursive::llm", body = %text, "error response");
182
183                    if let Some(backoff) =
184                        self.retry
185                            .backoff_for(attempt, Some(status.as_u16()), is_network_error)
186                    {
187                        tracing::warn!(
188                            target: "recursive::llm",
189                            attempt,
190                            backoff_ms = backoff.as_millis(),
191                            status = status.as_u16(),
192                            "transient HTTP error, retrying"
193                        );
194                        tokio::time::sleep(backoff).await;
195                        attempt += 1;
196                        continue;
197                    }
198
199                    // Non-transient (4xx or other)
200                    return Err(self.make_err(format!("HTTP {}: {}", status, text)));
201                }
202                Err(e) => {
203                    // Network error
204                    if let Some(backoff) = self.retry.backoff_for(attempt, None, true) {
205                        tracing::warn!(
206                            target: "recursive::llm",
207                            attempt,
208                            backoff_ms = backoff.as_millis(),
209                            error = %e,
210                            "network error, retrying"
211                        );
212                        tokio::time::sleep(backoff).await;
213                        attempt += 1;
214                        continue;
215                    }
216
217                    return Err(self.make_err(format!("request failed: {e}")));
218                }
219            }
220        }
221    }
222
223    async fn complete_structured(&self, req: StructuredRequest) -> Result<Value> {
224        let mut body = build_request(
225            &self.model,
226            self.temperature,
227            self.max_tokens,
228            &req.messages,
229            &[],
230        );
231        body["response_format"] = serde_json::json!({
232            "type": "json_schema",
233            "json_schema": {
234                "name": req.schema_name,
235                "strict": true,
236                "schema": req.schema,
237            }
238        });
239
240        let url = format!("{}/chat/completions", self.base_url);
241
242        let mut attempt = 0;
243        loop {
244            tracing::debug!(target: "recursive::llm", request = %body, "POST {} (structured)", url);
245            let result = self
246                .client
247                .post(&url)
248                .bearer_auth(&self.api_key)
249                .json(&body)
250                .send()
251                .await;
252
253            match result {
254                Ok(resp) => {
255                    let status = resp.status();
256                    let is_network_error = false;
257
258                    if status.is_success() {
259                        let text = resp.text().await?;
260                        let parsed: ChatResponse = serde_json::from_str(&text).map_err(|e| {
261                            self.make_err(format!("failed to parse response: {e}; body: {text}"))
262                        })?;
263                        let choice = parsed
264                            .choices
265                            .into_iter()
266                            .next()
267                            .ok_or_else(|| self.make_err("response had no choices"))?;
268                        let completion = parse_completion(choice, parsed.usage);
269                        // Parse the content as JSON
270                        if completion.content.trim().is_empty() {
271                            return Err(
272                                self.make_err("structured response had empty content".to_string())
273                            );
274                        }
275                        let parsed_json: Value = serde_json::from_str(&completion.content)
276                            .map_err(|e| {
277                                self.make_err(format!(
278                                    "failed to parse structured response as JSON: {e}; content: {}",
279                                    completion.content
280                                ))
281                            })?;
282                        return Ok(parsed_json);
283                    }
284
285                    let text = resp.text().await?;
286                    tracing::debug!(target: "recursive::llm", body = %text, "error response (structured)");
287
288                    if let Some(backoff) =
289                        self.retry
290                            .backoff_for(attempt, Some(status.as_u16()), is_network_error)
291                    {
292                        tracing::warn!(
293                            target: "recursive::llm",
294                            attempt,
295                            backoff_ms = backoff.as_millis(),
296                            status = status.as_u16(),
297                            "transient HTTP error, retrying (structured)"
298                        );
299                        tokio::time::sleep(backoff).await;
300                        attempt += 1;
301                        continue;
302                    }
303
304                    return Err(self.make_err(format!("HTTP {}: {}", status, text)));
305                }
306                Err(e) => {
307                    if let Some(backoff) = self.retry.backoff_for(attempt, None, true) {
308                        tracing::warn!(
309                            target: "recursive::llm",
310                            attempt,
311                            backoff_ms = backoff.as_millis(),
312                            error = %e,
313                            "network error, retrying (structured)"
314                        );
315                        tokio::time::sleep(backoff).await;
316                        attempt += 1;
317                        continue;
318                    }
319
320                    return Err(self.make_err(format!("request failed: {e}")));
321                }
322            }
323        }
324    }
325
326    async fn stream(
327        &self,
328        messages: &[Message],
329        tools: &[ToolSpec],
330        stream_tx: Option<StreamSender>,
331    ) -> Result<Completion> {
332        // If no stream_tx provided, fall back to the instance-level one
333        let tx = stream_tx.or_else(|| self.stream_tx.clone());
334        self.stream_inner(messages, tools, tx).await
335    }
336}
337
338impl OpenAiProvider {
339    async fn stream_inner(
340        &self,
341        messages: &[Message],
342        tools: &[ToolSpec],
343        stream_tx: Option<StreamSender>,
344    ) -> Result<Completion> {
345        let mut body = build_request(
346            &self.model,
347            self.temperature,
348            self.max_tokens,
349            messages,
350            tools,
351        );
352        body["stream"] = Value::Bool(true);
353
354        let url = format!("{}/chat/completions", self.base_url);
355
356        let mut attempt = 0;
357        loop {
358            tracing::debug!(target: "recursive::llm", request = %body, "POST {} (stream)", url);
359            let result = self
360                .client
361                .post(&url)
362                .bearer_auth(&self.api_key)
363                .json(&body)
364                .send()
365                .await;
366
367            match result {
368                Ok(resp) => {
369                    let status = resp.status();
370                    if status.is_success() {
371                        return self.parse_sse_stream(resp, stream_tx.clone()).await;
372                    }
373
374                    // Non-2xx: read body and check retry
375                    let text = resp.text().await?;
376                    tracing::debug!(target: "recursive::llm", body = %text, "error response (stream)");
377
378                    if let Some(backoff) =
379                        self.retry
380                            .backoff_for(attempt, Some(status.as_u16()), false)
381                    {
382                        tracing::warn!(
383                            target: "recursive::llm",
384                            attempt,
385                            backoff_ms = backoff.as_millis(),
386                            status = status.as_u16(),
387                            "transient HTTP error, retrying (stream)"
388                        );
389                        tokio::time::sleep(backoff).await;
390                        attempt += 1;
391                        continue;
392                    }
393
394                    return Err(self.make_err(format!("HTTP {}: {}", status, text)));
395                }
396                Err(e) => {
397                    if let Some(backoff) = self.retry.backoff_for(attempt, None, true) {
398                        tracing::warn!(
399                            target: "recursive::llm",
400                            attempt,
401                            backoff_ms = backoff.as_millis(),
402                            error = %e,
403                            "network error, retrying (stream)"
404                        );
405                        tokio::time::sleep(backoff).await;
406                        attempt += 1;
407                        continue;
408                    }
409
410                    return Err(self.make_err(format!("request failed: {e}")));
411                }
412            }
413        }
414    }
415
416    /// Parse an SSE stream from a successful HTTP response.
417    ///
418    /// Reads `data: {...}\n\n` chunks line-by-line, extracts
419    /// `choices[0].delta.content` deltas, accumulates them, and emits
420    /// each delta through `stream_tx` if configured. Returns the final
421    /// `Completion` matching the non-streaming shape.
422    async fn parse_sse_stream(
423        &self,
424        resp: reqwest::Response,
425        stream_tx: Option<StreamSender>,
426    ) -> Result<Completion> {
427        let mut content = String::new();
428        let tool_calls: Vec<ToolCall> = Vec::new();
429        let mut finish_reason: Option<String> = None;
430        let mut usage: Option<TokenUsage> = None;
431
432        // Read the byte stream line by line
433        let reader = resp.text().await?;
434        for line in reader.lines() {
435            if let Some(data) = line.strip_prefix("data: ") {
436                // Skip the final "[DONE]" marker
437                if data.trim() == "[DONE]" {
438                    break;
439                }
440
441                // Parse the JSON chunk
442                let chunk: Value = serde_json::from_str(data)
443                    .map_err(|e| self.make_err(format!("SSE parse error: {e}; data: {data}")))?;
444
445                // Extract delta content
446                if let Some(choices) = chunk.get("choices").and_then(|c| c.as_array()) {
447                    if let Some(choice) = choices.first() {
448                        // Delta content
449                        if let Some(delta) = choice.get("delta") {
450                            if let Some(delta_content) =
451                                delta.get("content").and_then(|c| c.as_str())
452                            {
453                                if !delta_content.is_empty() {
454                                    content.push_str(delta_content);
455                                    if let Some(ref tx) = stream_tx {
456                                        let _ = tx.send(delta_content.to_string());
457                                    }
458                                }
459                            }
460                        }
461
462                        // Finish reason (only on the last chunk)
463                        if let Some(fr) = choice.get("finish_reason").and_then(|f| f.as_str()) {
464                            if !fr.is_empty() {
465                                finish_reason = Some(fr.to_string());
466                            }
467                        }
468                    }
469                }
470
471                // Usage (only on the last chunk for some providers)
472                if let Some(u) = chunk.get("usage") {
473                    let prompt =
474                        u.get("prompt_tokens").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
475                    let completion = u
476                        .get("completion_tokens")
477                        .and_then(|v| v.as_u64())
478                        .unwrap_or(0) as u32;
479                    let total = u.get("total_tokens").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
480                    let cache_hit = u
481                        .get("prompt_cache_hit_tokens")
482                        .and_then(|v| v.as_u64())
483                        .unwrap_or(0) as u32;
484                    let cache_miss = u
485                        .get("prompt_cache_miss_tokens")
486                        .and_then(|v| v.as_u64())
487                        .unwrap_or(0) as u32;
488                    usage = Some(TokenUsage {
489                        prompt_tokens: prompt,
490                        completion_tokens: completion,
491                        total_tokens: total,
492                        cache_hit_tokens: cache_hit,
493                        cache_miss_tokens: cache_miss,
494                    });
495                }
496            }
497        }
498
499        Ok(Completion {
500            content,
501            tool_calls,
502            finish_reason,
503            usage,
504        })
505    }
506}
507
508fn build_request(
509    model: &str,
510    temperature: f64,
511    max_tokens: u32,
512    messages: &[Message],
513    tools: &[ToolSpec],
514) -> Value {
515    let mut req = serde_json::json!({
516        "model": model,
517        "temperature": temperature,
518        "max_tokens": max_tokens,
519        "messages": messages.iter().map(serialize_message).collect::<Vec<_>>(),
520    });
521    if !tools.is_empty() {
522        let tools_json: Vec<Value> = tools
523            .iter()
524            .map(|t| {
525                serde_json::json!({
526                    "type": "function",
527                    "function": {
528                        "name": t.name,
529                        "description": t.description,
530                        "parameters": t.parameters,
531                    }
532                })
533            })
534            .collect();
535        req["tools"] = Value::Array(tools_json);
536        req["tool_choice"] = Value::String("auto".into());
537    }
538    req
539}
540
541fn serialize_message(m: &Message) -> Value {
542    let role = match m.role {
543        Role::System => "system",
544        Role::User => "user",
545        Role::Assistant => "assistant",
546        Role::Tool => "tool",
547    };
548    let mut obj = serde_json::Map::new();
549    obj.insert("role".into(), Value::String(role.into()));
550    obj.insert("content".into(), Value::String(m.content.clone()));
551    if let Some(id) = &m.tool_call_id {
552        obj.insert("tool_call_id".into(), Value::String(id.clone()));
553    }
554    if !m.tool_calls.is_empty() {
555        let calls: Vec<Value> = m
556            .tool_calls
557            .iter()
558            .map(|c| {
559                serde_json::json!({
560                    "id": c.id,
561                    "type": "function",
562                    "function": {
563                        "name": c.name,
564                        "arguments": serde_json::to_string(&c.arguments).unwrap_or_else(|_| "{}".into()),
565                    }
566                })
567            })
568            .collect();
569        obj.insert("tool_calls".into(), Value::Array(calls));
570    }
571    Value::Object(obj)
572}
573
574#[derive(Debug, Deserialize)]
575struct ChatResponse {
576    choices: Vec<ChatChoice>,
577    #[serde(default)]
578    usage: Option<ResponseUsage>,
579}
580
581#[derive(Debug, Deserialize)]
582struct ResponseUsage {
583    #[serde(default)]
584    prompt_tokens: Option<u32>,
585    #[serde(default)]
586    completion_tokens: Option<u32>,
587    #[serde(default)]
588    total_tokens: Option<u32>,
589    #[serde(default)]
590    prompt_cache_hit_tokens: Option<u32>,
591    #[serde(default)]
592    prompt_cache_miss_tokens: Option<u32>,
593}
594
595impl ResponseUsage {
596    fn to_token_usage(&self) -> TokenUsage {
597        TokenUsage {
598            prompt_tokens: self.prompt_tokens.unwrap_or(0),
599            completion_tokens: self.completion_tokens.unwrap_or(0),
600            total_tokens: self.total_tokens.unwrap_or(0),
601            cache_hit_tokens: self.prompt_cache_hit_tokens.unwrap_or(0),
602            cache_miss_tokens: self.prompt_cache_miss_tokens.unwrap_or(0),
603        }
604    }
605}
606
607#[derive(Debug, Deserialize)]
608struct ChatChoice {
609    message: ChatChoiceMessage,
610    #[serde(default)]
611    finish_reason: Option<String>,
612}
613
614#[derive(Debug, Deserialize)]
615struct ChatChoiceMessage {
616    #[serde(default)]
617    content: Option<String>,
618    #[serde(default)]
619    tool_calls: Vec<RawToolCall>,
620}
621
622#[derive(Debug, Deserialize, Serialize)]
623struct RawToolCall {
624    id: String,
625    #[serde(default)]
626    function: RawFunction,
627}
628
629#[derive(Debug, Default, Deserialize, Serialize)]
630struct RawFunction {
631    #[serde(default)]
632    name: String,
633    #[serde(default)]
634    arguments: String,
635}
636
637fn parse_completion(choice: ChatChoice, usage: Option<ResponseUsage>) -> Completion {
638    let content = choice.message.content.unwrap_or_default();
639    let tool_calls = choice
640        .message
641        .tool_calls
642        .into_iter()
643        .map(|c| {
644            let args: Value = if c.function.arguments.trim().is_empty() {
645                Value::Object(Default::default())
646            } else {
647                serde_json::from_str(&c.function.arguments)
648                    .unwrap_or_else(|_| Value::String(c.function.arguments.clone()))
649            };
650            ToolCall {
651                id: c.id,
652                name: c.function.name,
653                arguments: args,
654            }
655        })
656        .collect();
657    Completion {
658        content,
659        tool_calls,
660        finish_reason: choice.finish_reason,
661        usage: usage.map(|u| u.to_token_usage()),
662    }
663}
664
665#[cfg(test)]
666mod tests {
667    use super::*;
668
669    #[test]
670    fn parses_plain_text_choice() {
671        let raw = r#"{"choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}"#;
672        let parsed: ChatResponse = serde_json::from_str(raw).unwrap();
673        let c = parse_completion(parsed.choices.into_iter().next().unwrap(), parsed.usage);
674        assert_eq!(c.content, "hi");
675        assert!(c.tool_calls.is_empty());
676        assert_eq!(c.finish_reason.as_deref(), Some("stop"));
677        assert!(c.usage.is_none());
678    }
679
680    #[test]
681    fn parses_tool_call_choice() {
682        let raw = r#"{
683            "choices":[{
684                "message":{
685                    "role":"assistant",
686                    "content":null,
687                    "tool_calls":[{
688                        "id":"call_1",
689                        "type":"function",
690                        "function":{"name":"read_file","arguments":"{\"path\":\"src/lib.rs\"}"}
691                    }]
692                },
693                "finish_reason":"tool_calls"
694            }]
695        }"#;
696        let parsed: ChatResponse = serde_json::from_str(raw).unwrap();
697        let c = parse_completion(parsed.choices.into_iter().next().unwrap(), parsed.usage);
698        assert_eq!(c.tool_calls.len(), 1);
699        assert_eq!(c.tool_calls[0].name, "read_file");
700        assert_eq!(c.tool_calls[0].arguments["path"], "src/lib.rs");
701    }
702
703    #[test]
704    fn parses_usage_from_response() {
705        let raw = r#"{
706            "choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],
707            "usage":{"prompt_tokens":41,"completion_tokens":7,"total_tokens":48}
708        }"#;
709        let parsed: ChatResponse = serde_json::from_str(raw).unwrap();
710        let c = parse_completion(parsed.choices.into_iter().next().unwrap(), parsed.usage);
711        assert!(c.usage.is_some());
712        let u = c.usage.unwrap();
713        assert_eq!(u.prompt_tokens, 41);
714        assert_eq!(u.completion_tokens, 7);
715        assert_eq!(u.total_tokens, 48);
716    }
717
718    #[test]
719    fn parses_missing_usage_as_none() {
720        let raw = r#"{"choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}"#;
721        let parsed: ChatResponse = serde_json::from_str(raw).unwrap();
722        let c = parse_completion(parsed.choices.into_iter().next().unwrap(), parsed.usage);
723        assert!(c.usage.is_none());
724    }
725
726    #[test]
727    fn parses_partial_usage_fills_zeros() {
728        let raw = r#"{
729            "choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],
730            "usage":{"total_tokens":50}
731        }"#;
732        let parsed: ChatResponse = serde_json::from_str(raw).unwrap();
733        let c = parse_completion(parsed.choices.into_iter().next().unwrap(), parsed.usage);
734        assert!(c.usage.is_some());
735        let u = c.usage.unwrap();
736        assert_eq!(u.prompt_tokens, 0);
737        assert_eq!(u.completion_tokens, 0);
738        assert_eq!(u.total_tokens, 50);
739        assert_eq!(u.cache_hit_tokens, 0);
740        assert_eq!(u.cache_miss_tokens, 0);
741    }
742
743    #[test]
744    fn parses_cache_fields_from_deepseek_usage() {
745        let raw = r#"{
746            "choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],
747            "usage":{
748                "prompt_tokens":100,
749                "completion_tokens":50,
750                "total_tokens":150,
751                "prompt_cache_hit_tokens":60,
752                "prompt_cache_miss_tokens":40
753            }
754        }"#;
755        let parsed: ChatResponse = serde_json::from_str(raw).unwrap();
756        let c = parse_completion(parsed.choices.into_iter().next().unwrap(), parsed.usage);
757        assert!(c.usage.is_some());
758        let u = c.usage.unwrap();
759        assert_eq!(u.prompt_tokens, 100);
760        assert_eq!(u.completion_tokens, 50);
761        assert_eq!(u.total_tokens, 150);
762        assert_eq!(u.cache_hit_tokens, 60);
763        assert_eq!(u.cache_miss_tokens, 40);
764    }
765
766    #[test]
767    fn parses_cache_fields_as_zero_when_absent() {
768        let raw = r#"{
769            "choices":[{"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],
770            "usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}
771        }"#;
772        let parsed: ChatResponse = serde_json::from_str(raw).unwrap();
773        let c = parse_completion(parsed.choices.into_iter().next().unwrap(), parsed.usage);
774        assert!(c.usage.is_some());
775        let u = c.usage.unwrap();
776        assert_eq!(u.cache_hit_tokens, 0);
777        assert_eq!(u.cache_miss_tokens, 0);
778    }
779
780    #[test]
781    fn serialises_assistant_with_tool_calls() {
782        let msg = Message::assistant_with_tool_calls(
783            "",
784            vec![ToolCall {
785                id: "abc".into(),
786                name: "write_file".into(),
787                arguments: serde_json::json!({"path":"a","contents":"b"}),
788            }],
789        );
790        let v = serialize_message(&msg);
791        assert_eq!(v["tool_calls"][0]["function"]["name"], "write_file");
792        let args = v["tool_calls"][0]["function"]["arguments"]
793            .as_str()
794            .unwrap();
795        let decoded: Value = serde_json::from_str(args).unwrap();
796        assert_eq!(decoded["contents"], "b");
797    }
798
799    #[test]
800    fn builds_request_without_tools_omits_field() {
801        let req = build_request("m", 0.2, 16384, &[Message::user("hi")], &[]);
802        assert!(req.get("tools").is_none());
803        assert_eq!(req["messages"][0]["role"], "user");
804        assert_eq!(req["max_tokens"], 16384);
805    }
806
807    #[test]
808    fn builds_request_includes_max_tokens() {
809        let req = build_request("m", 0.2, 1024, &[Message::user("hi")], &[]);
810        assert_eq!(req["max_tokens"], 1024);
811    }
812
813    #[tokio::test]
814    async fn error_includes_model_name_on_network_failure() {
815        // Bind a listener on an ephemeral port, then drop it so the port is freed.
816        // The next connect attempt gets ECONNREFUSED (a network error).
817        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
818        let addr = listener.local_addr().unwrap();
819        drop(listener);
820
821        // Small sleep so the OS releases the port.
822        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
823
824        let provider = OpenAiProvider::new(format!("http://{addr}"), "sk-noop", "test-model");
825        let err = provider
826            .complete(&[Message::user("hi")], &[])
827            .await
828            .unwrap_err();
829        let msg = err.to_string();
830        assert!(
831            msg.contains("test-model"),
832            "error should contain model name: {msg}"
833        );
834    }
835
836    #[tokio::test]
837    async fn error_includes_model_name_and_status_on_http_error() {
838        // Spawn a one-shot TCP listener that sends a 400 response.
839        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
840        let addr = listener.local_addr().unwrap();
841
842        // Use a dedicated thread with a blocking server to avoid tokio issues.
843        std::thread::spawn(move || {
844            let (mut stream, _) = listener.accept().unwrap();
845            use std::io::{Read, Write};
846            let mut buf = [0u8; 4096];
847            let _ = stream.read(&mut buf);
848            write!(
849                stream,
850                "HTTP/1.1 400 Bad Request\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}"
851            )
852            .unwrap();
853            stream.flush().unwrap();
854        });
855
856        // Give the server a moment to start
857        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
858
859        let provider = OpenAiProvider::new(format!("http://{addr}"), "sk-noop", "test-model-http");
860        let err = provider
861            .complete(&[Message::user("hi")], &[])
862            .await
863            .unwrap_err();
864        let msg = err.to_string();
865        assert!(
866            msg.contains("test-model-http"),
867            "error should contain model name: {msg}"
868        );
869        assert!(
870            msg.contains("400"),
871            "error should contain HTTP status: {msg}"
872        );
873    }
874
875    #[tokio::test]
876    async fn stream_concatenates_sse_chunks() {
877        // Spawn a one-shot TCP server that serves a canned SSE response
878        // with 3 chunks. Assert the returned Completion's content is the
879        // concatenation of the deltas.
880        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
881        let addr = listener.local_addr().unwrap();
882
883        std::thread::spawn(move || {
884            let (mut stream, _) = listener.accept().unwrap();
885            use std::io::{Read, Write};
886            let mut buf = [0u8; 4096];
887            let _ = stream.read(&mut buf);
888            let body = "\
889data: {\"choices\":[{\"delta\":{\"content\":\"Hello\"},\"finish_reason\":null}]}\n\n\
890data: {\"choices\":[{\"delta\":{\"content\":\" \"},\"finish_reason\":null}]}\n\n\
891data: {\"choices\":[{\"delta\":{\"content\":\"World\"},\"finish_reason\":\"stop\"}]}\n\n\
892data: [DONE]\n\n";
893            write!(
894                stream,
895                "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
896                body.len(),
897                body,
898            )
899            .unwrap();
900            stream.flush().unwrap();
901        });
902
903        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
904
905        let provider =
906            OpenAiProvider::new(format!("http://{addr}"), "sk-noop", "test-stream-model");
907        let completion = provider
908            .stream(&[Message::user("hi")], &[], None)
909            .await
910            .unwrap();
911        assert_eq!(completion.content, "Hello World");
912        assert_eq!(completion.finish_reason.as_deref(), Some("stop"));
913    }
914
915    #[tokio::test]
916    async fn stream_fallback_delegates_to_complete() {
917        // MockProvider doesn't override stream, so it falls back to complete.
918        // Verify the fallback path works by using a MockProvider.
919        use crate::llm::MockProvider;
920        let provider = MockProvider::new(vec![super::Completion {
921            content: "fallback works".to_string(),
922            tool_calls: vec![],
923            finish_reason: Some("stop".to_string()),
924            usage: None,
925        }]);
926        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
927        let completion = provider
928            .stream(&[Message::user("hi")], &[], Some(tx))
929            .await
930            .unwrap();
931        assert_eq!(completion.content, "fallback works");
932        // Should have received the full content as a single delta
933        let delta = rx.recv().await.unwrap();
934        assert_eq!(delta, "fallback works");
935    }
936
937    #[test]
938    fn policy_retries_5xx_with_exponential_backoff() {
939        let policy = RetryPolicy::default(); // max_retries = 2
940                                             // Attempt 0: should return initial_backoff (1s)
941        assert_eq!(
942            policy.backoff_for(0, Some(503), false),
943            Some(Duration::from_secs(1))
944        );
945        // Attempt 1: should return 2s (1s * 2^1)
946        assert_eq!(
947            policy.backoff_for(1, Some(500), false),
948            Some(Duration::from_secs(2))
949        );
950        // Attempt 2: should return None (exceeds max_retries=2)
951        assert_eq!(policy.backoff_for(2, Some(500), false), None);
952    }
953
954    #[test]
955    fn policy_retries_network_errors() {
956        let policy = RetryPolicy::default();
957        // Network error at attempt 0 should return initial_backoff
958        assert_eq!(
959            policy.backoff_for(0, None, true),
960            Some(Duration::from_secs(1))
961        );
962    }
963
964    #[test]
965    fn policy_does_not_retry_4xx() {
966        let policy = RetryPolicy::default();
967        // 4xx errors should not be retried
968        assert_eq!(policy.backoff_for(0, Some(400), false), None);
969        assert_eq!(policy.backoff_for(0, Some(401), false), None);
970        assert_eq!(policy.backoff_for(0, Some(404), false), None);
971        assert_eq!(policy.backoff_for(0, Some(429), false), None);
972    }
973
974    #[test]
975    fn policy_caps_backoff_at_max() {
976        let policy = RetryPolicy {
977            max_retries: 10,
978            initial_backoff: Duration::from_secs(1),
979            max_backoff: Duration::from_secs(3),
980        };
981        // At attempt 5, exponential backoff would be 32s but capped to 3s
982        assert_eq!(
983            policy.backoff_for(5, Some(500), false),
984            Some(Duration::from_secs(3))
985        );
986    }
987
988    #[tokio::test]
989    async fn openai_structured_includes_schema_in_request_body() {
990        // Spawn a mock server that captures the request body and returns
991        // a valid JSON response. Assert the request body contains the
992        // response_format block with the schema.
993        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
994        let addr = listener.local_addr().unwrap();
995        let captured = std::sync::Arc::new(std::sync::Mutex::new(String::new()));
996        let captured_clone = captured.clone();
997
998        std::thread::spawn(move || {
999            let (mut stream, _) = listener.accept().unwrap();
1000            use std::io::{Read, Write};
1001            let mut buf = [0u8; 8192];
1002            let n = stream.read(&mut buf).unwrap();
1003            let request = String::from_utf8_lossy(&buf[..n]).to_string();
1004            // Extract the JSON body (after the blank line)
1005            if let Some(body_start) = request.find("\r\n\r\n") {
1006                let body = request[body_start + 4..].trim().to_string();
1007                *captured_clone.lock().unwrap() = body.clone();
1008            }
1009            let response_body = r#"{"choices":[{"message":{"role":"assistant","content":"{\"answer\":42}"},"finish_reason":"stop"}],"usage":null}"#;
1010            write!(
1011                stream,
1012                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1013                response_body.len(),
1014                response_body,
1015            )
1016            .unwrap();
1017            stream.flush().unwrap();
1018        });
1019
1020        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1021
1022        let provider =
1023            OpenAiProvider::new(format!("http://{addr}"), "sk-noop", "test-structured-model");
1024
1025        let schema = serde_json::json!({
1026            "type": "object",
1027            "properties": {
1028                "answer": {"type": "integer"}
1029            },
1030            "required": ["answer"]
1031        });
1032
1033        let req = StructuredRequest {
1034            messages: vec![Message::user("what is 6 times 7?".to_string())],
1035            schema: schema.clone(),
1036            schema_name: "math_answer".to_string(),
1037        };
1038
1039        let _ = provider.complete_structured(req).await;
1040
1041        // Check the captured request body
1042        let body_str = captured.lock().unwrap().clone();
1043        let body: serde_json::Value = serde_json::from_str(&body_str).unwrap();
1044
1045        // Assert response_format is present with the right shape
1046        let rf = body.get("response_format").unwrap();
1047        assert_eq!(rf["type"], "json_schema");
1048        assert_eq!(rf["json_schema"]["name"], "math_answer");
1049        assert_eq!(rf["json_schema"]["strict"], true);
1050        assert_eq!(rf["json_schema"]["schema"], schema);
1051    }
1052
1053    #[tokio::test]
1054    async fn openai_structured_parses_response_json() {
1055        // Spawn a mock server that returns a known JSON response.
1056        // Assert the parsed value matches.
1057        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1058        let addr = listener.local_addr().unwrap();
1059
1060        std::thread::spawn(move || {
1061            let (mut stream, _) = listener.accept().unwrap();
1062            use std::io::{Read, Write};
1063            let mut buf = [0u8; 8192];
1064            let _ = stream.read(&mut buf);
1065            // Return a JSON object with summary and kept_facts
1066            let response_body = r#"{"choices":[{"message":{"role":"assistant","content":"{\"summary\":\"test\",\"kept_facts\":[\"a\",\"b\"]}"},"finish_reason":"stop"}],"usage":null}"#;
1067            write!(
1068                stream,
1069                "HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1070                response_body.len(),
1071                response_body,
1072            )
1073            .unwrap();
1074            stream.flush().unwrap();
1075        });
1076
1077        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
1078
1079        let provider =
1080            OpenAiProvider::new(format!("http://{addr}"), "sk-noop", "test-structured-model");
1081
1082        let schema = serde_json::json!({
1083            "type": "object",
1084            "properties": {
1085                "summary": {"type": "string"},
1086                "kept_facts": {"type": "array", "items": {"type": "string"}}
1087            },
1088            "required": ["summary", "kept_facts"]
1089        });
1090
1091        let req = StructuredRequest {
1092            messages: vec![Message::user("summarize".to_string())],
1093            schema,
1094            schema_name: "summary".to_string(),
1095        };
1096
1097        let result = provider.complete_structured(req).await;
1098        assert!(result.is_ok(), "got error: {:?}", result.err());
1099        let value = result.unwrap();
1100        assert_eq!(value["summary"], "test");
1101        assert_eq!(value["kept_facts"][0], "a");
1102        assert_eq!(value["kept_facts"][1], "b");
1103    }
1104}