1use crate::PROVIDER_NAME;
2use crate::{
3 DEEPSEEK_BASE_URL, DEFAULT_AUDIO_FORMAT, DEFAULT_AUDIO_MODEL, DEFAULT_AUDIO_VOICE,
4 DEFAULT_BASE_URL, DEFAULT_EMBEDDING_DIM, DEFAULT_EMBEDDING_MODEL, DEFAULT_IDLE_TIMEOUT,
5 DEFAULT_IMAGE_MODEL, DEFAULT_MODEL, DEFAULT_MODERATION_MODEL, DEFAULT_TRANSCRIPTION_MODEL,
6 OPENROUTER_BASE_URL,
7 error::OpenAIError,
8 request::{
9 ChatCompletionRequest, ChatMessagePayload, ParameterSnapshot, ResponsesInputItem,
10 ResponsesRequest, ResponsesTool, ToolPayload, convert_responses_tools, convert_tools,
11 responses_tool_choice, to_chat_messages, to_responses_input,
12 },
13 response::{
14 ChatCompletionChunk, ChatCompletionUsage, DeltaToolCall, ResponsesOutputItem,
15 ResponsesStreamEvent, ResponsesUsage, should_skip_event,
16 },
17};
18use aither_core::time::sleep;
19use aither_core::{
20 LanguageModel,
21 llm::{
22 Classify, Event, GenerateError, LLMRequest, ReasoningState, RetryPolicy, TokenCounting,
23 ToolCall, Usage,
24 model::{Ability, Profile as ModelProfile, ToolChoice},
25 oneshot,
26 },
27};
28use futures_core::Stream;
29use futures_lite::StreamExt;
30use std::{collections::HashMap, future::Future, sync::Arc, time::Duration};
31use zenwave::{Client, client, header};
32
33async fn within_idle<T>(idle: Duration, fut: impl Future<Output = T>) -> Result<T, OpenAIError> {
40 futures_lite::future::or(async move { Ok(fut.await) }, async move {
41 sleep(idle).await;
42 Err(OpenAIError::IdleTimeout { idle })
43 })
44 .await
45}
46
47async fn request_within_idle<T>(
49 idle: Duration,
50 fut: impl Future<Output = Result<T, zenwave::Error>>,
51) -> Result<T, OpenAIError> {
52 within_idle(idle, fut).await?.map_err(OpenAIError::Http)
53}
54
55type SseStreamResult = Result<zenwave::sse::SseStream, OpenAIError>;
57
58async fn sse_request_with_retry<F, Fut>(cfg: &Config, make_request: F) -> SseStreamResult
62where
63 F: Fn() -> Fut,
64 Fut: std::future::Future<Output = SseStreamResult>,
65{
66 let policy = &cfg.retry;
67 let mut attempt = 0;
68
69 loop {
70 match make_request().await {
71 Ok(stream) => return Ok(stream),
72 Err(err) => {
73 let failure = err.failure();
74 if policy.allows(attempt, &failure) {
75 let delay = policy.delay(attempt, &failure);
76 tracing::warn!(
77 attempt = attempt + 1,
78 max_retries = policy.max_retries,
79 delay_ms = delay.as_millis(),
80 error = %err,
81 "Request failed, retrying"
82 );
83 sleep(delay).await;
84 attempt += 1;
85 } else {
86 return Err(err);
87 }
88 }
89 }
90 }
91}
92
93#[derive(Clone, Debug)]
96pub struct OpenAI {
97 inner: Arc<Config>,
98}
99
100#[derive(Clone, Copy, Debug, Eq, PartialEq)]
102pub enum ApiKind {
103 Responses,
105 ChatCompletions,
107}
108
109impl OpenAI {
110 pub fn new(api_key: impl Into<String>) -> Self {
112 Self::builder(api_key).build()
113 }
114
115 pub fn deepseek(api_key: impl Into<String>) -> Self {
117 Self::builder(api_key).base_url(DEEPSEEK_BASE_URL).build()
118 }
119
120 pub fn openrouter(api_key: impl Into<String>) -> Self {
122 Self::builder(api_key).base_url(OPENROUTER_BASE_URL).build()
123 }
124
125 #[must_use]
127 pub fn builder(api_key: impl Into<String>) -> Builder {
128 Builder::new(api_key)
129 }
130
131 #[must_use]
133 pub fn with_model(mut self, model: impl Into<String>) -> Self {
134 let model = sanitize_model(model);
135 let cfg = Arc::make_mut(&mut self.inner);
136 #[cfg(feature = "tokenizer")]
137 {
138 cfg.vocabulary = aither_core::tokenizer::Vocabulary::for_model(&model);
139 }
140 cfg.chat_model = model;
141 self
142 }
143
144 #[must_use]
146 pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
147 Arc::make_mut(&mut self.inner).base_url = base_url.into();
148 self
149 }
150
151 #[must_use]
153 pub fn with_idle_timeout(mut self, idle_timeout: Duration) -> Self {
154 Arc::make_mut(&mut self.inner).idle_timeout = idle_timeout;
155 self
156 }
157
158 #[must_use]
160 pub fn with_api(mut self, api: ApiKind) -> Self {
161 Arc::make_mut(&mut self.inner).api_kind = api;
162 self
163 }
164
165 #[must_use]
167 pub fn with_responses_api(self) -> Self {
168 self.with_api(ApiKind::Responses)
169 }
170
171 #[must_use]
173 pub fn with_chat_completions_api(self) -> Self {
174 self.with_api(ApiKind::ChatCompletions)
175 }
176
177 #[must_use]
181 pub fn with_legacy_max_tokens(mut self, enabled: bool) -> Self {
182 Arc::make_mut(&mut self.inner).legacy_max_tokens = enabled;
183 self
184 }
185
186 #[must_use]
188 pub fn with_embedding_model(mut self, model: impl Into<String>) -> Self {
189 let model = sanitize_model(model);
190 let cfg = Arc::make_mut(&mut self.inner);
191 cfg.embedding_model = model;
192 if let Some(dim) = infer_embedding_dim(&cfg.embedding_model) {
193 cfg.embedding_dimensions = dim;
194 }
195 self
196 }
197
198 #[must_use]
200 pub fn with_embedding_dimensions(mut self, dimensions: usize) -> Self {
201 Arc::make_mut(&mut self.inner).embedding_dimensions = dimensions;
202 self
203 }
204
205 #[must_use]
207 pub fn with_image_model(mut self, model: impl Into<String>) -> Self {
208 Arc::make_mut(&mut self.inner).image_model = sanitize_model(model);
209 self
210 }
211
212 #[must_use]
214 pub fn with_audio_model(mut self, model: impl Into<String>) -> Self {
215 Arc::make_mut(&mut self.inner).audio_model = sanitize_model(model);
216 self
217 }
218
219 #[must_use]
221 pub fn with_audio_voice(mut self, voice: impl Into<String>) -> Self {
222 Arc::make_mut(&mut self.inner).audio_voice = voice.into();
223 self
224 }
225
226 #[must_use]
228 pub fn with_audio_format(mut self, format: impl Into<String>) -> Self {
229 Arc::make_mut(&mut self.inner).audio_format = format.into();
230 self
231 }
232
233 #[must_use]
235 pub fn with_transcription_model(mut self, model: impl Into<String>) -> Self {
236 Arc::make_mut(&mut self.inner).transcription_model = sanitize_model(model);
237 self
238 }
239
240 #[must_use]
242 pub fn with_moderation_model(mut self, model: impl Into<String>) -> Self {
243 Arc::make_mut(&mut self.inner).moderation_model = sanitize_model(model);
244 self
245 }
246
247 pub(crate) fn config(&self) -> Arc<Config> {
248 self.inner.clone()
249 }
250}
251
252impl LanguageModel for OpenAI {
253 type Error = OpenAIError;
254
255 fn token_counting(&self) -> TokenCounting {
256 #[cfg(feature = "tokenizer")]
257 if self.inner.vocabulary.is_some() {
258 return TokenCounting::Local;
259 }
260 TokenCounting::None
261 }
262
263 #[allow(clippy::unused_async_trait_impl)]
264 async fn count_tokens(
265 &self,
266 request: &LLMRequest,
267 ) -> Result<Option<u32>, GenerateError<Self::Error>> {
268 #[cfg(feature = "tokenizer")]
269 if let Some(vocabulary) = self.inner.vocabulary {
270 let request = request.clone();
271 return Ok(Some(
272 blocking::unblock(move || vocabulary.count_request(&request)).await,
273 ));
274 }
275 let _ = request;
276 Ok(None)
277 }
278
279 fn count_text(&self, text: &str) -> Option<u32> {
280 #[cfg(feature = "tokenizer")]
281 if let Some(vocabulary) = self.inner.vocabulary {
282 return Some(vocabulary.count_text(text));
283 }
284 let _ = text;
285 None
286 }
287
288 #[allow(clippy::too_many_lines)]
289 fn respond(
290 &self,
291 request: LLMRequest,
292 ) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
293 let cfg = self.inner.clone();
294 let (messages, parameters, tool_defs) = request.into_parts();
295 let tool_defs = filter_tool_definitions(tool_defs, ¶meters.tool_choice);
296 let mut snapshot = ParameterSnapshot::from(¶meters);
297 snapshot.legacy_max_tokens = cfg.legacy_max_tokens;
298 let has_attachments = messages.iter().any(|msg| !msg.attachments().is_empty());
299 let has_audio = messages.iter().any(|message| {
300 message
301 .attachments()
302 .iter()
303 .any(|attachment| attachment.media_type().as_ref().starts_with("audio/"))
304 });
305 let effective_api_kind = if cfg.api_kind == ApiKind::Responses && has_audio {
306 ApiKind::ChatCompletions
307 } else {
308 cfg.api_kind
309 };
310
311 async_stream::stream! {
312 if effective_api_kind == ApiKind::ChatCompletions
313 && messages.iter().flat_map(aither_core::llm::Message::attachments).any(|attachment| {
314 let media_type = attachment.media_type().as_ref();
315 !media_type.starts_with("image/") && !media_type.starts_with("audio/")
316 })
317 {
318 yield Err(OpenAIError::Api(
319 "Chat Completions accepts only image and audio attachments".to_string(),
320 ));
321 return;
322 }
323
324 if effective_api_kind == ApiKind::Responses
325 && messages.iter().flat_map(aither_core::llm::Message::attachments).any(|attachment| {
326 attachment.media_type().as_ref().starts_with("video/")
327 })
328 {
329 yield Err(OpenAIError::Api(
330 "OpenAI Responses API does not support video attachments".to_string(),
331 ));
332 return;
333 }
334
335 if effective_api_kind == ApiKind::ChatCompletions
336 && (!snapshot.openai_tools.is_empty() || snapshot.websearch || snapshot.code_execution)
337 {
338 yield Err(OpenAIError::Api(
339 "OpenAI native hosted tools require the Responses API".to_string(),
340 ));
341 return;
342 }
343
344 let messages = if has_attachments && effective_api_kind == ApiKind::Responses {
345 #[cfg(not(target_arch = "wasm32"))]
346 {
347 match crate::attachments::resolve_messages(&cfg, messages).await {
348 Ok(resolved) => resolved,
349 Err(err) => {
350 yield Err(err);
351 return;
352 }
353 }
354 }
355 #[cfg(target_arch = "wasm32")]
356 {
357 yield Err(OpenAIError::Api(
358 "file:// attachments are not supported on wasm32 targets".to_string(),
359 ));
360 return;
361 }
362 } else {
363 messages
364 };
365
366 match effective_api_kind {
367 ApiKind::ChatCompletions => {
368 let payload_messages = match to_chat_messages(&messages).await {
369 Ok(payload) => payload,
370 Err(error) => {
371 yield Err(error);
372 return;
373 }
374 };
375 let openai_tools = if tool_defs.is_empty() {
376 None
377 } else {
378 Some(convert_tools(tool_defs))
379 };
380
381 let mut events = chat_completions_stream(
382 cfg,
383 payload_messages,
384 snapshot,
385 openai_tools,
386 );
387
388 while let Some(event) = events.next().await {
389 yield event;
390 }
391 }
392 ApiKind::Responses => {
393 let responses_input = match to_responses_input(&messages) {
394 Ok(input) => input,
395 Err(err) => {
396 yield Err(err);
397 return;
398 }
399 };
400
401 let mut events = responses_stream(
402 cfg,
403 responses_input,
404 snapshot,
405 tool_defs,
406 );
407
408 while let Some(event) = events.next().await {
409 yield event;
410 }
411 }
412 }
413 }
414 }
415
416 fn complete(&self, prefix: &str) -> impl Stream<Item = Result<Event, Self::Error>> + Send {
417 self.respond(oneshot(
418 "Continue the user provided text without additional commentary.",
419 prefix,
420 ))
421 }
422
423 fn retry_policy(&self) -> RetryPolicy {
424 self.inner.retry
425 }
426
427 fn profile(&self) -> impl Future<Output = Result<ModelProfile, Self::Error>> + Send {
428 let cfg = self.inner.clone();
429 async move {
430 let context_length = match fetch_model_context_length(&cfg).await {
432 Ok(len) => len,
433 Err(e) => {
434 tracing::debug!("API did not return context_length: {e}");
435 aither_models::lookup(&cfg.chat_model)
436 .and_then(aither_models::ModelEntry::max_input_tokens)
437 .ok_or_else(|| {
438 OpenAIError::Api(format!(
439 "cannot determine context length for model '{model}': \
440 {models_url} request failed ({e}) and aither-models has no entry",
441 model = cfg.chat_model,
442 models_url = cfg.request_url("/models"),
443 ))
444 })?
445 }
446 };
447
448 let mut profile = ModelProfile::new(
449 cfg.chat_model.clone(),
450 "OpenAI",
451 cfg.chat_model.clone(),
452 "OpenAI GPT family model",
453 context_length,
454 )
455 .with_ability(Ability::ToolUse);
456 if takes_per_message_effort(&cfg) {
457 profile.abilities.push(Ability::PerMessageEffort);
458 }
459 profile.default_reasoning_effort =
460 aither_models::default_reasoning_effort(&cfg.chat_model);
461 for ability in &cfg.native_abilities {
462 if !profile.abilities.contains(ability) {
463 profile.abilities.push(*ability);
464 }
465 }
466 Ok(profile)
467 }
468 }
469}
470
471fn takes_per_message_effort(cfg: &Config) -> bool {
479 cfg.api_kind == ApiKind::Responses
480 && cfg.base_url.trim_end_matches('/') == DEFAULT_BASE_URL
481 && aither_models::lookup(&cfg.chat_model)
482 .is_some_and(|entry| entry.has_ability(Ability::PerMessageEffort))
483}
484
485async fn fetch_model_context_length(cfg: &Config) -> Result<u32, OpenAIError> {
487 use crate::response::ModelsListResponse;
488
489 let url = cfg.request_url("/models");
490 let mut backend = client();
491 let mut builder = backend
492 .get(&url)
493 .map_err(OpenAIError::Http)?
494 .header(
495 header::AUTHORIZATION.as_str(),
496 format!("Bearer {}", cfg.api_key),
497 )
498 .map_err(OpenAIError::Http)?;
499 for (name, value) in &cfg.extra_headers {
500 builder = builder
501 .header(name.clone(), value.clone())
502 .map_err(OpenAIError::Http)?;
503 }
504 let response: ModelsListResponse =
505 request_within_idle(cfg.idle_timeout, builder.json()).await?;
506
507 let mut model_found = false;
509 for model in response.data {
510 if model.id == cfg.chat_model {
511 model_found = true;
512 if let Some(ctx) = model.context_length.or(model.max_tokens) {
513 tracing::debug!(
514 "Fetched context_length={} for model '{}'",
515 ctx,
516 cfg.chat_model
517 );
518 return Ok(ctx);
519 }
520 }
521 }
522
523 if model_found {
525 Err(OpenAIError::Api(format!(
526 "Model '{}' found but missing context_length field (proxy may not support it)",
527 cfg.chat_model
528 )))
529 } else {
530 Err(OpenAIError::Api(format!(
531 "Model '{}' not found in /models response",
532 cfg.chat_model
533 )))
534 }
535}
536
537fn chat_completions_stream(
538 cfg: Arc<Config>,
539 payload_messages: Vec<ChatMessagePayload>,
540 snapshot: ParameterSnapshot,
541 openai_tools: Option<Vec<ToolPayload>>,
542) -> impl Stream<Item = Result<Event, OpenAIError>> + Send + Unpin {
543 Box::pin(chat_completions_stream_inner(
544 cfg,
545 payload_messages,
546 snapshot,
547 openai_tools,
548 ))
549}
550
551#[derive(Debug, Default)]
553struct ToolCallAccumulator {
554 id: Option<String>,
555 name: Option<String>,
556 arguments: String,
557 emitted: usize,
559 announced: bool,
561}
562
563fn accumulate_tool_call_delta<'a>(
570 tool_calls: &'a mut HashMap<usize, ToolCallAccumulator>,
571 call: &DeltaToolCall,
572) -> &'a mut ToolCallAccumulator {
573 let index = call.index.unwrap_or(0);
574 let acc = tool_calls.entry(index).or_default();
575 if let Some(id) = &call.id
576 && !id.is_empty()
577 {
578 acc.id = Some(id.clone());
579 }
580 if let Some(function) = &call.function {
581 if let Some(name) = &function.name
582 && !name.is_empty()
583 {
584 acc.name = Some(name.clone());
585 }
586 if let Some(args) = &function.arguments {
587 acc.arguments.push_str(args);
588 }
589 }
590 acc
591}
592
593async fn chat_completions_request(
595 cfg: &Config,
596 request: &ChatCompletionRequest,
597) -> SseStreamResult {
598 let endpoint = cfg.request_url("/chat/completions");
599 let mut backend = client();
600
601 let build_result = backend
602 .post(endpoint)
603 .and_then(|b| b.header(header::AUTHORIZATION.as_str(), cfg.request_auth()))
604 .and_then(|b| b.header(header::USER_AGENT.as_str(), "aither-openai/0.1"))
605 .and_then(|b| b.header(header::ACCEPT.as_str(), "text/event-stream"));
606
607 let mut builder = build_result.map_err(OpenAIError::Http)?;
608
609 if let Some(org) = &cfg.organization {
610 builder = builder
611 .header("OpenAI-Organization", org.clone())
612 .map_err(OpenAIError::Http)?;
613 }
614 for (name, value) in &cfg.extra_headers {
615 builder = builder
616 .header(name.clone(), value.clone())
617 .map_err(OpenAIError::Http)?;
618 }
619
620 request_within_idle(
621 cfg.idle_timeout,
622 builder.json_body(request).map_err(OpenAIError::Http)?.sse(),
623 )
624 .await
625}
626
627#[allow(clippy::too_many_lines)]
628fn chat_completions_stream_inner(
629 cfg: Arc<Config>,
630 payload_messages: Vec<ChatMessagePayload>,
631 snapshot: ParameterSnapshot,
632 openai_tools: Option<Vec<ToolPayload>>,
633) -> impl Stream<Item = Result<Event, OpenAIError>> + Send {
634 let include_reasoning = snapshot.include_reasoning;
635
636 async_stream::stream! {
637 let request = ChatCompletionRequest::new(
638 cfg.chat_model.clone(),
639 payload_messages,
640 &snapshot,
641 openai_tools,
642 true,
643 );
644
645 tracing::debug!(request = %serde_json::to_string_pretty(&request).unwrap_or_default(), "Sending chat completion request");
646
647 let sse_stream = match sse_request_with_retry(&cfg, || chat_completions_request(&cfg, &request)).await {
649 Ok(stream) => stream,
650 Err(e) => {
651 yield Err(e);
652 return;
653 }
654 };
655 futures_lite::pin!(sse_stream);
656
657 let mut tool_calls: std::collections::HashMap<usize, ToolCallAccumulator> =
659 std::collections::HashMap::new();
660 let mut usage: Option<Usage> = None;
661 loop {
662 let event = match within_idle(cfg.idle_timeout, sse_stream.next()).await {
663 Ok(Some(event)) => event,
664 Ok(None) => break,
665 Err(e) => {
666 yield Err(e);
667 return;
668 }
669 };
670 match event {
671 Ok(e) => {
672 if should_skip_event(&e) {
673 continue;
674 }
675 let data = e.text_data();
676 if data == "[DONE]" {
677 continue;
678 }
679 tracing::debug!(sse_event = %data, "Received SSE event");
680
681 if let Ok(error_obj) = serde_json::from_str::<serde_json::Value>(data)
683 && let Some(error) = error_obj.get("error") {
684 yield Err(OpenAIError::from_stream_event(error));
685 return;
686 }
687
688 match serde_json::from_str::<ChatCompletionChunk>(data) {
689 Ok(chunk) => {
690 if let Some(chunk_usage) = &chunk.usage {
691 usage = Some(usage_from_chat_completion(chunk_usage));
692 }
693 for choice in &chunk.choices {
695 if let Some(ref reason) = choice.finish_reason
697 && reason.contains("malformed_function_call") {
698 yield Err(OpenAIError::Api("malformed function call".to_string()));
699 return;
700 }
701
702 if let Some(content) = &choice.delta.content
703 && !content.is_empty() {
704 yield Ok(Event::Text(content.clone()));
705 }
706 if include_reasoning
708 && let Some(reasoning) = &choice.delta.reasoning_content
709 && !reasoning.is_empty() {
710 yield Ok(Event::Reasoning(reasoning.clone()));
711 }
712 if let Some(calls) = &choice.delta.tool_calls {
714 for call in calls {
715 let acc = accumulate_tool_call_delta(&mut tool_calls, call);
716 if let (Some(id), Some(name)) = (&acc.id, &acc.name) {
722 let fragment =
723 acc.arguments[acc.emitted..].to_string();
724 if !fragment.is_empty() || !acc.announced {
725 acc.emitted = acc.arguments.len();
726 acc.announced = true;
727 yield Ok(Event::ToolCallDelta {
728 id: id.clone(),
729 name: name.clone(),
730 arguments_fragment: fragment,
731 });
732 }
733 }
734 }
735 }
736 }
737 }
738 Err(e) => {
739 yield Err(OpenAIError::from(e));
740 return;
741 }
742 }
743 }
744 Err(e) => {
745 yield Err(OpenAIError::from(e));
746 return;
747 }
748 }
749 }
750
751 let mut sorted_calls: Vec<_> = tool_calls.into_iter().collect();
753 sorted_calls.sort_by_key(|(index, _)| *index);
754 for (_, acc) in sorted_calls {
755 if let (Some(id), Some(name)) = (acc.id, acc.name) {
756 let arguments = if acc.arguments.is_empty() {
757 serde_json::Value::Object(serde_json::Map::default())
758 } else {
759 serde_json::from_str(&acc.arguments).unwrap_or_else(|_| {
760 serde_json::Value::Object(serde_json::Map::default())
761 })
762 };
763 yield Ok(Event::ToolCall(ToolCall {
764 id,
765 name,
766 arguments,
767 reasoning_state: None,
768 }));
769 }
770 }
771 if let Some(final_usage) = usage {
772 yield Ok(Event::Usage(final_usage));
773 }
774 }
775}
776
777fn responses_stream(
778 cfg: Arc<Config>,
779 input: Vec<ResponsesInputItem>,
780 snapshot: ParameterSnapshot,
781 tool_defs: Vec<aither_core::llm::tool::ToolDefinition>,
782) -> impl Stream<Item = Result<Event, OpenAIError>> + Send + Unpin {
783 Box::pin(responses_stream_inner(cfg, input, snapshot, tool_defs))
784}
785
786#[derive(Debug, Default)]
788struct FunctionCallAccumulator {
789 item_id: Option<String>,
790 call_id: Option<String>,
791 name: Option<String>,
792 arguments: String,
793 emitted: bool,
794}
795
796fn normalize_response_call_id(call_id: Option<String>, fallback: &str) -> String {
797 match call_id {
798 Some(call_id) if !call_id.trim().is_empty() => call_id,
799 _ => fallback.to_string(),
800 }
801}
802
803fn non_empty_response_id(value: Option<String>) -> Option<String> {
804 value.filter(|value| !value.trim().is_empty())
805}
806
807fn fallback_response_item_id(output_index: usize) -> String {
808 format!("response_output_{output_index}")
809}
810
811fn parse_tool_call_arguments(arguments: &str) -> serde_json::Value {
812 if arguments.is_empty() {
813 serde_json::Value::Object(serde_json::Map::default())
814 } else {
815 serde_json::from_str(arguments)
816 .unwrap_or_else(|_| serde_json::Value::Object(serde_json::Map::default()))
817 }
818}
819
820fn usage_from_chat_completion(raw: &ChatCompletionUsage) -> Usage {
821 Usage {
822 prompt_tokens: raw.prompt_tokens,
823 completion_tokens: raw.completion_tokens,
824 total_tokens: raw.total_tokens,
825 reasoning_tokens: raw
826 .completion_tokens_details
827 .as_ref()
828 .and_then(|details| details.reasoning_tokens),
829 cache_read_tokens: raw
830 .prompt_tokens_details
831 .as_ref()
832 .and_then(|details| details.cached_tokens),
833 cache_write_tokens: None,
834 cost_usd: None,
835 stop_reason: None,
836 }
837}
838
839fn usage_from_responses(raw: &ResponsesUsage) -> Usage {
840 Usage {
841 prompt_tokens: raw.input_tokens,
842 completion_tokens: raw.output_tokens,
843 total_tokens: raw.total_tokens,
844 reasoning_tokens: raw
845 .output_tokens_details
846 .as_ref()
847 .and_then(|details| details.reasoning_tokens),
848 cache_read_tokens: raw
849 .input_tokens_details
850 .as_ref()
851 .and_then(|details| details.cached_tokens),
852 cache_write_tokens: None,
853 cost_usd: None,
854 stop_reason: None,
855 }
856}
857
858fn mark_and_emit_done_function_call(
859 function_calls: &mut HashMap<usize, FunctionCallAccumulator>,
860 output_index: usize,
861 item_id: Option<String>,
862 response_id: String,
863 call_id: Option<String>,
864 name: String,
865 arguments: &str,
866) -> ToolCall {
867 let fallback_id = non_empty_response_id(item_id.clone())
868 .or_else(|| non_empty_response_id(Some(response_id.clone())))
869 .unwrap_or_else(|| fallback_response_item_id(output_index));
870 let resolved_call_id = normalize_response_call_id(call_id, &fallback_id);
871
872 let acc = function_calls.entry(output_index).or_default();
873 acc.item_id =
874 non_empty_response_id(item_id).or_else(|| non_empty_response_id(Some(response_id)));
875 acc.call_id = Some(resolved_call_id.clone());
876 acc.name = Some(name.clone());
877 acc.arguments.clear();
878 acc.arguments.push_str(arguments);
879 acc.emitted = true;
880
881 ToolCall {
882 id: resolved_call_id,
883 name,
884 arguments: parse_tool_call_arguments(arguments),
885 reasoning_state: None,
886 }
887}
888
889fn drain_pending_function_calls(
890 function_calls: HashMap<usize, FunctionCallAccumulator>,
891) -> Vec<ToolCall> {
892 function_calls
893 .into_iter()
894 .filter(|(_, acc)| !acc.emitted)
895 .filter_map(|(output_index, acc)| {
896 let name = acc.name?;
897 let fallback_id = acc
898 .item_id
899 .clone()
900 .unwrap_or_else(|| fallback_response_item_id(output_index));
901 let call_id = normalize_response_call_id(acc.call_id, &fallback_id);
902 Some(ToolCall {
903 id: call_id,
904 name,
905 arguments: parse_tool_call_arguments(&acc.arguments),
906 reasoning_state: None,
907 })
908 })
909 .collect()
910}
911
912#[allow(clippy::items_after_statements)]
913fn validate_serialized_responses_request(request: &ResponsesRequest) -> Result<(), OpenAIError> {
914 let request_value = serde_json::to_value(request).map_err(OpenAIError::Json)?;
915 let Some(items) = request_value
916 .get("input")
917 .and_then(serde_json::Value::as_array)
918 else {
919 return Ok(());
920 };
921
922 fn find_blank_call_id(value: &serde_json::Value, path: &str) -> Option<(String, String)> {
923 match value {
924 serde_json::Value::Object(map) => {
925 for (key, child) in map {
926 let child_path = format!("{path}.{key}");
927 if key == "call_id"
928 && let Some(call_id) = child.as_str()
929 && call_id.trim().is_empty()
930 {
931 return Some((child_path, call_id.to_string()));
932 }
933 if let Some(found) = find_blank_call_id(child, &child_path) {
934 return Some(found);
935 }
936 }
937 None
938 }
939 serde_json::Value::Array(items) => {
940 for (index, child) in items.iter().enumerate() {
941 let child_path = format!("{path}[{index}]");
942 if let Some(found) = find_blank_call_id(child, &child_path) {
943 return Some(found);
944 }
945 }
946 None
947 }
948 serde_json::Value::Null
949 | serde_json::Value::Bool(_)
950 | serde_json::Value::Number(_)
951 | serde_json::Value::String(_) => None,
952 }
953 }
954
955 for (index, item) in items.iter().enumerate() {
956 if let Some((path, call_id)) = find_blank_call_id(item, &format!("input[{index}]")) {
957 let snippet = serde_json::to_string(item).map_err(OpenAIError::Json)?;
958 return Err(OpenAIError::Api(format!(
959 "responses request serialized blank call_id at {path}: {call_id:?}; item={snippet}"
960 )));
961 }
962 }
963 Ok(())
964}
965
966async fn responses_request(cfg: &Config, request: &ResponsesRequest) -> SseStreamResult {
968 validate_serialized_responses_request(request)?;
969 let serialized_request = serde_json::to_string(request).map_err(OpenAIError::Json)?;
970 let endpoint = cfg.request_url("/responses");
971 let mut backend = client();
972
973 let build_result = backend
974 .post(endpoint)
975 .and_then(|b| b.header(header::AUTHORIZATION.as_str(), cfg.request_auth()))
976 .and_then(|b| b.header(header::USER_AGENT.as_str(), "aither-openai/0.1"))
977 .and_then(|b| b.header(header::ACCEPT.as_str(), "text/event-stream"));
978
979 let mut builder = build_result.map_err(OpenAIError::Http)?;
980
981 if let Some(org) = &cfg.organization {
982 builder = builder
983 .header("OpenAI-Organization", org.clone())
984 .map_err(OpenAIError::Http)?;
985 }
986 for (name, value) in &cfg.extra_headers {
987 builder = builder
988 .header(name.clone(), value.clone())
989 .map_err(OpenAIError::Http)?;
990 }
991
992 match request_within_idle(
993 cfg.idle_timeout,
994 builder.json_body(request).map_err(OpenAIError::Http)?.sse(),
995 )
996 .await
997 {
998 Ok(stream) => Ok(stream),
999 Err(error) => {
1000 if error.to_string().contains("call_id") {
1001 return Err(OpenAIError::Api(format!(
1002 "{error}\nSerialized responses request: {serialized_request}"
1003 )));
1004 }
1005 Err(error)
1006 }
1007 }
1008}
1009
1010#[allow(clippy::too_many_lines, clippy::collapsible_match)]
1011fn responses_stream_inner(
1012 cfg: Arc<Config>,
1013 input: Vec<ResponsesInputItem>,
1014 snapshot: ParameterSnapshot,
1015 tool_defs: Vec<aither_core::llm::tool::ToolDefinition>,
1016) -> impl Stream<Item = Result<Event, OpenAIError>> + Send {
1017 let include_reasoning = snapshot.include_reasoning;
1018
1019 async_stream::stream! {
1020 let mut response_tools = convert_responses_tools(tool_defs);
1021 let allow_builtins = matches!(snapshot.tool_choice, ToolChoice::Auto | ToolChoice::Required);
1022 if allow_builtins {
1023 let native_tools = snapshot.openai_tools.clone();
1024 if snapshot.websearch || native_tools.web_search.is_some() {
1025 let tool = native_tools.web_search.unwrap_or_default();
1026 response_tools.push(ResponsesTool::from(tool));
1027 }
1028 for tool in native_tools.file_search {
1029 response_tools.push(ResponsesTool::from(tool));
1030 }
1031 if snapshot.code_execution || native_tools.code_interpreter.is_some() {
1032 let tool = native_tools.code_interpreter.unwrap_or_default();
1033 response_tools.push(ResponsesTool::from(tool));
1034 }
1035 if let Some(tool) = native_tools.image_generation {
1036 response_tools.push(ResponsesTool::from(tool));
1037 }
1038 for tool in native_tools.mcp {
1039 response_tools.push(ResponsesTool::from(tool));
1040 }
1041 if let Some(tool) = native_tools.computer_use {
1042 response_tools.push(ResponsesTool::from(tool));
1043 }
1044 }
1045 let response_tools = if response_tools.is_empty() {
1046 None
1047 } else {
1048 Some(response_tools)
1049 };
1050 let has_tools = response_tools.is_some();
1051 let tool_choice = responses_tool_choice(&snapshot, has_tools);
1052
1053 let mut request = ResponsesRequest::new(
1054 cfg.chat_model.clone(),
1055 input,
1056 &snapshot,
1057 response_tools,
1058 tool_choice,
1059 true, );
1061 request.store = cfg.store;
1062 let serialized_request = serde_json::to_string(&request).unwrap_or_default();
1063
1064 tracing::debug!(request = %serde_json::to_string_pretty(&request).unwrap_or_default(), "Sending responses request");
1065
1066 let sse_stream = match sse_request_with_retry(&cfg, || responses_request(&cfg, &request)).await {
1068 Ok(stream) => stream,
1069 Err(e) => {
1070 yield Err(e);
1071 return;
1072 }
1073 };
1074 futures_lite::pin!(sse_stream);
1075
1076 let mut function_calls: HashMap<usize, FunctionCallAccumulator> = HashMap::new();
1079 let mut usage: Option<Usage> = None;
1080 let mut usage_emitted = false;
1081
1082 loop {
1083 let event = match within_idle(cfg.idle_timeout, sse_stream.next()).await {
1084 Ok(Some(event)) => event,
1085 Ok(None) => break,
1086 Err(e) => {
1087 yield Err(e);
1088 return;
1089 }
1090 };
1091 match event {
1092 Ok(e) => {
1093 if should_skip_event(&e) {
1094 continue;
1095 }
1096 let data = e.text_data();
1097 if data == "[DONE]" {
1098 continue;
1099 }
1100 tracing::trace!(sse_event = %data, "Received Responses API SSE event");
1101
1102 if let Ok(error_obj) = serde_json::from_str::<serde_json::Value>(data)
1104 && let Some(error) = error_obj.get("error") {
1105 let mut event_error = OpenAIError::from_stream_event(error);
1106 if let OpenAIError::StreamEvent { message, .. } = &mut event_error
1107 && message.contains("call_id")
1108 {
1109 *message = format!(
1110 "{message}\nSerialized responses request: {serialized_request}"
1111 );
1112 }
1113 yield Err(event_error);
1114 return;
1115 }
1116
1117 match serde_json::from_str::<ResponsesStreamEvent>(data) {
1118 Ok(stream_event) => {
1119 match stream_event {
1120 ResponsesStreamEvent::ResponseCreated { response } => {
1121 if let Some(meta) = response.and_then(|resp| resp.usage) {
1122 usage = Some(usage_from_responses(&meta));
1123 }
1124 }
1125 ResponsesStreamEvent::OutputTextDelta { delta, .. } => {
1126 if !delta.is_empty() {
1127 yield Ok(Event::Text(delta));
1128 }
1129 }
1130 ResponsesStreamEvent::ReasoningTextDelta { delta, .. } |
1131 ResponsesStreamEvent::ReasoningSummaryTextDelta { delta, .. } => {
1132 if include_reasoning && !delta.is_empty() {
1133 yield Ok(Event::Reasoning(delta));
1134 }
1135 }
1136 ResponsesStreamEvent::OutputItemAdded { item, item_id, output_index } => {
1137 if let Some(event) = builtin_call_event(&item) {
1138 yield Ok(event);
1139 }
1140 if let ResponsesOutputItem::FunctionCall { id, call_id, name, .. } = item {
1142 let fallback_id = non_empty_response_id(item_id.clone())
1143 .or_else(|| non_empty_response_id(Some(id.clone())))
1144 .unwrap_or_else(|| fallback_response_item_id(output_index));
1145 let acc = function_calls.entry(output_index).or_default();
1146 acc.item_id = non_empty_response_id(item_id)
1147 .or_else(|| non_empty_response_id(Some(id)));
1148 acc.call_id = Some(normalize_response_call_id(call_id, &fallback_id));
1149 acc.name = Some(name.clone());
1150 if let Some(ref call_id) = acc.call_id {
1152 yield Ok(Event::ToolCallDelta {
1153 id: call_id.clone(),
1154 name,
1155 arguments_fragment: String::new(),
1156 });
1157 }
1158 }
1159 }
1160 ResponsesStreamEvent::FunctionCallArgumentsDelta { delta, output_index, .. } => {
1161 let acc = function_calls.entry(output_index).or_default();
1162 acc.arguments.push_str(&delta);
1163 if let (Some(call_id), Some(name)) = (&acc.call_id, &acc.name) {
1165 yield Ok(Event::ToolCallDelta {
1166 id: call_id.clone(),
1167 name: name.clone(),
1168 arguments_fragment: delta,
1169 });
1170 }
1171 }
1172 ResponsesStreamEvent::FunctionCallArgumentsDone { arguments, output_index, .. } => {
1173 let acc = function_calls.entry(output_index).or_default();
1174 acc.arguments = arguments;
1175 }
1176 ResponsesStreamEvent::OutputItemDone { item, item_id, output_index } => {
1177 if let Some(event) = builtin_result_event(&item) {
1178 yield Ok(event);
1179 }
1180 if let ResponsesOutputItem::FunctionCall { id, call_id, name, arguments } = item {
1182 let tool_call = mark_and_emit_done_function_call(
1183 &mut function_calls,
1184 output_index,
1185 item_id,
1186 id,
1187 call_id,
1188 name,
1189 &arguments,
1190 );
1191 yield Ok(Event::ToolCall(tool_call));
1192 } else if let ResponsesOutputItem::Reasoning {
1193 id, encrypted_content, ..
1194 } = item
1195 {
1196 if let Some(encrypted) = encrypted_content {
1199 let payload = serde_json::json!({
1200 "type": "reasoning",
1201 "id": id,
1202 "encrypted_content": encrypted,
1203 });
1204 yield Ok(Event::ReasoningState(ReasoningState::new(
1205 PROVIDER_NAME,
1206 payload.to_string(),
1207 )));
1208 }
1209 }
1210 }
1211 ResponsesStreamEvent::ResponseCompleted { response } => {
1212 if let Some(meta) = response.usage {
1213 let final_usage = usage_from_responses(&meta);
1214 usage = Some(final_usage.clone());
1215 yield Ok(Event::Usage(final_usage));
1216 usage_emitted = true;
1217 }
1218 }
1219 ResponsesStreamEvent::ResponseFailed { response } => {
1220 let (code, message) = response
1221 .and_then(|response| response.error)
1222 .map_or((None, None), |e| (e.code, e.message));
1223 yield Err(responses_event_error(
1224 code,
1225 message.unwrap_or_else(|| "Response failed".to_string()),
1226 &serialized_request,
1227 ));
1228 return;
1229 }
1230 ResponsesStreamEvent::Error { message, code } => {
1231 yield Err(responses_event_error(
1232 code,
1233 message.unwrap_or_else(|| "Unknown error".to_string()),
1234 &serialized_request,
1235 ));
1236 return;
1237 }
1238 _ => {}
1240 }
1241 }
1242 Err(e) => {
1243 tracing::warn!(error = %e, data = %data, "Failed to parse Responses API event");
1244 }
1245 }
1246 }
1247 Err(e) => {
1248 yield Err(OpenAIError::from(e));
1249 return;
1250 }
1251 }
1252 }
1253
1254 for tool_call in drain_pending_function_calls(function_calls) {
1256 yield Ok(Event::ToolCall(tool_call));
1257 }
1258 if !usage_emitted && let Some(final_usage) = usage {
1259 yield Ok(Event::Usage(final_usage));
1260 }
1261 }
1262}
1263
1264fn responses_event_error(
1270 code: Option<String>,
1271 message: String,
1272 serialized_request: &str,
1273) -> OpenAIError {
1274 let message = if message.contains("call_id") {
1275 format!("{message}\nSerialized responses request: {serialized_request}")
1276 } else {
1277 message
1278 };
1279 OpenAIError::StreamEvent {
1280 error_type: None,
1281 code,
1282 message,
1283 }
1284}
1285
1286fn builtin_call_event(item: &ResponsesOutputItem) -> Option<Event> {
1287 let (id, tool, detail) = match item {
1288 ResponsesOutputItem::WebSearchCall { id, action, .. } => (
1289 id.as_str(),
1290 "web_search",
1291 action
1292 .as_ref()
1293 .and_then(|action| {
1294 action
1295 .get("query")
1296 .or_else(|| action.get("url"))
1297 .and_then(serde_json::Value::as_str)
1298 })
1299 .unwrap_or_default()
1300 .to_string(),
1301 ),
1302 ResponsesOutputItem::FileSearchCall { id, queries, .. } => {
1303 (id.as_str(), "file_search", queries.join(", "))
1304 }
1305 ResponsesOutputItem::CodeInterpreterCall { id, code, .. } => (
1306 id.as_str(),
1307 "code_interpreter",
1308 code.clone().unwrap_or_default(),
1309 ),
1310 _ => return None,
1311 };
1312 Some(Event::builtin_call(id, tool, detail))
1313}
1314
1315fn builtin_result_event(item: &ResponsesOutputItem) -> Option<Event> {
1317 let (id, tool, result) = match item {
1318 ResponsesOutputItem::WebSearchCall { id, status, action } => {
1319 let detail = action.as_ref().and_then(|action| {
1320 action
1321 .get("query")
1322 .or_else(|| action.get("url"))
1323 .and_then(serde_json::Value::as_str)
1324 });
1325 let result = detail.map_or_else(
1326 || status.clone().unwrap_or_else(|| "completed".to_string()),
1327 |detail| format!("\"{detail}\""),
1328 );
1329 (id.as_str(), "web_search", result)
1330 }
1331 ResponsesOutputItem::FileSearchCall {
1332 id,
1333 queries,
1334 results,
1335 status,
1336 } => {
1337 let count = results.as_ref().map_or_else(
1338 || status.clone().unwrap_or_else(|| "completed".to_string()),
1339 |results| format!("{} results", results.len()),
1340 );
1341 (
1342 id.as_str(),
1343 "file_search",
1344 format!("{count} for {}", queries.join(", ")),
1345 )
1346 }
1347 ResponsesOutputItem::CodeInterpreterCall { id, status, code } => {
1348 let result = code
1349 .clone()
1350 .unwrap_or_else(|| status.clone().unwrap_or_else(|| "completed".to_string()));
1351 (id.as_str(), "code_interpreter", result)
1352 }
1353 _ => return None,
1354 };
1355 Some(Event::builtin_result(id, tool, result))
1356}
1357
1358#[cfg(test)]
1359mod tests {
1360 #[cfg(feature = "tokenizer")]
1364 #[tokio::test]
1365 async fn a_published_family_model_counts_locally() {
1366 let client = OpenAI::builder("key").model("gpt-4o").build();
1367 assert_eq!(client.token_counting(), TokenCounting::Local);
1368 assert_eq!(client.count_text("hello world"), Some(2));
1369 let request = LLMRequest::new(vec![aither_core::llm::Message::user("hello world")]);
1370 let counted = client
1371 .count_tokens(&request)
1372 .await
1373 .expect("count succeeds")
1374 .expect("the model counts");
1375 assert_eq!(counted, 8);
1377 }
1378
1379 #[cfg(feature = "tokenizer")]
1381 #[tokio::test]
1382 async fn an_unmapped_model_does_not_count() {
1383 let client = OpenAI::builder("key")
1384 .model("unregistered-stub-model")
1385 .build();
1386 assert_eq!(client.token_counting(), TokenCounting::None);
1387 assert_eq!(client.count_text("hello world"), None);
1388 }
1389
1390 use super::*;
1391 use crate::response::{
1392 ChatCompletionTokensDetails, ChatCompletionUsage, ChatPromptTokensDetails,
1393 DeltaToolFunction, ResponsesUsage,
1394 };
1395 use std::time::Duration;
1396
1397 fn chat_delta(id: Option<&str>, name: Option<&str>, arguments: &str) -> DeltaToolCall {
1398 DeltaToolCall {
1399 index: Some(0),
1400 id: id.map(str::to_string),
1401 function: Some(DeltaToolFunction {
1402 name: name.map(str::to_string),
1403 arguments: Some(arguments.to_string()),
1404 }),
1405 }
1406 }
1407
1408 #[test]
1409 fn chat_tool_call_accumulates_name_and_arguments() {
1410 let mut tool_calls = HashMap::new();
1411 accumulate_tool_call_delta(
1412 &mut tool_calls,
1413 &chat_delta(Some("call_1"), Some("search"), ""),
1414 );
1415 accumulate_tool_call_delta(&mut tool_calls, &chat_delta(None, None, "{\"q\":"));
1416 accumulate_tool_call_delta(&mut tool_calls, &chat_delta(None, None, "\"rust\"}"));
1417
1418 let acc = &tool_calls[&0];
1419 assert_eq!(acc.id.as_deref(), Some("call_1"));
1420 assert_eq!(acc.name.as_deref(), Some("search"));
1421 assert_eq!(acc.arguments, "{\"q\":\"rust\"}");
1422 }
1423
1424 #[test]
1425 fn chat_tool_call_empty_delta_fields_do_not_overwrite() {
1426 let mut tool_calls = HashMap::new();
1427 accumulate_tool_call_delta(
1428 &mut tool_calls,
1429 &chat_delta(Some("call_1"), Some("search"), ""),
1430 );
1431 accumulate_tool_call_delta(&mut tool_calls, &chat_delta(Some(""), Some(""), "{\"q\":"));
1434 accumulate_tool_call_delta(
1435 &mut tool_calls,
1436 &chat_delta(Some(""), Some(""), "\"rust\"}"),
1437 );
1438
1439 let acc = &tool_calls[&0];
1440 assert_eq!(acc.id.as_deref(), Some("call_1"));
1441 assert_eq!(acc.name.as_deref(), Some("search"));
1442 assert_eq!(acc.arguments, "{\"q\":\"rust\"}");
1443 }
1444
1445 #[test]
1446 fn done_function_call_is_not_emitted_twice() {
1447 let mut function_calls = HashMap::new();
1448 let emitted = mark_and_emit_done_function_call(
1449 &mut function_calls,
1450 1,
1451 Some("item_1".to_string()),
1452 "item_1".to_string(),
1453 Some("call_1".to_string()),
1454 "search".to_string(),
1455 r#"{"q":"rust"}"#,
1456 );
1457 assert_eq!(emitted.id, "call_1");
1458 assert_eq!(emitted.name, "search");
1459 assert_eq!(drain_pending_function_calls(function_calls).len(), 0);
1460 }
1461
1462 #[test]
1463 fn pending_function_call_is_emitted_once_via_fallback() {
1464 let mut function_calls = HashMap::new();
1465 function_calls.insert(
1466 2,
1467 FunctionCallAccumulator {
1468 item_id: Some("item_2".to_string()),
1469 call_id: Some("call_2".to_string()),
1470 name: Some("lookup".to_string()),
1471 arguments: r#"{"id":42}"#.to_string(),
1472 emitted: false,
1473 },
1474 );
1475 let pending = drain_pending_function_calls(function_calls);
1476 assert_eq!(pending.len(), 1);
1477 assert_eq!(pending[0].id, "call_2");
1478 assert_eq!(pending[0].name, "lookup");
1479 }
1480
1481 #[test]
1482 fn empty_done_call_id_falls_back_to_item_id() {
1483 let mut function_calls = HashMap::new();
1484 let emitted = mark_and_emit_done_function_call(
1485 &mut function_calls,
1486 3,
1487 Some("item_3".to_string()),
1488 "item_3".to_string(),
1489 Some(String::new()),
1490 "search".to_string(),
1491 r#"{"q":"terminal first"}"#,
1492 );
1493 assert_eq!(emitted.id, "item_3");
1494 }
1495
1496 #[test]
1497 fn empty_pending_call_id_falls_back_to_item_id() {
1498 let mut function_calls = HashMap::new();
1499 function_calls.insert(
1500 4,
1501 FunctionCallAccumulator {
1502 item_id: Some("item_4".to_string()),
1503 call_id: Some(" ".to_string()),
1504 name: Some("lookup".to_string()),
1505 arguments: r#"{"id":7}"#.to_string(),
1506 emitted: false,
1507 },
1508 );
1509 let pending = drain_pending_function_calls(function_calls);
1510 assert_eq!(pending.len(), 1);
1511 assert_eq!(pending[0].id, "item_4");
1512 assert_eq!(pending[0].name, "lookup");
1513 }
1514
1515 #[test]
1516 fn empty_stream_identifiers_fall_back_to_output_index() {
1517 let mut function_calls = HashMap::new();
1518 function_calls.insert(
1519 12,
1520 FunctionCallAccumulator {
1521 item_id: None,
1522 call_id: None,
1523 name: None,
1524 arguments: r#"{"q":"may"}"#.to_string(),
1525 emitted: false,
1526 },
1527 );
1528 let emitted = mark_and_emit_done_function_call(
1529 &mut function_calls,
1530 12,
1531 None,
1532 String::new(),
1533 Some(String::new()),
1534 "search".to_string(),
1535 r#"{"q":"may"}"#,
1536 );
1537 assert_eq!(emitted.id, "response_output_12");
1538 }
1539
1540 #[test]
1541 fn serialized_responses_request_rejects_empty_call_id() {
1542 let snapshot = ParameterSnapshot::from(&aither_core::llm::model::Parameters::default());
1543 let request = ResponsesRequest::new(
1544 "gpt-5.4".to_string(),
1545 vec![ResponsesInputItem::FunctionCall {
1546 kind: "function_call",
1547 call_id: String::new(),
1548 name: "search".to_string(),
1549 arguments: "{}".to_string(),
1550 }],
1551 &snapshot,
1552 None,
1553 responses_tool_choice(&snapshot, false),
1554 false,
1555 );
1556
1557 let error = validate_serialized_responses_request(&request)
1558 .expect_err("empty serialized call_id must fail");
1559 assert!(
1560 error.to_string().contains("input[0]"),
1561 "unexpected error: {error}"
1562 );
1563 }
1564
1565 #[test]
1566 fn serialized_responses_request_rejects_whitespace_call_id() {
1567 let snapshot = ParameterSnapshot::from(&aither_core::llm::model::Parameters::default());
1568 let request = ResponsesRequest::new(
1569 "gpt-5.4".to_string(),
1570 vec![ResponsesInputItem::FunctionCallOutput {
1571 kind: "function_call_output",
1572 call_id: " ".to_string(),
1573 output: "{}".to_string(),
1574 }],
1575 &snapshot,
1576 None,
1577 responses_tool_choice(&snapshot, false),
1578 false,
1579 );
1580
1581 let error = validate_serialized_responses_request(&request)
1582 .expect_err("whitespace serialized call_id must fail");
1583 assert!(
1584 error.to_string().contains("blank call_id"),
1585 "unexpected error: {error}"
1586 );
1587 }
1588
1589 fn serve_once(body: &'static str) -> String {
1591 use std::io::{Read, Write};
1592
1593 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind stub server");
1594 let addr = listener.local_addr().expect("stub server address");
1595 std::thread::spawn(move || {
1596 let Ok((mut stream, _)) = listener.accept() else {
1597 return;
1598 };
1599 let mut request = Vec::new();
1600 let mut chunk = [0u8; 4096];
1601 while !request.windows(4).any(|w| w == b"\r\n\r\n") {
1603 let Ok(n) = stream.read(&mut chunk) else {
1604 return;
1605 };
1606 if n == 0 {
1607 return;
1608 }
1609 request.extend_from_slice(&chunk[..n]);
1610 }
1611 let response = format!(
1612 "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
1613 body.len(),
1614 );
1615 let _ = stream.write_all(response.as_bytes());
1616 let _ = stream.flush();
1617 });
1618 format!("http://{addr}")
1619 }
1620
1621 #[test]
1624 fn per_message_effort_is_the_responses_apis_on_the_listed_models() {
1625 let model = |name: &str| OpenAI::builder("key").model(name).build();
1626 assert!(takes_per_message_effort(&model("gpt-6-sol").config()));
1627 assert!(!takes_per_message_effort(&model("gpt-5").config()));
1628 assert!(!takes_per_message_effort(
1629 &model("gpt-6-sol")
1630 .with_api(ApiKind::ChatCompletions)
1631 .config()
1632 ));
1633 assert!(!takes_per_message_effort(
1634 &model("gpt-6-sol")
1635 .with_base_url(OPENROUTER_BASE_URL)
1636 .config()
1637 ));
1638 }
1639
1640 #[tokio::test]
1641 async fn profile_errors_when_context_length_is_unknown() {
1642 let base_url = serve_once(
1646 r#"{"object":"list","data":[{"id":"unregistered-stub-model","object":"model","created":1,"owned_by":"stub"}]}"#,
1647 );
1648 let model = OpenAI::builder("test-key")
1649 .base_url(base_url)
1650 .model("unregistered-stub-model")
1651 .build();
1652
1653 let err = model
1654 .profile()
1655 .await
1656 .expect_err("profile must fail when the context window is unknown");
1657 let message = err.to_string();
1658 assert!(
1659 message.contains("unregistered-stub-model"),
1660 "error must name the model: {message}"
1661 );
1662 assert!(
1663 message.contains("/models"),
1664 "error must name the endpoint that was asked: {message}"
1665 );
1666 }
1667
1668 #[tokio::test]
1669 async fn the_idle_timeout_bounds_a_wait_that_never_ends() {
1670 let timeout = within_idle(
1671 Duration::from_millis(20),
1672 futures_lite::future::pending::<()>(),
1673 )
1674 .await;
1675 assert!(matches!(
1676 timeout,
1677 Err(OpenAIError::IdleTimeout { idle }) if idle == Duration::from_millis(20)
1678 ));
1679 }
1680
1681 #[test]
1682 fn the_idle_timeout_defaults_to_ninety_seconds() {
1683 assert_eq!(
1684 OpenAI::new("key").config().idle_timeout,
1685 Duration::from_secs(90)
1686 );
1687 assert_eq!(
1688 OpenAI::builder("key")
1689 .idle_timeout(Duration::from_secs(7))
1690 .build()
1691 .config()
1692 .idle_timeout,
1693 Duration::from_secs(7)
1694 );
1695 assert_eq!(
1696 OpenAI::new("key")
1697 .with_idle_timeout(Duration::from_secs(5))
1698 .config()
1699 .idle_timeout,
1700 Duration::from_secs(5)
1701 );
1702 }
1703
1704 enum Step {
1706 Send(String),
1708 Pause(Duration),
1710 Hold,
1712 }
1713
1714 const SSE_HEAD: &str =
1715 "HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n";
1716
1717 fn serve_scripted(scripts: Vec<Vec<Step>>) -> String {
1720 use std::io::{Read, Write};
1721
1722 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind stub server");
1723 let addr = listener.local_addr().expect("stub server address");
1724 std::thread::spawn(move || {
1725 for script in scripts {
1726 let Ok((mut stream, _)) = listener.accept() else {
1727 return;
1728 };
1729 std::thread::spawn(move || {
1730 let mut request = Vec::new();
1731 let mut chunk = [0_u8; 4096];
1732 let body_end = loop {
1735 let Ok(n) = stream.read(&mut chunk) else {
1736 return;
1737 };
1738 if n == 0 {
1739 return;
1740 }
1741 request.extend_from_slice(&chunk[..n]);
1742 if let Some(head_end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
1743 let head = String::from_utf8_lossy(&request[..head_end]).to_lowercase();
1744 let length = head
1745 .lines()
1746 .find_map(|line| line.strip_prefix("content-length:"))
1747 .and_then(|value| value.trim().parse::<usize>().ok())
1748 .unwrap_or(0);
1749 break head_end + 4 + length;
1750 }
1751 };
1752 while request.len() < body_end {
1753 let Ok(n) = stream.read(&mut chunk) else {
1754 return;
1755 };
1756 if n == 0 {
1757 return;
1758 }
1759 request.extend_from_slice(&chunk[..n]);
1760 }
1761 for step in script {
1762 match step {
1763 Step::Send(bytes) => {
1764 if stream.write_all(bytes.as_bytes()).is_err()
1765 || stream.flush().is_err()
1766 {
1767 return;
1768 }
1769 }
1770 Step::Pause(duration) => std::thread::sleep(duration),
1771 Step::Hold => while stream.read(&mut chunk).is_ok_and(|n| n > 0) {},
1772 }
1773 }
1774 });
1775 }
1776 });
1777 format!("http://{addr}")
1778 }
1779
1780 const TEST_IDLE: Duration = Duration::from_secs(1);
1784
1785 fn scripted_client(api: ApiKind, base_url: String, retry: RetryPolicy) -> OpenAI {
1787 OpenAI::builder("key")
1788 .base_url(base_url)
1789 .idle_timeout(TEST_IDLE)
1790 .retry(retry)
1791 .build()
1792 .with_api(api)
1793 }
1794
1795 fn text_event(api: ApiKind, text: &str) -> String {
1797 match api {
1798 ApiKind::ChatCompletions => format!(
1799 "data: {}\n\n",
1800 serde_json::json!({"choices": [{"index": 0, "delta": {"content": text}}]})
1801 ),
1802 ApiKind::Responses => format!(
1803 "data: {}\n\n",
1804 serde_json::json!({"type": "response.output_text.delta", "delta": text})
1805 ),
1806 }
1807 }
1808
1809 const BOTH_APIS: [ApiKind; 2] = [ApiKind::ChatCompletions, ApiKind::Responses];
1810
1811 fn retry_once() -> RetryPolicy {
1812 RetryPolicy {
1813 max_retries: 1,
1814 initial_delay: Duration::from_millis(10),
1815 max_delay: Duration::from_millis(10),
1816 multiplier: 1,
1817 }
1818 }
1819
1820 #[tokio::test]
1821 async fn a_server_that_never_answers_fails_the_attempt_with_idle_timeout() {
1822 for api in BOTH_APIS {
1823 let url = serve_scripted(vec![vec![Step::Hold]]);
1824 let client = scripted_client(api, url, RetryPolicy::none());
1825 let stream = client.respond(oneshot("system", "hello"));
1826 futures_lite::pin!(stream);
1827 let error = stream
1828 .next()
1829 .await
1830 .expect("stream yields")
1831 .expect_err("the server never answers");
1832 assert!(
1833 matches!(error, OpenAIError::IdleTimeout { idle } if idle == TEST_IDLE),
1834 "{api:?}: {error}"
1835 );
1836 assert_eq!(
1837 error.failure().kind,
1838 aither_core::llm::FailureKind::Network,
1839 "{api:?}"
1840 );
1841 assert!(stream.next().await.is_none(), "{api:?}: the stream ends");
1842 }
1843 }
1844
1845 #[tokio::test]
1846 async fn an_attempt_that_is_never_answered_is_retried() {
1847 for api in BOTH_APIS {
1848 let answer = vec![
1849 Step::Send(SSE_HEAD.to_string()),
1850 Step::Send(text_event(api, "again")),
1851 ];
1852 let url = serve_scripted(vec![vec![Step::Hold], answer]);
1853 let client = scripted_client(api, url, retry_once());
1854 let stream = client.respond(oneshot("system", "hello"));
1855 futures_lite::pin!(stream);
1856 let first = stream
1857 .next()
1858 .await
1859 .expect("stream yields")
1860 .expect("the retry is answered");
1861 assert!(
1862 matches!(&first, Event::Text(text) if text == "again"),
1863 "{api:?}: {first:?}"
1864 );
1865 }
1866 }
1867
1868 #[tokio::test]
1869 async fn a_stream_that_goes_silent_ends_with_idle_timeout() {
1870 for api in BOTH_APIS {
1871 let url = serve_scripted(vec![vec![
1872 Step::Send(SSE_HEAD.to_string()),
1873 Step::Send(text_event(api, "hi")),
1874 Step::Hold,
1875 ]]);
1876 let client = scripted_client(api, url, RetryPolicy::none());
1877 let stream = client.respond(oneshot("system", "hello"));
1878 futures_lite::pin!(stream);
1879 let first = stream
1880 .next()
1881 .await
1882 .expect("stream yields")
1883 .expect("the first event arrives");
1884 assert!(
1885 matches!(&first, Event::Text(text) if text == "hi"),
1886 "{api:?}: {first:?}"
1887 );
1888 let error = stream
1889 .next()
1890 .await
1891 .expect("stream yields")
1892 .expect_err("the stream goes silent");
1893 assert!(
1894 matches!(error, OpenAIError::IdleTimeout { .. }),
1895 "{api:?}: {error}"
1896 );
1897 assert!(stream.next().await.is_none(), "{api:?}: the stream ends");
1898 }
1899 }
1900
1901 #[tokio::test]
1902 async fn a_stream_that_keeps_sending_is_not_cut() {
1903 const EVENTS: usize = 30;
1904 const GAP: Duration = Duration::from_millis(50);
1905 for api in BOTH_APIS {
1906 let mut script = vec![Step::Send(SSE_HEAD.to_string())];
1909 for _ in 0..EVENTS {
1910 script.push(Step::Send(text_event(api, "x")));
1911 script.push(Step::Pause(GAP));
1912 }
1913 let url = serve_scripted(vec![script]);
1914 let client = scripted_client(api, url, RetryPolicy::none());
1915 let started = std::time::Instant::now();
1916 let stream = client.respond(oneshot("system", "hello"));
1917 futures_lite::pin!(stream);
1918 let mut texts = 0;
1919 while let Some(event) = stream.next().await {
1920 if let Event::Text(_) = event.expect("a stream that keeps sending is never cut") {
1921 texts += 1;
1922 }
1923 }
1924 assert_eq!(texts, EVENTS, "{api:?}");
1925 assert!(started.elapsed() > TEST_IDLE, "{api:?}");
1926 }
1927 }
1928
1929 #[tokio::test]
1933 async fn a_rate_limit_reported_mid_stream_is_transient() {
1934 let message = "Reached request rate limit. Your limit will reset in 4 seconds.";
1935 let error = serde_json::json!({"code": "rate_limit_exceeded", "message": message});
1936 let cases = [
1937 (
1938 ApiKind::Responses,
1939 serde_json::json!({"type": "error", "code": "rate_limit_exceeded", "message": message}),
1940 ),
1941 (
1942 ApiKind::Responses,
1943 serde_json::json!({
1944 "type": "response.failed",
1945 "response": {"status": "failed", "error": error},
1946 }),
1947 ),
1948 (
1949 ApiKind::ChatCompletions,
1950 serde_json::json!({"error": error}),
1951 ),
1952 ];
1953 for (api, event) in cases {
1954 let url = serve_scripted(vec![vec![
1955 Step::Send(SSE_HEAD.to_string()),
1956 Step::Send(text_event(api, "hi")),
1957 Step::Send(format!("data: {event}\n\n")),
1958 ]]);
1959 let client = scripted_client(api, url, RetryPolicy::none());
1960 let stream = client.respond(oneshot("system", "hello"));
1961 futures_lite::pin!(stream);
1962 let first = stream
1963 .next()
1964 .await
1965 .expect("stream yields")
1966 .expect("the first event arrives");
1967 assert!(
1968 matches!(&first, Event::Text(text) if text == "hi"),
1969 "{event}"
1970 );
1971 let error = stream
1972 .next()
1973 .await
1974 .expect("stream yields")
1975 .expect_err("the stream reports the rate limit");
1976 assert_eq!(
1977 error.failure().kind,
1978 aither_core::llm::FailureKind::Transient,
1979 "{event}: {error}"
1980 );
1981 assert!(error.to_string().contains(message), "{event}: {error}");
1982 }
1983 }
1984
1985 #[tokio::test]
1986 async fn a_models_request_that_never_answers_fails_with_idle_timeout() {
1987 let url = serve_scripted(vec![vec![Step::Hold]]);
1988 let client = scripted_client(ApiKind::Responses, url, RetryPolicy::none());
1989 let error = fetch_model_context_length(&client.config())
1990 .await
1991 .expect_err("the server never answers");
1992 assert!(matches!(error, OpenAIError::IdleTimeout { .. }), "{error}");
1993 }
1994
1995 #[test]
1996 fn chat_usage_mapping_keeps_reasoning_and_cache_tokens() {
1997 let usage = ChatCompletionUsage {
1998 prompt_tokens: Some(11),
1999 completion_tokens: Some(7),
2000 total_tokens: Some(18),
2001 prompt_tokens_details: Some(ChatPromptTokensDetails {
2002 cached_tokens: Some(3),
2003 }),
2004 completion_tokens_details: Some(ChatCompletionTokensDetails {
2005 reasoning_tokens: Some(2),
2006 }),
2007 };
2008 let mapped = usage_from_chat_completion(&usage);
2009 assert_eq!(mapped.prompt_tokens, Some(11));
2010 assert_eq!(mapped.completion_tokens, Some(7));
2011 assert_eq!(mapped.total_tokens, Some(18));
2012 assert_eq!(mapped.reasoning_tokens, Some(2));
2013 assert_eq!(mapped.cache_read_tokens, Some(3));
2014 }
2015
2016 #[test]
2017 fn responses_usage_mapping_keeps_reasoning_and_cache_tokens() {
2018 let usage: ResponsesUsage = serde_json::from_value(serde_json::json!({
2020 "input_tokens": 19,
2021 "input_tokens_details": { "cached_tokens": 4 },
2022 "output_tokens": 5,
2023 "output_tokens_details": { "reasoning_tokens": 1 },
2024 "total_tokens": 24
2025 }))
2026 .expect("deserialize Responses usage");
2027 let mapped = usage_from_responses(&usage);
2028 assert_eq!(mapped.prompt_tokens, Some(19));
2029 assert_eq!(mapped.completion_tokens, Some(5));
2030 assert_eq!(mapped.total_tokens, Some(24));
2031 assert_eq!(mapped.reasoning_tokens, Some(1));
2032 assert_eq!(mapped.cache_read_tokens, Some(4));
2033 }
2034}
2035
2036fn filter_tool_definitions(
2037 defs: Vec<aither_core::llm::tool::ToolDefinition>,
2038 choice: &ToolChoice,
2039) -> Vec<aither_core::llm::tool::ToolDefinition> {
2040 match choice {
2041 ToolChoice::None => Vec::new(),
2042 ToolChoice::Exact(name) => defs
2043 .into_iter()
2044 .filter(|tool| tool.name() == name)
2045 .collect(),
2046 ToolChoice::Auto | ToolChoice::Required => defs,
2047 }
2048}
2049
2050#[derive(Debug)]
2052pub struct Builder {
2053 api_key: String,
2054 base_url: String,
2055 api_kind: ApiKind,
2056 chat_model: String,
2057 embedding_model: String,
2058 embedding_dimensions: usize,
2059 image_model: String,
2060 audio_model: String,
2061 audio_voice: String,
2062 audio_format: String,
2063 transcription_model: String,
2064 moderation_model: String,
2065 legacy_max_tokens: bool,
2066 organization: Option<String>,
2067 native_abilities: Vec<Ability>,
2068 retry: RetryPolicy,
2069 idle_timeout: Duration,
2070 extra_headers: Vec<(String, String)>,
2071 store: Option<bool>,
2072}
2073
2074impl Builder {
2075 fn new(api_key: impl Into<String>) -> Self {
2076 Self {
2077 api_key: api_key.into(),
2078 base_url: DEFAULT_BASE_URL.to_string(),
2079 api_kind: ApiKind::Responses,
2080 chat_model: DEFAULT_MODEL.to_string(),
2081 embedding_model: DEFAULT_EMBEDDING_MODEL.to_string(),
2082 embedding_dimensions: DEFAULT_EMBEDDING_DIM,
2083 image_model: DEFAULT_IMAGE_MODEL.to_string(),
2084 audio_model: DEFAULT_AUDIO_MODEL.to_string(),
2085 audio_voice: DEFAULT_AUDIO_VOICE.to_string(),
2086 audio_format: DEFAULT_AUDIO_FORMAT.to_string(),
2087 transcription_model: DEFAULT_TRANSCRIPTION_MODEL.to_string(),
2088 moderation_model: DEFAULT_MODERATION_MODEL.to_string(),
2089 legacy_max_tokens: false,
2090 organization: None,
2091 native_abilities: Vec::new(),
2092 retry: RetryPolicy::default(),
2093 idle_timeout: DEFAULT_IDLE_TIMEOUT,
2094 extra_headers: Vec::new(),
2095 store: None,
2096 }
2097 }
2098
2099 #[must_use]
2101 pub fn base_url(mut self, url: impl Into<String>) -> Self {
2102 self.base_url = url.into();
2103 self
2104 }
2105
2106 #[must_use]
2108 pub const fn use_responses_api(mut self) -> Self {
2109 self.api_kind = ApiKind::Responses;
2110 self
2111 }
2112
2113 #[must_use]
2115 pub const fn use_chat_completions_api(mut self) -> Self {
2116 self.api_kind = ApiKind::ChatCompletions;
2117 self
2118 }
2119
2120 #[must_use]
2124 pub const fn legacy_max_tokens(mut self, enabled: bool) -> Self {
2125 self.legacy_max_tokens = enabled;
2126 self
2127 }
2128
2129 #[must_use]
2131 pub fn model(mut self, model: impl Into<String>) -> Self {
2132 self.chat_model = sanitize_model(model);
2133 self
2134 }
2135
2136 #[must_use]
2138 pub fn embedding_model(mut self, model: impl Into<String>) -> Self {
2139 let model = sanitize_model(model);
2140 if let Some(dim) = infer_embedding_dim(&model) {
2141 self.embedding_dimensions = dim;
2142 }
2143 self.embedding_model = model;
2144 self
2145 }
2146
2147 #[must_use]
2149 pub const fn embedding_dimensions(mut self, dimensions: usize) -> Self {
2150 self.embedding_dimensions = dimensions;
2151 self
2152 }
2153
2154 #[must_use]
2156 pub fn image_model(mut self, model: impl Into<String>) -> Self {
2157 self.image_model = sanitize_model(model);
2158 self
2159 }
2160
2161 #[must_use]
2163 pub fn audio_model(mut self, model: impl Into<String>) -> Self {
2164 self.audio_model = sanitize_model(model);
2165 self
2166 }
2167
2168 #[must_use]
2170 pub fn audio_voice(mut self, voice: impl Into<String>) -> Self {
2171 self.audio_voice = voice.into();
2172 self
2173 }
2174
2175 #[must_use]
2177 pub fn audio_format(mut self, format: impl Into<String>) -> Self {
2178 self.audio_format = format.into();
2179 self
2180 }
2181
2182 #[must_use]
2184 pub fn transcription_model(mut self, model: impl Into<String>) -> Self {
2185 self.transcription_model = sanitize_model(model);
2186 self
2187 }
2188
2189 #[must_use]
2191 pub fn moderation_model(mut self, model: impl Into<String>) -> Self {
2192 self.moderation_model = sanitize_model(model);
2193 self
2194 }
2195
2196 #[must_use]
2198 pub fn organization(mut self, organization: impl Into<String>) -> Self {
2199 self.organization = Some(organization.into());
2200 self
2201 }
2202
2203 #[must_use]
2209 pub fn extra_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
2210 self.extra_headers.push((name.into(), value.into()));
2211 self
2212 }
2213
2214 #[must_use]
2220 pub const fn store(mut self, store: bool) -> Self {
2221 self.store = Some(store);
2222 self
2223 }
2224
2225 #[must_use]
2227 pub fn native_capabilities(mut self, abilities: impl IntoIterator<Item = Ability>) -> Self {
2228 for ability in abilities {
2229 if !self.native_abilities.contains(&ability) {
2230 self.native_abilities.push(ability);
2231 }
2232 }
2233 self
2234 }
2235
2236 #[must_use]
2238 pub fn enable_native_web_search(self) -> Self {
2239 self.native_capabilities([Ability::WebSearch])
2240 }
2241
2242 #[must_use]
2244 pub fn enable_native_pdf(self) -> Self {
2245 self.native_capabilities([Ability::Pdf])
2246 }
2247
2248 #[must_use]
2255 pub const fn retry(mut self, policy: RetryPolicy) -> Self {
2256 self.retry = policy;
2257 self
2258 }
2259
2260 #[must_use]
2262 pub const fn max_retries(mut self, max_retries: u32) -> Self {
2263 self.retry.max_retries = max_retries;
2264 self
2265 }
2266
2267 #[must_use]
2269 pub fn no_retry(mut self) -> Self {
2270 self.retry = RetryPolicy::none();
2271 self
2272 }
2273
2274 #[must_use]
2281 pub const fn idle_timeout(mut self, idle_timeout: Duration) -> Self {
2282 self.idle_timeout = idle_timeout;
2283 self
2284 }
2285
2286 #[must_use]
2288 pub fn build(self) -> OpenAI {
2289 OpenAI {
2290 inner: Arc::new(Config {
2291 api_key: self.api_key,
2292 base_url: self.base_url,
2293 api_kind: self.api_kind,
2294 #[cfg(feature = "tokenizer")]
2295 vocabulary: aither_core::tokenizer::Vocabulary::for_model(&self.chat_model),
2296 chat_model: self.chat_model,
2297 embedding_model: self.embedding_model,
2298 embedding_dimensions: self.embedding_dimensions,
2299 image_model: self.image_model,
2300 audio_model: self.audio_model,
2301 audio_voice: self.audio_voice,
2302 audio_format: self.audio_format,
2303 transcription_model: self.transcription_model,
2304 moderation_model: self.moderation_model,
2305 legacy_max_tokens: self.legacy_max_tokens,
2306 organization: self.organization,
2307 native_abilities: self.native_abilities,
2308 retry: self.retry,
2309 idle_timeout: self.idle_timeout,
2310 extra_headers: self.extra_headers,
2311 store: self.store,
2312 }),
2313 }
2314 }
2315}
2316
2317#[derive(Debug, Clone)]
2318pub struct Config {
2319 pub(crate) api_key: String,
2320 pub(crate) base_url: String,
2321 pub(crate) api_kind: ApiKind,
2322 pub(crate) chat_model: String,
2323 pub(crate) embedding_model: String,
2324 pub(crate) embedding_dimensions: usize,
2325 pub(crate) image_model: String,
2326 pub(crate) audio_model: String,
2327 pub(crate) audio_voice: String,
2328 pub(crate) audio_format: String,
2329 pub(crate) transcription_model: String,
2330 pub(crate) moderation_model: String,
2331 pub(crate) legacy_max_tokens: bool,
2332 pub(crate) organization: Option<String>,
2333 pub(crate) native_abilities: Vec<Ability>,
2334 pub(crate) retry: RetryPolicy,
2335 pub(crate) idle_timeout: Duration,
2336 pub(crate) extra_headers: Vec<(String, String)>,
2337 pub(crate) store: Option<bool>,
2338 #[cfg(feature = "tokenizer")]
2340 pub(crate) vocabulary: Option<aither_core::tokenizer::Vocabulary>,
2341}
2342
2343impl Config {
2344 pub(crate) fn request_url(&self, path: &str) -> String {
2345 format!(
2346 "{}/{}",
2347 self.base_url.trim_end_matches('/'),
2348 path.trim_start_matches('/')
2349 )
2350 }
2351
2352 pub(crate) fn request_auth(&self) -> String {
2353 format!("Bearer {}", self.api_key)
2354 }
2355}
2356
2357fn sanitize_model(model: impl Into<String>) -> String {
2358 model.into().trim().to_string()
2359}
2360
2361fn infer_embedding_dim(model: &str) -> Option<usize> {
2362 match model {
2363 "text-embedding-3-large" => Some(3072),
2364 "text-embedding-3-small" | "text-embedding-ada-002" => Some(1536),
2365 _ => None,
2366 }
2367}