Skip to main content

strands/models/openai/
mod.rs

1//! The OpenAI provider, behind the `openai` feature.
2//!
3//! [`OpenAIModel`] streams from the Responses API by default, or from Chat Completions with
4//! [`OpenAIApi::Chat`], over HTTP with the official OpenAI SDK's transport behaviour (retries,
5//! timeout, error texts). It maps every content block, the system prompt, tool specs and tool
6//! choice, prompt caching ([`CacheConfig`]), server-managed conversation state on the Responses API
7//! ([`OpenAIModelConfig::stateful`]) and OpenAI's built-in tools, such as the native `web_search`,
8//! through [`OpenAIModelConfig::params`]. With the `mantle` feature,
9//! [`OpenAIModel::bedrock_mantle`] routes the model through Amazon Bedrock's OpenAI-compatible
10//! Mantle endpoint.
11//!
12//! ```
13//! use strands::models::openai::{OpenAIApi, OpenAIModel};
14//! use strands::models::Model;
15//!
16//! # fn main() -> strands::Result<()> {
17//! // Responses API (default)
18//! let model = OpenAIModel::builder().model_id("gpt-5.4").api_key("sk-...").build()?;
19//! assert_eq!(model.model_id().as_deref(), Some("gpt-5.4"));
20//!
21//! // Chat Completions
22//! let chat = OpenAIModel::builder()
23//!     .api(OpenAIApi::Chat)
24//!     .model_id("gpt-5.4")
25//!     .api_key("sk-...")
26//!     .build()?;
27//! assert_eq!(chat.api(), OpenAIApi::Chat);
28//! # Ok(())
29//! # }
30//! ```
31//!
32//! An agent on the Responses API with the built-in web search (the API key comes from
33//! `OPENAI_API_KEY`):
34//!
35//! ```no_run
36//! use serde_json::json;
37//! use strands::Agent;
38//! use strands::models::openai::OpenAIModel;
39//!
40//! # async fn run() -> strands::Result<()> {
41//! let model = OpenAIModel::builder()
42//!     .model_id("gpt-5.4")
43//!     .params(json!({"tools": [{"type": "web_search"}]}))
44//!     .build()?;
45//! let mut agent = Agent::builder().model(model).build()?;
46//! let result = agent.invoke("What changed in the latest Rust release?").await?;
47//! println!("{result}");
48//! # Ok(())
49//! # }
50//! ```
51
52mod cache;
53mod chat;
54mod client;
55mod errors;
56mod formatting;
57#[cfg(feature = "mantle")]
58mod mantle;
59mod responses;
60
61use std::fmt;
62use std::future::Future;
63use std::sync::{Arc, PoisonError, RwLock};
64use std::time::Duration;
65
66use async_trait::async_trait;
67use futures::StreamExt;
68use futures::future::BoxFuture;
69
70use self::chat::{
71    ChatStreamState, apply_chat_completions_tools, format_chat_request, map_chat_chunk, responses_hint,
72    warn_chat_managed_params,
73};
74use self::client::{CHAT_COMPLETIONS_PATH, Env, EventStream, HttpOpenAIClient, OpenAIClient, RESPONSES_PATH};
75use self::errors::{OpenAIErrorKind, classify_openai_error};
76use self::formatting::{positive_count, token_count};
77use self::open_a_i_model_options_builder::IsComplete;
78
79use self::responses::{
80    REASONING_PROVIDER, ResponsesStreamError, ResponsesStreamState, finalize_responses_stream,
81    format_responses_request, map_responses_event, warn_responses_managed_params, without_rejected_reasoning,
82};
83use super::defaults::{MODEL_DEFAULTS, default_model_warning_message};
84use super::http::{HttpError, RedactedHeaders, read_env};
85use super::model_info::{ChatCompletionsTools, server_side_summary_off};
86use super::streaming::{ModelMetadataEvent, ModelStreamEvent, Usage};
87use super::{
88    BaseModelConfig, BoxStream, CacheConfig, Model, ModelCapabilities, ModelInfo, ModelRequest, base_model_info,
89    resolve_config_metadata,
90};
91use crate::cancel::CancelSignal;
92use crate::error::{
93    BoxError, ContextWindowOverflowError, Error, ModelError, ModelNetworkError, ModelThrottledError, Result,
94};
95use crate::logging::warn_once;
96use crate::types::JsonValue;
97
98#[cfg(feature = "mantle")]
99pub use aws_credential_types::Credentials;
100#[cfg(feature = "mantle")]
101pub use aws_credential_types::provider::SharedCredentialsProvider;
102#[cfg(feature = "mantle")]
103pub use mantle::BedrockMantleConfig;
104
105/// The message of a request cancelled through its signal (the SDK's `APIUserAbortError`).
106const ABORTED_MESSAGE: &str = "Request was aborted.";
107
108/// Which OpenAI API a model streams from (`OpenAIApi`).
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
110#[non_exhaustive]
111pub enum OpenAIApi {
112    /// Chat Completions (`'chat'`), always stateless.
113    Chat,
114    /// The Responses API (`'responses'`), optionally with server-managed conversation state.
115    #[default]
116    Responses,
117}
118
119impl OpenAIApi {
120    /// The API's name: `"chat"` or `"responses"`.
121    #[must_use]
122    pub fn as_str(self) -> &'static str {
123        match self {
124            Self::Chat => "chat",
125            Self::Responses => "responses",
126        }
127    }
128}
129
130impl fmt::Display for OpenAIApi {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        f.write_str(self.as_str())
133    }
134}
135
136crate::callback::callback! {
137    /// A function returning an API key, called before each request (the SDK's `ApiKeySetter`).
138    pub struct ApiKeySetter(Fn() -> BoxFuture<'static, std::result::Result<String, BoxError>>);
139}
140
141/// An OpenAI API key: a fixed key or a function called before each request. Strings convert into
142/// [`ApiKey::Key`].
143#[derive(Clone)]
144#[non_exhaustive]
145pub enum ApiKey {
146    /// A fixed key.
147    Key(String),
148    /// A function returning the key, called before each request.
149    Setter(ApiKeySetter),
150}
151
152impl ApiKey {
153    /// An API key resolved by `setter` before each request, such as a short-lived token.
154    pub fn setter<F, Fut>(setter: F) -> Self
155    where
156        F: Fn() -> Fut + Send + Sync + 'static,
157        Fut: Future<Output = std::result::Result<String, BoxError>> + Send + 'static,
158    {
159        Self::Setter(ApiKeySetter::new(move || Box::pin(setter())))
160    }
161}
162
163impl From<&str> for ApiKey {
164    fn from(key: &str) -> Self {
165        Self::Key(key.to_owned())
166    }
167}
168
169impl From<String> for ApiKey {
170    fn from(key: String) -> Self {
171        Self::Key(key)
172    }
173}
174
175impl PartialEq for ApiKey {
176    fn eq(&self, other: &Self) -> bool {
177        match (self, other) {
178            (Self::Key(left), Self::Key(right)) => left == right,
179            (Self::Setter(left), Self::Setter(right)) => Arc::ptr_eq(&left.0, &right.0),
180            _ => false,
181        }
182    }
183}
184
185impl fmt::Debug for ApiKey {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        match self {
188            Self::Key(_) => f.write_str("Key(<redacted>)"),
189            Self::Setter(_) => f.write_str("Setter(<function>)"),
190        }
191    }
192}
193
194/// Configuration of an [`OpenAIModel`] (`OpenAIModelConfig`): the [`BaseModelConfig`] fields and
195/// the OpenAI ones, for both APIs.
196#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
197pub struct OpenAIModelConfig {
198    /// The model id, such as `gpt-5.4`, `gpt-5.4-mini` or `gpt-4o`. Defaults to `gpt-5.4`, which
199    /// can change between versions.
200    #[builder(into)]
201    pub model_id: Option<String>,
202    /// Maximum tokens to generate (`max_completion_tokens` on Chat Completions,
203    /// `max_output_tokens` on the Responses API).
204    pub max_tokens: Option<u64>,
205    /// Controls randomness in generation.
206    pub temperature: Option<f64>,
207    /// Nucleus sampling.
208    pub top_p: Option<f64>,
209    /// Context window size in tokens; filled from the shared model info when unset.
210    pub context_window_limit: Option<u64>,
211    /// Overrides for what the SDK knows about the model.
212    pub model_info: Option<ModelInfo>,
213    /// Extra request fields, for parameters without a config field. Built-in Responses tools go
214    /// here, before the agent's tools: `{"tools": [{"type": "web_search"}]}`. The provider
215    /// manages `model`, `messages` and `stream` (Chat Completions) and `model`, `input`, `stream`
216    /// and `store` (Responses); a warning is logged when `params` holds any of them, and the
217    /// provider's values win. Chat Completions sends `stream_options: {"include_usage": true}`
218    /// unless `params` sets it, and omits any `params` key set to `null`, such as
219    /// `"stream_options": null` for compatible endpoints that reject the field; without
220    /// `include_usage`, the endpoint may not report usage. Must be a JSON object, such as a
221    /// `json!({..})` literal.
222    pub params: Option<JsonValue>,
223    /// Prompt caching. On the Responses API, models whose model info says they take cache points
224    /// (GPT-5.6 and later) cache durable conversation prefixes before temporary context;
225    /// `messages_ttl: false` turns that off. There, a `"30m"` or `"12h"` `messages_ttl` sets each
226    /// checkpoint's `ttl`, and such a `ttl` sets `prompt_cache_options.ttl`. Older models and Chat
227    /// Completions cache implicitly. `cache_key` maps to `prompt_cache_key` and the retention
228    /// literals (`"in_memory"`, `"24h"`) to `prompt_cache_retention`. Caching fields in `params` win.
229    /// Checkpoints do not remove injected content that a stateful server-side conversation keeps.
230    pub cache_config: Option<CacheConfig>,
231    /// Reduces repetition of token sequences (-2.0 to 2.0). Chat Completions only.
232    pub frequency_penalty: Option<f64>,
233    /// Encourages the model to talk about new topics (-2.0 to 2.0). Chat Completions only.
234    pub presence_penalty: Option<f64>,
235    /// Whether the server manages conversation state (Responses API only): requests set
236    /// `store: true` and chain turns through `previous_response_id`, and the agent keeps no local
237    /// history. Default `false`, which sends the whole history on every turn. Set at construction;
238    /// [`OpenAIModel::update_config`] ignores it with a warning.
239    pub stateful: Option<bool>,
240}
241
242impl OpenAIModelConfig {
243    /// Shallow-merges `update` into `self`: every field `update` sets replaces the current value.
244    pub fn merge(&mut self, update: Self) {
245        let Self {
246            model_id,
247            max_tokens,
248            temperature,
249            top_p,
250            context_window_limit,
251            model_info,
252            params,
253            cache_config,
254            frequency_penalty,
255            presence_penalty,
256            stateful,
257        } = update;
258        self.model_id = model_id.or(self.model_id.take());
259        self.max_tokens = max_tokens.or(self.max_tokens);
260        self.temperature = temperature.or(self.temperature);
261        self.top_p = top_p.or(self.top_p);
262        self.context_window_limit = context_window_limit.or(self.context_window_limit);
263        self.model_info = model_info.or(self.model_info.take());
264        self.params = params.or(self.params.take());
265        self.cache_config = cache_config.or(self.cache_config.take());
266        self.frequency_penalty = frequency_penalty.or(self.frequency_penalty);
267        self.presence_penalty = presence_penalty.or(self.presence_penalty);
268        self.stateful = stateful.or(self.stateful);
269    }
270
271    /// The [`BaseModelConfig`] fields of this configuration.
272    #[must_use]
273    pub fn to_base(&self) -> BaseModelConfig {
274        BaseModelConfig {
275            model_id: self.model_id.clone(),
276            max_tokens: self.max_tokens,
277            temperature: self.temperature,
278            top_p: self.top_p,
279            context_window_limit: self.context_window_limit,
280            model_info: self.model_info.clone(),
281        }
282    }
283}
284
285impl From<BaseModelConfig> for OpenAIModelConfig {
286    fn from(config: BaseModelConfig) -> Self {
287        Self {
288            model_id: config.model_id,
289            max_tokens: config.max_tokens,
290            temperature: config.temperature,
291            top_p: config.top_p,
292            context_window_limit: config.context_window_limit,
293            model_info: config.model_info,
294            ..Self::default()
295        }
296    }
297}
298
299/// How the client reaches the OpenAI API.
300///
301/// `Debug` redacts the values of credential headers (`authorization`, `proxy-authorization`,
302/// `x-api-key`, `api-key`, `cookie`).
303#[derive(Clone, Default, PartialEq, Eq, bon::Builder)]
304pub struct OpenAIClientConfig {
305    /// The API base URL. Defaults to `OPENAI_BASE_URL`, else `https://api.openai.com/v1`.
306    #[builder(into)]
307    pub base_url: Option<String>,
308    /// The `OpenAI-Organization` header. Defaults to `OPENAI_ORG_ID`.
309    #[builder(into)]
310    pub organization: Option<String>,
311    /// The `OpenAI-Project` header. Defaults to `OPENAI_PROJECT_ID`.
312    #[builder(into)]
313    pub project: Option<String>,
314    /// Headers sent with every request, after those in `OPENAI_CUSTOM_HEADERS`; a later header
315    /// replaces an earlier one with the same name, and these replace the provider's own,
316    /// `Authorization` included.
317    #[builder(default)]
318    pub default_headers: Vec<(String, String)>,
319    /// Retries on connection errors, timeouts, 408, 409, 429 and 5xx responses. Default 2.
320    pub max_retries: Option<u32>,
321    /// Time each attempt may wait for the response headers. Default 10 minutes.
322    pub timeout: Option<Duration>,
323}
324
325impl fmt::Debug for OpenAIClientConfig {
326    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327        f.debug_struct("OpenAIClientConfig")
328            .field("base_url", &self.base_url)
329            .field("organization", &self.organization)
330            .field("project", &self.project)
331            .field("default_headers", &RedactedHeaders(&self.default_headers))
332            .field("max_retries", &self.max_retries)
333            .field("timeout", &self.timeout)
334            .finish()
335    }
336}
337
338/// Options for [`OpenAIModel::new`] (`OpenAIModelOptions`): the API, the [`OpenAIModelConfig`]
339/// fields and the client ones.
340///
341/// [`OpenAIModel::builder`] builds them and the model in one go; the options' own builder ends
342/// with [`build_options`](OpenAIModelOptionsBuilder::build_options).
343#[derive(Clone, Default, bon::Builder)]
344#[builder(finish_fn = build_options)]
345pub struct OpenAIModelOptions {
346    /// The API to stream from. Default [`OpenAIApi::Responses`]. Set at construction only.
347    #[builder(default)]
348    pub api: OpenAIApi,
349    /// See [`OpenAIModelConfig::model_id`].
350    #[builder(into)]
351    pub model_id: Option<String>,
352    /// See [`OpenAIModelConfig::max_tokens`].
353    pub max_tokens: Option<u64>,
354    /// See [`OpenAIModelConfig::temperature`].
355    pub temperature: Option<f64>,
356    /// See [`OpenAIModelConfig::top_p`].
357    pub top_p: Option<f64>,
358    /// See [`OpenAIModelConfig::context_window_limit`].
359    pub context_window_limit: Option<u64>,
360    /// See [`OpenAIModelConfig::model_info`].
361    pub model_info: Option<ModelInfo>,
362    /// See [`OpenAIModelConfig::params`].
363    pub params: Option<JsonValue>,
364    /// See [`OpenAIModelConfig::cache_config`].
365    pub cache_config: Option<CacheConfig>,
366    /// See [`OpenAIModelConfig::frequency_penalty`].
367    pub frequency_penalty: Option<f64>,
368    /// See [`OpenAIModelConfig::presence_penalty`].
369    pub presence_penalty: Option<f64>,
370    /// See [`OpenAIModelConfig::stateful`].
371    pub stateful: Option<bool>,
372    /// The API key, fixed or from a function called before each request. Defaults to
373    /// `OPENAI_API_KEY`.
374    #[builder(into)]
375    pub api_key: Option<ApiKey>,
376    /// How the client reaches the API.
377    pub client_config: Option<OpenAIClientConfig>,
378}
379
380impl fmt::Debug for OpenAIModelOptions {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        let mut debug = f.debug_struct("OpenAIModelOptions");
383        debug
384            .field("api", &self.api)
385            .field("config", &self.clone().into_parts().config)
386            .field("api_key", &self.api_key)
387            .field("client_config", &self.client_config);
388        debug.finish()
389    }
390}
391
392/// The options split into what the model keeps and what builds its client.
393struct OptionParts {
394    api: OpenAIApi,
395    config: OpenAIModelConfig,
396    api_key: Option<ApiKey>,
397    client_config: OpenAIClientConfig,
398}
399
400impl OpenAIModelOptions {
401    fn into_parts(self) -> OptionParts {
402        let config = OpenAIModelConfig {
403            model_id: self.model_id,
404            max_tokens: self.max_tokens,
405            temperature: self.temperature,
406            top_p: self.top_p,
407            context_window_limit: self.context_window_limit,
408            model_info: self.model_info,
409            params: self.params,
410            cache_config: self.cache_config,
411            frequency_penalty: self.frequency_penalty,
412            presence_penalty: self.presence_penalty,
413            stateful: self.stateful,
414        };
415        OptionParts {
416            api: self.api,
417            config,
418            api_key: self.api_key,
419            client_config: self.client_config.unwrap_or_default(),
420        }
421    }
422}
423
424impl From<OpenAIModelConfig> for OpenAIModelOptions {
425    fn from(config: OpenAIModelConfig) -> Self {
426        let OpenAIModelConfig {
427            model_id,
428            max_tokens,
429            temperature,
430            top_p,
431            context_window_limit,
432            model_info,
433            params,
434            cache_config,
435            frequency_penalty,
436            presence_penalty,
437            stateful,
438        } = config;
439        Self {
440            model_id,
441            max_tokens,
442            temperature,
443            top_p,
444            context_window_limit,
445            model_info,
446            params,
447            cache_config,
448            frequency_penalty,
449            presence_penalty,
450            stateful,
451            ..Self::default()
452        }
453    }
454}
455
456impl<S: IsComplete> OpenAIModelOptionsBuilder<S> {
457    /// Builds the model ([`OpenAIModel::new`]).
458    ///
459    /// # Errors
460    ///
461    /// See [`OpenAIModel::new`].
462    pub fn build(self) -> Result<OpenAIModel> {
463        OpenAIModel::new(self.build_options())
464    }
465}
466
467/// A model on the OpenAI Responses or Chat Completions API (`OpenAIModel`).
468///
469/// Cheap to clone and to share as `Arc<dyn Model>`: clones share one configuration and one HTTP
470/// client, so [`update_config`](Self::update_config) on any clone changes them all.
471#[derive(Clone)]
472pub struct OpenAIModel {
473    inner: Arc<Inner>,
474}
475
476impl fmt::Debug for OpenAIModel {
477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
478        f.debug_struct("OpenAIModel")
479            .field("api", &self.inner.api)
480            .field("config", &self.inner.config())
481            .finish_non_exhaustive()
482    }
483}
484
485struct Inner {
486    api: OpenAIApi,
487    config: RwLock<OpenAIModelConfig>,
488    client: RwLock<Arc<dyn OpenAIClient>>,
489    /// The model id whose replayed reasoning the endpoint rejected; it is not replayed again.
490    rejected_reasoning_model_id: RwLock<Option<String>>,
491    #[cfg(feature = "mantle")]
492    mantle: Option<RwLock<mantle::MantleRoute>>,
493}
494
495impl OpenAIModel {
496    /// Starts building a model from [`OpenAIModelOptions`] fields.
497    pub fn builder() -> OpenAIModelOptionsBuilder {
498        OpenAIModelOptions::builder()
499    }
500
501    /// Creates the model from options or a bare model configuration.
502    ///
503    /// Logs a one-time warning when `model_id` falls back to its default, and a warning for each
504    /// provider-managed key in `params`.
505    ///
506    /// # Errors
507    ///
508    /// Fails when `params` is not a JSON object, when there is no API key in the options or
509    /// `OPENAI_API_KEY`, or when the HTTP client cannot be built (an invalid base URL or header).
510    pub fn new(options: impl Into<OpenAIModelOptions>) -> Result<Self> {
511        Self::with_env(options.into(), &|name| std::env::var(name).ok())
512    }
513
514    fn with_env(options: OpenAIModelOptions, env: Env<'_>) -> Result<Self> {
515        let parts = options.into_parts();
516        let config = prepare_config(parts.api, parts.config)?;
517        let has_key = match &parts.api_key {
518            Some(ApiKey::Key(key)) => !key.is_empty(),
519            Some(ApiKey::Setter(_)) => true,
520            None => false,
521        };
522        let has_env_key = read_env(env, "OPENAI_API_KEY").is_some();
523        if !has_key && !has_env_key {
524            return Err(Error::other(
525                "OpenAI API key is required. Provide it via the 'api_key' option (string or function) or set the OPENAI_API_KEY environment variable.",
526            ));
527        }
528        let api_key = parts.api_key.filter(|_| has_key);
529        let client = HttpOpenAIClient::new(api_key.as_ref(), None, &parts.client_config, env).map_err(model_error)?;
530        Ok(Self::from_parts(parts.api, config, Arc::new(client)))
531    }
532
533    fn from_parts(api: OpenAIApi, config: OpenAIModelConfig, client: Arc<dyn OpenAIClient>) -> Self {
534        Self::from_inner(Inner {
535            api,
536            config: RwLock::new(config),
537            client: RwLock::new(client),
538            rejected_reasoning_model_id: RwLock::new(None),
539            #[cfg(feature = "mantle")]
540            mantle: None,
541        })
542    }
543
544    fn from_inner(inner: Inner) -> Self {
545        Self { inner: Arc::new(inner) }
546    }
547
548    /// The API this model streams from, set at construction.
549    #[must_use]
550    pub fn api(&self) -> OpenAIApi {
551        self.inner.api
552    }
553
554    /// The configuration, with `context_window_limit` filled from the model info when unset.
555    /// `model_id` stays unset when the default is used; [`Model::model_id`] reports the id requests
556    /// send.
557    #[must_use]
558    pub fn config(&self) -> OpenAIModelConfig {
559        resolve(&self.inner.config())
560    }
561
562    /// Merges `config` into the configuration: every field it sets replaces the current value.
563    /// Takes a [`BaseModelConfig`] too.
564    ///
565    /// `stateful` is construction-only: it is ignored with a warning, since changing it would break
566    /// the agent's history handling and `previous_response_id` chaining. On a
567    /// [`bedrock_mantle`](Self::bedrock_mantle) model, a `model_id` on the other base path rebuilds
568    /// the client against the new base URL.
569    ///
570    /// # Errors
571    ///
572    /// Fails, leaving the configuration unchanged, when `params` is not a JSON object or the
573    /// rebuilt Mantle client cannot be built.
574    pub fn update_config(&self, config: impl Into<OpenAIModelConfig>) -> Result<()> {
575        let mut config = config.into();
576        if let Some(stateful) = config.stateful.take() {
577            tracing::warn!(
578                "stateful=<{stateful}> | 'stateful' is construction-only and cannot be changed via update_config — ignoring"
579            );
580        }
581        #[cfg(feature = "mantle")]
582        if let Some(model_id) = &config.model_id {
583            self.inner.reroute_mantle(model_id)?;
584        }
585        validate_params(&config)?;
586        warn_managed_params(self.inner.api, config.params.as_ref());
587        self.inner.write_config().merge(config);
588        Ok(())
589    }
590}
591
592fn model_error(error: HttpError) -> Error {
593    ModelError::new(error.to_string()).with_source(error).into()
594}
595
596fn warn_managed_params(api: OpenAIApi, params: Option<&JsonValue>) {
597    let params = params.and_then(JsonValue::as_object);
598    match api {
599        OpenAIApi::Chat => warn_chat_managed_params(params),
600        OpenAIApi::Responses => warn_responses_managed_params(params),
601    }
602}
603
604/// Checks that `params` is a JSON object.
605fn validate_params(config: &OpenAIModelConfig) -> Result<()> {
606    if config.params.as_ref().is_some_and(|params| !params.is_object()) {
607        return Err(Error::other("'params' must be a JSON object"));
608    }
609    Ok(())
610}
611
612/// Validates the configuration and warns once about the default model id and about
613/// provider-managed `params` keys.
614fn prepare_config(api: OpenAIApi, config: OpenAIModelConfig) -> Result<OpenAIModelConfig> {
615    validate_params(&config)?;
616    if config.model_id.is_none() {
617        warn_once(&default_model_warning_message(MODEL_DEFAULTS.openai.model_id));
618    }
619    warn_managed_params(api, config.params.as_ref());
620    Ok(config)
621}
622
623fn model_id_of(config: &OpenAIModelConfig) -> &str {
624    config.model_id.as_deref().unwrap_or(MODEL_DEFAULTS.openai.model_id)
625}
626
627/// The configuration with the context window filled in.
628fn resolve(config: &OpenAIModelConfig) -> OpenAIModelConfig {
629    let base = resolve_config_metadata(config.to_base(), model_id_of(config));
630    OpenAIModelConfig {
631        context_window_limit: base.context_window_limit,
632        ..config.clone()
633    }
634}
635
636/// The model info: the base layers for the id requests send, server-side summaries off, whether
637/// the model is stateful (Responses with `stateful` only), the reasoning a Responses model takes
638/// back, and the user's override on top.
639fn model_info_of(api: OpenAIApi, config: &OpenAIModelConfig) -> ModelInfo {
640    let mut base = resolve(config).to_base();
641    base.model_id = Some(model_id_of(config).to_owned());
642    let responses = api == OpenAIApi::Responses;
643    let stateful = ModelInfo {
644        capabilities: ModelCapabilities {
645            stateful: Some(responses && config.stateful == Some(true)),
646            // Only reasoning from the configured model is replayed, which the request formatting checks.
647            reasoning_provider: responses.then(|| REASONING_PROVIDER.to_owned()),
648            ..ModelCapabilities::default()
649        },
650        ..ModelInfo::default()
651    };
652    ModelInfo::merge([
653        Some(&base_model_info(&base)),
654        Some(&server_side_summary_off()),
655        Some(&stateful),
656        config.model_info.as_ref(),
657    ])
658}
659
660/// Why a request failed, before translation to SDK errors.
661enum StreamFailure {
662    Http(HttpError),
663    Response(ResponsesStreamError),
664    Aborted,
665}
666
667impl StreamFailure {
668    fn message(&self) -> String {
669        match self {
670            Self::Http(error) => error.message().to_owned(),
671            Self::Response(error) => error.message.clone(),
672            Self::Aborted => ABORTED_MESSAGE.to_owned(),
673        }
674    }
675
676    /// The error's `code`: the error object's in an error body or event, the response error's.
677    fn code(&self) -> Option<JsonValue> {
678        match self {
679            Self::Http(error) => error
680                .body()
681                .and_then(|body| body.get("error"))
682                .and_then(|error| error.get("code"))
683                .cloned(),
684            Self::Response(error) => error.code.clone().map(JsonValue::String),
685            Self::Aborted => None,
686        }
687    }
688}
689
690/// Maps throttling and context overflow to the SDK's error types, transport failures to
691/// `ModelNetworkError` and the rest to `ModelError`, keeping the original as source.
692fn translate_error(failure: StreamFailure) -> Error {
693    let message = failure.message();
694    let status = match &failure {
695        StreamFailure::Http(error) => error.status_code(),
696        _ => None,
697    };
698    let code = failure.code();
699    match classify_openai_error(&message, status, code.as_ref()) {
700        Some(OpenAIErrorKind::Throttling) => {
701            tracing::debug!("throttled | error_message=<{message}>");
702            let throttled = ModelThrottledError::new(message);
703            return match failure {
704                StreamFailure::Http(error) => throttled.with_source(error).into(),
705                StreamFailure::Response(error) => throttled.with_source(error).into(),
706                StreamFailure::Aborted => throttled.into(),
707            };
708        }
709        Some(OpenAIErrorKind::ContextOverflow) => return ContextWindowOverflowError::new(message).into(),
710        None => {}
711    }
712    match failure {
713        StreamFailure::Http(error) if error.is_network() => ModelNetworkError::new(message).with_source(error).into(),
714        StreamFailure::Http(error) => ModelError::new(message).with_source(error).into(),
715        StreamFailure::Response(error) => ModelError::new(message).with_source(error).into(),
716        StreamFailure::Aborted => ModelError::new(message).into(),
717    }
718}
719
720/// [`translate_error`] for a Chat Completions request, pointing to the Responses API when OpenAI
721/// rejects tools for a model that accepts none there.
722fn translate_chat_error(error: HttpError, tool_limit: Option<ChatCompletionsTools>, model_id: &str) -> Error {
723    if tool_limit != Some(ChatCompletionsTools::Unsupported) || !rejects_reasoning_effort(&error) {
724        return translate_error(StreamFailure::Http(error));
725    }
726    let code = error
727        .body()
728        .and_then(|body| body.get("error"))
729        .and_then(|error| error.get("code"));
730    if classify_openai_error(error.message(), error.status_code(), code).is_some() {
731        return translate_error(StreamFailure::Http(error));
732    }
733    ModelError::new(responses_hint(error.message(), model_id))
734        .with_source(error)
735        .into()
736}
737
738/// Whether OpenAI rejected the request over `reasoning_effort`, which it names in both of its
739/// rejections: tools with reasoning, and `none` unsupported.
740fn rejects_reasoning_effort(error: &HttpError) -> bool {
741    error.status_code() == Some(400)
742        && error
743            .body()
744            .and_then(|body| body.get("error"))
745            .and_then(|error| error.get("param"))
746            .and_then(JsonValue::as_str)
747            == Some("reasoning_effort")
748}
749
750/// The next event, or `None` once `cancel` fires, which drops the in-flight request.
751async fn next_event(
752    events: &mut EventStream,
753    cancel: Option<&CancelSignal>,
754) -> Option<Option<std::result::Result<JsonValue, HttpError>>> {
755    let Some(cancel) = cancel else {
756        return Some(events.next().await);
757    };
758    tokio::select! {
759        biased;
760        () = cancel.cancelled() => None,
761        event = events.next() => Some(event),
762    }
763}
764
765/// The usage of a Chat Completions chunk, with prompt-cache reads and writes.
766fn chat_usage(usage: &JsonValue) -> Usage {
767    let count = |key| token_count(usage.get(key)).unwrap_or_default();
768    let mut mapped = Usage::new(
769        count("prompt_tokens"),
770        count("completion_tokens"),
771        count("total_tokens"),
772    );
773    let details = usage.get("prompt_tokens_details");
774    if let Some(cached) = positive_count(details.and_then(|details| details.get("cached_tokens"))) {
775        mapped = mapped.with_cache_read_input_tokens(cached);
776    }
777    if let Some(written) = positive_count(details.and_then(|details| details.get("cache_write_tokens"))) {
778        mapped = mapped.with_cache_write_input_tokens(written);
779    }
780    mapped
781}
782
783impl Inner {
784    fn config(&self) -> OpenAIModelConfig {
785        self.config.read().unwrap_or_else(PoisonError::into_inner).clone()
786    }
787
788    fn write_config(&self) -> std::sync::RwLockWriteGuard<'_, OpenAIModelConfig> {
789        self.config.write().unwrap_or_else(PoisonError::into_inner)
790    }
791
792    fn client(&self) -> Arc<dyn OpenAIClient> {
793        Arc::clone(&self.client.read().unwrap_or_else(PoisonError::into_inner))
794    }
795
796    fn stateful(&self) -> bool {
797        model_info_of(self.api, &self.config()).capabilities.stateful == Some(true)
798    }
799
800    fn stream(self: Arc<Self>, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>> {
801        if request.messages.is_empty() {
802            return Box::pin(futures::stream::once(async {
803                Err(Error::other("At least one message is required"))
804            }));
805        }
806        match self.api {
807            OpenAIApi::Chat => self.stream_chat(request),
808            OpenAIApi::Responses => self.stream_responses(request),
809        }
810    }
811
812    fn stream_chat(self: Arc<Self>, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>> {
813        Box::pin(async_stream::stream! {
814            let config = self.config();
815            let mut body = match format_chat_request(&config, &request) {
816                Ok(body) => body,
817                Err(error) => {
818                    yield Err(error);
819                    return;
820                }
821            };
822            let client = self.client();
823            let tool_limit = apply_chat_completions_tools(&mut body, client.base_url());
824            let model_id = body.get("model").and_then(JsonValue::as_str).unwrap_or_default().to_owned();
825            let cancel = request.cancel_signal.as_ref();
826            let mut events = client.stream(CHAT_COMPLETIONS_PATH, JsonValue::Object(body));
827            let mut state = ChatStreamState::default();
828            let mut buffered_usage: Option<Usage> = None;
829            loop {
830                let Some(event) = next_event(&mut events, cancel).await else {
831                    // Closes the connection before the consumer sees the abort.
832                    drop(events);
833                    yield Err(translate_error(StreamFailure::Aborted));
834                    return;
835                };
836                let Some(event) = event else {
837                    break;
838                };
839                let chunk = match event {
840                    Ok(chunk) => chunk,
841                    Err(error) => {
842                        drop(events);
843                        yield Err(translate_chat_error(error, tool_limit, &model_id));
844                        return;
845                    }
846                };
847                // OpenAI sends usage on a trailing chunk without choices; some compatible
848                // providers (OpenRouter) put it on the chunk with the finish reason.
849                if let Some(usage) = chunk.get("usage").filter(|usage| usage.is_object()) {
850                    buffered_usage = Some(chat_usage(usage));
851                }
852                for event in map_chat_chunk(&chunk, &mut state) {
853                    if matches!(event, ModelStreamEvent::MessageStop(_))
854                        && let Some(usage) = buffered_usage.take()
855                    {
856                        yield Ok(ModelMetadataEvent::new().with_usage(usage).into());
857                    }
858                    yield Ok(event);
859                }
860            }
861            drop(events);
862            if cancel.is_some_and(CancelSignal::is_cancelled) {
863                yield Err(translate_error(StreamFailure::Aborted));
864                return;
865            }
866            if let Some(usage) = buffered_usage {
867                yield Ok(ModelMetadataEvent::new().with_usage(usage).into());
868            }
869        })
870    }
871
872    fn replays_reasoning(&self, model_id: &str) -> bool {
873        self.rejected_reasoning_model_id
874            .read()
875            .unwrap_or_else(PoisonError::into_inner)
876            .as_deref()
877            != Some(model_id)
878    }
879
880    fn stop_replaying_reasoning(&self, model_id: &str) {
881        *self
882            .rejected_reasoning_model_id
883            .write()
884            .unwrap_or_else(PoisonError::into_inner) = Some(model_id.to_owned());
885    }
886
887    fn stream_responses(self: Arc<Self>, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>> {
888        Box::pin(async_stream::stream! {
889            let config = self.config();
890            let stateful = self.stateful();
891            let model_info = model_info_of(self.api, &config);
892            let model_id = model_id_of(&config).to_owned();
893            let replay = self.replays_reasoning(&model_id);
894            let body = format_responses_request(&config, &request, stateful, &model_info, replay);
895            let cancel = request.cancel_signal.as_ref();
896            let client = self.client();
897            let mut events = client.stream(RESPONSES_PATH, JsonValue::Object(body.clone()));
898            // Stateless only: a stored conversation keeps its reasoning server-side.
899            let mut state = ResponsesStreamState::new((!stateful).then(|| model_id.clone()));
900            let mut started = false;
901            loop {
902                let Some(event) = next_event(&mut events, cancel).await else {
903                    // Closes the connection before the consumer sees the abort.
904                    drop(events);
905                    yield Err(translate_error(StreamFailure::Aborted));
906                    return;
907                };
908                let Some(event) = event else {
909                    break;
910                };
911                let event = match event {
912                    Ok(event) => event,
913                    Err(error) => {
914                        let retry = (!started).then(|| without_rejected_reasoning(&body, &error)).flatten();
915                        if let Some(retry) = retry {
916                            // History keeps the reasoning for another model or a new instance; this one stops replaying it.
917                            tracing::warn!(
918                                "error=<{error}> | endpoint rejected replayed reasoning | retrying and no longer replaying it"
919                            );
920                            self.stop_replaying_reasoning(&model_id);
921                            started = true;
922                            events = client.stream(RESPONSES_PATH, JsonValue::Object(retry));
923                            continue;
924                        }
925                        drop(events);
926                        yield Err(translate_error(StreamFailure::Http(error)));
927                        return;
928                    }
929                };
930                started = true;
931                match map_responses_event(&event, &mut state, stateful, &request.model_state) {
932                    Ok(mapped) => {
933                        for event in mapped {
934                            yield Ok(event);
935                        }
936                    }
937                    Err(error) => {
938                        drop(events);
939                        yield Err(translate_error(StreamFailure::Response(error)));
940                        return;
941                    }
942                }
943            }
944            drop(events);
945            if cancel.is_some_and(CancelSignal::is_cancelled) {
946                yield Err(translate_error(StreamFailure::Aborted));
947                return;
948            }
949            for event in finalize_responses_stream(state) {
950                yield Ok(event);
951            }
952        })
953    }
954}
955
956#[async_trait]
957impl Model for OpenAIModel {
958    fn stream(&self, request: ModelRequest) -> BoxStream<'static, Result<ModelStreamEvent>> {
959        Arc::clone(&self.inner).stream(request)
960    }
961
962    fn get_config(&self) -> BaseModelConfig {
963        self.config().to_base()
964    }
965
966    fn update_config(&self, config: BaseModelConfig) -> Result<()> {
967        OpenAIModel::update_config(self, config)
968    }
969
970    /// The configured model id, else the default one requests send.
971    fn model_id(&self) -> Option<String> {
972        Some(model_id_of(&self.inner.config()).to_owned())
973    }
974
975    /// The shared model info with server-side summaries off and `stateful` set for a Responses
976    /// model built with `stateful: true`; the `model_info` override wins.
977    fn model_info(&self) -> ModelInfo {
978        model_info_of(self.inner.api, &self.inner.config())
979    }
980}
981
982#[cfg(test)]
983mod tests;