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 relocates_system_prompt_to_input(&self, request: &provider::LLMRequest, is_native_openai: bool) -> bool {
133 if !self.prompt_cache_hints_enabled || self.is_chatgpt_backend() {
134 return false;
135 }
136 if self.responses_api_state(&request.model) == ResponsesApiState::Disabled {
137 return false;
138 }
139
140 let native_explicit_cache_model =
141 is_native_openai && request_builder::supports_prompt_cache_options(&request.model);
142 let gpt62_or_later_model = request
143 .model
144 .parse::<vtcode_config::models::ModelId>()
145 .is_ok_and(|id| id.generation_at_least("6.2"));
146
147 native_explicit_cache_model || gpt62_or_later_model
148 }
149
150 fn uses_harmony(model: &str) -> bool {
151 harmony::uses_harmony(model)
152 }
153
154 fn requires_responses_api(model: &str) -> bool {
155 model == models::openai::GPT_5
156 }
157
158 fn default_responses_state(model: &str) -> ResponsesApiState {
159 if Self::requires_responses_api(model) {
160 ResponsesApiState::Required
161 } else if Self::is_responses_api_model(model) {
162 ResponsesApiState::Allowed
163 } else {
164 ResponsesApiState::Disabled
165 }
166 }
167
168 pub fn new(api_key: String) -> Self {
169 Self::with_model_internal(
170 api_key,
171 None,
172 models::openai::DEFAULT_MODEL.to_string(),
173 None,
174 None,
175 TimeoutsConfig::default(),
176 None,
177 None,
178 )
179 }
180
181 fn with_model(api_key: String, model: String) -> Self {
182 Self::with_model_internal(api_key, None, model, None, None, TimeoutsConfig::default(), None, None)
183 }
184
185 pub(crate) fn new_with_client(
186 api_key: String,
187 openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
188 model: String,
189 http_client: reqwest::Client,
190 base_url: String,
191 timeouts: TimeoutsConfig,
192 ) -> Self {
193 use hashbrown::HashMap;
194 use std::sync::Arc;
195 use std::sync::Mutex;
196
197 let backend_setup = if openai_chatgpt_auth.is_some() {
198 OpenAIBackendSetup::chatgpt_subscription_rig(base_url.clone())
199 } else {
200 OpenAIBackendSetup::api_key(base_url.clone())
201 };
202
203 Self {
204 api_key: Arc::from(api_key.as_str()),
205 provider_key_override: None,
206 provider_display_override: None,
207 custom_provider_auth: None,
208 api_format_override: None,
209 openai_chatgpt_auth,
210 http_client,
211 decisions_client: crate::http_client::HttpClientFactory::for_llm_without_redirects(&timeouts),
212 base_url: Arc::from(base_url.as_str()),
213 responses_url: Arc::from(format!("{base_url}/responses")),
214 responses_compact_url: Arc::from(format!("{base_url}/responses/compact")),
215 chat_completions_url: Arc::from(format!("{base_url}/chat/completions")),
216 backend_setup,
217 model: Arc::from(model.as_str()),
218 supported_models_override: None,
219 context_window_override: None,
220 prompt_cache_enabled: false,
221 prompt_cache_hints_enabled: true,
222 prompt_cache_settings: Default::default(),
223 prompt_cache_options_models: Vec::new(),
224 responses_api_modes: Mutex::new(HashMap::new()),
225 model_behavior: None,
226 websocket_mode: false,
227 responses_store: None,
228 responses_include: Vec::new(),
229 service_tier: None,
230 hosted_shell: OpenAIHostedShellConfig::default(),
231 websocket_session: Arc::new(AsyncMutex::new(None)),
232 websocket_continuation_cache: Arc::new(Mutex::new(None)),
233 websocket_streaming_ceiling: Duration::from_secs(if timeouts.streaming_ceiling_seconds == 0 {
234 600
235 } else {
236 timeouts.streaming_ceiling_seconds
237 }),
238 service_tier_unsupported_cache: Arc::new(Mutex::new(HashMap::new())),
239 cache_comparison: Arc::new(Mutex::new(None)),
240 }
241 }
242
243 pub fn from_config(
244 api_key: Option<String>,
245 openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
246 model: Option<String>,
247 base_url: Option<String>,
248 prompt_cache: Option<PromptCachingConfig>,
249 timeouts: Option<TimeoutsConfig>,
250 _anthropic: Option<AnthropicConfig>,
251 openai: Option<OpenAIConfig>,
252 model_behavior: Option<ModelConfig>,
253 ) -> Self {
254 let api_key_value = api_key.unwrap_or_default();
255 let model_value = resolve_model(model, models::openai::DEFAULT_MODEL);
256
257 Self::with_model_internal(
258 api_key_value,
259 openai_chatgpt_auth,
260 model_value,
261 prompt_cache,
262 base_url,
263 timeouts.unwrap_or_default(),
264 openai,
265 model_behavior,
266 )
267 }
268
269 #[expect(
271 clippy::too_many_arguments,
272 reason = "Intentional compatibility, platform, test, or API-shape suppression."
273 )]
274 pub fn from_custom_config(
275 provider_key: String,
276 display_name: String,
277 api_key: Option<String>,
278 model: Option<String>,
279 base_url: Option<String>,
280 prompt_cache: Option<PromptCachingConfig>,
281 timeouts: Option<TimeoutsConfig>,
282 openai: Option<OpenAIConfig>,
283 model_behavior: Option<ModelConfig>,
284 custom_provider_auth: Option<CustomProviderAuthHandle>,
285 supported_models_override: Option<Vec<String>>,
286 ) -> Self {
287 let mut provider = Self::from_config(
288 api_key,
289 None, model,
291 base_url,
292 prompt_cache,
293 timeouts,
294 None, openai,
296 model_behavior,
297 );
298 provider.provider_key_override = Some(Arc::from(provider_key.as_str()));
299 provider.provider_display_override = Some(Arc::from(display_name.as_str()));
300 provider.custom_provider_auth = custom_provider_auth;
301 provider.api_format_override = None;
302 if provider.custom_provider_auth.is_some() {
303 provider.backend_setup = provider.backend_setup.clone().with_custom_command_auth();
304 }
305 provider.supported_models_override = supported_models_override;
306 provider
307 }
308
309 pub(crate) fn with_prompt_cache_options_models(mut self, models: Vec<String>) -> Self {
310 self.prompt_cache_options_models = models;
311 self
312 }
313
314 pub(crate) fn with_api_format_override(mut self, api_format: Option<CustomProviderApiFormat>) -> Self {
315 self.api_format_override = api_format;
316 self
317 }
318
319 pub fn with_context_window(mut self, context_window: Option<usize>) -> Self {
321 self.context_window_override = context_window;
322 self
323 }
324
325 fn with_model_internal(
326 api_key: String,
327 openai_chatgpt_auth: Option<OpenAIChatGptAuthHandle>,
328 model: String,
329 prompt_cache: Option<PromptCachingConfig>,
330 base_url: Option<String>,
331 timeouts: TimeoutsConfig,
332 openai: Option<OpenAIConfig>,
333 model_behavior: Option<ModelConfig>,
334 ) -> Self {
335 let prompt_cache_hints_enabled = prompt_cache
336 .as_ref()
337 .is_none_or(|cfg| cfg.enabled && cfg.providers.openai.enabled);
338 let (prompt_cache_enabled, prompt_cache_settings) = extract_prompt_cache_settings(
339 prompt_cache,
340 |providers| &providers.openai,
341 |cfg, provider_settings| cfg.enabled && provider_settings.enabled,
342 );
343
344 let backend_setup = if openai_chatgpt_auth.is_some() {
345 OpenAIBackendSetup::from_chatgpt_subscription_config(base_url)
346 } else {
347 OpenAIBackendSetup::from_api_key_config(base_url)
348 };
349 let resolved_base_url = backend_setup.base_url().to_string();
350
351 let mut responses_api_modes = HashMap::new();
352 let default_state = Self::default_responses_state(&model);
353 let is_chatgpt_backend = backend_setup.is_chatgpt_codex_backend();
354 let is_xai = resolved_base_url.contains("api.x.ai");
355 let websocket_mode = openai.as_ref().map(|cfg| cfg.websocket_mode).unwrap_or(false);
356 let responses_store = openai.as_ref().and_then(|cfg| cfg.responses_store);
357 let responses_include = openai
358 .as_ref()
359 .map(|cfg| {
360 cfg.responses_include
361 .iter()
362 .map(|value| value.trim())
363 .filter(|value| !value.is_empty())
364 .map(ToOwned::to_owned)
365 .collect::<Vec<_>>()
366 })
367 .unwrap_or_default();
368 let service_tier = openai.as_ref().and_then(|cfg| cfg.service_tier);
369 let hosted_shell = openai.as_ref().map(|cfg| cfg.hosted_shell.clone()).unwrap_or_default();
370
371 let initial_state = if is_xai {
372 ResponsesApiState::Disabled
373 } else if is_chatgpt_backend {
374 match default_state {
375 ResponsesApiState::Disabled => ResponsesApiState::Allowed,
376 state => state,
377 }
378 } else {
379 default_state
380 };
381 responses_api_modes.insert(model.clone(), initial_state);
382
383 use crate::http_client::HttpClientFactory;
384 let http_client = HttpClientFactory::for_llm(&timeouts);
385 let decisions_client = HttpClientFactory::for_llm_without_redirects(&timeouts);
386
387 Self {
388 api_key: Arc::from(api_key.as_str()),
389 provider_key_override: None,
390 provider_display_override: None,
391 custom_provider_auth: None,
392 api_format_override: None,
393 openai_chatgpt_auth,
394 http_client,
395 base_url: Arc::from(resolved_base_url.as_str()),
396 decisions_client,
397 responses_url: Arc::from(format!("{resolved_base_url}/responses")),
398 responses_compact_url: Arc::from(format!("{resolved_base_url}/responses/compact")),
399 chat_completions_url: Arc::from(format!("{resolved_base_url}/chat/completions")),
400 backend_setup,
401 model: Arc::from(model.as_str()),
402 supported_models_override: None,
403 context_window_override: None,
404 responses_api_modes: Mutex::new(responses_api_modes),
405 prompt_cache_enabled,
406 prompt_cache_hints_enabled,
407 prompt_cache_settings,
408 prompt_cache_options_models: Vec::new(),
409 model_behavior,
410 websocket_mode,
411 responses_store,
412 responses_include,
413 service_tier,
414 hosted_shell,
415 websocket_session: Arc::new(AsyncMutex::new(None)),
416 websocket_continuation_cache: Arc::new(Mutex::new(None)),
417 websocket_streaming_ceiling: Duration::from_secs(if timeouts.streaming_ceiling_seconds == 0 {
418 600
419 } else {
420 timeouts.streaming_ceiling_seconds
421 }),
422 service_tier_unsupported_cache: Arc::new(Mutex::new(HashMap::new())),
423 cache_comparison: Arc::new(Mutex::new(None)),
424 }
425 }
426
427 fn is_native_openai_api(&self) -> bool {
428 self.provider_key_override.is_none() && self.backend_setup.is_native_openai_api()
429 }
430
431 fn supports_manual_openai_compaction_for_model(&self, model: &str) -> bool {
432 self.is_native_openai_api()
433 && !self.uses_chatgpt_auth()
434 && !matches!(self.responses_api_state(model), ResponsesApiState::Disabled)
435 }
436
437 fn manual_openai_compaction_unavailable_message_for_model(&self, model: &str) -> String {
438 let requested = if model.trim().is_empty() {
439 self.model.as_ref()
440 } else {
441 model
442 };
443
444 let (backend, reason) = if self.uses_chatgpt_auth() {
445 (
446 "ChatGPT subscription auth via chatgpt.com backend".to_string(),
447 "ChatGPT subscription auth does not expose the standalone `/responses/compact` endpoint".to_string(),
448 )
449 } else if self.provider_key_override.is_some() {
450 (
451 format!("custom OpenAI-compatible provider endpoint ({})", self.base_url),
452 "custom OpenAI-compatible provider endpoints do not expose the standalone `/responses/compact` endpoint"
453 .to_string(),
454 )
455 } else if !self.base_url.contains("api.openai.com") {
456 (
457 format!("configured OpenAI-compatible endpoint ({})", self.base_url),
458 "the standalone `/responses/compact` endpoint is only served by the native OpenAI API host".to_string(),
459 )
460 } else {
461 (
462 "native OpenAI API (api.openai.com)".to_string(),
463 "this model is not Responses-compatible on the native OpenAI API".to_string(),
464 )
465 };
466
467 format!(
468 "`--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.",
469 self.name(),
470 backend,
471 requested,
472 reason,
473 )
474 }
475
476 fn websocket_mode_enabled(&self, model: &str) -> bool {
477 self.websocket_mode
478 && self.backend_setup.transport().websocket
479 && !matches!(self.responses_api_state(model), ResponsesApiState::Disabled)
480 }
481
482 fn hosted_shell_for_model(&self, model: &str) -> Option<&OpenAIHostedShellConfig> {
483 (self.is_native_openai_api()
484 && !matches!(self.responses_api_state(model), ResponsesApiState::Disabled)
485 && self.hosted_shell.enabled
486 && self.hosted_shell.is_valid_for_runtime())
487 .then_some(&self.hosted_shell)
488 }
489
490 fn supports_responses_allowed_tools(&self, model: &str) -> bool {
491 self.supports_tools(model)
495 && !matches!(self.responses_api_state(model), ResponsesApiState::Disabled)
496 && (self.is_native_openai_api() || self.is_chatgpt_backend())
497 }
498
499 fn authorize_with_api_key(
500 &self,
501 builder: reqwest::RequestBuilder,
502 auth: &OpenAIRequestAuth,
503 ) -> reqwest::RequestBuilder {
504 self.backend_setup.authorize_request(builder, auth)
505 }
506
507 fn uses_chatgpt_auth(&self) -> bool {
508 self.backend_setup.uses_chatgpt_subscription_auth()
509 }
510
511 fn uses_refreshable_auth(&self) -> bool {
512 self.backend_setup.uses_refreshable_auth() || self.custom_provider_auth.is_some()
513 }
514
515 fn is_chatgpt_backend(&self) -> bool {
516 self.backend_setup.is_chatgpt_codex_backend()
517 }
518
519 fn allows_chat_completions_fallback(&self) -> bool {
520 self.backend_setup.transport().chat_completions_fallback
521 }
522
523 fn supports_temperature_parameter(model: &str) -> bool {
524 vtcode_config::models::model_catalog_entry("openai", model)
525 .map(|entry| entry.supports_sampling)
526 .unwrap_or_else(|| {
527 !matches!(model, models::openai::GPT_5 | models::openai::GPT_5_MINI | models::openai::GPT_5_NANO)
528 })
529 }
530
531 fn responses_api_state(&self, model: &str) -> ResponsesApiState {
532 if let Some(api_format) = self.api_format_override {
533 return match api_format {
534 CustomProviderApiFormat::Auto => Self::default_responses_state(model),
535 CustomProviderApiFormat::OpenAIChat => ResponsesApiState::Disabled,
536 CustomProviderApiFormat::OpenAIResponses => ResponsesApiState::Required,
537 CustomProviderApiFormat::AnthropicMessages => ResponsesApiState::Disabled,
538 };
539 }
540
541 let mut modes = match self.responses_api_modes.lock() {
542 Ok(guard) => guard,
543 Err(poisoned) => {
544 tracing::warn!("OpenAI responses_api_modes mutex poisoned, recovering");
545 poisoned.into_inner()
546 }
547 };
548 *modes
549 .entry(model.to_string())
550 .or_insert_with(|| Self::default_responses_state(model))
551 }
552
553 fn set_responses_api_state(&self, model: &str, state: ResponsesApiState) {
554 let mut modes = match self.responses_api_modes.lock() {
555 Ok(guard) => guard,
556 Err(poisoned) => {
557 tracing::warn!("OpenAI responses_api_modes mutex poisoned, recovering");
558 poisoned.into_inner()
559 }
560 };
561 modes.insert(model.to_string(), state);
562 }
563
564 fn validate_inline_file_inputs(request: &provider::LLMRequest) -> Result<(), provider::LLMError> {
565 Self::validate_inline_file_inputs_with_limit(request, MAX_INPUT_FILE_BYTES)
566 }
567
568 fn validate_inline_file_inputs_with_limit(
569 request: &provider::LLMRequest,
570 max_inline_file_bytes: u64,
571 ) -> Result<(), provider::LLMError> {
572 let mut total_inline_file_bytes = 0u64;
573
574 for message in request.messages.iter() {
575 let provider::MessageContent::Parts(parts) = &message.content else {
576 continue;
577 };
578
579 for part in parts {
580 let provider::ContentPart::File { filename, file_data, .. } = part else {
581 continue;
582 };
583 let Some(file_data) = file_data else {
584 continue;
585 };
586
587 let inline_file_bytes = decoded_base64_size(file_data).map_err(|error| {
588 let formatted = error_display::format_llm_error(
589 "OpenAI",
590 &format!("Invalid inline input_file payload: {error}"),
591 );
592 provider::LLMError::InvalidRequest { message: formatted, metadata: None }
593 })?;
594
595 if inline_file_bytes > max_inline_file_bytes {
596 let file_label = filename.as_deref().unwrap_or("attached file");
597 let formatted = error_display::format_llm_error(
598 "OpenAI",
599 &format!("{INLINE_FILE_LIMIT_ERROR_PREFIX}: '{file_label}' is {inline_file_bytes} bytes"),
600 );
601 return Err(provider::LLMError::InvalidRequest { message: formatted, metadata: None });
602 }
603
604 total_inline_file_bytes = total_inline_file_bytes.checked_add(inline_file_bytes).ok_or_else(|| {
605 provider::LLMError::InvalidRequest {
606 message: error_display::format_llm_error("OpenAI", INLINE_FILE_LIMIT_ERROR_PREFIX),
607 metadata: None,
608 }
609 })?;
610 }
611 }
612
613 if total_inline_file_bytes > max_inline_file_bytes {
614 let formatted = error_display::format_llm_error(
615 "OpenAI",
616 &format!("{INLINE_FILE_LIMIT_ERROR_PREFIX}: total inline file bytes = {total_inline_file_bytes}"),
617 );
618 return Err(provider::LLMError::InvalidRequest { message: formatted, metadata: None });
619 }
620
621 Ok(())
622 }
623
624 fn convert_to_openai_format(&self, request: &provider::LLMRequest) -> Result<Value, provider::LLMError> {
625 let is_native_openai = self.is_native_openai_api();
626 let prompt_cache_key = if self.prompt_cache_hints_enabled && is_native_openai {
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 ctx = request_builder::ChatRequestContext {
637 model: &self.model,
638 is_native_openai,
639 supports_tools: self.supports_tools(&request.model),
640 supports_parallel_tool_config: self.supports_parallel_tool_config(&request.model),
641 supports_temperature: Self::supports_temperature_parameter(&request.model),
642 prompt_cache_key,
643 default_service_tier,
644 include_structured_output: !self.is_chatgpt_backend(),
645 };
646
647 request_builder::build_chat_request(request, &ctx)
648 }
649
650 fn convert_to_openai_responses_format(&self, request: &provider::LLMRequest) -> Result<Value, provider::LLMError> {
651 Self::validate_inline_file_inputs(request)?;
652
653 let is_native_openai = self.is_native_openai_api();
654 let prompt_cache_key = if self.prompt_cache_hints_enabled && (is_native_openai || self.is_chatgpt_backend()) {
655 request.prompt_cache_key.as_deref()
656 } else {
657 None
658 };
659 let default_service_tier = if is_native_openai {
660 self.service_tier.map(OpenAIServiceTier::as_str)
661 } else {
662 None
663 };
664 let backend_defaults = self.backend_setup.responses_defaults();
665 let requested_ttl = self.requested_prompt_cache_ttl(&request.model);
666 let force_response_store_false = backend_defaults.force_store_false || self.responses_store != Some(true);
673 let ctx = request_builder::ResponsesRequestContext {
674 supports_tools: self.supports_tools(&request.model),
675 supports_allowed_tools: self.supports_responses_allowed_tools(&request.model),
676 supports_parallel_tool_config: self.supports_parallel_tool_config(&request.model),
677 supports_temperature: Self::supports_temperature_parameter(&request.model),
678 supports_reasoning_effort: self.supports_reasoning_effort(&request.model),
679 supported_reasoning_efforts: self.supported_reasoning_efforts(&request.model),
680 supports_reasoning: self.supports_reasoning(&request.model),
681 is_responses_api_model: Self::is_responses_api_model(&request.model),
682 include_max_output_tokens: is_native_openai,
683 include_output_types: !is_native_openai && backend_defaults.include_output_types,
684 include_sampling_parameters: backend_defaults.include_sampling_parameters,
685 force_response_store_false,
686 include_assistant_phase: is_native_openai,
687 prompt_cache_key,
688 include_prompt_cache_retention: self.prompt_cache_hints_enabled
689 && backend_defaults.include_prompt_cache_retention,
690 supports_prompt_cache_options: requested_ttl.is_some(),
691 prompt_cache_ttl: self.prompt_cache_settings.prompt_cache_ttl,
692 stable_prefix_ttl: requested_ttl.and(self.prompt_cache_settings.stable_prefix_ttl),
693 relocate_instructions_to_input: self.relocates_system_prompt_to_input(request, is_native_openai),
694 prompt_cache_retention: self.prompt_cache_settings.prompt_cache_retention.as_ref().map(|r| r.as_str()),
695 include_explicit_cache_breakpoints: self.prompt_cache_hints_enabled && is_native_openai,
696 default_service_tier,
697 default_response_store: self.responses_store,
698 default_responses_include: (!self.responses_include.is_empty())
699 .then_some(self.responses_include.as_slice()),
700 include_encrypted_reasoning: backend_defaults.include_encrypted_reasoning,
701 hosted_shell: self.hosted_shell_for_model(&request.model),
702 include_structured_history_in_input: backend_defaults.include_structured_history_in_input,
703 preserve_structured_history_on_replay: backend_defaults.preserve_structured_history_on_replay,
704 preserve_assistant_phase_on_replay: false,
705 reasoning_context: None,
706 safety_identifier: None,
707 include_structured_output: !self.is_chatgpt_backend(),
708 };
709
710 let mut payload = request_builder::build_responses_request(request, &ctx)?;
711 if let Some(tracker) = self.cache_comparison_tracker(request) {
712 tracker.add_comparison(&mut payload);
713 }
714 Ok(payload)
715 }
716
717 fn parse_openai_response(
718 &self,
719 response_json: Value,
720 model: String,
721 ) -> Result<provider::LLMResponse, provider::LLMError> {
722 let response = response_parser::parse_chat_response(response_json, model.clone(), true)?;
725 Ok(Self::normalize_reasoning_output(&model, response))
726 }
727
728 fn parse_openai_responses_response(
729 &self,
730 response_json: Value,
731 model: String,
732 ) -> Result<provider::LLMResponse, provider::LLMError> {
733 let response = parse_responses_completion(response_json, model.clone(), true)?;
734 Ok(Self::normalize_reasoning_output(&model, response))
735 }
736}
737
738#[cfg(test)]
739mod tests;
740
741mod harmony_client;
742mod provider_impl;