1mod 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
105const ABORTED_MESSAGE: &str = "Request was aborted.";
107
108#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
110#[non_exhaustive]
111pub enum OpenAIApi {
112 Chat,
114 #[default]
116 Responses,
117}
118
119impl OpenAIApi {
120 #[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 pub struct ApiKeySetter(Fn() -> BoxFuture<'static, std::result::Result<String, BoxError>>);
139}
140
141#[derive(Clone)]
144#[non_exhaustive]
145pub enum ApiKey {
146 Key(String),
148 Setter(ApiKeySetter),
150}
151
152impl ApiKey {
153 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#[derive(Debug, Clone, Default, PartialEq, bon::Builder)]
197pub struct OpenAIModelConfig {
198 #[builder(into)]
201 pub model_id: Option<String>,
202 pub max_tokens: Option<u64>,
205 pub temperature: Option<f64>,
207 pub top_p: Option<f64>,
209 pub context_window_limit: Option<u64>,
211 pub model_info: Option<ModelInfo>,
213 pub params: Option<JsonValue>,
223 pub cache_config: Option<CacheConfig>,
231 pub frequency_penalty: Option<f64>,
233 pub presence_penalty: Option<f64>,
235 pub stateful: Option<bool>,
240}
241
242impl OpenAIModelConfig {
243 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 #[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#[derive(Clone, Default, PartialEq, Eq, bon::Builder)]
304pub struct OpenAIClientConfig {
305 #[builder(into)]
307 pub base_url: Option<String>,
308 #[builder(into)]
310 pub organization: Option<String>,
311 #[builder(into)]
313 pub project: Option<String>,
314 #[builder(default)]
318 pub default_headers: Vec<(String, String)>,
319 pub max_retries: Option<u32>,
321 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#[derive(Clone, Default, bon::Builder)]
344#[builder(finish_fn = build_options)]
345pub struct OpenAIModelOptions {
346 #[builder(default)]
348 pub api: OpenAIApi,
349 #[builder(into)]
351 pub model_id: Option<String>,
352 pub max_tokens: Option<u64>,
354 pub temperature: Option<f64>,
356 pub top_p: Option<f64>,
358 pub context_window_limit: Option<u64>,
360 pub model_info: Option<ModelInfo>,
362 pub params: Option<JsonValue>,
364 pub cache_config: Option<CacheConfig>,
366 pub frequency_penalty: Option<f64>,
368 pub presence_penalty: Option<f64>,
370 pub stateful: Option<bool>,
372 #[builder(into)]
375 pub api_key: Option<ApiKey>,
376 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
392struct 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 pub fn build(self) -> Result<OpenAIModel> {
463 OpenAIModel::new(self.build_options())
464 }
465}
466
467#[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 rejected_reasoning_model_id: RwLock<Option<String>>,
491 #[cfg(feature = "mantle")]
492 mantle: Option<RwLock<mantle::MantleRoute>>,
493}
494
495impl OpenAIModel {
496 pub fn builder() -> OpenAIModelOptionsBuilder {
498 OpenAIModelOptions::builder()
499 }
500
501 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 #[must_use]
550 pub fn api(&self) -> OpenAIApi {
551 self.inner.api
552 }
553
554 #[must_use]
558 pub fn config(&self) -> OpenAIModelConfig {
559 resolve(&self.inner.config())
560 }
561
562 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
604fn 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
612fn 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
627fn 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
636fn 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 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
660enum 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 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
690fn 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
720fn 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
738fn 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
750async 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
765fn 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 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 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 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 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 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 fn model_id(&self) -> Option<String> {
972 Some(model_id_of(&self.inner.config()).to_owned())
973 }
974
975 fn model_info(&self) -> ModelInfo {
978 model_info_of(self.inner.api, &self.inner.config())
979 }
980}
981
982#[cfg(test)]
983mod tests;