open_ai.rs

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