Skip to main content

graphrt_llm/
openai.rs

1//! OpenAI-compatible chat completions provider.
2//!
3//! Works with any endpoint implementing `POST {base_url}/chat/completions` with
4//! streaming: OpenAI, Azure OpenAI ([`OpenAiConfig::azure`]: its v1 API, the key
5//! in the `api-key` header), Ollama, vLLM, LM Studio, Groq, OpenRouter, DeepSeek,
6//! Together, Mistral and others.
7
8use std::collections::HashMap;
9use std::fmt;
10use std::sync::Arc;
11use std::time::Duration;
12
13use futures::future::BoxFuture;
14use graphrt_core::event::Usage;
15use serde_json::{Map, Value as Json, json};
16
17use crate::credentials::{Credential, CredentialSource};
18use crate::error::LlmError;
19use crate::http::{Decoded, SseDecoder, send_sse, truncated};
20use crate::sse::SseEvent;
21use crate::types::{
22    ChatDelta, ChatModel, ChatRequest, ChatStream, ContentPart, FinishReason, Message, ResponseFormat, Role,
23    ToolChoice, check_extra, tool_images_intro, tool_text_with_image_note,
24};
25
26/// How the API key is sent.
27#[derive(Clone, Debug, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum AuthStyle {
30    /// `Authorization: Bearer <key>`.
31    Bearer,
32    /// A custom header, e.g. `api-key` for Azure OpenAI.
33    Header(String),
34}
35
36/// Configuration of an OpenAI-compatible endpoint.
37#[derive(Clone)]
38pub struct OpenAiConfig {
39    /// Base URL without the `/chat/completions` suffix, e.g. `https://api.openai.com/v1`.
40    pub base_url: String,
41    pub api_key: Option<String>,
42    pub auth: AuthStyle,
43    /// Extra headers sent with every request.
44    pub headers: Vec<(String, String)>,
45    /// Extra query parameters (e.g. `api-version`).
46    pub query: Vec<(String, String)>,
47    /// Ask for a final usage chunk (`stream_options.include_usage`). Disable for
48    /// endpoints that reject the field.
49    pub include_usage: bool,
50    /// Send `max_completion_tokens` instead of `max_tokens` (required by some newer models).
51    pub use_max_completion_tokens: bool,
52    pub connect_timeout: Duration,
53    /// Per-request credential source. When set it replaces `api_key`; its headers are
54    /// appended and its `base_url`, if any, overrides `base_url`. A 401/403 response
55    /// invalidates the credential and the request is retried once.
56    pub credentials: Option<Arc<dyn CredentialSource>>,
57    /// Provider name passed to the credential source (default `openai`).
58    pub credential_name: String,
59}
60
61impl fmt::Debug for OpenAiConfig {
62    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
63        f.debug_struct("OpenAiConfig")
64            .field("base_url", &self.base_url)
65            .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
66            .field("auth", &self.auth)
67            .field("headers", &self.headers.iter().map(|(k, _)| k).collect::<Vec<_>>())
68            .field("include_usage", &self.include_usage)
69            .field("credentials", &self.credentials.as_ref().map(|_| "<source>"))
70            .field("credential_name", &self.credential_name)
71            .finish_non_exhaustive()
72    }
73}
74
75impl Default for OpenAiConfig {
76    fn default() -> Self {
77        Self {
78            base_url: "https://api.openai.com/v1".to_owned(),
79            api_key: None,
80            auth: AuthStyle::Bearer,
81            headers: Vec::new(),
82            query: Vec::new(),
83            include_usage: true,
84            use_max_completion_tokens: false,
85            connect_timeout: Duration::from_secs(10),
86            credentials: None,
87            credential_name: "openai".to_owned(),
88        }
89    }
90}
91
92impl OpenAiConfig {
93    pub fn new(base_url: impl Into<String>, api_key: Option<String>) -> Self {
94        Self { base_url: base_url.into(), api_key, ..Self::default() }
95    }
96
97    /// Ask `source` for a credential before every request (see [`crate::credentials`]).
98    pub fn with_credentials(mut self, source: Arc<dyn CredentialSource>) -> Self {
99        self.credentials = Some(source);
100        self
101    }
102
103    /// Provider name passed to the credential source.
104    pub fn credential_name(mut self, name: impl Into<String>) -> Self {
105        self.credential_name = name.into();
106        self
107    }
108}
109
110/// The provider name of DeepSeek in a registry built from the environment
111/// ([`crate::ModelRegistry::from_vars`], `DEEPSEEK_API_KEY`).
112pub const DEEPSEEK_PROVIDER: &str = "deepseek";
113
114/// DeepSeek's OpenAI-compatible endpoint, used when `DEEPSEEK_BASE_URL` is not set.
115pub const DEEPSEEK_BASE_URL: &str = "https://api.deepseek.com/v1";
116
117/// The provider name of Azure OpenAI in a registry built from the environment
118/// ([`crate::ModelRegistry::from_vars`]).
119pub const AZURE_OPENAI_PROVIDER: &str = "azure-openai";
120
121/// The path of Azure OpenAI's v1 API under a resource endpoint.
122pub const AZURE_OPENAI_V1_PATH: &str = "/openai/v1";
123
124/// The v1 API root of an Azure OpenAI resource, `https://<resource>.openai.azure.com/openai/v1`,
125/// from its endpoint as the Azure portal shows it (`https://<resource>.openai.azure.com/`, a
126/// `cognitiveservices.azure.com` or `services.ai.azure.com` host, or any URL on the resource:
127/// only the scheme and host are kept). Plain `http` is accepted only for `localhost`, since the
128/// key travels in a header.
129///
130/// # Errors
131/// [`LlmError::Config`] when `endpoint` is not an `https` URL with a host.
132pub fn azure_openai_v1_base_url(endpoint: &str) -> Result<String, LlmError> {
133    let endpoint = endpoint.trim();
134    let invalid = |why: &str| LlmError::Config(format!("Azure OpenAI endpoint `{endpoint}` {why}"));
135    let (scheme, rest) = endpoint.split_once("://").ok_or_else(|| invalid("is not a URL"))?;
136    let scheme = scheme.to_ascii_lowercase();
137    let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
138    if authority.is_empty() || authority.contains('@') || authority.chars().any(char::is_whitespace) {
139        return Err(invalid("has no valid host"));
140    }
141    let host = authority.rsplit_once(':').map_or(authority, |(host, _port)| host);
142    let local = matches!(host, "localhost" | "127.0.0.1" | "[::1]");
143    match scheme.as_str() {
144        "https" => {}
145        "http" if local => {}
146        _ => return Err(invalid("must start with https://")),
147    }
148    Ok(format!("{scheme}://{}{AZURE_OPENAI_V1_PATH}", authority.to_ascii_lowercase()))
149}
150
151impl OpenAiConfig {
152    /// Azure OpenAI through its v1 API: one provider for every deployment of the resource
153    /// (the model name of a request is the deployment name), the key in the `api-key`
154    /// header and `max_completion_tokens` (which reasoning deployments require). The v1 API
155    /// takes no `api-version`; push one onto `query` only for preview features (`preview`).
156    ///
157    /// # Errors
158    /// [`LlmError::Config`] for an endpoint [`azure_openai_v1_base_url`] refuses.
159    pub fn azure(endpoint: &str, api_key: impl Into<String>) -> Result<Self, LlmError> {
160        Ok(Self {
161            base_url: azure_openai_v1_base_url(endpoint)?,
162            api_key: Some(api_key.into()),
163            auth: AuthStyle::Header("api-key".to_owned()),
164            use_max_completion_tokens: true,
165            credential_name: AZURE_OPENAI_PROVIDER.to_owned(),
166            ..Self::default()
167        })
168    }
169}
170
171/// An OpenAI-compatible chat model endpoint.
172#[derive(Clone)]
173pub struct OpenAiModel {
174    config: OpenAiConfig,
175    client: crate::http::LazyClient,
176}
177
178impl fmt::Debug for OpenAiModel {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        f.debug_struct("OpenAiModel").field("config", &self.config).finish_non_exhaustive()
181    }
182}
183
184impl OpenAiModel {
185    pub fn new(config: OpenAiConfig) -> Result<Self, LlmError> {
186        let client = crate::http::LazyClient::new(config.connect_timeout);
187        Ok(Self { config, client })
188    }
189
190    fn endpoint(&self, base_url: &str, with_query: bool) -> String {
191        let mut url = format!("{}/chat/completions", base_url.trim_end_matches('/'));
192        let query: &[(String, String)] = if with_query { &self.config.query } else { &[] };
193        for (i, (k, v)) in query.iter().enumerate() {
194            url.push(if i == 0 { '?' } else { '&' });
195            url.push_str(&percent_encode(k));
196            url.push('=');
197            url.push_str(&percent_encode(v));
198        }
199        url
200    }
201}
202
203/// Percent-encode a query component (RFC 3986 unreserved characters pass through).
204fn percent_encode(s: &str) -> String {
205    let mut out = String::with_capacity(s.len());
206    for b in s.bytes() {
207        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
208            out.push(char::from(b));
209        } else {
210            out.push_str(&format!("%{b:02X}"));
211        }
212    }
213    out
214}
215
216impl OpenAiModel {
217    fn request(&self, body: &Json, credential: Option<&Credential>) -> Result<reqwest::RequestBuilder, LlmError> {
218        let endpoint =
219            crate::http::resolve_endpoint(&self.config.base_url, credential.and_then(|c| c.base_url.as_deref()))?;
220        let mut builder = self.client.get()?.post(self.endpoint(&endpoint.base_url, endpoint.send_static)).json(body);
221        let key = credential.map(|c| c.secret.as_str()).or(self.config.api_key.as_deref());
222        if let Some(key) = key {
223            builder = match &self.config.auth {
224                AuthStyle::Bearer => builder.bearer_auth(key),
225                AuthStyle::Header(name) => builder.header(name.as_str(), key),
226            };
227        }
228        // Operator headers (gateway keys, org ids) never follow a credential override
229        // to another origin.
230        if endpoint.send_static {
231            for (k, v) in &self.config.headers {
232                builder = builder.header(k.as_str(), v.as_str());
233            }
234        }
235        if let Some(credential) = credential {
236            for (k, v) in &credential.headers {
237                builder = builder.header(k.as_str(), v.as_str());
238            }
239        }
240        Ok(builder)
241    }
242}
243
244impl ChatModel for OpenAiModel {
245    fn chat(&self, request: ChatRequest) -> BoxFuture<'_, Result<ChatStream, LlmError>> {
246        Box::pin(async move {
247            let body = build_body(&request, &self.config)?;
248            let name = self.config.credential_name.as_str();
249            let mut retried = false;
250            loop {
251                let credential = match &self.config.credentials {
252                    Some(source) => Some(source.credential(name).await?),
253                    None => None,
254                };
255                let result = send_sse(self.request(&body, credential.as_ref())?, OpenAiDecoder::default()).await;
256                match (result, &self.config.credentials) {
257                    // The credential was rejected: drop it and retry once with a fresh one.
258                    (Err(LlmError::Auth(_)), Some(source)) if !retried => {
259                        source.invalidate(name);
260                        retried = true;
261                    }
262                    (result, _) => return result,
263                }
264            }
265        })
266    }
267}
268
269fn content_json(parts: &[ContentPart]) -> Json {
270    if let [ContentPart::Text { text }] = parts {
271        return Json::String(text.clone());
272    }
273    let items: Vec<Json> = parts
274        .iter()
275        .map(|p| match p {
276            ContentPart::Text { text } => json!({"type": "text", "text": text}),
277            ContentPart::Image { url, detail } => {
278                let mut image = Map::new();
279                image.insert("url".into(), Json::String(url.clone()));
280                if let Some(d) = detail {
281                    image.insert("detail".into(), Json::String(d.clone()));
282                }
283                json!({"type": "image_url", "image_url": image})
284            }
285        })
286        .collect();
287    Json::Array(items)
288}
289
290fn message_json(m: &Message) -> Result<Json, LlmError> {
291    Ok(match m.role {
292        Role::System => json!({"role": "system", "content": content_json(&m.content)}),
293        Role::User => json!({"role": "user", "content": content_json(&m.content)}),
294        Role::Tool => {
295            let id = m
296                .tool_call_id
297                .as_deref()
298                .filter(|id| !id.is_empty())
299                .ok_or_else(|| LlmError::Config("tool message without tool_call_id".into()))?;
300            json!({"role": "tool", "tool_call_id": id, "content": tool_text_with_image_note(m)})
301        }
302        Role::Assistant => {
303            let mut obj = Map::new();
304            obj.insert("role".into(), json!("assistant"));
305            let text = m.text();
306            obj.insert("content".into(), if text.is_empty() { Json::Null } else { Json::String(text) });
307            if !m.tool_calls.is_empty() {
308                let calls: Vec<Json> = m
309                    .tool_calls
310                    .iter()
311                    .map(|c| json!({"id": c.id, "type": "function", "function": {"name": c.name, "arguments": c.arguments}}))
312                    .collect();
313                obj.insert("tool_calls".into(), Json::Array(calls));
314            }
315            Json::Object(obj)
316        }
317    })
318}
319
320/// Encode the conversation. Tool messages are text-only in chat completions,
321/// so images from tool results go in one user message after the run of tool
322/// messages they belong to.
323fn messages_json(messages: &[Message]) -> Result<Vec<Json>, LlmError> {
324    let mut out = Vec::with_capacity(messages.len());
325    let mut call_names: HashMap<&str, &str> = HashMap::new();
326    let mut deferred: Vec<Json> = Vec::new();
327    for m in messages {
328        if m.role != Role::Tool && !deferred.is_empty() {
329            out.push(json!({"role": "user", "content": std::mem::take(&mut deferred)}));
330        }
331        for c in &m.tool_calls {
332            call_names.insert(c.id.as_str(), c.name.as_str());
333        }
334        out.push(message_json(m)?);
335        if m.role == Role::Tool && m.images().next().is_some() {
336            let id = m.tool_call_id.as_deref().unwrap_or_default();
337            let intro = tool_images_intro(call_names.get(id).copied(), id);
338            deferred.push(json!({"type": "text", "text": intro}));
339            let images: Vec<ContentPart> = m.images().cloned().collect();
340            if let Json::Array(parts) = content_json(&images) {
341                deferred.extend(parts);
342            }
343        }
344    }
345    if !deferred.is_empty() {
346        out.push(json!({"role": "user", "content": deferred}));
347    }
348    Ok(out)
349}
350
351/// Build the JSON request body.
352pub(crate) fn build_body(req: &ChatRequest, config: &OpenAiConfig) -> Result<Json, LlmError> {
353    check_extra(req)?;
354    // Only the first choice is decoded; asking for more would silently discard them.
355    if let Some(n) = req.extra.get("n")
356        && n.as_u64() != Some(1)
357    {
358        return Err(LlmError::Config(format!("`n` must be 1 (got {n}); only one choice is supported")));
359    }
360    let mut body = Map::new();
361    body.insert("model".into(), json!(req.model));
362    body.insert("messages".into(), Json::Array(messages_json(&req.messages)?));
363    body.insert("stream".into(), json!(true));
364    if config.include_usage {
365        body.insert("stream_options".into(), json!({"include_usage": true}));
366    }
367    if !req.tools.is_empty() {
368        let tools: Vec<Json> = req
369            .tools
370            .iter()
371            .map(|t| json!({"type": "function", "function": {"name": t.name, "description": t.description, "parameters": t.parameters}}))
372            .collect();
373        body.insert("tools".into(), Json::Array(tools));
374    }
375    if let Some(choice) = &req.tool_choice {
376        let v = match choice {
377            ToolChoice::Auto => json!("auto"),
378            ToolChoice::None => json!("none"),
379            ToolChoice::Required => json!("required"),
380            ToolChoice::Tool(name) => json!({"type": "function", "function": {"name": name}}),
381        };
382        body.insert("tool_choice".into(), v);
383    }
384    if let Some(t) = req.temperature {
385        body.insert("temperature".into(), json!(t));
386    }
387    if let Some(p) = req.top_p {
388        body.insert("top_p".into(), json!(p));
389    }
390    if let Some(max) = req.output_limit() {
391        let key = if config.use_max_completion_tokens { "max_completion_tokens" } else { "max_tokens" };
392        body.insert(key.into(), json!(max));
393    }
394    if !req.stop.is_empty() {
395        body.insert("stop".into(), json!(req.stop));
396    }
397    match &req.response_format {
398        None | Some(ResponseFormat::Text) => {}
399        Some(ResponseFormat::JsonObject) => {
400            body.insert("response_format".into(), json!({"type": "json_object"}));
401        }
402        Some(ResponseFormat::JsonSchema { name, schema, strict }) => {
403            body.insert(
404                "response_format".into(),
405                json!({"type": "json_schema", "json_schema": {"name": name, "schema": schema, "strict": strict}}),
406            );
407        }
408    }
409    for (k, v) in &req.extra {
410        body.insert(k.clone(), v.clone());
411    }
412    Ok(Json::Object(body))
413}
414
415/// Decodes `chat.completion.chunk` events.
416///
417/// Tool-call fragments are keyed by their `index`. Some compatible servers omit
418/// `index`; then a fragment with a new `id` starts a new call and a fragment
419/// without `id` continues the most recent one.
420#[derive(Debug, Default)]
421pub(crate) struct OpenAiDecoder {
422    /// Call index assigned to each call id seen so far.
423    ids: HashMap<String, usize>,
424    /// Index of the most recent call fragment.
425    last: Option<usize>,
426    /// Smallest index not used yet.
427    next: usize,
428    /// A `finish_reason` was received (some servers end without `[DONE]`).
429    saw_finish: bool,
430}
431
432impl OpenAiDecoder {
433    fn call_index(&mut self, explicit: Option<usize>, id: Option<&str>) -> usize {
434        let index = match (explicit, id) {
435            (Some(i), _) => i,
436            (None, Some(id)) => match self.ids.get(id) {
437                Some(&i) => i,
438                None => self.next,
439            },
440            (None, None) => self.last.unwrap_or(self.next),
441        };
442        if let Some(id) = id {
443            self.ids.entry(id.to_owned()).or_insert(index);
444        }
445        self.last = Some(index);
446        self.next = self.next.max(index.saturating_add(1));
447        index
448    }
449}
450
451/// Classify an error object embedded in the stream.
452fn stream_error(err: &Json) -> LlmError {
453    let message = err.get("message").and_then(Json::as_str).map(str::to_owned).unwrap_or_else(|| err.to_string());
454    let kind = err.get("type").and_then(Json::as_str).unwrap_or_default();
455    let code = match err.get("code") {
456        Some(Json::String(c)) => c.clone(),
457        Some(Json::Number(n)) => n.to_string(),
458        _ => String::new(),
459    };
460    let tag = format!("{kind} {code}").to_ascii_lowercase();
461    if tag.contains("rate_limit") || code == "429" {
462        LlmError::RateLimit { message, retry_after_ms: None }
463    } else if tag.contains("context_length") {
464        LlmError::ContextLength(message)
465    } else if tag.contains("auth") || tag.contains("permission") || code == "401" || code == "403" {
466        LlmError::Auth(message)
467    } else if tag.contains("invalid_request") || code == "400" {
468        LlmError::BadRequest(message)
469    } else {
470        LlmError::Server { status: 0, message }
471    }
472}
473
474fn as_u64(v: Option<&Json>) -> u64 {
475    v.and_then(Json::as_u64).unwrap_or(0)
476}
477
478fn finish_reason(s: &str) -> FinishReason {
479    match s {
480        "stop" => FinishReason::Stop,
481        "length" => FinishReason::Length,
482        "tool_calls" | "function_call" => FinishReason::ToolCalls,
483        "content_filter" => FinishReason::ContentFilter,
484        other => FinishReason::Other(other.to_owned()),
485    }
486}
487
488impl SseDecoder for OpenAiDecoder {
489    fn decode(&mut self, event: SseEvent) -> Result<Decoded, LlmError> {
490        let data = event.data.trim();
491        if data == "[DONE]" {
492            if !self.saw_finish {
493                return Err(truncated());
494            }
495            return Ok(Decoded::done(Vec::new()));
496        }
497        if data.is_empty() {
498            return Ok(Decoded::default());
499        }
500        let chunk: Json = serde_json::from_str(data).map_err(|e| LlmError::Decode(format!("{e}: {data}")))?;
501        if let Some(err) = chunk.get("error").filter(|e| !e.is_null()) {
502            return Err(stream_error(err));
503        }
504        let mut deltas = Vec::new();
505        if let Some(choice) = chunk.get("choices").and_then(Json::as_array).and_then(|c| c.first()) {
506            if let Some(delta) = choice.get("delta") {
507                // Reasoning is exposed as `reasoning_content` (DeepSeek, vLLM) or `reasoning`
508                // (OpenRouter, Ollama). Some servers send both with the same text: use the first.
509                let reasoning = ["reasoning_content", "reasoning"]
510                    .iter()
511                    .find_map(|key| delta.get(*key).and_then(Json::as_str).filter(|s| !s.is_empty()));
512                if let Some(r) = reasoning {
513                    deltas.push(ChatDelta::Reasoning(r.to_owned()));
514                }
515                if let Some(text) = delta.get("content").and_then(Json::as_str).filter(|s| !s.is_empty()) {
516                    deltas.push(ChatDelta::Text(text.to_owned()));
517                }
518                if let Some(calls) = delta.get("tool_calls").and_then(Json::as_array) {
519                    for call in calls {
520                        let explicit = call.get("index").and_then(Json::as_u64).and_then(|i| usize::try_from(i).ok());
521                        let id = call.get("id").and_then(Json::as_str).filter(|s| !s.is_empty());
522                        let index = self.call_index(explicit, id);
523                        let function = call.get("function");
524                        let arguments = match function.and_then(|f| f.get("arguments")) {
525                            None | Some(Json::Null) => String::new(),
526                            Some(Json::String(s)) => s.clone(),
527                            // Some servers send the arguments as a JSON object instead of a string.
528                            Some(other) => other.to_string(),
529                        };
530                        deltas.push(ChatDelta::ToolCall {
531                            index,
532                            id: id.map(str::to_owned),
533                            name: function.and_then(|f| f.get("name")).and_then(Json::as_str).map(str::to_owned),
534                            arguments,
535                        });
536                    }
537                }
538            }
539            if let Some(reason) = choice.get("finish_reason").and_then(Json::as_str) {
540                self.saw_finish = true;
541                deltas.push(ChatDelta::Finish(finish_reason(reason)));
542            }
543        }
544        if let Some(usage) = chunk.get("usage").filter(|u| u.is_object()) {
545            deltas.push(ChatDelta::Usage(Usage {
546                prompt_tokens: as_u64(usage.get("prompt_tokens")),
547                completion_tokens: as_u64(usage.get("completion_tokens")),
548                total_tokens: as_u64(usage.get("total_tokens")),
549            }));
550        }
551        Ok(Decoded::deltas(deltas))
552    }
553
554    /// Servers that omit `[DONE]` are accepted once a `finish_reason` arrived.
555    fn end_of_stream(&mut self) -> Result<Vec<ChatDelta>, LlmError> {
556        if self.saw_finish { Ok(Vec::new()) } else { Err(truncated()) }
557    }
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563    use crate::sse::SseParser;
564    use crate::types::ToolCall;
565    use graphrt_core::tool::ToolSpec;
566
567    #[test]
568    fn body_shape() {
569        let mut assistant = Message::assistant("");
570        assistant.tool_calls = vec![ToolCall { id: "c1".into(), name: "search".into(), arguments: "{}".into() }];
571        let mut req = ChatRequest::new(
572            "gpt-4o-mini",
573            vec![
574                Message::system("sys"),
575                Message {
576                    role: Role::User,
577                    content: vec![
578                        ContentPart::Text { text: "look".into() },
579                        ContentPart::Image { url: "https://x/y.png".into(), detail: Some("high".into()) },
580                    ],
581                    tool_calls: vec![],
582                    tool_call_id: None,
583                    provider_state: None,
584                },
585                assistant,
586                Message::tool("c1", "result"),
587            ],
588        );
589        req.tools = vec![ToolSpec {
590            name: "search".into(),
591            description: "d".into(),
592            parameters: json!({"type": "object"}),
593            effects: Vec::new(),
594        }];
595        req.tool_choice = Some(ToolChoice::Tool("search".into()));
596        req.max_tokens = Some(10);
597        req.response_format =
598            Some(ResponseFormat::JsonSchema { name: "out".into(), schema: json!({"type": "object"}), strict: true });
599        req.extra.insert("seed".into(), json!(7));
600        let body = build_body(&req, &OpenAiConfig::default()).unwrap();
601        assert_eq!(body["stream"], true);
602        assert_eq!(body["stream_options"]["include_usage"], true);
603        assert_eq!(body["messages"][0]["content"], "sys");
604        assert_eq!(body["messages"][1]["content"][1]["image_url"]["detail"], "high");
605        assert_eq!(body["messages"][2]["content"], Json::Null);
606        assert_eq!(body["messages"][2]["tool_calls"][0]["function"]["name"], "search");
607        assert_eq!(body["messages"][3]["tool_call_id"], "c1");
608        assert_eq!(body["tools"][0]["function"]["parameters"]["type"], "object");
609        assert_eq!(body["tool_choice"]["function"]["name"], "search");
610        assert_eq!(body["max_tokens"], 10);
611        assert_eq!(body["response_format"]["json_schema"]["strict"], true);
612        assert_eq!(body["seed"], 7);
613
614        let cfg = OpenAiConfig { use_max_completion_tokens: true, include_usage: false, ..OpenAiConfig::default() };
615        let body = build_body(&req, &cfg).unwrap();
616        assert_eq!(body["max_completion_tokens"], 10);
617        assert!(body.get("stream_options").is_none());
618    }
619
620    fn two_tool_calls() -> Message {
621        let mut assistant = Message::assistant("");
622        assistant.tool_calls = vec![
623            ToolCall { id: "c1".into(), name: "screenshot".into(), arguments: "{}".into() },
624            ToolCall { id: "c2".into(), name: "clock".into(), arguments: "{}".into() },
625        ];
626        assistant
627    }
628
629    #[test]
630    fn tool_images_follow_the_tool_messages_in_a_user_message() {
631        let req = ChatRequest::new(
632            "gpt-4o",
633            vec![
634                Message::user("what is on screen?"),
635                two_tool_calls(),
636                Message::tool_with_images("c1", "1280x800", ["data:image/png;base64,AAAA".to_owned()]),
637                Message::tool("c2", "noon"),
638                Message::user("thanks"),
639            ],
640        );
641        let body = build_body(&req, &OpenAiConfig::default()).unwrap();
642        assert_eq!(
643            body["messages"],
644            json!([
645                {"role": "user", "content": "what is on screen?"},
646                {"role": "assistant", "content": null, "tool_calls": [
647                    {"id": "c1", "type": "function", "function": {"name": "screenshot", "arguments": "{}"}},
648                    {"id": "c2", "type": "function", "function": {"name": "clock", "arguments": "{}"}}
649                ]},
650                {"role": "tool", "tool_call_id": "c1", "content": "1280x800\n[1 image attached after the tool results]"},
651                {"role": "tool", "tool_call_id": "c2", "content": "noon"},
652                {"role": "user", "content": [
653                    {"type": "text", "text": "Images returned by tool `screenshot` (call c1):"},
654                    {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}
655                ]},
656                {"role": "user", "content": "thanks"}
657            ])
658        );
659    }
660
661    #[test]
662    fn tool_images_at_the_end_of_the_history_are_flushed() {
663        let req = ChatRequest::new(
664            "gpt-4o",
665            vec![
666                Message::user("q"),
667                two_tool_calls(),
668                Message::tool_with_images("c1", "", ["https://x/a.png".to_owned()]),
669                Message::tool_with_images("c2", "b", ["https://x/b.png".to_owned()]),
670            ],
671        );
672        let body = build_body(&req, &OpenAiConfig::default()).unwrap();
673        let messages = body["messages"].as_array().unwrap();
674        assert_eq!(messages.len(), 5);
675        assert_eq!(messages[2]["content"], "[1 image attached after the tool results]");
676        let images = &messages[4];
677        assert_eq!(images["role"], "user");
678        assert_eq!(images["content"][2]["text"], "Images returned by tool `clock` (call c2):");
679        assert_eq!(images["content"][3]["image_url"]["url"], "https://x/b.png");
680    }
681
682    #[test]
683    fn body_rejects_reserved_extra_n_and_missing_tool_id() {
684        let req = ChatRequest::new("m", vec![Message::user("x")]).with_extra("stream", json!(false));
685        assert!(matches!(build_body(&req, &OpenAiConfig::default()), Err(LlmError::Config(_))));
686        let req = ChatRequest::new("m", vec![Message::user("x")]).with_extra("n", json!(2));
687        assert!(matches!(build_body(&req, &OpenAiConfig::default()), Err(LlmError::Config(_))));
688        let mut tool = Message::tool("x", "r");
689        tool.tool_call_id = None;
690        let req = ChatRequest::new("m", vec![tool]);
691        assert!(matches!(build_body(&req, &OpenAiConfig::default()), Err(LlmError::Config(_))));
692    }
693
694    fn decode_all(fixture: &str) -> (Vec<ChatDelta>, Result<bool, LlmError>) {
695        let mut parser = SseParser::new();
696        let mut decoder = OpenAiDecoder::default();
697        let mut deltas = Vec::new();
698        for ev in parser.push(fixture.as_bytes()).unwrap() {
699            match decoder.decode(ev) {
700                Ok(d) => {
701                    deltas.extend(d.deltas);
702                    if d.done {
703                        return (deltas, Ok(true));
704                    }
705                }
706                Err(e) => return (deltas, Err(e)),
707            }
708        }
709        match decoder.end_of_stream() {
710            Ok(d) => {
711                deltas.extend(d);
712                (deltas, Ok(false))
713            }
714            Err(e) => (deltas, Err(e)),
715        }
716    }
717
718    #[test]
719    fn truncated_stream_is_a_retryable_error() {
720        let (_, end) = decode_all("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hel\"}}]}\n\n");
721        let err = end.unwrap_err();
722        assert!(matches!(err, LlmError::Network(_)));
723        assert!(err.is_retryable());
724        // `[DONE]` without any finish_reason is also incomplete.
725        let (_, end) =
726            decode_all("data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"x\"}}]}\n\ndata: [DONE]\n\n");
727        assert!(end.is_err());
728        // A finish_reason without `[DONE]` is accepted.
729        let (deltas, end) = decode_all(
730            "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"x\"},\"finish_reason\":\"stop\"}]}\n\n",
731        );
732        assert!(!end.unwrap());
733        assert_eq!(deltas.last(), Some(&ChatDelta::Finish(FinishReason::Stop)));
734    }
735
736    #[tokio::test]
737    async fn tool_calls_without_index_and_object_arguments() {
738        let fixture = concat!(
739            "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"id\":\"a\",\"function\":{\"name\":\"one\",\"arguments\":{\"x\":1}}}]}}]}\n\n",
740            "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"id\":\"b\",\"function\":{\"name\":\"two\",\"arguments\":\"{\\\"y\\\":\"}}]}}]}\n\n",
741            "data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"function\":{\"arguments\":\"2}\"}}]}}]}\n\n",
742            "data: {\"choices\":[{\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
743            "data: [DONE]\n\n",
744        );
745        let (deltas, end) = decode_all(fixture);
746        assert!(end.unwrap());
747        let r =
748            crate::types::collect(Box::pin(futures::stream::iter(deltas.into_iter().map(Ok))), |_| {}).await.unwrap();
749        assert_eq!(r.tool_calls.len(), 2, "{:?}", r.tool_calls);
750        assert_eq!(r.tool_calls[0].arguments_json().unwrap()["x"], 1);
751        assert_eq!(r.tool_calls[1].name, "two");
752        assert_eq!(r.tool_calls[1].arguments_json().unwrap()["y"], 2);
753    }
754
755    #[test]
756    fn duplicate_reasoning_fields_are_not_doubled() {
757        let (deltas, _) = decode_all(
758            "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"r\",\"reasoning\":\"r\"},\"finish_reason\":\"stop\"}]}\n\n",
759        );
760        assert_eq!(deltas.iter().filter(|d| matches!(d, ChatDelta::Reasoning(_))).count(), 1);
761    }
762
763    #[test]
764    fn decode_recorded_stream() {
765        let fixture = concat!(
766            "data: {\"choices\":[{\"index\":0,\"delta\":{\"role\":\"assistant\",\"reasoning_content\":\"think\"}}]}\n\n",
767            "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hel\"}}]}\n\n",
768            "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"lo\"}}]}\n\n",
769            "data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"call_1\",\"type\":\"function\",\"function\":{\"name\":\"get\",\"arguments\":\"\"}}]}}]}\n\n",
770            "data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\"{\\\"a\\\":1}\"}}]}}]}\n\n",
771            "data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n",
772            "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":5,\"completion_tokens\":2,\"total_tokens\":7}}\n\n",
773            "data: [DONE]\n\n",
774        );
775        let (deltas, done) = decode_all(fixture);
776        assert!(done.unwrap());
777        assert_eq!(deltas[0], ChatDelta::Reasoning("think".into()));
778        assert_eq!(deltas[1], ChatDelta::Text("Hel".into()));
779        assert!(matches!(&deltas[3], ChatDelta::ToolCall { index: 0, name: Some(n), .. } if n == "get"));
780        assert!(matches!(&deltas[4], ChatDelta::ToolCall { arguments, .. } if arguments == "{\"a\":1}"));
781        assert_eq!(deltas[5], ChatDelta::Finish(FinishReason::ToolCalls));
782        assert_eq!(deltas[6], ChatDelta::Usage(Usage { prompt_tokens: 5, completion_tokens: 2, total_tokens: 7 }));
783    }
784
785    #[test]
786    fn stream_error_object() {
787        let mut d = OpenAiDecoder::default();
788        let ev = SseEvent { data: "{\"error\":{\"message\":\"boom\"}}".into(), ..SseEvent::default() };
789        assert!(matches!(d.decode(ev), Err(LlmError::Server { .. })));
790        let ev = SseEvent {
791            data: "{\"error\":{\"message\":\"slow\",\"type\":\"rate_limit_exceeded\"}}".into(),
792            ..SseEvent::default()
793        };
794        assert!(matches!(d.decode(ev), Err(LlmError::RateLimit { .. })));
795        let ev = SseEvent {
796            data: "{\"error\":{\"message\":\"long\",\"code\":\"context_length_exceeded\"}}".into(),
797            ..SseEvent::default()
798        };
799        assert!(matches!(d.decode(ev), Err(LlmError::ContextLength(_))));
800    }
801
802    #[test]
803    fn debug_redacts_key() {
804        let cfg = OpenAiConfig::new("https://x", Some("sk-secret".into()));
805        assert!(!format!("{cfg:?}").contains("sk-secret"));
806    }
807
808    #[test]
809    fn azure_endpoints_become_the_v1_root_of_the_resource() {
810        for (endpoint, root) in [
811            ("https://acme.openai.azure.com/", "https://acme.openai.azure.com/openai/v1"),
812            ("https://ACME.openai.azure.com", "https://acme.openai.azure.com/openai/v1"),
813            (" https://acme.openai.azure.com/openai/v1/ ", "https://acme.openai.azure.com/openai/v1"),
814            (
815                "https://acme.openai.azure.com/openai/deployments/gpt4o/chat/completions?api-version=2024-06-01",
816                "https://acme.openai.azure.com/openai/v1",
817            ),
818            ("https://acme.cognitiveservices.azure.com/", "https://acme.cognitiveservices.azure.com/openai/v1"),
819            ("https://acme.services.ai.azure.com/api/projects/p1", "https://acme.services.ai.azure.com/openai/v1"),
820            ("http://127.0.0.1:8080", "http://127.0.0.1:8080/openai/v1"),
821            ("http://localhost:9/x", "http://localhost:9/openai/v1"),
822        ] {
823            assert_eq!(azure_openai_v1_base_url(endpoint).unwrap(), root, "{endpoint}");
824        }
825        for endpoint in [
826            "acme.openai.azure.com",
827            "http://acme.openai.azure.com",
828            "ftp://acme.openai.azure.com",
829            "https://",
830            "https:///openai/v1",
831            "https://user:pw@acme.openai.azure.com",
832        ] {
833            assert!(matches!(azure_openai_v1_base_url(endpoint), Err(LlmError::Config(_))), "{endpoint} accepted");
834        }
835    }
836
837    #[test]
838    fn azure_config_sends_the_key_as_api_key_and_max_completion_tokens() {
839        let cfg = OpenAiConfig::azure("https://acme.openai.azure.com", "azure-secret").unwrap();
840        assert_eq!(cfg.base_url, "https://acme.openai.azure.com/openai/v1");
841        assert_eq!(cfg.auth, AuthStyle::Header("api-key".into()));
842        assert!(cfg.use_max_completion_tokens && cfg.query.is_empty());
843        assert_eq!(cfg.credential_name, AZURE_OPENAI_PROVIDER);
844        assert!(!format!("{cfg:?}").contains("azure-secret"));
845        let request = ChatRequest::new("gpt-4o-deployment", vec![Message::user("hi")]).with_max_tokens(5);
846        let body = build_body(&request, &cfg).unwrap();
847        assert_eq!(body["model"], "gpt-4o-deployment");
848        assert_eq!(body["max_completion_tokens"], 5);
849        assert!(body.get("max_tokens").is_none());
850    }
851
852    #[test]
853    fn forced_final_turn_keeps_the_tool_history_and_says_to_answer_after_it() {
854        let req = crate::nodes::common::final_turn_request_for_tests();
855        let body = build_body(&req, &OpenAiConfig::default()).unwrap();
856        let messages = body["messages"].as_array().unwrap();
857        let roles: Vec<&str> = messages.iter().map(|m| m["role"].as_str().unwrap()).collect();
858        assert_eq!(roles, ["system", "user", "assistant", "tool", "system"]);
859        assert_eq!(messages[4]["content"], crate::nodes::common::FINAL_TURN_INSTRUCTION);
860        assert_eq!(messages[2]["tool_calls"][0]["function"]["name"], "get_weather");
861        assert_eq!(body["tool_choice"], "none");
862        assert_eq!(body["tools"][0]["function"]["name"], "get_weather");
863    }
864}