Skip to main content

adk_model/openai/
config.rs

1//! Configuration types for OpenAI providers.
2
3use serde::{Deserialize, Serialize};
4
5/// Reasoning effort level for OpenAI reasoning models (e.g., o1, o3).
6///
7/// Controls how much reasoning effort the model applies. Maps directly to
8/// the OpenAI `reasoning_effort` API field.
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
10#[serde(rename_all = "lowercase")]
11pub enum ReasoningEffort {
12    /// Minimal reasoning — fastest, cheapest.
13    Low,
14    /// Balanced reasoning (default for most reasoning models).
15    Medium,
16    /// Maximum reasoning — most thorough but slowest.
17    High,
18}
19
20/// Complete reasoning-effort vocabulary supported across OpenAI model generations.
21///
22/// This additive type preserves the original exhaustive [`ReasoningEffort`] enum while
23/// exposing the `none`, `minimal`, `xhigh`, and `max` values used by newer models.
24/// GPT-5.6 supports every value except `minimal` through the Responses API;
25/// Chat Completions supports up to `xhigh`. Older GPT-5 models may support
26/// `minimal` but not `max`.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "lowercase")]
29pub enum OpenAIReasoningEffort {
30    /// Disable reasoning for the lowest latency.
31    None,
32    /// Use minimal reasoning on models that retain the legacy setting.
33    Minimal,
34    /// Use low reasoning effort.
35    Low,
36    /// Use balanced reasoning effort.
37    Medium,
38    /// Use high reasoning effort.
39    High,
40    /// Use extra-high reasoning effort.
41    XHigh,
42    /// Use maximum reasoning effort on models that support it through Responses.
43    Max,
44}
45
46/// The harness effort levels (spec 3.1 §7.23) as `reasoning_effort` values.
47///
48/// # Example
49///
50/// ```rust
51/// use adk_model::openai::ReasoningEffort;
52///
53/// assert_eq!(ReasoningEffort::from(adk_core::Effort::Low), ReasoningEffort::Low);
54/// ```
55impl From<adk_core::Effort> for ReasoningEffort {
56    fn from(effort: adk_core::Effort) -> Self {
57        match effort {
58            adk_core::Effort::Low => Self::Low,
59            adk_core::Effort::Medium => Self::Medium,
60            adk_core::Effort::High => Self::High,
61        }
62    }
63}
64
65/// The harness effort levels (spec 3.1 §7.23); `None`, `Minimal`, `XHigh` and `Max` stay
66/// reachable only through the client's own configuration.
67impl From<adk_core::Effort> for OpenAIReasoningEffort {
68    fn from(effort: adk_core::Effort) -> Self {
69        ReasoningEffort::from(effort).into()
70    }
71}
72
73impl From<ReasoningEffort> for OpenAIReasoningEffort {
74    fn from(value: ReasoningEffort) -> Self {
75        match value {
76            ReasoningEffort::Low => Self::Low,
77            ReasoningEffort::Medium => Self::Medium,
78            ReasoningEffort::High => Self::High,
79        }
80    }
81}
82
83/// Whether `model` is a reasoning model that takes `reasoning_effort` (spec 3.1 §7.23): the
84/// o-series, GPT-OSS, and GPT-5 and later except their `-chat` variants.
85pub(crate) fn takes_reasoning_effort(model: &str) -> bool {
86    let model = model.strip_prefix("ft:").unwrap_or(model);
87    let model = model.rsplit('/').next().unwrap_or(model);
88    if model.starts_with("gpt-oss") {
89        return true;
90    }
91    if let Some(rest) = model.strip_prefix('o') {
92        return rest.starts_with(|c: char| c.is_ascii_digit());
93    }
94    let Some(version) = model.strip_prefix("gpt-") else {
95        return false;
96    };
97    let major_end = version.find(|c: char| !c.is_ascii_digit()).unwrap_or(version.len());
98    version[..major_end].parse::<u32>().is_ok_and(|major| major >= 5) && !model.contains("-chat")
99}
100
101/// The reasoning effort of one request (spec 3.1 §7.23, §10 C4): the request's `effort` wins
102/// over the client's `configured` level for this call when the model takes one — a reasoning
103/// model, or any model whose client was configured with an effort — and is logged and
104/// ignored otherwise.
105pub(crate) fn request_reasoning_effort(
106    model: &str,
107    configured: Option<OpenAIReasoningEffort>,
108    request: &adk_core::LlmRequest,
109) -> Option<OpenAIReasoningEffort> {
110    let Some(level) = request.config.as_ref().and_then(|config| config.effort) else {
111        return configured;
112    };
113    if configured.is_some() || takes_reasoning_effort(model) {
114        return Some(level.into());
115    }
116    tracing::debug!(
117        model.name = model,
118        effort = %level,
119        "model takes no reasoning effort; the request's effort is ignored"
120    );
121    configured
122}
123
124/// Configuration for OpenAI API.
125///
126/// The API key is redacted from `Debug` output and omitted when serializing.
127#[derive(Clone, Serialize, Deserialize)]
128pub struct OpenAIConfig {
129    /// OpenAI API key. Never serialized; deserializing a config without it
130    /// yields an empty key.
131    #[serde(skip_serializing, default)]
132    pub api_key: String,
133    /// Model name (e.g., "gpt-6.1-sol", "gpt-5.6-sol").
134    pub model: String,
135    /// Optional organization ID.
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub organization_id: Option<String>,
138    /// Optional project ID.
139    #[serde(skip_serializing_if = "Option::is_none")]
140    pub project_id: Option<String>,
141    /// Optional custom base URL for OpenAI-compatible APIs.
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub base_url: Option<String>,
144    /// Reasoning effort for OpenAI reasoning models (o1, o3, etc.).
145    ///
146    /// When set, the `reasoning_effort` field is included in the API request.
147    /// Only applicable to reasoning-capable models.
148    #[serde(skip_serializing_if = "Option::is_none")]
149    pub reasoning_effort: Option<ReasoningEffort>,
150}
151
152impl std::fmt::Debug for OpenAIConfig {
153    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        f.debug_struct("OpenAIConfig")
155            .field("api_key", &"[REDACTED]")
156            .field("model", &self.model)
157            .field("organization_id", &self.organization_id)
158            .field("project_id", &self.project_id)
159            .field("base_url", &self.base_url)
160            .field("reasoning_effort", &self.reasoning_effort)
161            .finish()
162    }
163}
164
165impl Default for OpenAIConfig {
166    fn default() -> Self {
167        Self {
168            api_key: String::new(),
169            model: crate::catalog::OPENAI_DEFAULT.to_string(),
170            organization_id: None,
171            project_id: None,
172            base_url: None,
173            reasoning_effort: None,
174        }
175    }
176}
177
178impl OpenAIConfig {
179    /// Create a new OpenAI config with the given API key and model.
180    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
181        Self { api_key: api_key.into(), model: model.into(), ..Default::default() }
182    }
183
184    /// Create a config for an OpenAI-compatible API (e.g., Ollama, vLLM).
185    pub fn compatible(
186        api_key: impl Into<String>,
187        base_url: impl Into<String>,
188        model: impl Into<String>,
189    ) -> Self {
190        Self {
191            api_key: api_key.into(),
192            model: model.into(),
193            base_url: Some(base_url.into()),
194            ..Default::default()
195        }
196    }
197
198    /// Set the organization ID.
199    pub fn with_organization(mut self, org_id: impl Into<String>) -> Self {
200        self.organization_id = Some(org_id.into());
201        self
202    }
203
204    /// Set the project ID.
205    pub fn with_project(mut self, project_id: impl Into<String>) -> Self {
206        self.project_id = Some(project_id.into());
207        self
208    }
209
210    /// Set the reasoning effort for reasoning models (o1, o3, etc.).
211    pub fn with_reasoning_effort(mut self, effort: ReasoningEffort) -> Self {
212        self.reasoning_effort = Some(effort);
213        self
214    }
215}
216
217/// Configuration for Azure OpenAI Service.
218///
219/// The API key is redacted from `Debug` output and omitted when serializing.
220#[derive(Clone, Serialize, Deserialize)]
221pub struct AzureConfig {
222    /// Azure OpenAI API key. Never serialized; deserializing a config without
223    /// it yields an empty key.
224    #[serde(skip_serializing, default)]
225    pub api_key: String,
226    /// Azure resource endpoint (e.g., `https://my-resource.openai.azure.com`).
227    pub api_base: String,
228    /// API version (e.g., "2024-02-15-preview").
229    pub api_version: String,
230    /// Deployment name/ID.
231    pub deployment_id: String,
232}
233
234impl std::fmt::Debug for AzureConfig {
235    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236        f.debug_struct("AzureConfig")
237            .field("api_key", &"[REDACTED]")
238            .field("api_base", &self.api_base)
239            .field("api_version", &self.api_version)
240            .field("deployment_id", &self.deployment_id)
241            .finish()
242    }
243}
244
245impl AzureConfig {
246    /// Create a new Azure OpenAI config.
247    pub fn new(
248        api_key: impl Into<String>,
249        api_base: impl Into<String>,
250        api_version: impl Into<String>,
251        deployment_id: impl Into<String>,
252    ) -> Self {
253        Self {
254            api_key: api_key.into(),
255            api_base: api_base.into(),
256            api_version: api_version.into(),
257            deployment_id: deployment_id.into(),
258        }
259    }
260}
261
262/// Service tier for processing priority.
263///
264/// Controls the processing priority for API requests. Priority tier
265/// provides lower latency and more consistent token generation speed.
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "lowercase")]
268pub enum ServiceTier {
269    /// Automatic tier selection (default behavior).
270    Auto,
271    /// Priority processing for lower latency.
272    Priority,
273}
274
275/// Prompt cache retention duration.
276///
277/// Controls how long prompt prefixes are cached for repeated requests.
278/// Caching reduces costs for requests that share the same prompt prefix.
279#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
280#[serde(rename_all = "snake_case")]
281pub enum PromptCacheRetention {
282    /// In-memory cache (shortest retention, lowest cost).
283    InMemory,
284    /// 24-hour cache retention.
285    #[serde(rename = "24h")]
286    TwentyFourHours,
287}
288
289/// Reasoning summary mode for the Responses API.
290///
291/// Controls whether and how the model generates a summary of its internal
292/// reasoning process. Only applicable to o-series reasoning models.
293#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
294#[serde(rename_all = "lowercase")]
295pub enum ReasoningSummary {
296    /// Let the model decide whether to include a summary.
297    Auto,
298    /// Include a brief summary of the reasoning.
299    Concise,
300    /// Include a thorough summary of the reasoning.
301    Detailed,
302}
303
304/// Configuration for the OpenAI Responses API client.
305///
306/// # Example
307///
308/// ```rust,ignore
309/// use adk_model::openai::{OpenAIResponsesConfig, ReasoningEffort, ReasoningSummary};
310///
311/// let config = OpenAIResponsesConfig::new("sk-...", "o3")
312///     .with_reasoning_effort(ReasoningEffort::High)
313///     .with_reasoning_summary(ReasoningSummary::Concise);
314/// ```
315///
316/// The API key is redacted from `Debug` output and omitted when serializing.
317#[derive(Clone, Serialize, Deserialize)]
318pub struct OpenAIResponsesConfig {
319    /// OpenAI API key. Never serialized; deserializing a config without it
320    /// yields an empty key.
321    #[serde(skip_serializing, default)]
322    pub api_key: String,
323    /// Model name (e.g., "o3", "o4-mini", "gpt-4.1").
324    pub model: String,
325    /// Optional organization ID.
326    #[serde(skip_serializing_if = "Option::is_none")]
327    pub organization_id: Option<String>,
328    /// Optional project ID.
329    #[serde(skip_serializing_if = "Option::is_none")]
330    pub project_id: Option<String>,
331    /// Optional custom base URL.
332    #[serde(skip_serializing_if = "Option::is_none")]
333    pub base_url: Option<String>,
334    /// Reasoning effort for o-series models.
335    #[serde(skip_serializing_if = "Option::is_none")]
336    pub reasoning_effort: Option<ReasoningEffort>,
337    /// Reasoning summary mode for o-series models.
338    #[serde(skip_serializing_if = "Option::is_none")]
339    pub reasoning_summary: Option<ReasoningSummary>,
340    /// Default service tier for processing priority.
341    #[serde(skip_serializing_if = "Option::is_none")]
342    pub service_tier: Option<ServiceTier>,
343    /// Default prompt cache retention policy.
344    #[serde(skip_serializing_if = "Option::is_none")]
345    pub prompt_cache_retention: Option<PromptCacheRetention>,
346    /// Enable Open Responses mode for third-party compatibility.
347    ///
348    /// When enabled, relaxes strict OpenAI field validation to support
349    /// Open Responses-compatible endpoints (LM Studio, Ollama, vLLM).
350    #[serde(skip_serializing_if = "Option::is_none")]
351    pub open_responses_mode: Option<bool>,
352}
353
354impl std::fmt::Debug for OpenAIResponsesConfig {
355    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
356        f.debug_struct("OpenAIResponsesConfig")
357            .field("api_key", &"[REDACTED]")
358            .field("model", &self.model)
359            .field("organization_id", &self.organization_id)
360            .field("project_id", &self.project_id)
361            .field("base_url", &self.base_url)
362            .field("reasoning_effort", &self.reasoning_effort)
363            .field("reasoning_summary", &self.reasoning_summary)
364            .field("service_tier", &self.service_tier)
365            .field("prompt_cache_retention", &self.prompt_cache_retention)
366            .field("open_responses_mode", &self.open_responses_mode)
367            .finish()
368    }
369}
370
371impl OpenAIResponsesConfig {
372    /// Create a new Responses API config with the given API key and model.
373    pub fn new(api_key: impl Into<String>, model: impl Into<String>) -> Self {
374        Self {
375            api_key: api_key.into(),
376            model: model.into(),
377            organization_id: None,
378            project_id: None,
379            base_url: None,
380            reasoning_effort: None,
381            reasoning_summary: None,
382            service_tier: None,
383            prompt_cache_retention: None,
384            open_responses_mode: None,
385        }
386    }
387
388    /// Set the organization ID.
389    #[must_use]
390    pub fn with_organization(mut self, org_id: impl Into<String>) -> Self {
391        self.organization_id = Some(org_id.into());
392        self
393    }
394
395    /// Set the project ID.
396    #[must_use]
397    pub fn with_project(mut self, project_id: impl Into<String>) -> Self {
398        self.project_id = Some(project_id.into());
399        self
400    }
401
402    /// Set the base URL.
403    #[must_use]
404    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
405        self.base_url = Some(base_url.into());
406        self
407    }
408
409    /// Set the reasoning effort for o-series models.
410    #[must_use]
411    pub fn with_reasoning_effort(mut self, effort: ReasoningEffort) -> Self {
412        self.reasoning_effort = Some(effort);
413        self
414    }
415
416    /// Set the reasoning summary mode for o-series models.
417    #[must_use]
418    pub fn with_reasoning_summary(mut self, summary: ReasoningSummary) -> Self {
419        self.reasoning_summary = Some(summary);
420        self
421    }
422
423    /// Set the default service tier for processing priority.
424    ///
425    /// Priority tier provides lower latency and more consistent token generation.
426    #[must_use]
427    pub fn with_service_tier(mut self, tier: ServiceTier) -> Self {
428        self.service_tier = Some(tier);
429        self
430    }
431
432    /// Set the default prompt cache retention policy.
433    ///
434    /// Controls how long prompt prefixes are cached for cost optimization.
435    #[must_use]
436    pub fn with_prompt_cache_retention(mut self, retention: PromptCacheRetention) -> Self {
437        self.prompt_cache_retention = Some(retention);
438        self
439    }
440
441    /// Enable or disable Open Responses mode.
442    ///
443    /// When enabled, relaxes strict OpenAI field validation for compatibility
444    /// with third-party Open Responses-compatible endpoints.
445    #[must_use]
446    pub fn with_open_responses_mode(mut self, enabled: bool) -> Self {
447        self.open_responses_mode = Some(enabled);
448        self
449    }
450}
451
452#[cfg(test)]
453mod effort_tests {
454    use super::{OpenAIReasoningEffort, ReasoningEffort};
455
456    #[test]
457    fn reasoning_models_take_a_reasoning_effort() {
458        for model in
459            ["gpt-5.6-terra", "gpt-5", "o3", "o4-mini", "openai/gpt-oss-120b", "ft:gpt-5:org"]
460        {
461            assert!(super::takes_reasoning_effort(model), "{model}");
462        }
463        for model in ["gpt-4.1", "gpt-4o-mini", "gpt-5-chat-latest", "omni-moderation", "llama-4"] {
464            assert!(!super::takes_reasoning_effort(model), "{model}");
465        }
466    }
467
468    /// The harness levels map to their namesakes on both effort vocabularies.
469    #[test]
470    fn every_harness_effort_maps_to_its_namesake() {
471        for (core, provider) in [
472            (adk_core::Effort::Low, ReasoningEffort::Low),
473            (adk_core::Effort::Medium, ReasoningEffort::Medium),
474            (adk_core::Effort::High, ReasoningEffort::High),
475        ] {
476            assert_eq!(ReasoningEffort::from(core), provider);
477            assert_eq!(OpenAIReasoningEffort::from(core), OpenAIReasoningEffort::from(provider));
478        }
479    }
480}