1use anyhow::{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;
7use strum::EnumIter;
8
9pub const MISTRAL_API_URL: &str = "https://api.mistral.ai/v1";
10
11#[derive(Clone, Copy, Serialize, Deserialize, Debug, Eq, PartialEq)]
12#[serde(rename_all = "lowercase")]
13pub enum Role {
14 User,
15 Assistant,
16 System,
17 Tool,
18}
19
20impl TryFrom<String> for Role {
21 type Error = anyhow::Error;
22
23 fn try_from(value: String) -> Result<Self> {
24 match value.as_str() {
25 "user" => Ok(Self::User),
26 "assistant" => Ok(Self::Assistant),
27 "system" => Ok(Self::System),
28 "tool" => Ok(Self::Tool),
29 _ => anyhow::bail!("invalid role '{value}'"),
30 }
31 }
32}
33
34impl From<Role> for String {
35 fn from(val: Role) -> Self {
36 match val {
37 Role::User => "user".to_owned(),
38 Role::Assistant => "assistant".to_owned(),
39 Role::System => "system".to_owned(),
40 Role::Tool => "tool".to_owned(),
41 }
42 }
43}
44
45#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
46#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, EnumIter)]
47pub enum Model {
48 #[serde(rename = "codestral-latest", alias = "codestral-latest")]
49 #[default]
50 CodestralLatest,
51
52 #[serde(rename = "mistral-large-latest", alias = "mistral-large-latest")]
53 MistralLargeLatest,
54 #[serde(rename = "mistral-medium-latest", alias = "mistral-medium-latest")]
55 MistralMediumLatest,
56 #[serde(rename = "mistral-small-latest", alias = "mistral-small-latest")]
57 MistralSmallLatest,
58
59 #[serde(rename = "magistral-medium-latest", alias = "magistral-medium-latest")]
60 MagistralMediumLatest,
61 #[serde(rename = "magistral-small-latest", alias = "magistral-small-latest")]
62 MagistralSmallLatest,
63
64 #[serde(rename = "open-mistral-nemo", alias = "open-mistral-nemo")]
65 OpenMistralNemo,
66 #[serde(rename = "open-codestral-mamba", alias = "open-codestral-mamba")]
67 OpenCodestralMamba,
68
69 #[serde(rename = "devstral-medium-latest", alias = "devstral-medium-latest")]
70 DevstralMediumLatest,
71 #[serde(rename = "devstral-small-latest", alias = "devstral-small-latest")]
72 DevstralSmallLatest,
73
74 #[serde(rename = "pixtral-12b-latest", alias = "pixtral-12b-latest")]
75 Pixtral12BLatest,
76 #[serde(rename = "pixtral-large-latest", alias = "pixtral-large-latest")]
77 PixtralLargeLatest,
78
79 #[serde(rename = "custom")]
80 Custom {
81 name: String,
82 /// The name displayed in the UI, such as in the assistant panel model dropdown menu.
83 display_name: Option<String>,
84 max_tokens: u64,
85 max_output_tokens: Option<u64>,
86 max_completion_tokens: Option<u64>,
87 supports_tools: Option<bool>,
88 supports_images: Option<bool>,
89 supports_thinking: Option<bool>,
90 },
91}
92
93impl Model {
94 pub fn default_fast() -> Self {
95 Model::MistralSmallLatest
96 }
97
98 pub fn from_id(id: &str) -> Result<Self> {
99 match id {
100 "codestral-latest" => Ok(Self::CodestralLatest),
101 "mistral-large-latest" => Ok(Self::MistralLargeLatest),
102 "mistral-medium-latest" => Ok(Self::MistralMediumLatest),
103 "mistral-small-latest" => Ok(Self::MistralSmallLatest),
104 "magistral-medium-latest" => Ok(Self::MagistralMediumLatest),
105 "magistral-small-latest" => Ok(Self::MagistralSmallLatest),
106 "open-mistral-nemo" => Ok(Self::OpenMistralNemo),
107 "open-codestral-mamba" => Ok(Self::OpenCodestralMamba),
108 "devstral-medium-latest" => Ok(Self::DevstralMediumLatest),
109 "devstral-small-latest" => Ok(Self::DevstralSmallLatest),
110 "pixtral-12b-latest" => Ok(Self::Pixtral12BLatest),
111 "pixtral-large-latest" => Ok(Self::PixtralLargeLatest),
112 invalid_id => anyhow::bail!("invalid model id '{invalid_id}'"),
113 }
114 }
115
116 pub fn id(&self) -> &str {
117 match self {
118 Self::CodestralLatest => "codestral-latest",
119 Self::MistralLargeLatest => "mistral-large-latest",
120 Self::MistralMediumLatest => "mistral-medium-latest",
121 Self::MistralSmallLatest => "mistral-small-latest",
122 Self::MagistralMediumLatest => "magistral-medium-latest",
123 Self::MagistralSmallLatest => "magistral-small-latest",
124 Self::OpenMistralNemo => "open-mistral-nemo",
125 Self::OpenCodestralMamba => "open-codestral-mamba",
126 Self::DevstralMediumLatest => "devstral-medium-latest",
127 Self::DevstralSmallLatest => "devstral-small-latest",
128 Self::Pixtral12BLatest => "pixtral-12b-latest",
129 Self::PixtralLargeLatest => "pixtral-large-latest",
130 Self::Custom { name, .. } => name,
131 }
132 }
133
134 pub fn display_name(&self) -> &str {
135 match self {
136 Self::CodestralLatest => "codestral-latest",
137 Self::MistralLargeLatest => "mistral-large-latest",
138 Self::MistralMediumLatest => "mistral-medium-latest",
139 Self::MistralSmallLatest => "mistral-small-latest",
140 Self::MagistralMediumLatest => "magistral-medium-latest",
141 Self::MagistralSmallLatest => "magistral-small-latest",
142 Self::OpenMistralNemo => "open-mistral-nemo",
143 Self::OpenCodestralMamba => "open-codestral-mamba",
144 Self::DevstralMediumLatest => "devstral-medium-latest",
145 Self::DevstralSmallLatest => "devstral-small-latest",
146 Self::Pixtral12BLatest => "pixtral-12b-latest",
147 Self::PixtralLargeLatest => "pixtral-large-latest",
148 Self::Custom {
149 name, display_name, ..
150 } => display_name.as_ref().unwrap_or(name),
151 }
152 }
153
154 pub fn max_token_count(&self) -> u64 {
155 match self {
156 Self::CodestralLatest => 256000,
157 Self::MistralLargeLatest => 131000,
158 Self::MistralMediumLatest => 128000,
159 Self::MistralSmallLatest => 32000,
160 Self::MagistralMediumLatest => 40000,
161 Self::MagistralSmallLatest => 40000,
162 Self::OpenMistralNemo => 131000,
163 Self::OpenCodestralMamba => 256000,
164 Self::DevstralMediumLatest => 128000,
165 Self::DevstralSmallLatest => 262144,
166 Self::Pixtral12BLatest => 128000,
167 Self::PixtralLargeLatest => 128000,
168 Self::Custom { max_tokens, .. } => *max_tokens,
169 }
170 }
171
172 pub fn max_output_tokens(&self) -> Option<u64> {
173 match self {
174 Self::Custom {
175 max_output_tokens, ..
176 } => *max_output_tokens,
177 _ => None,
178 }
179 }
180
181 pub fn supports_tools(&self) -> bool {
182 match self {
183 Self::CodestralLatest
184 | Self::MistralLargeLatest
185 | Self::MistralMediumLatest
186 | Self::MistralSmallLatest
187 | Self::MagistralMediumLatest
188 | Self::MagistralSmallLatest
189 | Self::OpenMistralNemo
190 | Self::OpenCodestralMamba
191 | Self::DevstralMediumLatest
192 | Self::DevstralSmallLatest
193 | Self::Pixtral12BLatest
194 | Self::PixtralLargeLatest => true,
195 Self::Custom { supports_tools, .. } => supports_tools.unwrap_or(false),
196 }
197 }
198
199 pub fn supports_images(&self) -> bool {
200 match self {
201 Self::Pixtral12BLatest
202 | Self::PixtralLargeLatest
203 | Self::MistralMediumLatest
204 | Self::MistralSmallLatest => true,
205 Self::CodestralLatest
206 | Self::MistralLargeLatest
207 | Self::MagistralMediumLatest
208 | Self::MagistralSmallLatest
209 | Self::OpenMistralNemo
210 | Self::OpenCodestralMamba
211 | Self::DevstralMediumLatest
212 | Self::DevstralSmallLatest => false,
213 Self::Custom {
214 supports_images, ..
215 } => supports_images.unwrap_or(false),
216 }
217 }
218
219 pub fn supports_thinking(&self) -> bool {
220 match self {
221 Self::MagistralMediumLatest | Self::MagistralSmallLatest => true,
222 Self::Custom {
223 supports_thinking, ..
224 } => supports_thinking.unwrap_or(false),
225 _ => 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_tokens: Option<u64>,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
238 pub temperature: Option<f32>,
239 #[serde(default, skip_serializing_if = "Option::is_none")]
240 pub response_format: Option<ResponseFormat>,
241 #[serde(default, skip_serializing_if = "Option::is_none")]
242 pub tool_choice: Option<ToolChoice>,
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(rename_all = "snake_case")]
251pub enum ResponseFormat {
252 Text,
253 #[serde(rename = "json_object")]
254 JsonObject,
255}
256
257#[derive(Debug, Serialize, Deserialize)]
258#[serde(tag = "type", rename_all = "snake_case")]
259pub enum ToolDefinition {
260 Function { function: FunctionDefinition },
261}
262
263#[derive(Debug, Serialize, Deserialize)]
264pub struct FunctionDefinition {
265 pub name: String,
266 pub description: Option<String>,
267 pub parameters: Option<Value>,
268}
269
270#[derive(Debug, Serialize, Deserialize)]
271pub struct CompletionRequest {
272 pub model: String,
273 pub prompt: String,
274 pub max_tokens: u32,
275 pub temperature: f32,
276 #[serde(default, skip_serializing_if = "Option::is_none")]
277 pub prediction: Option<Prediction>,
278 #[serde(default, skip_serializing_if = "Option::is_none")]
279 pub rewrite_speculation: Option<bool>,
280}
281
282#[derive(Clone, Deserialize, Serialize, Debug)]
283#[serde(tag = "type", rename_all = "snake_case")]
284pub enum Prediction {
285 Content { content: String },
286}
287
288#[derive(Debug, Serialize, Deserialize)]
289#[serde(rename_all = "snake_case")]
290pub enum ToolChoice {
291 Auto,
292 Required,
293 None,
294 Any,
295 Function(ToolDefinition),
296}
297
298#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
299#[serde(tag = "role", rename_all = "lowercase")]
300pub enum RequestMessage {
301 Assistant {
302 #[serde(flatten)]
303 #[serde(default, skip_serializing_if = "Option::is_none")]
304 content: Option<MessageContent>,
305 #[serde(default, skip_serializing_if = "Vec::is_empty")]
306 tool_calls: Vec<ToolCall>,
307 },
308 User {
309 #[serde(flatten)]
310 content: MessageContent,
311 },
312 System {
313 #[serde(flatten)]
314 content: MessageContent,
315 },
316 Tool {
317 content: String,
318 tool_call_id: String,
319 },
320}
321
322#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
323#[serde(untagged)]
324pub enum MessageContent {
325 #[serde(rename = "content")]
326 Plain { content: String },
327 #[serde(rename = "content")]
328 Multipart { content: Vec<MessagePart> },
329}
330
331impl MessageContent {
332 pub fn empty() -> Self {
333 Self::Plain {
334 content: String::new(),
335 }
336 }
337
338 pub fn push_part(&mut self, part: MessagePart) {
339 match self {
340 Self::Plain { content } => match part {
341 MessagePart::Text { text } => {
342 content.push_str(&text);
343 }
344 part => {
345 let mut parts = if content.is_empty() {
346 Vec::new()
347 } else {
348 vec![MessagePart::Text {
349 text: content.clone(),
350 }]
351 };
352 parts.push(part);
353 *self = Self::Multipart { content: parts };
354 }
355 },
356 Self::Multipart { content } => {
357 content.push(part);
358 }
359 }
360 }
361}
362
363#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
364#[serde(tag = "type", rename_all = "snake_case")]
365pub enum MessagePart {
366 Text { text: String },
367 ImageUrl { image_url: String },
368 Thinking { thinking: Vec<ThinkingPart> },
369}
370
371// Backwards-compatibility alias for provider code that refers to ContentPart
372pub type ContentPart = MessagePart;
373
374#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
375#[serde(tag = "type", rename_all = "snake_case")]
376pub enum ThinkingPart {
377 Text { text: String },
378}
379
380#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
381pub struct ToolCall {
382 pub id: String,
383 #[serde(flatten)]
384 pub content: ToolCallContent,
385}
386
387#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
388#[serde(tag = "type", rename_all = "lowercase")]
389pub enum ToolCallContent {
390 Function { function: FunctionContent },
391}
392
393#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
394pub struct FunctionContent {
395 pub name: String,
396 pub arguments: String,
397}
398
399#[derive(Serialize, Deserialize, Debug)]
400pub struct CompletionChoice {
401 pub text: String,
402}
403
404#[derive(Serialize, Deserialize, Debug)]
405pub struct Response {
406 pub id: String,
407 pub object: String,
408 pub created: u64,
409 pub model: String,
410 pub choices: Vec<Choice>,
411 pub usage: Usage,
412}
413
414#[derive(Serialize, Deserialize, Debug)]
415pub struct Usage {
416 pub prompt_tokens: u64,
417 pub completion_tokens: u64,
418 pub total_tokens: u64,
419}
420
421#[derive(Serialize, Deserialize, Debug)]
422pub struct Choice {
423 pub index: u32,
424 pub message: RequestMessage,
425 pub finish_reason: Option<String>,
426}
427
428#[derive(Serialize, Deserialize, Debug)]
429pub struct StreamResponse {
430 pub id: String,
431 pub object: String,
432 pub created: u64,
433 pub model: String,
434 pub choices: Vec<StreamChoice>,
435 pub usage: Option<Usage>,
436}
437
438#[derive(Serialize, Deserialize, Debug)]
439pub struct StreamChoice {
440 pub index: u32,
441 pub delta: StreamDelta,
442 pub finish_reason: Option<String>,
443}
444
445#[derive(Serialize, Deserialize, Debug, Clone)]
446pub struct StreamDelta {
447 pub role: Option<Role>,
448 #[serde(default, skip_serializing_if = "Option::is_none")]
449 pub content: Option<MessageContentDelta>,
450 #[serde(default, skip_serializing_if = "Option::is_none")]
451 pub tool_calls: Option<Vec<ToolCallChunk>>,
452}
453
454#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
455#[serde(untagged)]
456pub enum MessageContentDelta {
457 Text(String),
458 Parts(Vec<MessagePart>),
459}
460
461#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
462pub struct ToolCallChunk {
463 pub index: usize,
464 pub id: Option<String>,
465 pub function: Option<FunctionChunk>,
466}
467
468#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
469pub struct FunctionChunk {
470 pub name: Option<String>,
471 pub arguments: Option<String>,
472}
473
474pub async fn stream_completion(
475 client: &dyn HttpClient,
476 api_url: &str,
477 api_key: &str,
478 request: Request,
479) -> Result<BoxStream<'static, Result<StreamResponse>>> {
480 let uri = format!("{api_url}/chat/completions");
481 let request_builder = HttpRequest::builder()
482 .method(Method::POST)
483 .uri(uri)
484 .header("Content-Type", "application/json")
485 .header("Authorization", format!("Bearer {}", api_key.trim()));
486
487 let request = request_builder.body(AsyncBody::from(serde_json::to_string(&request)?))?;
488 let mut response = client.send(request).await?;
489
490 if response.status().is_success() {
491 let reader = BufReader::new(response.into_body());
492 Ok(reader
493 .lines()
494 .filter_map(|line| async move {
495 match line {
496 Ok(line) => {
497 let line = line.strip_prefix("data: ")?;
498 if line == "[DONE]" {
499 None
500 } else {
501 match serde_json::from_str(line) {
502 Ok(response) => Some(Ok(response)),
503 Err(error) => Some(Err(anyhow!(error))),
504 }
505 }
506 }
507 Err(error) => Some(Err(anyhow!(error))),
508 }
509 })
510 .boxed())
511 } else {
512 let mut body = String::new();
513 response.body_mut().read_to_string(&mut body).await?;
514 anyhow::bail!(
515 "Failed to connect to Mistral API: {} {}",
516 response.status(),
517 body,
518 );
519 }
520}