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)]
271#[serde(rename_all = "lowercase")]
272pub enum ToolChoice {
273 Auto,
274 Required,
275 None,
276 Any,
277 #[serde(untagged)]
278 Function(ToolDefinition),
279}
280
281#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
282#[serde(tag = "role", rename_all = "lowercase")]
283pub enum RequestMessage {
284 Assistant {
285 #[serde(flatten)]
286 #[serde(default, skip_serializing_if = "Option::is_none")]
287 content: Option<MessageContent>,
288 #[serde(default, skip_serializing_if = "Vec::is_empty")]
289 tool_calls: Vec<ToolCall>,
290 },
291 User {
292 #[serde(flatten)]
293 content: MessageContent,
294 },
295 System {
296 #[serde(flatten)]
297 content: MessageContent,
298 },
299 Tool {
300 content: String,
301 tool_call_id: String,
302 },
303}
304
305#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
306#[serde(untagged)]
307pub enum MessageContent {
308 #[serde(rename = "content")]
309 Plain { content: String },
310 #[serde(rename = "content")]
311 Multipart { content: Vec<MessagePart> },
312}
313
314impl MessageContent {
315 pub fn empty() -> Self {
316 Self::Plain {
317 content: String::new(),
318 }
319 }
320
321 pub fn push_part(&mut self, part: MessagePart) {
322 match self {
323 Self::Plain { content } => match part {
324 MessagePart::Text { text } => {
325 content.push_str(&text);
326 }
327 part => {
328 let mut parts = if content.is_empty() {
329 Vec::new()
330 } else {
331 vec![MessagePart::Text {
332 text: content.clone(),
333 }]
334 };
335 parts.push(part);
336 *self = Self::Multipart { content: parts };
337 }
338 },
339 Self::Multipart { content } => {
340 content.push(part);
341 }
342 }
343 }
344}
345
346#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
347#[serde(tag = "type", rename_all = "snake_case")]
348pub enum MessagePart {
349 Text { text: String },
350 ImageUrl { image_url: String },
351 Thinking { thinking: Vec<ThinkingPart> },
352}
353
354// Backwards-compatibility alias for provider code that refers to ContentPart
355pub type ContentPart = MessagePart;
356
357#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
358#[serde(tag = "type", rename_all = "snake_case")]
359pub enum ThinkingPart {
360 Text { text: String },
361}
362
363#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
364pub struct ToolCall {
365 pub id: String,
366 #[serde(flatten)]
367 pub content: ToolCallContent,
368}
369
370#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
371#[serde(tag = "type", rename_all = "lowercase")]
372pub enum ToolCallContent {
373 Function { function: FunctionContent },
374}
375
376#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)]
377pub struct FunctionContent {
378 pub name: String,
379 pub arguments: String,
380}
381
382#[derive(Serialize, Deserialize, Debug)]
383pub struct Usage {
384 pub prompt_tokens: u64,
385 pub completion_tokens: u64,
386 pub total_tokens: u64,
387}
388
389#[derive(Serialize, Deserialize, Debug)]
390pub struct StreamResponse {
391 pub id: String,
392 pub object: String,
393 pub created: u64,
394 pub model: String,
395 pub choices: Vec<StreamChoice>,
396 pub usage: Option<Usage>,
397}
398
399#[derive(Serialize, Deserialize, Debug)]
400pub struct StreamChoice {
401 pub index: u32,
402 pub delta: StreamDelta,
403 pub finish_reason: Option<String>,
404}
405
406#[derive(Serialize, Deserialize, Debug, Clone)]
407pub struct StreamDelta {
408 pub role: Option<Role>,
409 #[serde(default, skip_serializing_if = "Option::is_none")]
410 pub content: Option<MessageContentDelta>,
411 #[serde(default, skip_serializing_if = "Option::is_none")]
412 pub tool_calls: Option<Vec<ToolCallChunk>>,
413}
414
415#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
416#[serde(untagged)]
417pub enum MessageContentDelta {
418 Text(String),
419 Parts(Vec<MessagePart>),
420}
421
422#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
423pub struct ToolCallChunk {
424 pub index: usize,
425 pub id: Option<String>,
426 pub function: Option<FunctionChunk>,
427}
428
429#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
430pub struct FunctionChunk {
431 pub name: Option<String>,
432 pub arguments: Option<String>,
433}
434
435pub async fn stream_completion(
436 client: &dyn HttpClient,
437 api_url: &str,
438 api_key: &str,
439 request: Request,
440) -> Result<BoxStream<'static, Result<StreamResponse>>> {
441 let uri = format!("{api_url}/chat/completions");
442 let request_builder = HttpRequest::builder()
443 .method(Method::POST)
444 .uri(uri)
445 .header("Content-Type", "application/json")
446 .header("Authorization", format!("Bearer {}", api_key.trim()));
447
448 let request = request_builder.body(AsyncBody::from(serde_json::to_string(&request)?))?;
449 let mut response = client.send(request).await?;
450
451 if response.status().is_success() {
452 let reader = BufReader::new(response.into_body());
453 Ok(reader
454 .lines()
455 .filter_map(|line| async move {
456 match line {
457 Ok(line) => {
458 let line = line.strip_prefix("data: ")?;
459 if line == "[DONE]" {
460 None
461 } else {
462 match serde_json::from_str(line) {
463 Ok(response) => Some(Ok(response)),
464 Err(error) => Some(Err(anyhow!(error))),
465 }
466 }
467 }
468 Err(error) => Some(Err(anyhow!(error))),
469 }
470 })
471 .boxed())
472 } else {
473 let mut body = String::new();
474 response.body_mut().read_to_string(&mut body).await?;
475 anyhow::bail!(
476 "Failed to connect to Mistral API: {} {}",
477 response.status(),
478 body,
479 );
480 }
481}