Skip to main content

adk_model/
openai_compatible.rs

1//! Shared OpenAI-compatible provider implementation.
2
3use crate::openai::{OpenAIReasoningEffort, convert};
4use crate::retry::{RetryConfig, execute_with_retry, is_retryable_model_error};
5use crate::sse::take_line;
6use adk_core::{
7    AdkError, Content, ErrorCategory, ErrorComponent, FinishReason, GenericSchemaAdapter, Llm,
8    LlmRequest, LlmResponse, LlmResponseStream, Part, SchemaAdapter, SchemaCache, UsageMetadata,
9};
10use async_openai::types::chat::{
11    CreateChatCompletionRequestArgs, ReasoningEffort as OaiReasoningEffort, ResponseFormat,
12};
13use async_stream::try_stream;
14use async_trait::async_trait;
15use futures::StreamExt;
16use serde::{Deserialize, Serialize};
17use std::collections::HashMap;
18
19/// Assistant-message field accepted by an OpenAI-compatible provider for reasoning replay.
20///
21/// Reasoning replay is disabled by default. Enabling it selects `reasoning_content`;
22/// an explicit field overrides that choice for endpoints such as newer vLLM servers.
23///
24/// # Example
25///
26/// ```
27/// use adk_model::ReasoningReplayField;
28///
29/// let field = ReasoningReplayField::ReasoningContent;
30/// assert_eq!(field, ReasoningReplayField::ReasoningContent);
31/// ```
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum ReasoningReplayField {
35    /// Use the `reasoning_content` assistant-message field.
36    ReasoningContent,
37    /// Use the `reasoning` assistant-message field, as used by newer vLLM servers.
38    Reasoning,
39}
40
41/// Configuration for OpenAI-compatible providers.
42///
43/// The API key is redacted from `Debug` output and omitted when serializing.
44#[derive(Clone, Serialize, Deserialize)]
45pub struct OpenAICompatibleConfig {
46    /// Provider display name used in error messages.
47    pub provider_name: String,
48    /// API key. Never serialized; deserializing a config without it yields an empty key.
49    #[serde(skip_serializing, default)]
50    pub api_key: String,
51    /// Model name.
52    pub model: String,
53    /// Optional API base URL.
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub base_url: Option<String>,
56    /// Optional organization ID.
57    #[serde(skip_serializing_if = "Option::is_none")]
58    pub organization_id: Option<String>,
59    /// Optional project ID for providers that support it.
60    #[serde(skip_serializing_if = "Option::is_none")]
61    pub project_id: Option<String>,
62    /// Optional reasoning effort for OpenAI reasoning models.
63    #[serde(skip_serializing_if = "Option::is_none")]
64    pub reasoning_effort: Option<OaiReasoningEffort>,
65    /// Whether to allow the model to call multiple tools in a single turn.
66    pub parallel_tool_calls: bool,
67}
68
69impl std::fmt::Debug for OpenAICompatibleConfig {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        f.debug_struct("OpenAICompatibleConfig")
72            .field("provider_name", &self.provider_name)
73            .field("api_key", &"[REDACTED]")
74            .field("model", &self.model)
75            .field("base_url", &self.base_url)
76            .field("organization_id", &self.organization_id)
77            .field("project_id", &self.project_id)
78            .field("reasoning_effort", &self.reasoning_effort)
79            .field("parallel_tool_calls", &self.parallel_tool_calls)
80            .finish()
81    }
82}
83
84impl OpenAICompatibleConfig {
85    /// Create config for an OpenAI-compatible provider.
86    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
87        Self {
88            provider_name: "openai-compatible".to_string(),
89            api_key: api_key.into(),
90            model: model.into(),
91            base_url: None,
92            organization_id: None,
93            project_id: None,
94            reasoning_effort: None,
95            parallel_tool_calls: true,
96        }
97    }
98
99    /// Set provider display name used in errors.
100    pub fn with_provider_name(mut self, provider_name: impl Into<String>) -> Self {
101        self.provider_name = provider_name.into();
102        self
103    }
104
105    /// Set a custom API base URL.
106    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
107        self.base_url = Some(base_url.into());
108        self
109    }
110
111    /// Set organization ID.
112    pub fn with_organization(mut self, organization_id: impl Into<String>) -> Self {
113        self.organization_id = Some(organization_id.into());
114        self
115    }
116
117    /// Set project ID.
118    pub fn with_project(mut self, project_id: impl Into<String>) -> Self {
119        self.project_id = Some(project_id.into());
120        self
121    }
122
123    /// Set reasoning effort for reasoning models.
124    pub fn with_reasoning_effort(mut self, effort: OaiReasoningEffort) -> Self {
125        self.reasoning_effort = Some(effort);
126        self
127    }
128
129    /// Set whether parallel tool calls are allowed.
130    pub fn with_parallel_tool_calls(mut self, parallel_tool_calls: bool) -> Self {
131        self.parallel_tool_calls = parallel_tool_calls;
132        self
133    }
134
135    // ── Provider presets ─────────────────────────────────────────
136
137    /// Fireworks AI preset.
138    ///
139    /// Default model: `accounts/fireworks/models/kimi-k3`
140    pub fn fireworks(api_key: impl Into<String>, model: impl Into<String>) -> Self {
141        Self::new(api_key, model)
142            .with_provider_name("fireworks")
143            .with_base_url("https://api.fireworks.ai/inference/v1")
144    }
145
146    /// Together AI preset.
147    ///
148    /// Default model: `moonshotai/Kimi-K3.1-Pro`
149    pub fn together(api_key: impl Into<String>, model: impl Into<String>) -> Self {
150        Self::new(api_key, model)
151            .with_provider_name("together")
152            .with_base_url("https://api.together.xyz/v1")
153    }
154
155    /// Mistral AI preset.
156    ///
157    /// Default model: `mistral-large-latest`
158    pub fn mistral(api_key: impl Into<String>, model: impl Into<String>) -> Self {
159        Self::new(api_key, model)
160            .with_provider_name("mistral")
161            .with_base_url("https://api.mistral.ai/v1")
162    }
163
164    /// Perplexity preset.
165    ///
166    /// Default model: `sonar-pro`
167    pub fn perplexity(api_key: impl Into<String>, model: impl Into<String>) -> Self {
168        Self::new(api_key, model)
169            .with_provider_name("perplexity")
170            .with_base_url("https://api.perplexity.ai")
171    }
172
173    /// Cerebras preset.
174    ///
175    /// Default model: `gpt-oss-120b`
176    pub fn cerebras(api_key: impl Into<String>, model: impl Into<String>) -> Self {
177        Self::new(api_key, model)
178            .with_provider_name("cerebras")
179            .with_base_url("https://api.cerebras.ai/v1")
180    }
181
182    /// SambaNova preset.
183    ///
184    /// Default model: `gpt-oss-120b`
185    pub fn sambanova(api_key: impl Into<String>, model: impl Into<String>) -> Self {
186        Self::new(api_key, model)
187            .with_provider_name("sambanova")
188            .with_base_url("https://api.sambanova.ai/v1")
189    }
190
191    /// xAI (Grok) preset.
192    ///
193    /// Default model: `grok-4.7`
194    pub fn xai(api_key: impl Into<String>, model: impl Into<String>) -> Self {
195        Self::new(api_key, model).with_provider_name("xai").with_base_url("https://api.x.ai/v1")
196    }
197
198    /// OrcaRouter preset.
199    ///
200    /// OrcaRouter routes one OpenAI-compatible endpoint to models from several
201    /// vendors; model IDs carry a vendor prefix such as `openai/` or `anthropic/`.
202    ///
203    /// Default model suggestion: `openai/gpt-5.6-terra`
204    ///
205    /// # Example
206    ///
207    /// ```
208    /// use adk_model::{OpenAICompatible, OpenAICompatibleConfig};
209    ///
210    /// let config = OpenAICompatibleConfig::orcarouter("sk-orca-...", "openai/gpt-5.6-terra");
211    /// assert_eq!(config.base_url.as_deref(), Some("https://api.orcarouter.ai/v1"));
212    ///
213    /// let model = OpenAICompatible::new(config)?;
214    /// # let _ = model;
215    /// # Ok::<(), adk_core::AdkError>(())
216    /// ```
217    pub fn orcarouter(api_key: impl Into<String>, model: impl Into<String>) -> Self {
218        Self::new(api_key, model)
219            .with_provider_name("orcarouter")
220            .with_base_url("https://api.orcarouter.ai/v1")
221    }
222
223    /// Vultr Serverless Inference preset.
224    ///
225    /// Vultr serves open models (GLM, Qwen, DeepSeek, MiniMax, Nemotron and others) behind
226    /// one OpenAI-compatible endpoint with Bearer auth; `GET /v1/models` lists the IDs a
227    /// subscription can use, with each model's modalities and supported parameters. Rate
228    /// limits apply per subscription and per model.
229    ///
230    /// Default model suggestion: `qwen3.8-27b` (tool calling and vision)
231    ///
232    /// # Example
233    ///
234    /// ```
235    /// use adk_model::{OpenAICompatible, OpenAICompatibleConfig};
236    ///
237    /// let config = OpenAICompatibleConfig::vultr("vultr-inference-key", "qwen3.8-27b");
238    /// assert_eq!(config.base_url.as_deref(), Some("https://api.vultrinference.com/v1"));
239    ///
240    /// let model = OpenAICompatible::new(config)?;
241    /// # let _ = model;
242    /// # Ok::<(), adk_core::AdkError>(())
243    /// ```
244    pub fn vultr(api_key: impl Into<String>, model: impl Into<String>) -> Self {
245        Self::new(api_key, model)
246            .with_provider_name("vultr")
247            .with_base_url("https://api.vultrinference.com/v1")
248    }
249
250    /// API Route preset.
251    ///
252    /// API Route serves models from several vendors behind one OpenAI-compatible
253    /// endpoint; `GET /v1/models` lists the model IDs a key can use.
254    ///
255    /// # Example
256    ///
257    /// ```
258    /// use adk_model::{OpenAICompatible, OpenAICompatibleConfig};
259    ///
260    /// let config = OpenAICompatibleConfig::api_route("sk-...", "gpt-6.1-sol");
261    /// assert_eq!(config.base_url.as_deref(), Some("https://global.api-route.com/v1"));
262    ///
263    /// let model = OpenAICompatible::new(config)?;
264    /// # let _ = model;
265    /// # Ok::<(), adk_core::AdkError>(())
266    /// ```
267    pub fn api_route(api_key: impl Into<String>, model: impl Into<String>) -> Self {
268        Self::new(api_key, model)
269            .with_provider_name("api-route")
270            .with_base_url("https://global.api-route.com/v1")
271    }
272
273    /// Google Gemini (OpenAI-compatible) preset.
274    ///
275    /// Targets Gemini's OpenAI-compatibility endpoint, letting you use a Gemini
276    /// API key and a Gemini model (e.g. `gemini-3.8-flash`) through the OpenAI
277    /// Chat Completions wire format. Use a `GEMINI_API_KEY` for the `api_key`.
278    ///
279    /// For native Gemini features (thinking levels, server-side tools, the
280    /// Interactions API), prefer [`GeminiModel`](crate::gemini::GeminiModel).
281    /// This preset is for callers who want a single OpenAI-compatible code path
282    /// across providers.
283    ///
284    /// Default model suggestion: `gemini-3.8-flash`.
285    pub fn gemini(api_key: impl Into<String>, model: impl Into<String>) -> Self {
286        Self::new(api_key, model)
287            .with_provider_name("gemini")
288            .with_base_url("https://generativelanguage.googleapis.com/v1beta/openai")
289    }
290
291    /// MiniMax preset.
292    ///
293    /// Default model: `MiniMax-M3` (case-sensitive)
294    pub fn minimax(api_key: impl Into<String>, model: impl Into<String>) -> Self {
295        Self::new(api_key, model)
296            .with_provider_name("minimax")
297            .with_base_url("https://api.minimax.chat/v1")
298    }
299
300    /// ByteDance Doubao (Volcano Engine Ark) preset.
301    ///
302    /// Default model: `doubao-1-5-pro-256k`
303    pub fn bytedance(api_key: impl Into<String>, model: impl Into<String>) -> Self {
304        Self::new(api_key, model)
305            .with_provider_name("bytedance")
306            .with_base_url("https://ark.cn-beijing.volces.com/api/v3")
307    }
308
309    /// Zhipu AI (GLM) preset.
310    ///
311    /// Default model: `glm-5.3`
312    pub fn zhipu(api_key: impl Into<String>, model: impl Into<String>) -> Self {
313        Self::new(api_key, model)
314            .with_provider_name("zhipu")
315            .with_base_url("https://open.bigmodel.cn/api/paas/v4")
316    }
317
318    /// Baidu ERNIE (Qianfan) preset via OpenAI-compatible endpoint.
319    ///
320    /// Default model: `ernie-5.1`
321    ///
322    /// Note: Uses the Qianfan OpenAI-compatible endpoint. For the native
323    /// Qianfan API with OAuth2 token exchange, use a dedicated client.
324    pub fn baidu(api_key: impl Into<String>, model: impl Into<String>) -> Self {
325        Self::new(api_key, model)
326            .with_provider_name("baidu")
327            .with_base_url("https://qianfan.baidubce.com/v2")
328    }
329
330    /// Cohere preset via OpenAI-compatible endpoint.
331    ///
332    /// Default model: `command-a-plus-05-2026`
333    ///
334    /// Note: For full Cohere features (citations, connectors, RAG), use
335    /// the native Cohere API. This preset provides basic chat completions.
336    pub fn cohere(api_key: impl Into<String>, model: impl Into<String>) -> Self {
337        Self::new(api_key, model)
338            .with_provider_name("cohere")
339            .with_base_url("https://api.cohere.com/compatibility/v1")
340    }
341}
342
343/// Error codes a compatible client reports.
344///
345/// Native services routed through [`OpenAICompatible`] keep the codes their
346/// dedicated clients reported, because error codes are part of the public contract.
347#[derive(Debug, Clone, Copy)]
348pub(crate) struct ErrorCodes {
349    /// Transport failure: no response arrived, or its body stopped arriving.
350    pub(crate) request: &'static str,
351    /// Non-success HTTP status without a status-specific code.
352    pub(crate) api_error: &'static str,
353    /// Response body that is not valid JSON.
354    pub(crate) parse: &'static str,
355    /// Stream that ended, or whose connection failed, before the response finished.
356    pub(crate) incomplete_stream: &'static str,
357    /// Error the provider reported inside a response or stream.
358    pub(crate) stream_error: &'static str,
359    /// Status-specific codes that take precedence over `api_error`.
360    pub(crate) status: &'static [(u16, &'static str)],
361    /// Non-success HTTP status whose body says the account is out of quota or credit,
362    /// whatever the status.
363    pub(crate) quota_exhausted: &'static str,
364}
365
366impl ErrorCodes {
367    /// Codes for providers reached through the generic compatible client.
368    pub(crate) const COMPATIBLE: Self = Self {
369        request: "model.openai_compat.request",
370        api_error: "model.openai_compat.api_error",
371        parse: "model.openai_compat.parse",
372        incomplete_stream: "model.openai_compat.incomplete_stream",
373        stream_error: "model.openai_compat.stream_error",
374        status: &[],
375        quota_exhausted: "model.openai_compat.quota_exhausted",
376    };
377
378    fn for_status(&self, status: u16) -> &'static str {
379        self.status
380            .iter()
381            .find_map(|(candidate, code)| (*candidate == status).then_some(*code))
382            .unwrap_or(self.api_error)
383    }
384}
385
386/// Shared OpenAI-compatible client implementation.
387pub struct OpenAICompatible {
388    completion_url: Option<String>,
389    http: reqwest::Client,
390    /// Headers added to every request, kept so later calls extend rather than replace them.
391    default_headers: http::HeaderMap,
392    request_adapter: Option<crate::openai::RequestAdapter>,
393    api_key: String,
394    base_url: String,
395    model: String,
396    provider_name: String,
397    retry_config: RetryConfig,
398    reasoning_effort: Option<OpenAIReasoningEffort>,
399    organization_id: Option<String>,
400    parallel_tool_calls: bool,
401    reasoning_replay_field: Option<ReasoningReplayField>,
402    error_codes: ErrorCodes,
403}
404
405/// Builds the redirect-free HTTP client; adapters receive defaults on each request.
406fn compatible_http_client(
407    timeouts: crate::HttpTimeouts,
408    provider_name: &str,
409) -> Result<reqwest::Client, AdkError> {
410    timeouts
411        .apply(reqwest::Client::builder())
412        .redirect(reqwest::redirect::Policy::none())
413        .build()
414        .map_err(|err| {
415            AdkError::new(
416                ErrorComponent::Model,
417                ErrorCategory::Internal,
418                "model.openai.http_client_init",
419                format!("failed to initialize the {provider_name} HTTP client: {err}"),
420            )
421            .with_provider(provider_name)
422            .with_source(err)
423        })
424}
425
426impl OpenAICompatible {
427    /// Create a new OpenAI-compatible client.
428    pub fn new(config: OpenAICompatibleConfig) -> Result<Self, AdkError> {
429        let reasoning_effort = config.reasoning_effort.clone().map(|effort| match effort {
430            OaiReasoningEffort::None => OpenAIReasoningEffort::None,
431            OaiReasoningEffort::Minimal => OpenAIReasoningEffort::Minimal,
432            OaiReasoningEffort::Low => OpenAIReasoningEffort::Low,
433            OaiReasoningEffort::Medium => OpenAIReasoningEffort::Medium,
434            OaiReasoningEffort::High => OpenAIReasoningEffort::High,
435            OaiReasoningEffort::Xhigh => OpenAIReasoningEffort::XHigh,
436        });
437        Self::new_with_reasoning_effort(config, reasoning_effort)
438    }
439
440    /// Create an OpenAI-compatible client with the complete OpenAI reasoning vocabulary.
441    ///
442    /// This supports newer values such as `none`, `xhigh`, and `max` without changing
443    /// the backward-compatible [`OpenAICompatibleConfig::reasoning_effort`] field type.
444    pub fn new_with_reasoning_effort(
445        config: OpenAICompatibleConfig,
446        reasoning_effort: Option<OpenAIReasoningEffort>,
447    ) -> Result<Self, AdkError> {
448        crate::catalog::warn_if_obsolete(&config.provider_name, &config.model);
449        let base_url = config.base_url.unwrap_or_else(|| "https://api.openai.com/v1".to_string());
450
451        let timeouts = crate::HttpTimeouts::default();
452        Ok(Self {
453            completion_url: None,
454            http: compatible_http_client(timeouts, &config.provider_name)?,
455            default_headers: http::HeaderMap::new(),
456            request_adapter: None,
457            api_key: config.api_key,
458            base_url,
459            model: config.model,
460            provider_name: config.provider_name,
461            retry_config: RetryConfig::default(),
462            reasoning_effort,
463            organization_id: config.organization_id,
464            parallel_tool_calls: config.parallel_tool_calls,
465            reasoning_replay_field: None,
466            error_codes: ErrorCodes::COMPATIBLE,
467        })
468    }
469
470    /// Adds default HTTP headers to every request, replacing earlier defaults with the same name.
471    ///
472    /// The bearer token and organization headers set per request take precedence.
473    /// Headers are applied per request without replacing the HTTP transport or its
474    /// timeout settings; redirects stay disabled.
475    ///
476    /// # Example
477    ///
478    /// ```
479    /// use adk_model::{OpenAICompatible, OpenAICompatibleConfig};
480    /// use http::header::{HeaderMap, HeaderValue};
481    ///
482    /// let mut headers = HeaderMap::new();
483    /// headers.insert("x-session-id", HeaderValue::from_static("conversation-1"));
484    /// let client = OpenAICompatible::new(OpenAICompatibleConfig::new("api-key", "model"))?
485    ///     .with_default_headers(headers)?;
486    /// # Ok::<(), adk_core::AdkError>(())
487    /// ```
488    pub fn with_default_headers(mut self, headers: http::HeaderMap) -> Result<Self, AdkError> {
489        self.default_headers.extend(headers);
490        Ok(self)
491    }
492
493    /// Sets the connect and idle timeouts of the HTTP transport.
494    ///
495    /// The idle timeout bounds each wait for data, so a stream that stalls fails with a
496    /// `Timeout` error instead of holding the run; see [`HttpTimeouts`](crate::HttpTimeouts)
497    /// for the defaults. This rebuilds the `reqwest` client, so it returns `Result`.
498    ///
499    /// # Example
500    ///
501    /// ```
502    /// use std::time::Duration;
503    ///
504    /// use adk_model::{HttpTimeouts, OpenAICompatible, OpenAICompatibleConfig};
505    ///
506    /// let client = OpenAICompatible::new(OpenAICompatibleConfig::new("api-key", "model"))?
507    ///     .with_timeouts(HttpTimeouts::new(Duration::from_secs(10), Duration::from_secs(120)))?;
508    /// # let _ = client;
509    /// # Ok::<(), adk_core::AdkError>(())
510    /// ```
511    ///
512    /// # Errors
513    ///
514    /// Returns an `Internal` error with code `model.openai.http_client_init` when the
515    /// HTTP client cannot be built.
516    pub fn with_timeouts(mut self, timeouts: crate::HttpTimeouts) -> Result<Self, AdkError> {
517        self.http = compatible_http_client(timeouts, &self.provider_name)?;
518        Ok(self)
519    }
520
521    /// Set the retry configuration (builder pattern).
522    #[must_use]
523    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
524        self.retry_config = retry_config;
525        self
526    }
527
528    /// Customize generation request fields and headers before each HTTP attempt.
529    ///
530    /// The adapter runs under this client's [`RetryConfig`]; see
531    /// [`RequestAdapter`](crate::openai::RequestAdapter) for an example.
532    #[must_use]
533    pub fn with_request_adapter(mut self, adapter: crate::openai::RequestAdapter) -> Self {
534        self.request_adapter = Some(adapter);
535        self
536    }
537
538    /// Use a native service's fully qualified Chat Completions route.
539    pub(crate) fn with_completion_url(mut self, url: String) -> Self {
540        self.completion_url = Some(url);
541        self
542    }
543
544    pub(crate) fn with_reasoning_effort(mut self, effort: Option<OpenAIReasoningEffort>) -> Self {
545        self.reasoning_effort = effort;
546        self
547    }
548
549    /// Report a native service's error codes instead of the compatible ones.
550    pub(crate) fn with_error_codes(mut self, error_codes: ErrorCodes) -> Self {
551        self.error_codes = error_codes;
552        self
553    }
554
555    /// Set the retry configuration (mutable reference).
556    pub fn set_retry_config(&mut self, retry_config: RetryConfig) {
557        self.retry_config = retry_config;
558    }
559
560    /// Returns the current retry configuration.
561    pub fn retry_config(&self) -> &RetryConfig {
562        &self.retry_config
563    }
564
565    /// Enables or disables assistant reasoning replay through `reasoning_content`.
566    ///
567    /// Disabled by default. Passing `true` selects `reasoning_content`, replacing
568    /// any previous field selection; passing `false` clears the selection.
569    /// This controls history serialization, not whether the model thinks.
570    ///
571    /// # Example
572    ///
573    /// ```
574    /// use adk_model::{OpenAICompatible, OpenAICompatibleConfig};
575    ///
576    /// let client = OpenAICompatible::new(OpenAICompatibleConfig::new("key", "model"))?
577    ///     .with_reasoning_replay(true);
578    /// # let _ = client;
579    /// # Ok::<(), adk_core::AdkError>(())
580    /// ```
581    #[must_use]
582    pub fn with_reasoning_replay(mut self, enabled: bool) -> Self {
583        self.reasoning_replay_field = enabled.then_some(ReasoningReplayField::ReasoningContent);
584        self
585    }
586
587    /// Enables assistant reasoning replay with an explicit provider field.
588    ///
589    /// Newer vLLM servers use `ReasoningReplayField::Reasoning`. Older deployments
590    /// may still require `reasoning_content`; select the field the endpoint accepts.
591    /// The last call to either reasoning-replay builder determines the selection.
592    ///
593    /// # Example
594    ///
595    /// ```
596    /// use adk_model::{
597    ///     OpenAICompatible, OpenAICompatibleConfig, ReasoningReplayField,
598    /// };
599    ///
600    /// let client = OpenAICompatible::new(OpenAICompatibleConfig::new("key", "model"))?
601    ///     .with_reasoning_replay_field(ReasoningReplayField::Reasoning);
602    /// # let _ = client;
603    /// # Ok::<(), adk_core::AdkError>(())
604    /// ```
605    #[must_use]
606    pub fn with_reasoning_replay_field(mut self, field: ReasoningReplayField) -> Self {
607        self.reasoning_replay_field = Some(field);
608        self
609    }
610}
611
612/// Adds the reasoning of each assistant content to the message it became; `owners[i]` is the
613/// index in `contents` of the content that produced message `i`.
614fn inject_assistant_reasoning(
615    body: &mut serde_json::Value,
616    contents: &[Content],
617    owners: &[usize],
618    field: Option<ReasoningReplayField>,
619) {
620    let Some(field) = field else {
621        return;
622    };
623    let Some(messages) = body.get_mut("messages").and_then(serde_json::Value::as_array_mut) else {
624        return;
625    };
626    let field_name = match field {
627        ReasoningReplayField::ReasoningContent => "reasoning_content",
628        ReasoningReplayField::Reasoning => "reasoning",
629    };
630
631    for (message, content) in messages.iter_mut().zip(owners.iter().map(|owner| &contents[*owner]))
632    {
633        if !matches!(content.role.as_str(), "model" | "assistant") {
634            continue;
635        }
636        let Some(reasoning) = convert::extract_reasoning_content(&content.parts) else {
637            continue;
638        };
639        let Some(message) = message.as_object_mut() else {
640            continue;
641        };
642
643        message.insert(field_name.to_string(), serde_json::Value::String(reasoning));
644    }
645}
646
647/// Provider capabilities that shape a Chat Completions request body.
648#[derive(Debug, Clone, Copy)]
649pub(crate) struct ChatCapabilities {
650    /// Value of `parallel_tool_calls` sent with tool declarations.
651    pub(crate) parallel_tool_calls: bool,
652    /// Send inline PDFs as `file` parts. Only OpenAI and Azure OpenAI accept them,
653    /// so every other compatible provider keeps the text fallback.
654    pub(crate) native_pdf: bool,
655}
656
657/// Build the serialized JSON request body from an `LlmRequest`.
658///
659/// This is shared between the streaming and non-streaming paths so that
660/// request parameter construction is identical regardless of mode.
661pub(crate) fn build_request_json(
662    model: &str,
663    request: &LlmRequest,
664    reasoning_effort: &Option<OpenAIReasoningEffort>,
665    capabilities: ChatCapabilities,
666    reasoning_replay_field: Option<ReasoningReplayField>,
667    adapter: &dyn SchemaAdapter,
668    cache: &SchemaCache,
669) -> Result<serde_json::Value, AdkError> {
670    let bare_model = model.strip_prefix("models/").unwrap_or(model);
671    if matches!(bare_model, "gemini-3.6-flash" | "gemini-3.7-flash" | "gemini-3.8-flash")
672        && request.config.as_ref().is_some_and(|config| {
673            config.temperature.is_some() || config.top_p.is_some() || config.top_k.is_some()
674        })
675    {
676        return Err(AdkError::new(
677            ErrorComponent::Model,
678            ErrorCategory::InvalidInput,
679            "model.gemini.sampling_unsupported",
680            format!(
681                "{bare_model} does not accept temperature, top_p, or top_k; remove explicit sampling parameters"
682            ),
683        )
684        .with_provider("gemini"));
685    }
686    let contents = crate::tool_result::with_images(&request.contents);
687    let mut messages = Vec::with_capacity(contents.len());
688    let mut owners = Vec::with_capacity(contents.len());
689    for (index, content) in contents.iter().enumerate() {
690        for message in convert::content_to_messages(content, capabilities.native_pdf) {
691            messages.push(message);
692            owners.push(index);
693        }
694    }
695
696    let mut request_builder = CreateChatCompletionRequestArgs::default();
697    request_builder.model(model).messages(messages);
698
699    if !request.tools.is_empty() {
700        let tools = convert::convert_tools(&request.tools, adapter, cache);
701        request_builder.tools(tools);
702        // OpenAI defaults parallel_tool_calls to true.
703        request_builder.parallel_tool_calls(capabilities.parallel_tool_calls);
704    }
705
706    let reasoning_effort =
707        crate::openai::request_reasoning_effort(model, *reasoning_effort, request);
708    if let Some(effort) = reasoning_effort.and_then(to_oai_reasoning_effort) {
709        request_builder.reasoning_effort(effort);
710    }
711
712    crate::generation_config::reject_unsupported(
713        "openai-compatible",
714        request.config.as_ref(),
715        crate::generation_config::Supports {
716            stop_sequences: true,
717            seed: true,
718            penalties: true,
719            top_logprobs: true,
720        },
721    )?;
722
723    if let Some(config) = &request.config {
724        if let Some(temp) = config.temperature {
725            request_builder.temperature(temp);
726        }
727        if let Some(top_p) = config.top_p {
728            request_builder.top_p(top_p);
729        }
730        if let Some(max_tokens) = config.max_output_tokens {
731            request_builder.max_completion_tokens(max_tokens as u32);
732        }
733
734        if let Some(schema) = &config.response_schema {
735            let json_schema = convert::json_schema_format(&request.model, schema);
736            request_builder.response_format(ResponseFormat::JsonSchema { json_schema });
737        }
738    }
739
740    let openai_request = request_builder
741        .build()
742        .map_err(|e| AdkError::model(format!("failed to build request: {e}")))?;
743
744    let mut body = serde_json::to_value(&openai_request)
745        .map_err(|e| AdkError::model(format!("failed to serialize request: {e}")))?;
746
747    if matches!(reasoning_effort, Some(OpenAIReasoningEffort::Max)) {
748        body["reasoning_effort"] = serde_json::Value::String("max".to_string());
749    }
750
751    // Written into the body: the typed request marks `seed` deprecated.
752    if let Some(config) = &request.config
753        && let Some(fields) = body.as_object_mut()
754    {
755        if !config.stop_sequences.is_empty() {
756            fields.insert("stop".to_string(), serde_json::json!(config.stop_sequences));
757        }
758        if let Some(seed) = config.seed {
759            fields.insert("seed".to_string(), serde_json::json!(seed));
760        }
761        if let Some(penalty) = config.frequency_penalty {
762            fields.insert("frequency_penalty".to_string(), serde_json::json!(penalty));
763        }
764        if let Some(penalty) = config.presence_penalty {
765            fields.insert("presence_penalty".to_string(), serde_json::json!(penalty));
766        }
767        if let Some(top_logprobs) = config.top_logprobs {
768            fields.insert("logprobs".to_string(), serde_json::Value::Bool(true));
769            fields.insert("top_logprobs".to_string(), serde_json::json!(top_logprobs));
770        }
771    }
772
773    inject_assistant_reasoning(&mut body, &contents, &owners, reasoning_replay_field);
774
775    // Merge provider-specific extensions from config.extensions["openai"] into
776    // the request body.  This allows users to pass provider-specific fields
777    // that the typed builder doesn't cover (e.g. provider-specific parameters
778    // for OpenAI-compatible APIs like DeepSeek, Together, etc.).
779    if let Some(config) = &request.config
780        && let Some(openai_ext) = config.extensions.get("openai")
781        && let (Some(body_obj), Some(ext_obj)) = (body.as_object_mut(), openai_ext.as_object())
782    {
783        for (key, value) in ext_obj {
784            body_obj.insert(key.clone(), value.clone());
785        }
786    }
787
788    Ok(body)
789}
790
791fn to_oai_reasoning_effort(effort: OpenAIReasoningEffort) -> Option<OaiReasoningEffort> {
792    match effort {
793        OpenAIReasoningEffort::None => Some(OaiReasoningEffort::None),
794        OpenAIReasoningEffort::Minimal => Some(OaiReasoningEffort::Minimal),
795        OpenAIReasoningEffort::Low => Some(OaiReasoningEffort::Low),
796        OpenAIReasoningEffort::Medium => Some(OaiReasoningEffort::Medium),
797        OpenAIReasoningEffort::High => Some(OaiReasoningEffort::High),
798        OpenAIReasoningEffort::XHigh => Some(OaiReasoningEffort::Xhigh),
799        OpenAIReasoningEffort::Max => None,
800    }
801}
802
803/// Destination, credentials and error codes of one generation request.
804#[derive(Clone)]
805struct RequestTarget {
806    url: String,
807    headers: http::HeaderMap,
808    api_key: String,
809    organization_id: Option<String>,
810    provider_name: String,
811    adapter: Option<crate::openai::RequestAdapter>,
812    error_codes: ErrorCodes,
813}
814
815/// Send an HTTP POST and handle error status codes.
816///
817/// Returns the raw `reqwest::Response` on success so the caller can decide
818/// whether to parse it as JSON (non-streaming) or consume it as an SSE byte
819/// stream (streaming).
820async fn send_request(
821    http: &reqwest::Client,
822    target: &RequestTarget,
823    body: &serde_json::Value,
824) -> Result<reqwest::Response, AdkError> {
825    let RequestTarget {
826        url,
827        headers,
828        api_key,
829        organization_id,
830        provider_name,
831        adapter,
832        error_codes,
833    } = target;
834    let request_error = |error: reqwest::Error| {
835        AdkError::new(
836            ErrorComponent::Model,
837            crate::http_timeouts::transport_category(&error),
838            error_codes.request,
839            format!("{provider_name} request error: {error}"),
840        )
841        .with_provider(provider_name)
842    };
843    let mut builder = http.post(url).json(body);
844    if !api_key.is_empty() {
845        builder = builder.bearer_auth(api_key);
846    }
847    if let Some(org_id) = organization_id {
848        builder = builder.header("OpenAI-Organization", org_id);
849    }
850    let mut request = builder.build().map_err(&request_error)?;
851    for (name, value) in headers {
852        request.headers_mut().entry(name).or_insert_with(|| value.clone());
853    }
854    if let Some(adapter) = adapter {
855        let mut body = body.clone();
856        adapter(&mut body, request.headers_mut())?;
857        *request.body_mut() = Some(body.to_string().into());
858        request.headers_mut().remove(reqwest::header::CONTENT_LENGTH);
859    }
860    let http_resp = http.execute(request).await.map_err(request_error)?;
861
862    if !http_resp.status().is_success() {
863        let status = http_resp.status();
864        let status_code = status.as_u16();
865        let retry_after = http_resp
866            .headers()
867            .get(reqwest::header::RETRY_AFTER)
868            .and_then(|value| value.to_str().ok())
869            .and_then(crate::retry::parse_retry_after);
870        let body = http_resp.text().await.unwrap_or_default();
871        // OpenAI answers HTTP 429 both for a rate limit and for an account with no credit.
872        let quota_exhausted = crate::error_metadata::body_reports_exhausted_quota(&body);
873        let error = AdkError::new(
874            ErrorComponent::Model,
875            crate::retry::category_for_status_code(status_code),
876            if quota_exhausted {
877                error_codes.quota_exhausted
878            } else {
879                error_codes.for_status(status_code)
880            },
881            format!(
882                "{provider_name} API error (HTTP {status}): {}",
883                adk_core::upstream_excerpt(&body)
884            ),
885        )
886        .with_upstream_status(status_code)
887        .with_provider(provider_name);
888        let error = crate::error_metadata::classify_quota(error, quota_exhausted);
889        return Err(crate::retry::with_retry_after(
890            crate::error_metadata::from_body(error, &body),
891            retry_after,
892        ));
893    }
894
895    Ok(http_resp)
896}
897
898/// Parse a finish_reason string into an ADK `FinishReason`.
899///
900/// `"error"` is not a finish reason but a failure, and callers reject it first.
901fn parse_finish_reason(fr: &str) -> FinishReason {
902    match fr {
903        "stop" | "tool_calls" | "function_call" => FinishReason::Stop,
904        "length" => FinishReason::MaxTokens,
905        "content_filter" => FinishReason::Safety,
906        _ => FinishReason::Other,
907    }
908}
909
910/// Accumulate string deltas while treating structured values as complete snapshots.
911fn append_tool_call_arguments(accumulator: &mut String, arguments: &serde_json::Value) {
912    match arguments {
913        serde_json::Value::String(fragment) => accumulator.push_str(fragment),
914        serde_json::Value::Null => {}
915        structured => {
916            let empty_snapshot = matches!(structured, serde_json::Value::Object(fields) if fields.is_empty())
917                || matches!(structured, serde_json::Value::Array(items) if items.is_empty());
918            if !empty_snapshot {
919                accumulator.clear();
920                accumulator.push_str(&structured.to_string());
921            }
922        }
923    }
924}
925
926/// Parse usage metadata from a raw SSE chunk JSON value.
927fn parse_usage_from_chunk(chunk: &serde_json::Value) -> Option<UsageMetadata> {
928    chunk.get("usage").and_then(convert::usage_metadata_from_raw)
929}
930
931#[async_trait]
932impl Llm for OpenAICompatible {
933    // The request's `max_completion_tokens`, reasoning included, or the model's output limit.
934    fn max_cost_micro_usd(&self, request: &adk_core::LlmRequest) -> Option<u64> {
935        crate::pricing::PricingCatalog::standard().max_cost_micro_usd(
936            Some(&self.provider_name),
937            self.name(),
938            request,
939            crate::pricing::request_output_cap(request),
940        )
941    }
942
943    fn context_window(&self) -> Option<u64> {
944        crate::pricing::PricingCatalog::standard()
945            .context_window(Some(&self.provider_name), self.name())
946    }
947
948    // A server at a loopback address, such as vLLM or LM Studio on this machine, keeps the
949    // request on it.
950    fn data_locality(&self) -> adk_core::DataLocality {
951        adk_core::DataLocality::of_url(self.completion_url.as_deref().unwrap_or(&self.base_url))
952    }
953
954    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
955        vec![adk_core::DataDestination::of_url(
956            &self.provider_name,
957            self.completion_url.as_deref().unwrap_or(&self.base_url),
958        )]
959    }
960
961    fn name(&self) -> &str {
962        &self.model
963    }
964
965    #[tracing::instrument(
966        name = "model.generate_content",
967        skip_all,
968        fields(
969            model.name = %self.name(),
970            stream = %stream,
971            request.contents_count = %request.contents.len(),
972            request.tools_count = %request.tools.len()
973        )
974    )]
975    async fn generate_content(
976        &self,
977        mut request: LlmRequest,
978        stream: bool,
979    ) -> Result<LlmResponseStream, AdkError> {
980        // Native items reach this provider only from the turns its own origin marks.
981        adk_core::history::retain_replayable(
982            &mut request.contents,
983            &adk_core::history::ProviderOrigin::new(&self.provider_name, &self.model),
984        );
985        let model = self.model.clone();
986        let provider_name = self.provider_name.clone();
987        let attribution = (self.provider_name.clone(), self.model.clone());
988        let http = self.http.clone();
989        let retry_config = self.retry_config.clone();
990        let reasoning_effort = self.reasoning_effort;
991        let reasoning_replay_field = self.reasoning_replay_field;
992        let error_codes = self.error_codes;
993        let target = RequestTarget {
994            headers: self.default_headers.clone(),
995            url: self
996                .completion_url
997                .clone()
998                .unwrap_or_else(|| format!("{}/chat/completions", self.base_url)),
999            api_key: self.api_key.clone(),
1000            organization_id: self.organization_id.clone(),
1001            provider_name: provider_name.clone(),
1002            adapter: self.request_adapter.clone(),
1003            error_codes,
1004        };
1005        // Text-encoded tool calls are honoured only for tools this request declared.
1006        let declared_tools: std::collections::HashSet<String> =
1007            request.tools.keys().cloned().collect();
1008
1009        // Normalize tool schemas at request time using the schema adapter.
1010        let adapter = self.schema_adapter();
1011        use std::sync::LazyLock;
1012        static SCHEMA_CACHE: LazyLock<SchemaCache> =
1013            LazyLock::new(|| SchemaCache::for_adapter(std::sync::Arc::new(GenericSchemaAdapter)));
1014        let request_body = build_request_json(
1015            &model,
1016            &request,
1017            &reasoning_effort,
1018            ChatCapabilities {
1019                parallel_tool_calls: self.parallel_tool_calls,
1020                native_pdf: matches!(provider_name.as_str(), "openai" | "azure-openai"),
1021            },
1022            reasoning_replay_field,
1023            adapter,
1024            &SCHEMA_CACHE,
1025        )?;
1026
1027        let usage_span = crate::telemetry::inference_span(&provider_name, &model, stream, &request);
1028
1029        if stream {
1030            // ── Streaming path ──────────────────────────────────────
1031            let response_stream = try_stream! {
1032                // Inject streaming fields into the pre-built request body.
1033                let mut body = request_body.clone();
1034                if let Some(obj) = body.as_object_mut() {
1035                    obj.insert("stream".to_string(), serde_json::json!(true));
1036                    obj.insert(
1037                        "stream_options".to_string(),
1038                        serde_json::json!({"include_usage": true}),
1039                    );
1040                }
1041
1042                // Retry covers only the initial HTTP request, not stream consumption.
1043                let response = execute_with_retry(&retry_config, is_retryable_model_error, || {
1044                    let http = http.clone();
1045                    let target = target.clone();
1046                    let body = body.clone();
1047                    async move { send_request(&http, &target, &body).await }
1048                })
1049                .await?;
1050
1051                // Process SSE byte stream (following DeepSeekClient pattern).
1052                let mut byte_stream = response.bytes_stream();
1053                let mut buffer = Vec::new();
1054                let mut tool_call_accumulators: HashMap<u32, (String, String, String)> =
1055                    HashMap::new();
1056                let mut text_tool_buffer =
1057                    crate::tool_call_parser::ToolCallBuffer::for_declared_tools(declared_tools);
1058                // Token log probabilities from every chunk, reported on the final response.
1059                let mut logprobs: Vec<serde_json::Value> = Vec::new();
1060                // A finish reason or `[DONE]` marks a complete response; without one the
1061                // answer or a tool call may be truncated.
1062                let mut finished = false;
1063                // The model declined in `delta.refusal`, so the turn finishes with `Refusal`.
1064                let mut refused = false;
1065                let mut ended = false;
1066
1067                'body: while !ended {
1068                    match byte_stream.next().await {
1069                        Some(Ok(chunk)) => buffer.extend_from_slice(&chunk),
1070                        Some(Err(_)) if finished => break,
1071                        Some(Err(error)) => Err(crate::stream_error::interrupted(
1072                            &provider_name, error_codes.incomplete_stream, &error,
1073                        ))?,
1074                        None => {
1075                            ended = true;
1076                            // The last line may arrive without its line ending.
1077                            buffer.push(b'\n');
1078                        }
1079                    }
1080
1081                    // Process complete SSE lines.
1082                    while let Some(line) = match take_line(&mut buffer) {
1083                        Ok(line) => line,
1084                        Err(_) if finished => break 'body,
1085                        Err(error) => Err(error)?,
1086                    } {
1087                        let Some(data) = crate::sse::data(&line) else {
1088                            continue;
1089                        };
1090
1091                        if data == "[DONE]" {
1092                            if !tool_call_accumulators.is_empty() {
1093                                Err(crate::stream_error::incomplete(
1094                                    &provider_name,
1095                                    error_codes.incomplete_stream,
1096                                    "its tool calls finished",
1097                                ))?;
1098                            }
1099                            finished = true;
1100                            ended = true;
1101                            break;
1102                        }
1103
1104                        {
1105                            let parsed = serde_json::from_str::<serde_json::Value>(data);
1106                            // A cut-off trailer after a finished response loses nothing.
1107                            if parsed.is_err() && finished {
1108                                continue;
1109                            }
1110                            let chunk_json = parsed.map_err(|error| {
1111                                crate::stream_error::undecodable(
1112                                    &provider_name,
1113                                    error_codes.parse,
1114                                    &error,
1115                                )
1116                            })?;
1117                            if let Some(error) =
1118                                chunk_json.get("error").filter(|error| !error.is_null())
1119                            {
1120                                Err(crate::stream_error::reported(
1121                                    &provider_name,
1122                                    error_codes.stream_error,
1123                                    error,
1124                                ))?;
1125                            }
1126                            let usage_metadata = parse_usage_from_chunk(&chunk_json);
1127
1128                            let choice = match chunk_json.get("choices").and_then(|c| c.get(0)) {
1129                                Some(c) => c,
1130                                None => {
1131                                    if let Some(usage_metadata) = usage_metadata {
1132                                        yield LlmResponse {
1133                                            usage_metadata: Some(usage_metadata),
1134                                            partial: true,
1135                                            ..Default::default()
1136                                        };
1137                                    }
1138                                    continue;
1139                                }
1140                            };
1141                            if let Some(tokens) =
1142                                choice.pointer("/logprobs/content").and_then(|v| v.as_array())
1143                            {
1144                                logprobs.extend(tokens.iter().cloned());
1145                            }
1146                            let delta = match choice.get("delta") {
1147                                Some(d) => d,
1148                                None => continue,
1149                            };
1150
1151                            let finish_reason_str = choice
1152                                .get("finish_reason")
1153                                .and_then(|v| v.as_str())
1154                                .map(String::from);
1155
1156                            // Accumulate tool calls by index.
1157                            if let Some(tool_calls) = delta.get("tool_calls").and_then(|v| v.as_array()) {
1158                                for tc in tool_calls {
1159                                    let index = tc.get("index").and_then(|v| v.as_u64()).unwrap_or(0) as u32;
1160                                    let entry = tool_call_accumulators
1161                                        .entry(index)
1162                                        .or_insert_with(|| {
1163                                            let call_id = tc
1164                                                .get("id")
1165                                                .and_then(|v| v.as_str())
1166                                                .unwrap_or("")
1167                                                .to_string();
1168                                            (call_id, String::new(), String::new())
1169                                        });
1170
1171                                    if let Some(id) = tc.get("id").and_then(|v| v.as_str())
1172                                        && !id.is_empty() {
1173                                            entry.0 = id.to_string();
1174                                        }
1175
1176                                    if let Some(func) = tc.get("function") {
1177                                        if let Some(name) = func.get("name").and_then(|v| v.as_str()) {
1178                                            entry.1 = name.to_string();
1179                                        }
1180                                        if let Some(arguments) = func.get("arguments") {
1181                                            append_tool_call_arguments(&mut entry.2, arguments);
1182                                        }
1183                                    }
1184                                }
1185                            }
1186
1187                            // A terminal chunk may still carry reasoning. Emit it before
1188                            // the final response so neither stop nor tool calls drop it.
1189                            // Some compatible providers use "reasoning" instead.
1190                            let reasoning = delta.get("reasoning_content")
1191                                .or_else(|| delta.get("reasoning"))
1192                                .and_then(|v| v.as_str());
1193                            if let Some(reasoning) = reasoning
1194                                && !reasoning.is_empty() {
1195                                    yield LlmResponse {
1196                                        content: Some(Content {
1197                                            role: "model".to_string(),
1198                                            parts: vec![Part::Thinking {
1199                                                thinking: reasoning.to_string(),
1200                                                signature: None,
1201                                            }],
1202                                        }),
1203                                        usage_metadata: None,
1204                                        finish_reason: None,
1205                                        citation_metadata: None,
1206                                        partial: true,
1207                                        turn_complete: false,
1208                                        interrupted: false,
1209                                        error_code: None,
1210                                        error_message: None,
1211                                        provider_metadata: None,
1212                                        interaction_id: None,
1213                                        model: None,
1214                                        provider: None,
1215                                    };
1216                                }
1217
1218                            // A refusal is the turn's answer text; it never encodes a tool call.
1219                            if let Some(refusal) = delta.get("refusal").and_then(|v| v.as_str())
1220                                && !refusal.is_empty() {
1221                                    refused = true;
1222                                    yield LlmResponse {
1223                                        content: Some(Content {
1224                                            role: "model".to_string(),
1225                                            parts: vec![Part::Text { text: refusal.to_string() }],
1226                                        }),
1227                                        partial: true,
1228                                        turn_complete: false,
1229                                        ..Default::default()
1230                                    };
1231                                }
1232
1233                            // Check for finish_reason → emit final response.
1234                            if let Some(ref fr) = finish_reason_str {
1235                                if fr == "error" {
1236                                    Err(crate::stream_error::reported(
1237                                        &provider_name,
1238                                        error_codes.stream_error,
1239                                        &serde_json::Value::Null,
1240                                    ))?;
1241                                }
1242                                finished = true;
1243                                let finish_reason = Some(if refused {
1244                                    FinishReason::Refusal
1245                                } else {
1246                                    parse_finish_reason(fr)
1247                                });
1248                                let provider_metadata = (!logprobs.is_empty()).then(|| {
1249                                    serde_json::json!({
1250                                        "logprobs": {"content": std::mem::take(&mut logprobs)}
1251                                    })
1252                                });
1253
1254                                // Emit accumulated tool calls if any.
1255                                if !tool_call_accumulators.is_empty() {
1256                                    let mut sorted_calls: Vec<_> =
1257                                        tool_call_accumulators.drain().collect();
1258                                    sorted_calls.sort_by_key(|(idx, _)| *idx);
1259
1260                                    let parts: Vec<Part> = sorted_calls
1261                                        .into_iter()
1262                                        .map(|(_, (id, name, args_str))| {
1263                                            let args = crate::tool_args::streamed_tool_arguments(
1264                                                &provider_name,
1265                                                &name,
1266                                                &args_str,
1267                                            );
1268                                            Part::FunctionCall {
1269                                                name,
1270                                                args,
1271                                                id: Some(id),
1272                                                thought_signature: None,
1273                                            }
1274                                        })
1275                                        .collect();
1276
1277                                    let mut buffered = text_tool_buffer.flush();
1278                                    buffered.extend(parts);
1279                                    let response = LlmResponse {
1280                                        content: Some(Content {
1281                                            role: "model".to_string(),
1282                                            parts: buffered,
1283                                        }),
1284                                        usage_metadata,
1285                                        finish_reason,
1286                                        citation_metadata: None,
1287                                        partial: false,
1288                                        // Tool-call turns are not complete — tool
1289                                        // results must still be processed (issue #401).
1290                                        turn_complete: false,
1291                                        interrupted: false,
1292                                        error_code: None,
1293                                        error_message: None,
1294                                        provider_metadata,
1295                                        interaction_id: None,
1296                                        model: None,
1297                                        provider: None,
1298                                    };
1299                                    yield response;
1300                                    continue;
1301                                }
1302
1303                                // Flush literal prefixes before the final becomes authoritative.
1304                                let mut parts = text_tool_buffer.flush();
1305                                if let Some(text) = delta.get("content").and_then(|v| v.as_str())
1306                                    && !text.is_empty() {
1307                                        parts.push(Part::Text { text: text.to_string() });
1308                                    }
1309
1310                                let response = LlmResponse {
1311                                    content: if parts.is_empty() { None } else {
1312                                        Some(Content {
1313                                            role: "model".to_string(),
1314                                            parts,
1315                                        })
1316                                    },
1317                                    usage_metadata,
1318                                    finish_reason,
1319                                    citation_metadata: None,
1320                                    partial: false,
1321                                    turn_complete: true,
1322                                    interrupted: false,
1323                                    error_code: None,
1324                                    error_message: None,
1325                                    provider_metadata,
1326                                    interaction_id: None,
1327                                    model: None,
1328                                    provider: None,
1329                                };
1330                                yield response;
1331                                continue;
1332                            }
1333
1334                            // Emit partial text content via tool call buffer.
1335                            // The buffer detects <tool_call> tags split across chunks
1336                            // and converts them to Part::FunctionCall.
1337                            if let Some(text) = delta.get("content").and_then(|v| v.as_str())
1338                                && !text.is_empty() {
1339                                    match text_tool_buffer.push(text) {
1340                                        crate::tool_call_parser::BufferAction::Emit(parts) => {
1341                                            for part in parts {
1342                                                let is_tool = matches!(part, Part::FunctionCall { .. });
1343                                                yield LlmResponse {
1344                                                    content: Some(Content {
1345                                                        role: "model".to_string(),
1346                                                        parts: vec![part],
1347                                                    }),
1348                                                    usage_metadata: None,
1349                                                    finish_reason: None,
1350                                                    citation_metadata: None,
1351                                                    partial: !is_tool,
1352                                                    turn_complete: false,
1353                                                    interrupted: false,
1354                                                    error_code: None,
1355                                                    error_message: None,
1356                                                    provider_metadata: None,
1357                                                    interaction_id: None,
1358                                                    model: None,
1359                                                    provider: None,
1360                                                };
1361                                            }
1362                                        }
1363                                        crate::tool_call_parser::BufferAction::Buffering => {
1364                                            // Still accumulating a potential tool call
1365                                        }
1366                                    }
1367                                }
1368                        }
1369                    }
1370                }
1371
1372                if !finished {
1373                    Err(crate::stream_error::incomplete(
1374                        &provider_name,
1375                        error_codes.incomplete_stream,
1376                        if tool_call_accumulators.is_empty() {
1377                            "the response finished"
1378                        } else {
1379                            "its tool calls finished"
1380                        },
1381                    ))?;
1382                }
1383
1384                // Flush any remaining buffered content from the tool call buffer
1385                for part in text_tool_buffer.flush() {
1386                    let is_tool = matches!(part, Part::FunctionCall { .. });
1387                    yield LlmResponse {
1388                        content: Some(Content {
1389                            role: "model".to_string(),
1390                            parts: vec![part],
1391                        }),
1392                        usage_metadata: None,
1393                        finish_reason: if is_tool { Some(adk_core::FinishReason::Stop) } else { None },
1394                        citation_metadata: None,
1395                        partial: !is_tool,
1396                        turn_complete: false,
1397                        interrupted: false,
1398                        error_code: None,
1399                        error_message: None,
1400                        provider_metadata: None,
1401                        interaction_id: None,
1402                        model: None,
1403                        provider: None,
1404                    };
1405                }
1406            };
1407
1408            Ok(crate::usage_tracking::with_priced_usage_tracking(
1409                crate::usage_tracking::with_terminal_usage(Box::pin(response_stream)),
1410                usage_span,
1411                attribution.0,
1412                attribution.1,
1413            ))
1414        } else {
1415            // ── Non-streaming path (preserved identically) ──────────
1416            let response_stream = try_stream! {
1417                let response = execute_with_retry(&retry_config, is_retryable_model_error, || {
1418                    let model = model.clone();
1419                    let provider_name = provider_name.clone();
1420                    let http = http.clone();
1421                    let target = target.clone();
1422                    let body = request_body.clone();
1423                    async move {
1424                        let http_resp = send_request(&http, &target, &body).await?;
1425
1426                        let bytes = http_resp.bytes().await.map_err(|e| {
1427                            AdkError::new(
1428                                ErrorComponent::Model,
1429                                crate::http_timeouts::transport_category(&e),
1430                                error_codes.request,
1431                                format!("{provider_name} response could not be read: {e}"),
1432                            )
1433                            .with_provider(&provider_name)
1434                        })?;
1435                        let raw_json: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| {
1436                            AdkError::new(
1437                                ErrorComponent::Model,
1438                                ErrorCategory::Internal,
1439                                error_codes.parse,
1440                                format!(
1441                                    "{provider_name} response parse error: {}",
1442                                    adk_core::json_error_summary(&e)
1443                                ),
1444                            )
1445                            .with_provider(&provider_name)
1446                        })?;
1447
1448                        tracing::debug!(
1449                            provider = %provider_name,
1450                            model = %model,
1451                            has_reasoning = raw_json
1452                                .pointer("/choices/0/message/reasoning_content")
1453                                .is_some(),
1454                            "openai chat completion response"
1455                        );
1456
1457                        Ok(raw_json)
1458                    }
1459                })
1460                .await?;
1461
1462                // Some providers answer HTTP 200 with an error object or an `error` finish.
1463                let reported_error = response.get("error").filter(|error| !error.is_null()).or_else(|| {
1464                    (response.pointer("/choices/0/finish_reason").and_then(serde_json::Value::as_str)
1465                        == Some("error"))
1466                    .then_some(&serde_json::Value::Null)
1467                });
1468                if let Some(error) = reported_error {
1469                    Err(crate::stream_error::reported(&provider_name, error_codes.stream_error, error))?;
1470                }
1471
1472                yield convert::from_raw_openai_response(
1473                    &provider_name,
1474                    &response,
1475                    &declared_tools,
1476                );
1477            };
1478
1479            Ok(crate::usage_tracking::with_priced_usage_tracking(
1480                Box::pin(response_stream),
1481                usage_span,
1482                attribution.0,
1483                attribution.1,
1484            ))
1485        }
1486    }
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491    use super::*;
1492    use adk_core::{GenericSchemaAdapter, LlmRequest, SchemaCache};
1493    use std::sync::Arc;
1494
1495    mod sse_lines {
1496        use super::take_line;
1497
1498        #[test]
1499        fn preserves_every_split() {
1500            let expected = r#"data: {"text":"é中文🙂�","arguments":"{\"path\":\"资料.txt\",\"text\":\"改动🙂\"}"}"#;
1501            let framed = format!("{expected}\r\n");
1502            for split in 0..framed.len() {
1503                let mut buffer = framed.as_bytes()[..split].to_vec();
1504                assert_eq!(take_line(&mut buffer).unwrap(), None);
1505                buffer.extend_from_slice(&framed.as_bytes()[split..]);
1506                assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some(expected));
1507                assert!(buffer.is_empty());
1508            }
1509        }
1510
1511        #[test]
1512        fn accepts_bytewise_delivery() {
1513            let expected = "data: 中文🙂é";
1514            let mut buffer = Vec::new();
1515            for byte in expected.as_bytes() {
1516                buffer.push(*byte);
1517                assert_eq!(take_line(&mut buffer).unwrap(), None);
1518            }
1519            buffer.push(b'\n');
1520            assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some(expected));
1521            assert!(buffer.is_empty());
1522        }
1523
1524        #[test]
1525        fn leaves_following_lines() {
1526            let mut buffer = "data: 第一行\r\n\r\ndata: 第二行🙂\n".as_bytes().to_vec();
1527            assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some("data: 第一行"));
1528            assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some(""));
1529            assert_eq!(take_line(&mut buffer).unwrap().as_deref(), Some("data: 第二行🙂"));
1530            assert_eq!(take_line(&mut buffer).unwrap(), None);
1531        }
1532
1533        #[test]
1534        fn rejects_invalid_utf8() {
1535            for invalid in [b"data: \xc3(\n".as_slice(), b"data: \xf0\x9f\n".as_slice()] {
1536                assert!(take_line(&mut invalid.to_vec()).is_err());
1537            }
1538        }
1539    }
1540
1541    #[test]
1542    fn test_parallel_tool_calls_config() {
1543        let config =
1544            OpenAICompatibleConfig::new("test-key", "test-model").with_parallel_tool_calls(false);
1545
1546        assert!(!config.parallel_tool_calls, "parallel_tool_calls should be false in config");
1547
1548        let client = OpenAICompatible::new(config).expect("client creation failed");
1549        assert!(!client.parallel_tool_calls, "parallel_tool_calls should be false in client");
1550    }
1551
1552    #[test]
1553    fn test_parallel_tool_calls_default() {
1554        let config = OpenAICompatibleConfig::new("test-key", "test-model");
1555
1556        assert!(config.parallel_tool_calls, "parallel_tool_calls should default to true");
1557
1558        let client = OpenAICompatible::new(config).expect("client creation failed");
1559        assert!(client.parallel_tool_calls, "parallel_tool_calls should default to true in client");
1560    }
1561
1562    #[test]
1563    fn streamed_tool_arguments_require_valid_json() {
1564        let parse = |name: &str, arguments: &str| {
1565            crate::tool_args::streamed_tool_arguments("compatible-provider", name, arguments)
1566        };
1567        assert_eq!(parse("bash", r#"{"command":"pwd"}"#)["command"], "pwd");
1568        for empty in ["", "   ", "[]"] {
1569            assert_eq!(parse("no_args", empty), serde_json::json!({}), "{empty:?}");
1570        }
1571        // A truncated or non-object payload is marked, never run with substituted arguments.
1572        for malformed in [r#"{"command":"#, r#"["pwd"]"#] {
1573            let args = parse("bash", malformed);
1574            assert!(adk_core::invalid_tool_arguments_reason(&args).is_some(), "{malformed:?}");
1575        }
1576    }
1577
1578    #[test]
1579    fn streamed_structured_tool_arguments_are_canonicalized() {
1580        let mut arguments = String::new();
1581        append_tool_call_arguments(&mut arguments, &serde_json::json!({"command": "pwd"}));
1582
1583        assert_eq!(
1584            crate::tool_args::streamed_tool_arguments("compatible-provider", "bash", &arguments),
1585            serde_json::json!({"command": "pwd"})
1586        );
1587    }
1588
1589    #[test]
1590    fn streamed_empty_snapshot_before_string_fragments_is_ignored() {
1591        for placeholder in [serde_json::json!({}), serde_json::json!([])] {
1592            let mut arguments = String::new();
1593            append_tool_call_arguments(&mut arguments, &placeholder);
1594            assert_eq!(
1595                crate::tool_args::streamed_tool_arguments(
1596                    "compatible-provider",
1597                    "no_args",
1598                    &arguments
1599                ),
1600                serde_json::json!({})
1601            );
1602
1603            append_tool_call_arguments(&mut arguments, &serde_json::json!(r#"{"command""#));
1604            append_tool_call_arguments(&mut arguments, &serde_json::json!(r#": "pwd"}"#));
1605
1606            assert_eq!(
1607                crate::tool_args::streamed_tool_arguments(
1608                    "compatible-provider",
1609                    "bash",
1610                    &arguments
1611                ),
1612                serde_json::json!({"command": "pwd"})
1613            );
1614        }
1615    }
1616
1617    #[test]
1618    fn gpt_56_chat_tools_preserve_configured_reasoning() {
1619        let adapter = GenericSchemaAdapter;
1620        let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
1621        let mut request = LlmRequest {
1622            model: crate::catalog::OPENAI_DEFAULT.to_string(),
1623            contents: Vec::new(),
1624            config: None,
1625            tools: adk_core::ToolDeclarations::new(),
1626            previous_response_id: None,
1627        };
1628        request.tools.insert(
1629            "lookup".to_string(),
1630            serde_json::json!({
1631                "description": "Look up a record",
1632                "parameters": {"type": "object", "properties": {}}
1633            }),
1634        );
1635
1636        for (configured_effort, expected) in [
1637            (None, None),
1638            (Some(OpenAIReasoningEffort::Medium), Some("medium")),
1639            (Some(OpenAIReasoningEffort::Max), Some("max")),
1640        ] {
1641            let body = build_request_json(
1642                crate::catalog::OPENAI_DEFAULT,
1643                &request,
1644                &configured_effort,
1645                ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
1646                None,
1647                &adapter,
1648                &cache,
1649            )
1650            .expect("request should build");
1651
1652            assert_eq!(body.get("reasoning_effort").and_then(serde_json::Value::as_str), expected);
1653        }
1654    }
1655
1656    #[test]
1657    fn gpt_56_without_tools_keeps_server_reasoning_default() {
1658        let adapter = GenericSchemaAdapter;
1659        let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
1660        let request = LlmRequest {
1661            model: crate::catalog::OPENAI_DEFAULT.to_string(),
1662            contents: Vec::new(),
1663            config: None,
1664            tools: adk_core::ToolDeclarations::new(),
1665            previous_response_id: None,
1666        };
1667
1668        let body = build_request_json(
1669            crate::catalog::OPENAI_DEFAULT,
1670            &request,
1671            &None,
1672            ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
1673            None,
1674            &adapter,
1675            &cache,
1676        )
1677        .expect("request should build");
1678
1679        assert!(body.get("reasoning_effort").is_none());
1680    }
1681
1682    #[test]
1683    fn gpt_56_chat_serializes_max_reasoning() {
1684        let adapter = GenericSchemaAdapter;
1685        let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
1686        let request = LlmRequest {
1687            model: crate::catalog::OPENAI_DEFAULT.to_string(),
1688            contents: Vec::new(),
1689            config: None,
1690            tools: adk_core::ToolDeclarations::new(),
1691            previous_response_id: None,
1692        };
1693
1694        let body = build_request_json(
1695            crate::catalog::OPENAI_DEFAULT,
1696            &request,
1697            &Some(OpenAIReasoningEffort::Max),
1698            ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
1699            None,
1700            &adapter,
1701            &cache,
1702        )
1703        .expect("request should build");
1704
1705        assert_eq!(body["reasoning_effort"], "max");
1706    }
1707
1708    #[test]
1709    fn gemini_37_compatible_path_rejects_sampling_locally() {
1710        for model in ["gemini-3.7-flash", "gemini-3.8-flash"] {
1711            let mut request = LlmRequest::new(model, Vec::new());
1712            request.config =
1713                Some(adk_core::GenerateContentConfig { top_p: Some(0.9), ..Default::default() });
1714            let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
1715
1716            let error = build_request_json(
1717                model,
1718                &request,
1719                &None,
1720                ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
1721                None,
1722                &GenericSchemaAdapter,
1723                &cache,
1724            )
1725            .expect_err("sampling should be rejected before network I/O");
1726
1727            assert_eq!(error.code, "model.gemini.sampling_unsupported", "{model}");
1728        }
1729    }
1730
1731    #[test]
1732    fn orcarouter_preset_sets_endpoint_and_provider() {
1733        let config = OpenAICompatibleConfig::orcarouter("test-key", "openai/gpt-5.6-terra");
1734        assert_eq!(config.provider_name, "orcarouter");
1735        assert_eq!(config.model, "openai/gpt-5.6-terra");
1736        assert_eq!(config.base_url.as_deref(), Some("https://api.orcarouter.ai/v1"));
1737        assert_eq!(config.api_key, "test-key");
1738
1739        let client = OpenAICompatible::new(config).expect("client builds");
1740        assert_eq!(client.name(), "openai/gpt-5.6-terra");
1741    }
1742
1743    #[test]
1744    fn vultr_preset_sets_endpoint_and_provider() {
1745        let config = OpenAICompatibleConfig::vultr("test-key", "qwen3.8-27b");
1746        assert_eq!(config.provider_name, "vultr");
1747        assert_eq!(config.model, "qwen3.8-27b");
1748        assert_eq!(config.base_url.as_deref(), Some("https://api.vultrinference.com/v1"));
1749        assert_eq!(config.api_key, "test-key");
1750
1751        let client = OpenAICompatible::new(config).expect("client builds");
1752        assert_eq!(client.name(), "qwen3.8-27b");
1753    }
1754
1755    #[test]
1756    fn api_route_preset_sets_endpoint_and_provider() {
1757        let config = OpenAICompatibleConfig::api_route("test-key", "gpt-6.1-sol");
1758        assert_eq!(config.provider_name, "api-route");
1759        assert_eq!(config.model, "gpt-6.1-sol");
1760        assert_eq!(config.base_url.as_deref(), Some("https://global.api-route.com/v1"));
1761        assert_eq!(config.api_key, "test-key");
1762
1763        let client = OpenAICompatible::new(config).expect("client builds");
1764        assert_eq!(client.name(), "gpt-6.1-sol");
1765    }
1766
1767    #[test]
1768    fn gemini_preset_sets_endpoint_and_provider() {
1769        let config = OpenAICompatibleConfig::gemini("test-key", "gemini-3.5-flash");
1770        assert_eq!(config.provider_name, "gemini");
1771        assert_eq!(config.model, "gemini-3.5-flash");
1772        assert_eq!(
1773            config.base_url.as_deref(),
1774            Some("https://generativelanguage.googleapis.com/v1beta/openai")
1775        );
1776        assert_eq!(config.api_key, "test-key");
1777    }
1778
1779    #[test]
1780    fn gemini_preset_supports_reasoning_effort() {
1781        // Gemini's OpenAI-compat layer maps reasoning_effort onto thinking levels.
1782        let config = OpenAICompatibleConfig::gemini("k", "gemini-3.5-flash")
1783            .with_reasoning_effort(OaiReasoningEffort::Low);
1784        assert_eq!(config.reasoning_effort, Some(OaiReasoningEffort::Low));
1785    }
1786
1787    #[test]
1788    fn gemini_preset_builds_client() {
1789        let config = OpenAICompatibleConfig::gemini("k", "gemini-3.5-flash");
1790        let client = OpenAICompatible::new(config).expect("client builds");
1791        assert_eq!(client.name(), "gemini-3.5-flash");
1792    }
1793
1794    fn chat_body(contents: Vec<Content>) -> serde_json::Value {
1795        let request = LlmRequest::new("gpt-4.1-mini", contents);
1796        let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
1797        build_request_json(
1798            "gpt-4.1-mini",
1799            &request,
1800            &None,
1801            ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
1802            Some(ReasoningReplayField::ReasoningContent),
1803            &GenericSchemaAdapter,
1804            &cache,
1805        )
1806        .expect("request should build")
1807    }
1808
1809    fn response(id: &str, value: serde_json::Value) -> Part {
1810        Part::FunctionResponse {
1811            function_response: adk_core::FunctionResponseData::new("get_weather", value),
1812            id: Some(id.to_string()),
1813            annotations: None,
1814        }
1815    }
1816
1817    #[test]
1818    fn several_function_responses_become_one_tool_message_each() {
1819        let call = |id: &str| Part::FunctionCall {
1820            name: "get_weather".to_string(),
1821            args: serde_json::json!({"city": id}),
1822            id: Some(id.to_string()),
1823            thought_signature: None,
1824        };
1825        let body = chat_body(vec![
1826            Content::new("user").with_text("Weather in Paris and Tokyo?"),
1827            Content {
1828                role: "model".to_string(),
1829                parts: vec![
1830                    Part::Thinking { thinking: "two cities".to_string(), signature: None },
1831                    call("call_paris"),
1832                    call("call_tokyo"),
1833                ],
1834            },
1835            Content {
1836                role: "function".to_string(),
1837                parts: vec![
1838                    response("call_paris", serde_json::json!({"error": "not run"})),
1839                    response("call_tokyo", serde_json::json!({"error": "not run"})),
1840                    Part::Text { text: "Both calls were refused.".to_string() },
1841                ],
1842            },
1843            Content::new("model").with_text("I could not check."),
1844        ]);
1845
1846        let messages = body["messages"].as_array().expect("messages");
1847        let shape: Vec<(String, Option<String>)> = messages
1848            .iter()
1849            .map(|message| {
1850                (
1851                    message["role"].as_str().unwrap_or_default().to_string(),
1852                    message["tool_call_id"].as_str().map(str::to_string),
1853                )
1854            })
1855            .collect();
1856        assert_eq!(
1857            shape,
1858            vec![
1859                ("user".to_string(), None),
1860                ("assistant".to_string(), None),
1861                ("tool".to_string(), Some("call_paris".to_string())),
1862                ("tool".to_string(), Some("call_tokyo".to_string())),
1863                ("user".to_string(), None),
1864                ("assistant".to_string(), None),
1865            ]
1866        );
1867        assert_eq!(messages[4]["content"], "Both calls were refused.");
1868        // Reasoning stays on the assistant message its content became.
1869        assert_eq!(messages[1]["reasoning_content"], "two cities");
1870        assert!(messages[5].get("reasoning_content").is_none());
1871    }
1872
1873    #[test]
1874    fn user_role_function_responses_are_tool_messages() {
1875        let body = chat_body(vec![Content {
1876            role: "user".to_string(),
1877            parts: vec![response("call_1", serde_json::json!({"ok": true}))],
1878        }]);
1879        assert_eq!(body["messages"][0]["role"], "tool");
1880        assert_eq!(body["messages"][0]["tool_call_id"], "call_1");
1881        assert_eq!(body["messages"].as_array().map(Vec::len), Some(1));
1882    }
1883
1884    #[test]
1885    fn generation_config_fields_reach_the_chat_request() {
1886        let mut request =
1887            LlmRequest::new("gpt-4.1-mini", vec![Content::new("user").with_text("hi")]);
1888        request.config = Some(adk_core::GenerateContentConfig {
1889            stop_sequences: vec!["7".to_string()],
1890            seed: Some(42),
1891            presence_penalty: Some(0.5),
1892            frequency_penalty: Some(0.25),
1893            top_logprobs: Some(2),
1894            ..Default::default()
1895        });
1896        let cache = SchemaCache::for_adapter(Arc::new(GenericSchemaAdapter));
1897        let body = build_request_json(
1898            "gpt-4.1-mini",
1899            &request,
1900            &None,
1901            ChatCapabilities { parallel_tool_calls: true, native_pdf: false },
1902            None,
1903            &GenericSchemaAdapter,
1904            &cache,
1905        )
1906        .expect("request should build");
1907
1908        assert_eq!(body["stop"], serde_json::json!(["7"]));
1909        assert_eq!(body["seed"], 42);
1910        assert_eq!(body["presence_penalty"], 0.5);
1911        assert_eq!(body["frequency_penalty"], 0.25);
1912        assert_eq!(body["logprobs"], true);
1913        assert_eq!(body["top_logprobs"], 2);
1914    }
1915
1916    #[test]
1917    fn returned_logprobs_are_kept_in_provider_metadata() {
1918        let raw = serde_json::json!({
1919            "model": "gpt-4.1-mini",
1920            "choices": [{
1921                "index": 0,
1922                "message": {"role": "assistant", "content": "1"},
1923                "logprobs": {"content": [{"token": "1", "logprob": -0.01, "top_logprobs": []}]},
1924                "finish_reason": "stop"
1925            }]
1926        });
1927        let response = convert::from_raw_openai_response("openai", &raw, &Default::default());
1928        assert_eq!(response.provider_metadata.unwrap()["logprobs"]["content"][0]["token"], "1");
1929    }
1930}