open_ai.rs

  1pub mod batches;
  2pub mod responses;
  3
  4use anyhow::{Context as _, Result, anyhow};
  5use futures::{AsyncBufReadExt, AsyncReadExt, StreamExt, io::BufReader, stream::BoxStream};
  6use http_client::{
  7    AsyncBody, HttpClient, Method, Request as HttpRequest, StatusCode,
  8    http::{HeaderMap, HeaderValue},
  9};
 10use serde::{Deserialize, Serialize};
 11use serde_json::Value;
 12pub use settings::OpenAiReasoningEffort as ReasoningEffort;
 13use std::{convert::TryFrom, future::Future};
 14use strum::EnumIter;
 15use thiserror::Error;
 16
 17pub const OPEN_AI_API_URL: &str = "https://api.openai.com/v1";
 18
 19fn is_none_or_empty<T: AsRef<[U]>, U>(opt: &Option<T>) -> bool {
 20    opt.as_ref().is_none_or(|v| v.as_ref().is_empty())
 21}
 22
 23#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
 24#[serde(rename_all = "lowercase")]
 25pub enum Role {
 26    User,
 27    Assistant,
 28    System,
 29    Tool,
 30}
 31
 32impl TryFrom<String> for Role {
 33    type Error = anyhow::Error;
 34
 35    fn try_from(value: String) -> Result<Self> {
 36        match value.as_str() {
 37            "user" => Ok(Self::User),
 38            "assistant" => Ok(Self::Assistant),
 39            "system" => Ok(Self::System),
 40            "tool" => Ok(Self::Tool),
 41            _ => anyhow::bail!("invalid role '{value}'"),
 42        }
 43    }
 44}
 45
 46impl From<Role> for String {
 47    fn from(val: Role) -> Self {
 48        match val {
 49            Role::User => "user".to_owned(),
 50            Role::Assistant => "assistant".to_owned(),
 51            Role::System => "system".to_owned(),
 52            Role::Tool => "tool".to_owned(),
 53        }
 54    }
 55}
 56
 57#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
 58#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, EnumIter)]
 59pub enum Model {
 60    #[serde(rename = "gpt-3.5-turbo")]
 61    ThreePointFiveTurbo,
 62    #[serde(rename = "gpt-4")]
 63    Four,
 64    #[serde(rename = "gpt-4-turbo")]
 65    FourTurbo,
 66    #[serde(rename = "gpt-4o-mini")]
 67    FourOmniMini,
 68    #[serde(rename = "gpt-4.1-nano")]
 69    FourPointOneNano,
 70    #[serde(rename = "o1")]
 71    O1,
 72    #[serde(rename = "o3-mini")]
 73    O3Mini,
 74    #[serde(rename = "o3")]
 75    O3,
 76    #[serde(rename = "gpt-5")]
 77    Five,
 78    #[serde(rename = "gpt-5-codex")]
 79    FiveCodex,
 80    #[serde(rename = "gpt-5-mini")]
 81    #[default]
 82    FiveMini,
 83    #[serde(rename = "gpt-5-nano")]
 84    FiveNano,
 85    #[serde(rename = "gpt-5.1")]
 86    FivePointOne,
 87    #[serde(rename = "gpt-5.2")]
 88    FivePointTwo,
 89    #[serde(rename = "gpt-5.2-codex")]
 90    FivePointTwoCodex,
 91    #[serde(rename = "gpt-5.3-codex")]
 92    FivePointThreeCodex,
 93    #[serde(rename = "gpt-5.4")]
 94    FivePointFour,
 95    #[serde(rename = "gpt-5.4-pro")]
 96    FivePointFourPro,
 97    #[serde(rename = "custom")]
 98    Custom {
 99        name: String,
100        /// The name displayed in the UI, such as in the assistant panel model dropdown menu.
101        display_name: Option<String>,
102        max_tokens: u64,
103        max_output_tokens: Option<u64>,
104        max_completion_tokens: Option<u64>,
105        reasoning_effort: Option<ReasoningEffort>,
106        #[serde(default = "default_supports_chat_completions")]
107        supports_chat_completions: bool,
108    },
109}
110
111const fn default_supports_chat_completions() -> bool {
112    true
113}
114
115impl Model {
116    pub fn default_fast() -> Self {
117        Self::FiveMini
118    }
119
120    pub fn from_id(id: &str) -> Result<Self> {
121        match id {
122            "gpt-3.5-turbo" => Ok(Self::ThreePointFiveTurbo),
123            "gpt-4" => Ok(Self::Four),
124            "gpt-4-turbo-preview" => Ok(Self::FourTurbo),
125            "gpt-4o-mini" => Ok(Self::FourOmniMini),
126            "gpt-4.1-nano" => Ok(Self::FourPointOneNano),
127            "o1" => Ok(Self::O1),
128            "o3-mini" => Ok(Self::O3Mini),
129            "o3" => Ok(Self::O3),
130            "gpt-5" => Ok(Self::Five),
131            "gpt-5-codex" => Ok(Self::FiveCodex),
132            "gpt-5-mini" => Ok(Self::FiveMini),
133            "gpt-5-nano" => Ok(Self::FiveNano),
134            "gpt-5.1" => Ok(Self::FivePointOne),
135            "gpt-5.2" => Ok(Self::FivePointTwo),
136            "gpt-5.2-codex" => Ok(Self::FivePointTwoCodex),
137            "gpt-5.3-codex" => Ok(Self::FivePointThreeCodex),
138            "gpt-5.4" => Ok(Self::FivePointFour),
139            "gpt-5.4-pro" => Ok(Self::FivePointFourPro),
140            invalid_id => anyhow::bail!("invalid model id '{invalid_id}'"),
141        }
142    }
143
144    pub fn id(&self) -> &str {
145        match self {
146            Self::ThreePointFiveTurbo => "gpt-3.5-turbo",
147            Self::Four => "gpt-4",
148            Self::FourTurbo => "gpt-4-turbo",
149            Self::FourOmniMini => "gpt-4o-mini",
150            Self::FourPointOneNano => "gpt-4.1-nano",
151            Self::O1 => "o1",
152            Self::O3Mini => "o3-mini",
153            Self::O3 => "o3",
154            Self::Five => "gpt-5",
155            Self::FiveCodex => "gpt-5-codex",
156            Self::FiveMini => "gpt-5-mini",
157            Self::FiveNano => "gpt-5-nano",
158            Self::FivePointOne => "gpt-5.1",
159            Self::FivePointTwo => "gpt-5.2",
160            Self::FivePointTwoCodex => "gpt-5.2-codex",
161            Self::FivePointThreeCodex => "gpt-5.3-codex",
162            Self::FivePointFour => "gpt-5.4",
163            Self::FivePointFourPro => "gpt-5.4-pro",
164            Self::Custom { name, .. } => name,
165        }
166    }
167
168    pub fn display_name(&self) -> &str {
169        match self {
170            Self::ThreePointFiveTurbo => "gpt-3.5-turbo",
171            Self::Four => "gpt-4",
172            Self::FourTurbo => "gpt-4-turbo",
173            Self::FourOmniMini => "gpt-4o-mini",
174            Self::FourPointOneNano => "gpt-4.1-nano",
175            Self::O1 => "o1",
176            Self::O3Mini => "o3-mini",
177            Self::O3 => "o3",
178            Self::Five => "gpt-5",
179            Self::FiveCodex => "gpt-5-codex",
180            Self::FiveMini => "gpt-5-mini",
181            Self::FiveNano => "gpt-5-nano",
182            Self::FivePointOne => "gpt-5.1",
183            Self::FivePointTwo => "gpt-5.2",
184            Self::FivePointTwoCodex => "gpt-5.2-codex",
185            Self::FivePointThreeCodex => "gpt-5.3-codex",
186            Self::FivePointFour => "gpt-5.4",
187            Self::FivePointFourPro => "gpt-5.4-pro",
188            Self::Custom { display_name, .. } => display_name.as_deref().unwrap_or(&self.id()),
189        }
190    }
191
192    pub fn max_token_count(&self) -> u64 {
193        match self {
194            Self::ThreePointFiveTurbo => 16_385,
195            Self::Four => 8_192,
196            Self::FourTurbo => 128_000,
197            Self::FourOmniMini => 128_000,
198            Self::FourPointOneNano => 1_047_576,
199            Self::O1 => 200_000,
200            Self::O3Mini => 200_000,
201            Self::O3 => 200_000,
202            Self::Five => 272_000,
203            Self::FiveCodex => 272_000,
204            Self::FiveMini => 400_000,
205            Self::FiveNano => 400_000,
206            Self::FivePointOne => 400_000,
207            Self::FivePointTwo => 400_000,
208            Self::FivePointTwoCodex => 400_000,
209            Self::FivePointThreeCodex => 400_000,
210            Self::FivePointFour => 1_050_000,
211            Self::FivePointFourPro => 1_050_000,
212            Self::Custom { max_tokens, .. } => *max_tokens,
213        }
214    }
215
216    pub fn max_output_tokens(&self) -> Option<u64> {
217        match self {
218            Self::Custom {
219                max_output_tokens, ..
220            } => *max_output_tokens,
221            Self::ThreePointFiveTurbo => Some(4_096),
222            Self::Four => Some(8_192),
223            Self::FourTurbo => Some(4_096),
224            Self::FourOmniMini => Some(16_384),
225            Self::FourPointOneNano => Some(32_768),
226            Self::O1 => Some(100_000),
227            Self::O3Mini => Some(100_000),
228            Self::O3 => Some(100_000),
229            Self::Five => Some(128_000),
230            Self::FiveCodex => Some(128_000),
231            Self::FiveMini => Some(128_000),
232            Self::FiveNano => Some(128_000),
233            Self::FivePointOne => Some(128_000),
234            Self::FivePointTwo => Some(128_000),
235            Self::FivePointTwoCodex => Some(128_000),
236            Self::FivePointThreeCodex => Some(128_000),
237            Self::FivePointFour => Some(128_000),
238            Self::FivePointFourPro => Some(128_000),
239        }
240    }
241
242    pub fn reasoning_effort(&self) -> Option<ReasoningEffort> {
243        match self {
244            Self::Custom {
245                reasoning_effort, ..
246            } => reasoning_effort.to_owned(),
247            Self::FivePointThreeCodex | Self::FivePointFourPro => Some(ReasoningEffort::Medium),
248            _ => None,
249        }
250    }
251
252    pub fn supports_chat_completions(&self) -> bool {
253        match self {
254            Self::Custom {
255                supports_chat_completions,
256                ..
257            } => *supports_chat_completions,
258            Self::FiveCodex
259            | Self::FivePointTwoCodex
260            | Self::FivePointThreeCodex
261            | Self::FivePointFourPro => false,
262            _ => true,
263        }
264    }
265
266    /// Returns whether the given model supports the `parallel_tool_calls` parameter.
267    ///
268    /// If the model does not support the parameter, do not pass it up, or the API will return an error.
269    pub fn supports_parallel_tool_calls(&self) -> bool {
270        match self {
271            Self::ThreePointFiveTurbo
272            | Self::Four
273            | Self::FourTurbo
274            | Self::FourOmniMini
275            | Self::FourPointOneNano
276            | Self::Five
277            | Self::FiveCodex
278            | Self::FiveMini
279            | Self::FivePointOne
280            | Self::FivePointTwo
281            | Self::FivePointTwoCodex
282            | Self::FivePointThreeCodex
283            | Self::FivePointFour
284            | Self::FivePointFourPro
285            | Self::FiveNano => true,
286            Self::O1 | Self::O3 | Self::O3Mini | Model::Custom { .. } => false,
287        }
288    }
289
290    /// Returns whether the given model supports the `prompt_cache_key` parameter.
291    ///
292    /// If the model does not support the parameter, do not pass it up.
293    pub fn supports_prompt_cache_key(&self) -> bool {
294        true
295    }
296}
297
298#[derive(Debug, Serialize, Deserialize)]
299pub struct Request {
300    pub model: String,
301    pub messages: Vec<RequestMessage>,
302    pub stream: bool,
303    #[serde(default, skip_serializing_if = "Option::is_none")]
304    pub max_completion_tokens: Option<u64>,
305    #[serde(default, skip_serializing_if = "Vec::is_empty")]
306    pub stop: Vec<String>,
307    #[serde(default, skip_serializing_if = "Option::is_none")]
308    pub temperature: Option<f32>,
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub tool_choice: Option<ToolChoice>,
311    /// Whether to enable parallel function calling during tool use.
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub parallel_tool_calls: Option<bool>,
314    #[serde(default, skip_serializing_if = "Vec::is_empty")]
315    pub tools: Vec<ToolDefinition>,
316    #[serde(default, skip_serializing_if = "Option::is_none")]
317    pub prompt_cache_key: Option<String>,
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub reasoning_effort: Option<ReasoningEffort>,
320}
321
322#[derive(Debug, Serialize, Deserialize)]
323#[serde(rename_all = "lowercase")]
324pub enum ToolChoice {
325    Auto,
326    Required,
327    None,
328    #[serde(untagged)]
329    Other(ToolDefinition),
330}
331
332#[derive(Clone, Deserialize, Serialize, Debug)]
333#[serde(tag = "type", rename_all = "snake_case")]
334pub enum ToolDefinition {
335    #[allow(dead_code)]
336    Function { function: FunctionDefinition },
337}
338
339#[derive(Clone, Debug, Serialize, Deserialize)]
340pub struct FunctionDefinition {
341    pub name: String,
342    pub description: Option<String>,
343    pub parameters: Option<Value>,
344}
345
346#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
347#[serde(tag = "role", rename_all = "lowercase")]
348pub enum RequestMessage {
349    Assistant {
350        content: Option<MessageContent>,
351        #[serde(default, skip_serializing_if = "Vec::is_empty")]
352        tool_calls: Vec<ToolCall>,
353    },
354    User {
355        content: MessageContent,
356    },
357    System {
358        content: MessageContent,
359    },
360    Tool {
361        content: MessageContent,
362        tool_call_id: String,
363    },
364}
365
366#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
367#[serde(untagged)]
368pub enum MessageContent {
369    Plain(String),
370    Multipart(Vec<MessagePart>),
371}
372
373impl MessageContent {
374    pub fn empty() -> Self {
375        MessageContent::Multipart(vec![])
376    }
377
378    pub fn push_part(&mut self, part: MessagePart) {
379        match self {
380            MessageContent::Plain(text) => {
381                *self =
382                    MessageContent::Multipart(vec![MessagePart::Text { text: text.clone() }, part]);
383            }
384            MessageContent::Multipart(parts) if parts.is_empty() => match part {
385                MessagePart::Text { text } => *self = MessageContent::Plain(text),
386                MessagePart::Image { .. } => *self = MessageContent::Multipart(vec![part]),
387            },
388            MessageContent::Multipart(parts) => parts.push(part),
389        }
390    }
391}
392
393impl From<Vec<MessagePart>> for MessageContent {
394    fn from(mut parts: Vec<MessagePart>) -> Self {
395        if let [MessagePart::Text { text }] = parts.as_mut_slice() {
396            MessageContent::Plain(std::mem::take(text))
397        } else {
398            MessageContent::Multipart(parts)
399        }
400    }
401}
402
403#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
404#[serde(tag = "type")]
405pub enum MessagePart {
406    #[serde(rename = "text")]
407    Text { text: String },
408    #[serde(rename = "image_url")]
409    Image { image_url: ImageUrl },
410}
411
412#[derive(Serialize, Deserialize, Clone, Debug, Eq, PartialEq)]
413pub struct ImageUrl {
414    pub url: String,
415    #[serde(skip_serializing_if = "Option::is_none")]
416    pub detail: Option<String>,
417}
418
419#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
420pub struct ToolCall {
421    pub id: String,
422    #[serde(flatten)]
423    pub content: ToolCallContent,
424}
425
426#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
427#[serde(tag = "type", rename_all = "lowercase")]
428pub enum ToolCallContent {
429    Function { function: FunctionContent },
430}
431
432#[derive(Clone, Serialize, Deserialize, Debug, Eq, PartialEq)]
433pub struct FunctionContent {
434    pub name: String,
435    pub arguments: String,
436}
437
438#[derive(Clone, Serialize, Deserialize, Debug)]
439pub struct Response {
440    pub id: String,
441    pub object: String,
442    pub created: u64,
443    pub model: String,
444    pub choices: Vec<Choice>,
445    pub usage: Usage,
446}
447
448#[derive(Clone, Serialize, Deserialize, Debug)]
449pub struct Choice {
450    pub index: u32,
451    pub message: RequestMessage,
452    pub finish_reason: Option<String>,
453}
454
455#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
456pub struct ResponseMessageDelta {
457    pub role: Option<Role>,
458    pub content: Option<String>,
459    #[serde(default, skip_serializing_if = "is_none_or_empty")]
460    pub tool_calls: Option<Vec<ToolCallChunk>>,
461    #[serde(default, skip_serializing_if = "is_none_or_empty")]
462    pub reasoning_content: Option<String>,
463}
464
465#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
466pub struct ToolCallChunk {
467    pub index: usize,
468    pub id: Option<String>,
469
470    // There is also an optional `type` field that would determine if a
471    // function is there. Sometimes this streams in with the `function` before
472    // it streams in the `type`
473    pub function: Option<FunctionChunk>,
474}
475
476#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
477pub struct FunctionChunk {
478    pub name: Option<String>,
479    pub arguments: Option<String>,
480}
481
482#[derive(Clone, Serialize, Deserialize, Debug)]
483pub struct Usage {
484    pub prompt_tokens: u64,
485    pub completion_tokens: u64,
486    pub total_tokens: u64,
487}
488
489#[derive(Serialize, Deserialize, Debug)]
490pub struct ChoiceDelta {
491    pub index: u32,
492    pub delta: Option<ResponseMessageDelta>,
493    pub finish_reason: Option<String>,
494}
495
496#[derive(Error, Debug)]
497pub enum RequestError {
498    #[error("HTTP response error from {provider}'s API: status {status_code} - {body:?}")]
499    HttpResponseError {
500        provider: String,
501        status_code: StatusCode,
502        body: String,
503        headers: HeaderMap<HeaderValue>,
504    },
505    #[error(transparent)]
506    Other(#[from] anyhow::Error),
507}
508
509#[derive(Serialize, Deserialize, Debug)]
510pub struct ResponseStreamError {
511    message: String,
512}
513
514#[derive(Serialize, Deserialize, Debug)]
515#[serde(untagged)]
516pub enum ResponseStreamResult {
517    Ok(ResponseStreamEvent),
518    Err { error: ResponseStreamError },
519}
520
521#[derive(Serialize, Deserialize, Debug)]
522pub struct ResponseStreamEvent {
523    pub choices: Vec<ChoiceDelta>,
524    pub usage: Option<Usage>,
525}
526
527pub async fn non_streaming_completion(
528    client: &dyn HttpClient,
529    api_url: &str,
530    api_key: &str,
531    request: Request,
532) -> Result<Response, RequestError> {
533    let uri = format!("{api_url}/chat/completions");
534    let request_builder = HttpRequest::builder()
535        .method(Method::POST)
536        .uri(uri)
537        .header("Content-Type", "application/json")
538        .header("Authorization", format!("Bearer {}", api_key.trim()));
539
540    let request = request_builder
541        .body(AsyncBody::from(
542            serde_json::to_string(&request).map_err(|e| RequestError::Other(e.into()))?,
543        ))
544        .map_err(|e| RequestError::Other(e.into()))?;
545
546    let mut response = client.send(request).await?;
547    if response.status().is_success() {
548        let mut body = String::new();
549        response
550            .body_mut()
551            .read_to_string(&mut body)
552            .await
553            .map_err(|e| RequestError::Other(e.into()))?;
554
555        serde_json::from_str(&body).map_err(|e| RequestError::Other(e.into()))
556    } else {
557        let mut body = String::new();
558        response
559            .body_mut()
560            .read_to_string(&mut body)
561            .await
562            .map_err(|e| RequestError::Other(e.into()))?;
563
564        Err(RequestError::HttpResponseError {
565            provider: "openai".to_owned(),
566            status_code: response.status(),
567            body,
568            headers: response.headers().clone(),
569        })
570    }
571}
572
573pub async fn stream_completion(
574    client: &dyn HttpClient,
575    provider_name: &str,
576    api_url: &str,
577    api_key: &str,
578    request: Request,
579) -> Result<BoxStream<'static, Result<ResponseStreamEvent>>, RequestError> {
580    let uri = format!("{api_url}/chat/completions");
581    let request_builder = HttpRequest::builder()
582        .method(Method::POST)
583        .uri(uri)
584        .header("Content-Type", "application/json")
585        .header("Authorization", format!("Bearer {}", api_key.trim()));
586
587    let request = request_builder
588        .body(AsyncBody::from(
589            serde_json::to_string(&request).map_err(|e| RequestError::Other(e.into()))?,
590        ))
591        .map_err(|e| RequestError::Other(e.into()))?;
592
593    let mut response = client.send(request).await?;
594    if response.status().is_success() {
595        let reader = BufReader::new(response.into_body());
596        Ok(reader
597            .lines()
598            .filter_map(|line| async move {
599                match line {
600                    Ok(line) => {
601                        let line = line.strip_prefix("data: ").or_else(|| line.strip_prefix("data:"))?;
602                        if line == "[DONE]" {
603                            None
604                        } else {
605                            match serde_json::from_str(line) {
606                                Ok(ResponseStreamResult::Ok(response)) => Some(Ok(response)),
607                                Ok(ResponseStreamResult::Err { error }) => {
608                                    Some(Err(anyhow!(error.message)))
609                                }
610                                Err(error) => {
611                                    log::error!(
612                                        "Failed to parse OpenAI response into ResponseStreamResult: `{}`\n\
613                                        Response: `{}`",
614                                        error,
615                                        line,
616                                    );
617                                    Some(Err(anyhow!(error)))
618                                }
619                            }
620                        }
621                    }
622                    Err(error) => Some(Err(anyhow!(error))),
623                }
624            })
625            .boxed())
626    } else {
627        let mut body = String::new();
628        response
629            .body_mut()
630            .read_to_string(&mut body)
631            .await
632            .map_err(|e| RequestError::Other(e.into()))?;
633
634        Err(RequestError::HttpResponseError {
635            provider: provider_name.to_owned(),
636            status_code: response.status(),
637            body,
638            headers: response.headers().clone(),
639        })
640    }
641}
642
643#[derive(Copy, Clone, Serialize, Deserialize)]
644pub enum OpenAiEmbeddingModel {
645    #[serde(rename = "text-embedding-3-small")]
646    TextEmbedding3Small,
647    #[serde(rename = "text-embedding-3-large")]
648    TextEmbedding3Large,
649}
650
651#[derive(Serialize)]
652struct OpenAiEmbeddingRequest<'a> {
653    model: OpenAiEmbeddingModel,
654    input: Vec<&'a str>,
655}
656
657#[derive(Deserialize)]
658pub struct OpenAiEmbeddingResponse {
659    pub data: Vec<OpenAiEmbedding>,
660}
661
662#[derive(Deserialize)]
663pub struct OpenAiEmbedding {
664    pub embedding: Vec<f32>,
665}
666
667pub fn embed<'a>(
668    client: &dyn HttpClient,
669    api_url: &str,
670    api_key: &str,
671    model: OpenAiEmbeddingModel,
672    texts: impl IntoIterator<Item = &'a str>,
673) -> impl 'static + Future<Output = Result<OpenAiEmbeddingResponse>> {
674    let uri = format!("{api_url}/embeddings");
675
676    let request = OpenAiEmbeddingRequest {
677        model,
678        input: texts.into_iter().collect(),
679    };
680    let body = AsyncBody::from(serde_json::to_string(&request).unwrap());
681    let request = HttpRequest::builder()
682        .method(Method::POST)
683        .uri(uri)
684        .header("Content-Type", "application/json")
685        .header("Authorization", format!("Bearer {}", api_key.trim()))
686        .body(body)
687        .map(|request| client.send(request));
688
689    async move {
690        let mut response = request?.await?;
691        let mut body = String::new();
692        response.body_mut().read_to_string(&mut body).await?;
693
694        anyhow::ensure!(
695            response.status().is_success(),
696            "error during embedding, status: {:?}, body: {:?}",
697            response.status(),
698            body
699        );
700        let response: OpenAiEmbeddingResponse =
701            serde_json::from_str(&body).context("failed to parse OpenAI embedding response")?;
702        Ok(response)
703    }
704}