Skip to main content

adk_model/openai/
client.rs

1//! OpenAI client implementation.
2
3use super::config::{OpenAIConfig, OpenAIReasoningEffort, OpenAIResponsesConfig};
4use super::responses_client::OpenAIResponsesClient;
5use super::schema_adapter::OpenAiSchemaAdapter;
6use crate::openai_compatible::{OpenAICompatible, OpenAICompatibleConfig};
7use crate::retry::RetryConfig;
8use adk_core::{
9    AdkError, ErrorCategory, ErrorComponent, Llm, LlmRequest, LlmResponseStream, SchemaAdapter,
10};
11use async_trait::async_trait;
12
13/// OpenAI client for standard OpenAI API and OpenAI-compatible APIs.
14///
15/// Requests go to Chat Completions (`/chat/completions`). OpenAI's Chat Completions
16/// endpoint rejects function tools on GPT-5.6 and later models unless reasoning is
17/// disabled, so a client built with [`OpenAIClient::new`] for one of those models
18/// sends every request that declares tools through the Responses API
19/// (`/responses`) instead, with the same credentials, base URL, reasoning effort,
20/// and retry policy. Routed requests set `store: false`, matching the Chat
21/// Completions default of not storing responses. Requests without tools, models
22/// before GPT-5.6, reasoning effort [`OpenAIReasoningEffort::None`], and clients
23/// built with [`OpenAIClient::compatible`] stay on Chat Completions.
24///
25/// # Example
26///
27/// ```
28/// use adk_model::openai::{OpenAIClient, OpenAIConfig};
29///
30/// // Tool-carrying requests for this model use the Responses API automatically.
31/// let client = OpenAIClient::new(OpenAIConfig::new("sk-key", "gpt-6.1-sol"))?;
32/// # Ok::<(), adk_core::AdkError>(())
33/// ```
34pub struct OpenAIClient {
35    inner: OpenAICompatible,
36    /// Responses API client for requests that declare tools, present only when the
37    /// model's Chat Completions endpoint rejects function tools with reasoning on.
38    tool_route: Option<OpenAIResponsesClient>,
39    /// The configured reasoning effort, which decides whether a request reasons.
40    reasoning_effort: Option<OpenAIReasoningEffort>,
41}
42
43/// Returns whether OpenAI Chat Completions rejects function tools for `model` while
44/// reasoning is enabled, which applies to GPT-5.6 and every later GPT generation.
45///
46/// The API answers such a request with HTTP 400: "Function tools with
47/// reasoning_effort are not supported for <model> in /v1/chat/completions".
48fn chat_rejects_reasoning_tools(model: &str) -> bool {
49    let model = model.strip_prefix("ft:").unwrap_or(model);
50    let Some(version) = model.strip_prefix("gpt-") else {
51        return false;
52    };
53    let version_end =
54        version.find(|c: char| !c.is_ascii_digit() && c != '.').unwrap_or(version.len());
55    let mut numbers = version[..version_end].split('.').map(str::parse::<u32>);
56    match (numbers.next(), numbers.next()) {
57        (Some(Ok(major)), Some(Ok(minor))) => (major, minor) >= (5, 6),
58        (Some(Ok(major)), None) => major >= 6,
59        _ => false,
60    }
61}
62
63impl OpenAIClient {
64    /// Create a new OpenAI client.
65    pub fn new(config: OpenAIConfig) -> Result<Self, AdkError> {
66        crate::catalog::warn_if_obsolete("openai", &config.model);
67        let reasoning_effort = config.reasoning_effort.map(OpenAIReasoningEffort::from);
68
69        Self::new_inner(config, reasoning_effort)
70    }
71
72    /// Create a client with the complete OpenAI reasoning-effort vocabulary.
73    ///
74    /// Use this constructor for newer Chat Completions values such as
75    /// [`OpenAIReasoningEffort::None`] or [`OpenAIReasoningEffort::XHigh`].
76    /// [`OpenAIReasoningEffort::Max`] is supported by the Responses API, not
77    /// Chat Completions. The original [`OpenAIConfig::reasoning_effort`] field
78    /// remains available for backward compatibility.
79    pub fn new_with_reasoning_effort(
80        config: OpenAIConfig,
81        reasoning_effort: OpenAIReasoningEffort,
82    ) -> Result<Self, AdkError> {
83        crate::catalog::warn_if_obsolete("openai", &config.model);
84        if reasoning_effort == OpenAIReasoningEffort::Max {
85            return Err(AdkError::new(
86                ErrorComponent::Model,
87                ErrorCategory::InvalidInput,
88                "model.openai.reasoning_effort_unsupported",
89                "OpenAI Chat Completions does not support reasoning effort `max`; use OpenAIResponsesClient for `max`, or use `xhigh` with OpenAIClient",
90            )
91            .with_provider("openai"));
92        }
93        Self::new_inner(config, Some(reasoning_effort))
94    }
95
96    fn new_inner(
97        config: OpenAIConfig,
98        reasoning_effort: Option<OpenAIReasoningEffort>,
99    ) -> Result<Self, AdkError> {
100        // An empty key cannot build the Responses client; the request then fails
101        // authentication on Chat Completions exactly as before. A client configured with
102        // reasoning off still gets the route: a request's effort turns reasoning on for that
103        // call (spec 3.1 §7.23).
104        let tool_route =
105            if chat_rejects_reasoning_tools(&config.model) && !config.api_key.is_empty() {
106                let mut responses_config =
107                    OpenAIResponsesConfig::new(config.api_key.clone(), config.model.clone());
108                responses_config.organization_id.clone_from(&config.organization_id);
109                responses_config.project_id.clone_from(&config.project_id);
110                responses_config.base_url.clone_from(&config.base_url);
111                let client = match reasoning_effort {
112                    Some(effort) => {
113                        OpenAIResponsesClient::new_with_reasoning_effort(responses_config, effort)?
114                    }
115                    None => OpenAIResponsesClient::new(responses_config)?,
116                };
117                // Chat Completions does not store responses by default; keep that.
118                let store_off: super::RequestAdapter = std::sync::Arc::new(|body, _headers| {
119                    if let Some(body) = body.as_object_mut() {
120                        body.entry("store").or_insert(serde_json::Value::Bool(false));
121                    }
122                    Ok(())
123                });
124                Some(client.with_request_adapter(store_off))
125            } else {
126                None
127            };
128        let mut compat_config =
129            OpenAICompatibleConfig::new(config.api_key, config.model).with_provider_name("openai");
130        if let Some(base_url) = config.base_url {
131            compat_config = compat_config.with_base_url(base_url);
132        }
133        if let Some(org_id) = config.organization_id {
134            compat_config = compat_config.with_organization(org_id);
135        }
136        if let Some(project_id) = config.project_id {
137            compat_config = compat_config.with_project(project_id);
138        }
139        Ok(Self {
140            inner: OpenAICompatible::new_with_reasoning_effort(compat_config, reasoning_effort)?,
141            tool_route,
142            reasoning_effort,
143        })
144    }
145
146    /// Create a client for an OpenAI-compatible API.
147    pub fn compatible(
148        api_key: impl Into<String>,
149        base_url: impl Into<String>,
150        model: impl Into<String>,
151    ) -> Result<Self, AdkError> {
152        let config = OpenAICompatibleConfig::new(api_key, model)
153            .with_provider_name("openai-compatible")
154            .with_base_url(base_url);
155        Ok(Self { inner: OpenAICompatible::new(config)?, tool_route: None, reasoning_effort: None })
156    }
157
158    /// Set the retry configuration (builder pattern).
159    #[must_use]
160    pub fn with_retry_config(mut self, retry_config: RetryConfig) -> Self {
161        self.tool_route =
162            self.tool_route.map(|route| route.with_retry_config(retry_config.clone()));
163        self.inner = self.inner.with_retry_config(retry_config);
164        self
165    }
166
167    /// Set the retry configuration (mutable reference).
168    pub fn set_retry_config(&mut self, retry_config: RetryConfig) {
169        if let Some(route) = &mut self.tool_route {
170            route.set_retry_config(retry_config.clone());
171        }
172        self.inner.set_retry_config(retry_config);
173    }
174
175    /// Returns the current retry configuration.
176    pub fn retry_config(&self) -> &RetryConfig {
177        self.inner.retry_config()
178    }
179
180    /// Sets the connect and idle timeouts of the Chat Completions transport and of the
181    /// Responses route, so a stalled stream fails instead of holding the run.
182    ///
183    /// See [`HttpTimeouts`](crate::HttpTimeouts) for the defaults.
184    ///
185    /// # Example
186    ///
187    /// ```
188    /// use std::time::Duration;
189    ///
190    /// use adk_model::openai::{OpenAIClient, OpenAIConfig};
191    /// use adk_model::HttpTimeouts;
192    ///
193    /// let client = OpenAIClient::new(OpenAIConfig::new("sk-key", "gpt-6.1-sol"))?
194    ///     .with_timeouts(HttpTimeouts::new(Duration::from_secs(10), Duration::from_secs(120)))?;
195    /// # let _ = client;
196    /// # Ok::<(), adk_core::AdkError>(())
197    /// ```
198    ///
199    /// # Errors
200    ///
201    /// Returns an `Internal` error with code `model.openai.http_client_init` when an HTTP
202    /// client cannot be built.
203    pub fn with_timeouts(mut self, timeouts: crate::HttpTimeouts) -> Result<Self, AdkError> {
204        self.inner = self.inner.with_timeouts(timeouts)?;
205        self.tool_route = self.tool_route.map(|route| route.with_timeouts(timeouts)).transpose()?;
206        Ok(self)
207    }
208}
209
210#[async_trait]
211impl Llm for OpenAIClient {
212    fn max_cost_micro_usd(&self, request: &adk_core::LlmRequest) -> Option<u64> {
213        self.inner.max_cost_micro_usd(request)
214    }
215
216    fn context_window(&self) -> Option<u64> {
217        self.inner.context_window()
218    }
219
220    // The tool route shares the configured base URL.
221    fn data_locality(&self) -> adk_core::DataLocality {
222        self.inner.data_locality()
223    }
224
225    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
226        self.inner.data_destinations()
227    }
228
229    fn name(&self) -> &str {
230        self.inner.name()
231    }
232
233    fn schema_adapter(&self) -> &dyn SchemaAdapter {
234        static ADAPTER: OpenAiSchemaAdapter = OpenAiSchemaAdapter;
235        &ADAPTER
236    }
237
238    #[tracing::instrument(
239        name = "model.generate_content",
240        skip_all,
241        fields(
242            model.name = %self.name(),
243            stream = %stream,
244            request.contents_count = %request.contents.len(),
245            request.tools_count = %request.tools.len()
246        )
247    )]
248    async fn generate_content(
249        &self,
250        request: LlmRequest,
251        stream: bool,
252    ) -> Result<LlmResponseStream, AdkError> {
253        // A request that disables reasoning through the `openai` extension is accepted
254        // by Chat Completions, so it keeps the endpoint the caller configured; so is one
255        // on a client configured with reasoning off, unless the request sets an effort.
256        let config = request.config.as_ref();
257        let reasoning_disabled = config
258            .and_then(|config| config.extensions.get("openai"))
259            .and_then(|openai| openai.get("reasoning_effort"))
260            .and_then(serde_json::Value::as_str)
261            == Some("none")
262            || (config.and_then(|config| config.effort).is_none()
263                && self.reasoning_effort == Some(OpenAIReasoningEffort::None));
264        if let Some(route) = &self.tool_route
265            && !request.tools.is_empty()
266            && !reasoning_disabled
267        {
268            tracing::debug!(
269                model.name = %self.name(),
270                "chat completions rejects function tools for this model; using the responses api"
271            );
272            return route.generate_content(request, stream).await;
273        }
274        self.inner.generate_content(request, stream).await
275    }
276}
277
278#[cfg(test)]
279mod tests {
280    use super::*;
281
282    #[test]
283    fn chat_completions_rejects_responses_only_max_effort() {
284        let config = OpenAIConfig::new("test-key", "gpt-5.6-terra");
285        let error =
286            match OpenAIClient::new_with_reasoning_effort(config, OpenAIReasoningEffort::Max) {
287                Ok(_) => panic!("Chat Completions must reject max reasoning effort"),
288                Err(error) => error,
289            };
290
291        assert_eq!(error.code, "model.openai.reasoning_effort_unsupported");
292        assert!(error.to_string().contains("OpenAIResponsesClient"));
293    }
294
295    #[test]
296    fn gpt_5_6_and_later_need_the_responses_api_for_reasoning_tools() {
297        let rejecting = [
298            "gpt-5.6",
299            "gpt-5.6-terra",
300            "gpt-5.6-luna",
301            "gpt-5.6-sol",
302            "gpt-5.10",
303            "gpt-6-astra",
304            "gpt-6-luna",
305            "gpt-6.1-sol",
306            "ft:gpt-5.6-terra:acme::abc123",
307        ];
308        let accepting = [
309            "gpt-5.5",
310            "gpt-5.4",
311            "gpt-5",
312            "gpt-5-mini",
313            "gpt-4.1",
314            "gpt-4o-mini",
315            "gpt-oss-120b",
316            "gpt-realtime-2.1",
317            "o4-mini",
318            "llama-3.3-70b",
319        ];
320        assert_eq!(
321            rejecting.map(chat_rejects_reasoning_tools),
322            [true; 9],
323            "models that reject Chat Completions function tools: {rejecting:?}"
324        );
325        assert_eq!(
326            accepting.map(chat_rejects_reasoning_tools),
327            [false; 10],
328            "models that accept Chat Completions function tools: {accepting:?}"
329        );
330    }
331
332    #[test]
333    fn only_affected_openai_clients_build_a_responses_route() {
334        let routed = |config: OpenAIConfig| OpenAIClient::new(config).unwrap().tool_route.is_some();
335        assert!(routed(OpenAIConfig::new("test-key", crate::catalog::OPENAI_DEFAULT)));
336        assert!(!routed(OpenAIConfig::new("test-key", "gpt-5.5")));
337        assert!(!routed(OpenAIConfig::new("", "gpt-5.6-terra")));
338        let disabled = OpenAIClient::new_with_reasoning_effort(
339            OpenAIConfig::new("test-key", "gpt-5.6-terra"),
340            OpenAIReasoningEffort::None,
341        )
342        .unwrap();
343        // A request's effort turns reasoning on for one call (spec 3.1 §7.23), so the
344        // route exists; a request without one stays on Chat Completions.
345        assert!(disabled.tool_route.is_some());
346        let compatible =
347            OpenAIClient::compatible("test-key", "http://localhost:8000/v1", "gpt-6-astra")
348                .unwrap();
349        assert!(compatible.tool_route.is_none());
350    }
351}