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