Skip to main content

deepstrike_sdk/providers/
openai.rs

1use async_trait::async_trait;
2use deepstrike_core::context::renderer::InternalRenderedContext;
3use deepstrike_core::types::message::{Content, ContentPart, Role, ToolSchema};
4use futures::{Stream, StreamExt};
5use reqwest::Client;
6use serde_json::{Value, json};
7
8use super::{LLMProvider, RuntimePolicy, StreamEvent};
9use crate::{Error, Result};
10
11/// Cached-prompt-token count from an OpenAI-compatible usage object: the standard
12/// `prompt_tokens_details.cached_tokens` (OpenAI, Qwen, MiniMax, GLM, Kimi) and
13/// DeepSeek's `prompt_cache_hit_tokens`. These caches bill reads only (no
14/// cache-creation count); the figure is a subset of `prompt_tokens`.
15fn openai_cached_prompt_tokens(usage: &Value) -> u32 {
16    let standard = usage["prompt_tokens_details"]["cached_tokens"]
17        .as_u64()
18        .unwrap_or(0);
19    let deepseek = usage["prompt_cache_hit_tokens"].as_u64().unwrap_or(0);
20    standard.max(deepseek) as u32
21}
22
23pub struct OpenAIProvider {
24    client: Client,
25    api_key: String,
26    model: String,
27    base_url: String,
28}
29
30impl OpenAIProvider {
31    pub fn new(api_key: impl Into<String>) -> Self {
32        Self::with_base_url(api_key, "gpt-4o", "https://api.openai.com/v1")
33    }
34
35    pub fn with_base_url(
36        api_key: impl Into<String>,
37        model: impl Into<String>,
38        base_url: impl Into<String>,
39    ) -> Self {
40        Self {
41            client: Client::new(),
42            api_key: api_key.into(),
43            model: model.into(),
44            base_url: base_url.into(),
45        }
46    }
47}
48
49pub fn qwen(api_key: impl Into<String>) -> OpenAIProvider {
50    OpenAIProvider::with_base_url(
51        api_key,
52        "qwen-max",
53        "https://dashscope.aliyuncs.com/compatible-mode/v1",
54    )
55}
56
57pub fn deepseek(api_key: impl Into<String>) -> OpenAIProvider {
58    OpenAIProvider::with_base_url(api_key, "deepseek-chat", "https://api.deepseek.com/v1")
59}
60
61pub fn minimax(api_key: impl Into<String>) -> OpenAIProvider {
62    OpenAIProvider::with_base_url(api_key, "MiniMax-Text-01", "https://api.minimax.chat/v1")
63}
64
65pub fn ollama(model: impl Into<String>) -> OpenAIProvider {
66    OpenAIProvider::with_base_url("", model, "http://localhost:11434/v1")
67}
68
69pub fn kimi(api_key: impl Into<String>) -> OpenAIProvider {
70    OpenAIProvider::with_base_url(api_key, "moonshot-v1-8k", "https://api.moonshot.cn/v1")
71}
72
73/// Map an audio MIME type to OpenAI's `input_audio.format` (accepts "mp3" | "wav").
74/// `audio/mpeg` must become "mp3", not the raw "mpeg" subtype.
75fn openai_audio_format(media_type: &str) -> &str {
76    match media_type.split('/').nth(1).unwrap_or("wav") {
77        "mpeg" | "mp3" => "mp3",
78        "wav" | "wave" | "x-wav" => "wav",
79        other => other,
80    }
81}
82
83fn content_part_to_openai(part: &ContentPart) -> Value {
84    match part {
85        ContentPart::Text { text } => json!({ "type": "text", "text": text }),
86        ContentPart::Image {
87            source: deepstrike_core::types::durable_content::DurableSource::Url { url },
88            detail,
89            ..
90        } => {
91            let image_url = match detail.as_deref() {
92                Some(d) => json!({ "url": url, "detail": d }),
93                None => json!({ "url": url }),
94            };
95            json!({ "type": "image_url", "image_url": image_url })
96        }
97        ContentPart::Image {
98            source: deepstrike_core::types::durable_content::DurableSource::Base64 { data },
99            media_type,
100            detail,
101            ..
102        } => {
103            let mt = media_type.as_deref().unwrap_or("image/png");
104            let url = format!("data:{mt};base64,{data}");
105            let image_url = match detail.as_deref() {
106                Some(d) => json!({ "url": url, "detail": d }),
107                None => json!({ "url": url }),
108            };
109            json!({ "type": "image_url", "image_url": image_url })
110        }
111        ContentPart::Image { .. } => json!({ "type": "text", "text": "" }),
112        ContentPart::Audio {
113            source: deepstrike_core::types::durable_content::DurableSource::Base64 { data },
114            media_type,
115        } => {
116            json!({ "type": "input_audio", "input_audio": { "data": data, "format": openai_audio_format(media_type) } })
117        }
118        ContentPart::Audio { .. } => json!({ "type": "text", "text": "" }),
119        ContentPart::ToolResult { output, .. } => {
120            json!({ "type": "text", "text": output })
121        }
122    }
123}
124
125fn content_to_openai(content: &Content) -> Value {
126    match content {
127        Content::Text(s) => json!(s),
128        Content::Parts(parts) => {
129            let blocks: Vec<Value> = parts.iter().map(content_part_to_openai).collect();
130            json!(blocks)
131        }
132    }
133}
134
135fn context_to_openai(context: &InternalRenderedContext) -> Vec<Value> {
136    let mut messages = Vec::new();
137    if !context.system_text.is_empty() {
138        messages.push(json!({ "role": "system", "content": context.system_text }));
139    }
140    // OpenAI auto-caches by prefix; the volatile State turn is appended as the
141    // latest turn so the history stays a stable cacheable prefix. `state_turn` is
142    // None on un-rebuilt bindings, where the state is still inside `turns`.
143    for message in context.turns.iter().chain(context.state_turn.iter()) {
144        if message.role == Role::Tool {
145            if let Content::Parts(parts) = &message.content {
146                for part in parts {
147                    if let ContentPart::ToolResult {
148                        call_id, output, ..
149                    } = part
150                    {
151                        messages.push(json!({
152                            "role": "tool",
153                            "tool_call_id": call_id.as_str(),
154                            "content": output,
155                        }));
156                    }
157                }
158            }
159            continue;
160        }
161
162        let role = match message.role {
163            Role::System => "system",
164            Role::User => "user",
165            Role::Tool => "tool",
166            Role::Assistant => "assistant",
167        };
168        let mut next = json!({
169            "role": role,
170            "content": content_to_openai(&message.content),
171        });
172        if message.role == Role::Assistant && !message.tool_calls.is_empty() {
173            next["tool_calls"] = json!(
174                message
175                    .tool_calls
176                    .iter()
177                    .map(|tc| json!({
178                        "id": tc.id.as_str(),
179                        "type": "function",
180                        "function": {
181                            "name": tc.name.as_str(),
182                            "arguments": tc.arguments.to_string(),
183                        }
184                    }))
185                    .collect::<Vec<_>>()
186            );
187        }
188        messages.push(next);
189    }
190    messages
191}
192
193#[async_trait]
194impl LLMProvider for OpenAIProvider {
195    fn runtime_policy(&self) -> RuntimePolicy {
196        match self.model.as_str() {
197            // OpenAI
198            "gpt-4o" => RuntimePolicy {
199                max_turns: Some(25),
200                timeout_ms: None,
201            },
202            "gpt-4o-mini" => RuntimePolicy {
203                max_turns: Some(15),
204                timeout_ms: None,
205            },
206            "gpt-4.1" => RuntimePolicy {
207                max_turns: Some(35),
208                timeout_ms: None,
209            },
210            "gpt-4.1-mini" => RuntimePolicy {
211                max_turns: Some(20),
212                timeout_ms: None,
213            },
214            "gpt-4.1-nano" => RuntimePolicy {
215                max_turns: Some(15),
216                timeout_ms: None,
217            },
218            "gpt-5" => RuntimePolicy {
219                max_turns: Some(50),
220                timeout_ms: None,
221            },
222            "gpt-5-mini" => RuntimePolicy {
223                max_turns: Some(25),
224                timeout_ms: None,
225            },
226            "o3" | "o3-mini" | "o4-mini" => RuntimePolicy {
227                max_turns: Some(50),
228                timeout_ms: None,
229            },
230            // DeepSeek
231            "deepseek-chat" | "deepseek-v4-flash" => RuntimePolicy {
232                max_turns: Some(25),
233                timeout_ms: None,
234            },
235            "deepseek-reasoner" | "deepseek-r1" => RuntimePolicy {
236                max_turns: Some(50),
237                timeout_ms: None,
238            },
239            "deepseek-v4-pro" => RuntimePolicy {
240                max_turns: Some(35),
241                timeout_ms: None,
242            },
243            // Qwen
244            "qwen-max" => RuntimePolicy {
245                max_turns: Some(25),
246                timeout_ms: None,
247            },
248            "qwen-plus" => RuntimePolicy {
249                max_turns: Some(20),
250                timeout_ms: None,
251            },
252            "qwq-plus" | "qwq-32b" => RuntimePolicy {
253                max_turns: Some(40),
254                timeout_ms: None,
255            },
256            "qwen3-235b-a22b" => RuntimePolicy {
257                max_turns: Some(35),
258                timeout_ms: None,
259            },
260            "qwen3-72b" => RuntimePolicy {
261                max_turns: Some(25),
262                timeout_ms: None,
263            },
264            "qwen3-32b" | "qwen3-14b" | "qwen3-8b" => RuntimePolicy {
265                max_turns: Some(20),
266                timeout_ms: None,
267            },
268            // Kimi (Moonshot)
269            "moonshot-v1-8k" => RuntimePolicy {
270                max_turns: Some(15),
271                timeout_ms: None,
272            },
273            "moonshot-v1-32k" => RuntimePolicy {
274                max_turns: Some(20),
275                timeout_ms: None,
276            },
277            "moonshot-v1-128k" | "kimi-k2.5" => RuntimePolicy {
278                max_turns: Some(30),
279                timeout_ms: None,
280            },
281            "kimi-k2.6" => RuntimePolicy {
282                max_turns: Some(35),
283                timeout_ms: None,
284            },
285            // MiniMax
286            "MiniMax-M2.7" => RuntimePolicy {
287                max_turns: Some(35),
288                timeout_ms: None,
289            },
290            "MiniMax-M2.5" | "MiniMax-M1" => RuntimePolicy {
291                max_turns: Some(25),
292                timeout_ms: None,
293            },
294            "MiniMax-Text-01" => RuntimePolicy {
295                max_turns: Some(20),
296                timeout_ms: None,
297            },
298            // Ollama prefix matching
299            m if m.starts_with("deepseek-r1") => RuntimePolicy {
300                max_turns: Some(40),
301                timeout_ms: None,
302            },
303            m if m.starts_with("qwq") => RuntimePolicy {
304                max_turns: Some(35),
305                timeout_ms: None,
306            },
307            m if m.starts_with("llama3") => RuntimePolicy {
308                max_turns: Some(20),
309                timeout_ms: None,
310            },
311            m if m.starts_with("mistral") || m.starts_with("gemma") || m.starts_with("phi") => {
312                RuntimePolicy {
313                    max_turns: Some(20),
314                    timeout_ms: None,
315                }
316            }
317            _ => RuntimePolicy {
318                max_turns: Some(20),
319                timeout_ms: None,
320            },
321        }
322    }
323
324    async fn stream(
325        &self,
326        context: &InternalRenderedContext,
327        tools: &[ToolSchema],
328        extensions: Option<&Value>,
329        _state: Option<&super::ProviderRunState>,
330    ) -> Result<Box<dyn Stream<Item = Result<StreamEvent>> + Send + Unpin>> {
331        let mut body = json!({
332            "model": self.model,
333            "messages": context_to_openai(context),
334            "stream": true,
335            "stream_options": { "include_usage": true },
336        });
337        if !tools.is_empty() {
338            body["tools"] = json!(tools.iter().map(|t| json!({
339                "type": "function",
340                "function": { "name": t.name.as_str(), "description": t.description, "parameters": t.parameters }
341            })).collect::<Vec<_>>());
342        }
343        let mut expose_reasoning = false;
344        if let Some(ext) = extensions {
345            if let Some(obj) = ext.as_object() {
346                for (k, v) in obj {
347                    if k == "expose_reasoning" {
348                        expose_reasoning = v.as_bool().unwrap_or(false);
349                    } else {
350                        body[k] = v.clone();
351                    }
352                }
353            }
354        }
355
356        let resp = self
357            .client
358            .post(format!("{}/chat/completions", self.base_url))
359            .header("Authorization", format!("Bearer {}", self.api_key))
360            .header("content-type", "application/json")
361            .body(body.to_string())
362            .send()
363            .await
364            .map_err(|e| Error::from(super::ProviderError::transport("openai", e.to_string())))?;
365
366        if !resp.status().is_success() {
367            let status = resp.status().as_u16();
368            let text = resp.text().await.unwrap_or_default();
369            return Err(super::ProviderError::from_http("openai", status, text).into());
370        }
371
372        let byte_stream = resp.bytes_stream();
373        let stream = parse_openai_sse(byte_stream, expose_reasoning);
374        Ok(Box::new(Box::pin(stream)))
375    }
376}
377
378fn parse_openai_sse(
379    byte_stream: impl Stream<Item = reqwest::Result<bytes::Bytes>> + Send + 'static,
380    expose_reasoning: bool,
381) -> impl Stream<Item = Result<StreamEvent>> + Send {
382    let tool_accum: std::collections::HashMap<usize, (String, String, String)> =
383        std::collections::HashMap::new();
384
385    futures::stream::unfold(
386        // 5th element: the last finish_reason seen — "length" flags an output-cap truncation, which
387        // arrives on a choices frame before the trailing usage frame, so it's carried in state and
388        // attached to the Usage event the runner reads.
389        (
390            Box::pin(byte_stream),
391            String::new(),
392            tool_accum,
393            false,
394            None::<String>,
395        ),
396        move |(mut stream, mut buf, mut tool_accum, mut flushed, mut finish_reason)| async move {
397            if flushed {
398                return None;
399            }
400            loop {
401                if let Some(pos) = buf.find('\n') {
402                    let line = buf[..pos].trim().to_string();
403                    buf = buf[pos + 1..].to_string();
404
405                    if !line.starts_with("data: ") {
406                        continue;
407                    }
408                    let data = &line[6..];
409                    if data == "[DONE]" {
410                        // flush accumulated tool calls
411                        if let Some((_, (id, name, args_buf))) = tool_accum.iter().next() {
412                            let arguments: Value = serde_json::from_str(args_buf)
413                                .unwrap_or(Value::Object(Default::default()));
414                            let evt = StreamEvent::ToolCall {
415                                id: id.clone(),
416                                name: name.clone(),
417                                arguments,
418                            };
419                            flushed = true;
420                            return Some((
421                                Ok(evt),
422                                (stream, buf, tool_accum, flushed, finish_reason),
423                            ));
424                        }
425                        return None;
426                    }
427
428                    let Ok(chunk) = serde_json::from_str::<Value>(data) else {
429                        continue;
430                    };
431                    // Capture finish_reason from choices frames; the usage frame (empty choices)
432                    // leaves it untouched, preserving a "length" seen earlier this turn.
433                    if let Some(fr) = chunk["choices"][0]["finish_reason"].as_str() {
434                        finish_reason = Some(fr.to_string());
435                    }
436                    if let Some(total) = chunk["usage"]["total_tokens"].as_u64() {
437                        let usage = &chunk["usage"];
438                        return Some((
439                            Ok(StreamEvent::Usage {
440                                total_tokens: total as u32,
441                                input_tokens: usage["prompt_tokens"].as_u64().unwrap_or(0) as u32,
442                                output_tokens: usage["completion_tokens"].as_u64().unwrap_or(0)
443                                    as u32,
444                                cache_read_input_tokens: openai_cached_prompt_tokens(usage),
445                                cache_creation_input_tokens: 0,
446                                // I1: OpenAI-family providers auto-cache; no per-slot attribution.
447                                cache_read_input_tokens_by_slot: None,
448                                // finish_reason="length" (captured from an earlier choices frame)
449                                // flags an output-cap truncation and drives the kernel's recovery.
450                                stop_reason: finish_reason.clone(),
451                            }),
452                            (stream, buf, tool_accum, flushed, finish_reason),
453                        ));
454                    }
455                    let delta = &chunk["choices"][0]["delta"];
456                    if expose_reasoning {
457                        if let Some(reasoning) = delta["reasoning_content"].as_str() {
458                            if !reasoning.is_empty() {
459                                return Some((
460                                    Ok(StreamEvent::ThinkingDelta {
461                                        delta: reasoning.to_string(),
462                                    }),
463                                    (stream, buf, tool_accum, flushed, finish_reason),
464                                ));
465                            }
466                        }
467                    }
468                    if let Some(content) = delta["content"].as_str() {
469                        if !content.is_empty() {
470                            return Some((
471                                Ok(StreamEvent::TextDelta {
472                                    delta: content.to_string(),
473                                }),
474                                (stream, buf, tool_accum, flushed, finish_reason),
475                            ));
476                        }
477                    }
478                    if let Some(tcs) = delta["tool_calls"].as_array() {
479                        for tc in tcs {
480                            let idx = tc["index"].as_u64().unwrap_or(0) as usize;
481                            let entry = tool_accum.entry(idx).or_insert_with(|| {
482                                (
483                                    tc["id"].as_str().unwrap_or("").to_string(),
484                                    tc["function"]["name"].as_str().unwrap_or("").to_string(),
485                                    String::new(),
486                                )
487                            });
488                            entry
489                                .2
490                                .push_str(tc["function"]["arguments"].as_str().unwrap_or(""));
491                        }
492                    }
493                    continue;
494                }
495
496                match stream.next().await {
497                    Some(Ok(chunk)) => buf.push_str(&String::from_utf8_lossy(&chunk)),
498                    Some(Err(e)) => {
499                        return Some((
500                            Err(super::ProviderError::transport("openai", e.to_string()).into()),
501                            (stream, buf, tool_accum, flushed, finish_reason),
502                        ));
503                    }
504                    None => return None,
505                }
506            }
507        },
508    )
509}
510
511#[cfg(test)]
512mod tests {
513    use super::*;
514    use compact_str::CompactString;
515    use deepstrike_core::types::message::{ContentPart, CoreMessage, ToolCall};
516
517    #[test]
518    fn context_replays_tool_calls_and_results_natively() {
519        let context = InternalRenderedContext {
520            system_text: "system rules".into(),
521            system_stable: "system rules".into(),
522            system_knowledge: String::new(),
523            budget_overflow: None,
524            turns: vec![
525                CoreMessage::user("What is the weather?"),
526                CoreMessage {
527                    role: Role::Assistant,
528                    content: Content::Text("I'll check.".into()),
529                    tool_calls: vec![ToolCall {
530                        id: CompactString::new("call_1"),
531                        name: CompactString::new("get_weather"),
532                        arguments: json!({ "city": "Shanghai" }),
533                    }],
534                },
535                CoreMessage::tool(vec![ContentPart::ToolResult {
536                    call_id: CompactString::new("call_1"),
537                    output: "sunny".into(),
538                    is_error: false,
539                    durable_content: None,
540                }]),
541            ],
542            state_turn: None,
543            frozen_prefix_len: None,
544        };
545
546        assert_eq!(
547            context_to_openai(&context),
548            vec![
549                json!({ "role": "system", "content": "system rules" }),
550                json!({ "role": "user", "content": "What is the weather?" }),
551                json!({
552                    "role": "assistant",
553                    "content": "I'll check.",
554                    "tool_calls": [{
555                        "id": "call_1",
556                        "type": "function",
557                        "function": {
558                            "name": "get_weather",
559                            "arguments": "{\"city\":\"Shanghai\"}",
560                        }
561                    }],
562                }),
563                json!({ "role": "tool", "tool_call_id": "call_1", "content": "sunny" }),
564            ]
565        );
566    }
567
568    #[test]
569    fn state_turn_appended_as_latest_turn() {
570        let context = InternalRenderedContext {
571            system_text: "sys".into(),
572            system_stable: "sys".into(),
573            system_knowledge: String::new(),
574            turns: vec![CoreMessage::user("history msg")],
575            state_turn: Some(CoreMessage::user("[TASK STATE] goal: g\n\nProceed.")),
576            frozen_prefix_len: None,
577            budget_overflow: None,
578        };
579        let msgs = context_to_openai(&context);
580        // [system][history][state] — history is the stable cacheable prefix, state last.
581        assert_eq!(msgs[0]["role"], "system");
582        assert_eq!(msgs[1]["content"], "history msg");
583        assert_eq!(msgs[2]["role"], "user");
584        assert!(
585            msgs[2]["content"]
586                .as_str()
587                .unwrap()
588                .contains("[TASK STATE]")
589        );
590    }
591}