mistral.rs

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