1use reqwest::Client;
2use crate::chat::ChatClient;
3use crate::ocr::OcrClient;
4use std::fmt;
5use std::error::Error;
6use serde::Deserialize;
7
8pub mod ocr;
9pub mod chat;
10pub mod files;
11
12pub struct MistralClient {
13 client: Client,
14 api_key: String,
15 base_url: String,
16}
17
18impl MistralClient {
19 pub fn new(api_key: &str, base_url: &str) -> Self {
20 MistralClient {
21 client: Client::new(),
22 api_key: api_key.to_string(),
23 base_url: base_url.to_string(),
24 }
25 }
26
27 pub fn file_client(&self) -> files::FileClient {
28 files::FileClient::new(self)
29 }
30
31 pub fn chat_client(&self, model: &str, temperature: f32) -> ChatClient {
32 ChatClient::new(self, model, temperature)
33 }
34
35 pub fn ocr_client(&self, model: &str) -> OcrClient {
36 OcrClient::new(&self, model)
37 }
38}
39
40#[derive(Debug)]
41pub enum MistralError {
42 Api(MistralApiError),
43 Http(reqwest::StatusCode),
44 Network(reqwest::Error),
45 Parse(serde_json::Error),
46}
47
48impl Error for MistralError {}
49impl fmt::Display for MistralError {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 match self {
52 MistralError::Api(err) => write!(
53 f,
54 "Mistral API error (code {}): {}",
55 err.code, err.message
56 ),
57 MistralError::Http(code) => write!(f, "Unexpected HTTP status: {}", code),
58 MistralError::Network(err) => write!(f, "Network error: {}", err),
59 MistralError::Parse(err) => write!(f, "Parse error: {}", err),
60 }
61 }
62}
63
64#[derive(Debug, Deserialize)]
65pub struct MistralApiError {
66 pub code: u32,
67 #[serde(rename = "type")]
68 pub error_type: String,
69 pub message: String,
70 pub object: String,
71 pub param: Option<String>,
72 #[serde(skip_deserializing)]
73 pub description: String,
74}
75
76pub(crate) fn error_description(code: u32) -> &'static str {
77 match code {
78 2210 => "Invalid request filter: The JSON body could not be parsed.",
79 401 => "Unauthorized: Check your API key.",
80 422 => "Unprocessable Entity: The request was well-formed but unable to be followed due to semantic errors.",
81 _ => "An unknown error occurred.",
82 }
83}