1#![allow(
2 clippy::collapsible_if,
3 clippy::manual_contains,
4 clippy::nonminimal_bool,
5 clippy::single_match,
6 unused_imports,
7 reason = "The OpenAI provider keeps compatibility imports and provider-specific branches for feature-gated request paths."
8)]
9
10use crate::error_display;
11use crate::provider;
12use crate::provider::LLMProvider;
13use hashbrown::{HashMap, HashSet};
14use reqwest::Client as HttpClient;
15use reqwest::StatusCode;
16use reqwest::header::HeaderMap;
17use serde_json::{Value, json};
18use std::sync::Arc;
19use std::sync::Mutex;
20use std::time::Duration;
21#[cfg(debug_assertions)]
22use std::time::Instant;
23use tokio::sync::Mutex as AsyncMutex;
24use tracing::debug;
25use uuid::Uuid;
26use vtcode_commons::file_input::{MAX_INPUT_FILE_BYTES, decoded_base64_size};
27use vtcode_commons::model_family::find_family_for_model;
28use vtcode_config::TimeoutsConfig;
29use vtcode_config::auth::{OpenAIChatGptAuthHandle, OpenAIChatGptSession};
30use vtcode_config::constants::models;
31use vtcode_config::core::{
32 AnthropicConfig, ModelConfig, OpenAIConfig, OpenAIHostedShellConfig, OpenAIPromptCacheSettings, OpenAIServiceTier,
33 PromptCachingConfig,
34};
35
36use super::CustomProviderAuthHandle;
38use super::backend_setup::{OpenAIBackendSetup, OpenAIRequestAuth};
39use super::harmony;
40use super::request_builder;
41use super::response_parser;
42use super::responses_api::parse_responses_completion;
43use super::types::{MAX_COMPLETION_TOKENS_FIELD, OpenAIResponsesPayload, ResponsesApiState};
44
45mod auth;
46mod cache_diagnostics;
47mod decisions;
48mod generation;
49mod streaming;
50mod websocket;
51
52use self::websocket::{OpenAIResponsesWebSocketContinuationCache, OpenAIResponsesWebSocketSession};
53use super::super::{
54 common::{extract_prompt_cache_settings, parse_client_prompt_common, resolve_model},
55 extract_reasoning_trace,
56};
57use crate::system_prompt::default_system_prompt;
58use vtcode_config::core::CustomProviderApiFormat;
59
60const INLINE_FILE_LIMIT_ERROR_PREFIX: &str = "Inline OpenAI input_file payload exceeds the 50 MB request limit";
61
62pub struct OpenAIProvider {
63 api_key: Arc<str>,
64 provider_key_override: Option<Arc<str>>,
67 provider_display_override: Option<Arc<str>>,
70 custom_provider_auth: Option<CustomProviderAuthHandle>,
71 api_format_override: Option<CustomProviderApiFormat>,
72 openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
73 http_client: HttpClient,
74 decisions_client: Result<HttpClient, reqwest::Error>,
75 base_url: Arc<str>,
76 responses_url: Arc<str>,
77 responses_compact_url: Arc<str>,
78 chat_completions_url: Arc<str>,
79 backend_setup: OpenAIBackendSetup,
80 model: Arc<str>,
81 supported_models_override: Option<Vec<String>>,
82 context_window_override: Option<usize>,
83 responses_api_modes: Mutex<HashMap<String, ResponsesApiState>>,
84 prompt_cache_enabled: bool,
85 prompt_cache_hints_enabled: bool,
86 prompt_cache_settings: OpenAIPromptCacheSettings,
87 prompt_cache_options_models: Vec<String>,
88 model_behavior: Option<ModelConfig>,
89 websocket_mode: bool,
90 responses_store: Option<bool>,
91 responses_include: Vec<String>,
92 service_tier: Option<OpenAIServiceTier>,
93 hosted_shell: OpenAIHostedShellConfig,
94 websocket_session: Arc<AsyncMutex<Option<OpenAIResponsesWebSocketSession>>>,
95 websocket_continuation_cache: Arc<Mutex<Option<OpenAIResponsesWebSocketContinuationCache>>>,
96 websocket_streaming_ceiling: Duration,
97 service_tier_unsupported_cache: Arc<Mutex<HashMap<String, bool>>>,
101 cache_comparison: Arc<Mutex<Option<cache_diagnostics::CacheComparison>>>,
102}
103
104impl OpenAIProvider {
105 fn requires_streaming_responses(model: &str) -> bool {
106 models::openai::STREAMING_REQUIRED_MODELS.contains(&model)
107 }
108
109 fn model_supports_reasoning_summaries(model: &str) -> bool {
110 find_family_for_model(model).supports_reasoning_summaries
111 }
112
113 fn normalize_reasoning_output(model: &str, mut response: provider::LLMResponse) -> provider::LLMResponse {
114 crate::providers::common::suppress_unsupported_reasoning_output(model, &mut response);
115 response
116 }
117
118 fn is_responses_api_model(model: &str) -> bool {
119 models::openai::RESPONSES_API_MODELS.contains(&model)
120 }
121
122 fn uses_harmony(model: &str) -> bool {
123 harmony::uses_harmony(model)
124 }
125
126 fn requires_responses_api(model: &str) -> bool {
127 model == models::openai::GPT_5
128 }
129
130 fn default_responses_state(model: &str) -> ResponsesApiState {
131 if Self::requires_responses_api(model) {
132 ResponsesApiState::Required
133 } else if Self::is_responses_api_model(model) {
134 ResponsesApiState::Allowed
135 } else {
136 ResponsesApiState::Disabled
137 }
138 }
139
140 pub fn new(api_key: String) -> Self {
141 Self::with_model_internal(
142 api_key,
143 None,
144 models::openai::DEFAULT_MODEL.to_string(),
145 None,
146 None,
147 TimeoutsConfig::default(),
148 None,
149 None,
150 )
151 }
152
153 fn with_model(api_key: String, model: String) -> Self {
154 Self::with_model_internal(api_key, None, model, None, None, TimeoutsConfig::default(), None, None)
155 }
156
157 pub(crate) fn new_with_client(
158 api_key: String,
159 openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
160 model: String,
161 http_client: reqwest::Client,
162 base_url: String,
163 timeouts: TimeoutsConfig,
164 ) -> Self {
165 use hashbrown::HashMap;
166 use std::sync::Arc;
167 use std::sync::Mutex;
168
169 let backend_setup = if openai_chatgpt_auth.is_some() {
170 OpenAIBackendSetup::chatgpt_subscription_rig(base_url.clone())
171 } else {
172 OpenAIBackendSetup::api_key(base_url.clone())
173 };
174
175 Self {
176 api_key: Arc::from(api_key.as_str()),
177 provider_key_override: None,
178 provider_display_override: None,
179 custom_provider_auth: None,
180 api_format_override: None,
181 openai_chatgpt_auth,
182 http_client,
183 decisions_client: crate::http_client::HttpClientFactory::for_llm_without_redirects(&timeouts),
184 base_url: Arc::from(base_url.as_str()),
185 responses_url: Arc::from(format!("{base_url}/responses")),
186 responses_compact_url: Arc::from(format!("{base_url}/responses/compact")),
187 chat_completions_url: Arc::from(format!("{base_url}/chat/completions")),
188 backend_setup,
189 model: Arc::from(model.as_str()),
190 supported_models_override: None,
191 context_window_override: None,
192 prompt_cache_enabled: false,
193 prompt_cache_hints_enabled: true,
194 prompt_cache_settings: Default::default(),
195 prompt_cache_options_models: Vec::new(),
196 responses_api_modes: Mutex::new(HashMap::new()),
197 model_behavior: None,
198 websocket_mode: false,
199 responses_store: None,
200 responses_include: Vec::new(),
201 service_tier: None,
202 hosted_shell: OpenAIHostedShellConfig::default(),
203 websocket_session: Arc::new(AsyncMutex::new(None)),
204 websocket_continuation_cache: Arc::new(Mutex::new(None)),
205 websocket_streaming_ceiling: Duration::from_secs(if timeouts.streaming_ceiling_seconds == 0 {
206 600
207 } else {
208 timeouts.streaming_ceiling_seconds
209 }),
210 service_tier_unsupported_cache: Arc::new(Mutex::new(HashMap::new())),
211 cache_comparison: Arc::new(Mutex::new(None)),
212 }
213 }
214
215 pub fn from_config(
216 api_key: Option<String>,
217 openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
218 model: Option<String>,
219 base_url: Option<String>,
220 prompt_cache: Option<PromptCachingConfig>,
221 timeouts: Option<TimeoutsConfig>,
222 _anthropic: Option<AnthropicConfig>,
223 openai: Option<OpenAIConfig>,
224 model_behavior: Option<ModelConfig>,
225 ) -> Self {
226 let api_key_value = api_key.unwrap_or_default();
227 let model_value = resolve_model(model, models::openai::DEFAULT_MODEL);
228
229 Self::with_model_internal(
230 api_key_value,
231 openai_chatgpt_auth,
232 model_value,
233 prompt_cache,
234 base_url,
235 timeouts.unwrap_or_default(),
236 openai,
237 model_behavior,
238 )
239 }
240
241 #[expect(
243 clippy::too_many_arguments,
244 reason = "Intentional compatibility, platform, test, or API-shape suppression."
245 )]
246 pub fn from_custom_config(
247 provider_key: String,
248 display_name: String,
249 api_key: Option<String>,
250 model: Option<String>,
251 base_url: Option<String>,
252 prompt_cache: Option<PromptCachingConfig>,
253 timeouts: Option<TimeoutsConfig>,
254 openai: Option<OpenAIConfig>,
255 model_behavior: Option<ModelConfig>,
256 custom_provider_auth: Option<CustomProviderAuthHandle>,
257 supported_models_override: Option<Vec<String>>,
258 ) -> Self {
259 let mut provider = Self::from_config(
260 api_key,
261 None, model,
263 base_url,
264 prompt_cache,
265 timeouts,
266 None, openai,
268 model_behavior,
269 );
270 provider.provider_key_override = Some(Arc::from(provider_key.as_str()));
271 provider.provider_display_override = Some(Arc::from(display_name.as_str()));
272 provider.custom_provider_auth = custom_provider_auth;
273 provider.api_format_override = None;
274 if provider.custom_provider_auth.is_some() {
275 provider.backend_setup = provider.backend_setup.clone().with_custom_command_auth();
276 }
277 provider.supported_models_override = supported_models_override;
278 provider
279 }
280
281 pub(crate) fn with_prompt_cache_options_models(mut self, models: Vec<String>) -> Self {
282 self.prompt_cache_options_models = models;
283 self
284 }
285
286 pub(crate) fn with_api_format_override(mut self, api_format: Option<CustomProviderApiFormat>) -> Self {
287 self.api_format_override = api_format;
288 self
289 }
290
291 pub fn with_context_window(mut self, context_window: Option<usize>) -> Self {
293 self.context_window_override = context_window;
294 self
295 }
296
297 fn with_model_internal(
298 api_key: String,
299 openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
300 model: String,
301 prompt_cache: Option<PromptCachingConfig>,
302 base_url: Option<String>,
303 timeouts: TimeoutsConfig,
304 openai: Option<OpenAIConfig>,
305 model_behavior: Option<ModelConfig>,
306 ) -> Self {
307 let prompt_cache_hints_enabled = prompt_cache
308 .as_ref()
309 .is_none_or(|cfg| cfg.enabled && cfg.providers.openai.enabled);
310 let (prompt_cache_enabled, prompt_cache_settings) = extract_prompt_cache_settings(
311 prompt_cache,
312 |providers| &providers.openai,
313 |cfg, provider_settings| cfg.enabled && provider_settings.enabled,
314 );
315
316 let backend_setup = if openai_chatgpt_auth.is_some() {
317 OpenAIBackendSetup::from_chatgpt_subscription_config(base_url)
318 } else {
319 OpenAIBackendSetup::from_api_key_config(base_url)
320 };
321 let resolved_base_url = backend_setup.base_url().to_string();
322
323 let mut responses_api_modes = HashMap::new();
324 let default_state = Self::default_responses_state(&model);
325 let is_chatgpt_backend = backend_setup.is_chatgpt_codex_backend();
326 let is_xai = resolved_base_url.contains("api.x.ai");
327 let websocket_mode = openai.as_ref().map(|cfg| cfg.websocket_mode).unwrap_or(false);
328 let responses_store = openai.as_ref().and_then(|cfg| cfg.responses_store);
329 let responses_include = openai
330 .as_ref()
331 .map(|cfg| {
332 cfg.responses_include
333 .iter()
334 .map(|value| value.trim())
335 .filter(|value| !value.is_empty())
336 .map(ToOwned::to_owned)
337 .collect::<Vec<_>>()
338 })
339 .unwrap_or_default();
340 let service_tier = openai.as_ref().and_then(|cfg| cfg.service_tier);
341 let hosted_shell = openai.as_ref().map(|cfg| cfg.hosted_shell.clone()).unwrap_or_default();
342
343 let initial_state = if is_xai {
344 ResponsesApiState::Disabled
345 } else if is_chatgpt_backend {
346 match default_state {
347 ResponsesApiState::Disabled => ResponsesApiState::Allowed,
348 state => state,
349 }
350 } else {
351 default_state
352 };
353 responses_api_modes.insert(model.clone(), initial_state);
354
355 use crate::http_client::HttpClientFactory;
356 let http_client = HttpClientFactory::for_llm(&timeouts);
357 let decisions_client = HttpClientFactory::for_llm_without_redirects(&timeouts);
358
359 Self {
360 api_key: Arc::from(api_key.as_str()),
361 provider_key_override: None,
362 provider_display_override: None,
363 custom_provider_auth: None,
364 api_format_override: None,
365 openai_chatgpt_auth,
366 http_client,
367 base_url: Arc::from(resolved_base_url.as_str()),
368 decisions_client,
369 responses_url: Arc::from(format!("{resolved_base_url}/responses")),
370 responses_compact_url: Arc::from(format!("{resolved_base_url}/responses/compact")),
371 chat_completions_url: Arc::from(format!("{resolved_base_url}/chat/completions")),
372 backend_setup,
373 model: Arc::from(model.as_str()),
374 supported_models_override: None,
375 context_window_override: None,
376 responses_api_modes: Mutex::new(responses_api_modes),
377 prompt_cache_enabled,
378 prompt_cache_hints_enabled,
379 prompt_cache_settings,
380 prompt_cache_options_models: Vec::new(),
381 model_behavior,
382 websocket_mode,
383 responses_store,
384 responses_include,
385 service_tier,
386 hosted_shell,
387 websocket_session: Arc::new(AsyncMutex::new(None)),
388 websocket_continuation_cache: Arc::new(Mutex::new(None)),
389 websocket_streaming_ceiling: Duration::from_secs(if timeouts.streaming_ceiling_seconds == 0 {
390 600
391 } else {
392 timeouts.streaming_ceiling_seconds
393 }),
394 service_tier_unsupported_cache: Arc::new(Mutex::new(HashMap::new())),
395 cache_comparison: Arc::new(Mutex::new(None)),
396 }
397 }
398
399 fn is_native_openai_api(&self) -> bool {
400 self.provider_key_override.is_none() && self.backend_setup.is_native_openai_api()
401 }
402
403 fn supports_manual_openai_compaction_for_model(&self, model: &str) -> bool {
404 self.is_native_openai_api()
405 && !self.uses_chatgpt_auth()
406 && !matches!(self.responses_api_state(model), ResponsesApiState::Disabled)
407 }
408
409 fn manual_openai_compaction_unavailable_message_for_model(&self, model: &str) -> String {
410 let requested = if model.trim().is_empty() {
411 self.model.as_ref()
412 } else {
413 model
414 };
415
416 let (backend, reason) = if self.uses_chatgpt_auth() {
417 (
418 "ChatGPT subscription auth via chatgpt.com backend".to_string(),
419 "ChatGPT subscription auth does not expose the standalone `/responses/compact` endpoint".to_string(),
420 )
421 } else if self.provider_key_override.is_some() {
422 (
423 format!("custom OpenAI-compatible provider endpoint ({})", self.base_url),
424 "custom OpenAI-compatible provider endpoints do not expose the standalone `/responses/compact` endpoint"
425 .to_string(),
426 )
427 } else if !self.base_url.contains("api.openai.com") {
428 (
429 format!("configured OpenAI-compatible endpoint ({})", self.base_url),
430 "the standalone `/responses/compact` endpoint is only served by the native OpenAI API host".to_string(),
431 )
432 } else {
433 (
434 "native OpenAI API (api.openai.com)".to_string(),
435 "this model is not Responses-compatible on the native OpenAI API".to_string(),
436 )
437 };
438
439 format!(
440 "`--native-only` `/compact` requires a native server-side compaction endpoint, which is unavailable for this configuration. Active provider/backend/model: {} / {} / {}. Reason: {}. Run `/compact` without `--native-only` to compact via the local summarization fallback.",
441 self.name(),
442 backend,
443 requested,
444 reason,
445 )
446 }
447
448 fn websocket_mode_enabled(&self, model: &str) -> bool {
449 self.websocket_mode
450 && self.backend_setup.transport().websocket
451 && !matches!(self.responses_api_state(model), ResponsesApiState::Disabled)
452 }
453
454 fn hosted_shell_for_model(&self, model: &str) -> Option<&OpenAIHostedShellConfig> {
455 (self.is_native_openai_api()
456 && !matches!(self.responses_api_state(model), ResponsesApiState::Disabled)
457 && self.hosted_shell.enabled
458 && self.hosted_shell.is_valid_for_runtime())
459 .then_some(&self.hosted_shell)
460 }
461
462 fn supports_responses_allowed_tools(&self, model: &str) -> bool {
463 self.supports_tools(model)
467 && !matches!(self.responses_api_state(model), ResponsesApiState::Disabled)
468 && (self.is_native_openai_api() || self.is_chatgpt_backend())
469 }
470
471 fn authorize_with_api_key(
472 &self,
473 builder: reqwest::RequestBuilder,
474 auth: &OpenAIRequestAuth,
475 ) -> reqwest::RequestBuilder {
476 self.backend_setup.authorize_request(builder, auth)
477 }
478
479 fn uses_chatgpt_auth(&self) -> bool {
480 self.backend_setup.uses_chatgpt_subscription_auth()
481 }
482
483 fn uses_refreshable_auth(&self) -> bool {
484 self.backend_setup.uses_refreshable_auth() || self.custom_provider_auth.is_some()
485 }
486
487 fn is_chatgpt_backend(&self) -> bool {
488 self.backend_setup.is_chatgpt_codex_backend()
489 }
490
491 fn allows_chat_completions_fallback(&self) -> bool {
492 self.backend_setup.transport().chat_completions_fallback
493 }
494
495 fn supports_temperature_parameter(model: &str) -> bool {
496 vtcode_config::models::model_catalog_entry("openai", model)
497 .map(|entry| entry.supports_sampling)
498 .unwrap_or_else(|| {
499 !matches!(model, models::openai::GPT_5 | models::openai::GPT_5_MINI | models::openai::GPT_5_NANO)
500 })
501 }
502
503 fn responses_api_state(&self, model: &str) -> ResponsesApiState {
504 if let Some(api_format) = self.api_format_override {
505 return match api_format {
506 CustomProviderApiFormat::Auto => Self::default_responses_state(model),
507 CustomProviderApiFormat::OpenAIChat => ResponsesApiState::Disabled,
508 CustomProviderApiFormat::OpenAIResponses => ResponsesApiState::Required,
509 CustomProviderApiFormat::AnthropicMessages => ResponsesApiState::Disabled,
510 };
511 }
512
513 let mut modes = match self.responses_api_modes.lock() {
514 Ok(guard) => guard,
515 Err(poisoned) => {
516 tracing::warn!("OpenAI responses_api_modes mutex poisoned, recovering");
517 poisoned.into_inner()
518 }
519 };
520 *modes
521 .entry(model.to_string())
522 .or_insert_with(|| Self::default_responses_state(model))
523 }
524
525 fn set_responses_api_state(&self, model: &str, state: ResponsesApiState) {
526 let mut modes = match self.responses_api_modes.lock() {
527 Ok(guard) => guard,
528 Err(poisoned) => {
529 tracing::warn!("OpenAI responses_api_modes mutex poisoned, recovering");
530 poisoned.into_inner()
531 }
532 };
533 modes.insert(model.to_string(), state);
534 }
535
536 fn validate_inline_file_inputs(request: &provider::LLMRequest) -> Result<(), provider::LLMError> {
537 Self::validate_inline_file_inputs_with_limit(request, MAX_INPUT_FILE_BYTES)
538 }
539
540 fn validate_inline_file_inputs_with_limit(
541 request: &provider::LLMRequest,
542 max_inline_file_bytes: u64,
543 ) -> Result<(), provider::LLMError> {
544 let mut total_inline_file_bytes = 0u64;
545
546 for message in request.messages.iter() {
547 let provider::MessageContent::Parts(parts) = &message.content else {
548 continue;
549 };
550
551 for part in parts {
552 let provider::ContentPart::File { filename, file_data, .. } = part else {
553 continue;
554 };
555 let Some(file_data) = file_data else {
556 continue;
557 };
558
559 let inline_file_bytes = decoded_base64_size(file_data).map_err(|error| {
560 let formatted = error_display::format_llm_error(
561 "OpenAI",
562 &format!("Invalid inline input_file payload: {error}"),
563 );
564 provider::LLMError::InvalidRequest { message: formatted, metadata: None }
565 })?;
566
567 if inline_file_bytes > max_inline_file_bytes {
568 let file_label = filename.as_deref().unwrap_or("attached file");
569 let formatted = error_display::format_llm_error(
570 "OpenAI",
571 &format!("{INLINE_FILE_LIMIT_ERROR_PREFIX}: '{file_label}' is {inline_file_bytes} bytes"),
572 );
573 return Err(provider::LLMError::InvalidRequest { message: formatted, metadata: None });
574 }
575
576 total_inline_file_bytes = total_inline_file_bytes.checked_add(inline_file_bytes).ok_or_else(|| {
577 provider::LLMError::InvalidRequest {
578 message: error_display::format_llm_error("OpenAI", INLINE_FILE_LIMIT_ERROR_PREFIX),
579 metadata: None,
580 }
581 })?;
582 }
583 }
584
585 if total_inline_file_bytes > max_inline_file_bytes {
586 let formatted = error_display::format_llm_error(
587 "OpenAI",
588 &format!("{INLINE_FILE_LIMIT_ERROR_PREFIX}: total inline file bytes = {total_inline_file_bytes}"),
589 );
590 return Err(provider::LLMError::InvalidRequest { message: formatted, metadata: None });
591 }
592
593 Ok(())
594 }
595
596 fn convert_to_openai_format(&self, request: &provider::LLMRequest) -> Result<Value, provider::LLMError> {
597 let is_native_openai = self.is_native_openai_api();
598 let prompt_cache_key = if self.prompt_cache_hints_enabled && is_native_openai {
599 request.prompt_cache_key.as_deref()
600 } else {
601 None
602 };
603 let default_service_tier = if is_native_openai {
604 self.service_tier.map(OpenAIServiceTier::as_str)
605 } else {
606 None
607 };
608 let ctx = request_builder::ChatRequestContext {
609 model: &self.model,
610 is_native_openai,
611 supports_tools: self.supports_tools(&request.model),
612 supports_parallel_tool_config: self.supports_parallel_tool_config(&request.model),
613 supports_temperature: Self::supports_temperature_parameter(&request.model),
614 prompt_cache_key,
615 default_service_tier,
616 include_structured_output: !self.is_chatgpt_backend(),
617 };
618
619 request_builder::build_chat_request(request, &ctx)
620 }
621
622 fn convert_to_openai_responses_format(&self, request: &provider::LLMRequest) -> Result<Value, provider::LLMError> {
623 Self::validate_inline_file_inputs(request)?;
624
625 let is_native_openai = self.is_native_openai_api();
626 let prompt_cache_key = if self.prompt_cache_hints_enabled && (is_native_openai || self.is_chatgpt_backend()) {
627 request.prompt_cache_key.as_deref()
628 } else {
629 None
630 };
631 let default_service_tier = if is_native_openai {
632 self.service_tier.map(OpenAIServiceTier::as_str)
633 } else {
634 None
635 };
636 let backend_defaults = self.backend_setup.responses_defaults();
637 let requested_ttl = self.requested_prompt_cache_ttl(&request.model);
638 let force_response_store_false = backend_defaults.force_store_false || self.responses_store != Some(true);
645 let ctx = request_builder::ResponsesRequestContext {
646 supports_tools: self.supports_tools(&request.model),
647 supports_allowed_tools: self.supports_responses_allowed_tools(&request.model),
648 supports_parallel_tool_config: self.supports_parallel_tool_config(&request.model),
649 supports_temperature: Self::supports_temperature_parameter(&request.model),
650 supports_reasoning_effort: self.supports_reasoning_effort(&request.model),
651 supported_reasoning_efforts: self.supported_reasoning_efforts(&request.model),
652 supports_reasoning: self.supports_reasoning(&request.model),
653 is_responses_api_model: Self::is_responses_api_model(&request.model),
654 include_max_output_tokens: is_native_openai,
655 include_output_types: !is_native_openai && backend_defaults.include_output_types,
656 include_sampling_parameters: backend_defaults.include_sampling_parameters,
657 force_response_store_false,
658 include_assistant_phase: is_native_openai,
659 prompt_cache_key,
660 include_prompt_cache_retention: self.prompt_cache_hints_enabled
661 && backend_defaults.include_prompt_cache_retention,
662 supports_prompt_cache_options: requested_ttl.is_some(),
663 prompt_cache_ttl: self.prompt_cache_settings.prompt_cache_ttl,
664 stable_prefix_ttl: requested_ttl.and(self.prompt_cache_settings.stable_prefix_ttl),
665 prompt_cache_retention: self.prompt_cache_settings.prompt_cache_retention.as_ref().map(|r| r.as_str()),
666 include_explicit_cache_breakpoints: self.prompt_cache_hints_enabled && is_native_openai,
667 default_service_tier,
668 default_response_store: self.responses_store,
669 default_responses_include: (!self.responses_include.is_empty())
670 .then_some(self.responses_include.as_slice()),
671 include_encrypted_reasoning: backend_defaults.include_encrypted_reasoning,
672 hosted_shell: self.hosted_shell_for_model(&request.model),
673 include_structured_history_in_input: backend_defaults.include_structured_history_in_input,
674 preserve_structured_history_on_replay: backend_defaults.preserve_structured_history_on_replay,
675 preserve_assistant_phase_on_replay: false,
676 reasoning_context: None,
677 safety_identifier: None,
678 include_structured_output: !self.is_chatgpt_backend(),
679 };
680
681 let mut payload = request_builder::build_responses_request(request, &ctx)?;
682 if let Some(tracker) = self.cache_comparison_tracker(request) {
683 tracker.add_comparison(&mut payload);
684 }
685 Ok(payload)
686 }
687
688 fn parse_openai_response(
689 &self,
690 response_json: Value,
691 model: String,
692 ) -> Result<provider::LLMResponse, provider::LLMError> {
693 let response = response_parser::parse_chat_response(response_json, model.clone(), true)?;
696 Ok(Self::normalize_reasoning_output(&model, response))
697 }
698
699 fn parse_openai_responses_response(
700 &self,
701 response_json: Value,
702 model: String,
703 ) -> Result<provider::LLMResponse, provider::LLMError> {
704 let response = parse_responses_completion(response_json, model.clone(), true)?;
705 Ok(Self::normalize_reasoning_output(&model, response))
706 }
707}
708
709#[cfg(test)]
710mod tests;
711
712mod harmony_client;
713mod provider_impl;