lc-providers 0.17.0

LLM provider integrations for langchainrust — OpenAI, Anthropic, Ollama, Gemini, etc.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
// lc-providers/src/providers/mistral.rs
//! Mistral AI API implementation (OpenAI-compatible).
//!
//! Mistral's chat API is compatible with the OpenAI `/v1/chat/completions` format,
//! so this implementation wraps `OpenAIChat` and delegates all calls.
//!
//! # Supported Models
//!
//! - `mistral-large-latest` — flagship model
//! - `mistral-medium-latest` — balanced performance
//! - `mistral-small-latest` — fast and cost-effective
//! - `open-mistral-nemo` — open-weight model
//! - `codestral-latest` — code generation
//! - `mistral-embed` — embedding model (use `MistralEmbeddings` in lc-embeddings)
//!
//! # Example
//!
//! ```rust,ignore
//! use lc_providers::providers::{MistralChat, MistralConfig};
//!
//! let llm = MistralChat::new(MistralConfig::new("your-api-key"));
//! let result = llm.chat(messages, None).await?;
//! ```

use crate::error::ProviderError;
use crate::openai::{OpenAIChat, OpenAIConfig, OpenAIError, StructuredOutputMethod};
use async_trait::async_trait;
use futures_util::Stream;
use lc_core::language_models::{BaseChatModel, BaseLanguageModel, LLMResult};
use lc_core::runnables::Runnable;
use lc_core::tools::ToolDefinition;
use lc_core::RunnableConfig;
use lc_schema::Message;
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use std::env;
use std::pin::Pin;

/// Mistral AI API endpoint.
pub const MISTRAL_BASE_URL: &str = "https://api.mistral.ai/v1";

/// Mistral model list.
pub const MISTRAL_MODELS: [&str; 6] = [
    "mistral-large-latest",
    "mistral-medium-latest",
    "mistral-small-latest",
    "open-mistral-nemo",
    "codestral-latest",
    "mistral-embed",
];

/// Mistral AI configuration.
#[derive(Debug, Clone)]
pub struct MistralConfig {
    /// Mistral API key.
    pub api_key: String,
    /// Base URL of the Mistral API endpoint.
    pub base_url: String,
    /// Model name to use.
    pub model: String,
    /// Sampling temperature.
    pub temperature: Option<f32>,
    /// Maximum number of tokens to generate.
    pub max_tokens: Option<usize>,
}

impl Default for MistralConfig {
    fn default() -> Self {
        Self {
            api_key: String::new(),
            base_url: MISTRAL_BASE_URL.to_string(),
            model: "mistral-large-latest".to_string(),
            temperature: None,
            max_tokens: None,
        }
    }
}

impl MistralConfig {
    /// Creates a new MistralConfig with the given API key.
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            api_key: api_key.into(),
            ..Default::default()
        }
    }

    /// Creates a MistralConfig from environment variables, returning a Result.
    ///
    /// Environment variables:
    /// - `MISTRAL_API_KEY`: API key (required)
    /// - `MISTRAL_BASE_URL`: API endpoint (optional)
    /// - `MISTRAL_MODEL`: Model name (optional)
    pub fn from_env_result() -> Result<Self, ProviderError> {
        let api_key = env::var("MISTRAL_API_KEY").map_err(|_| {
            ProviderError::Config("MISTRAL_API_KEY environment variable not set".to_string())
        })?;

        let base_url =
            env::var("MISTRAL_BASE_URL").unwrap_or_else(|_| MISTRAL_BASE_URL.to_string());

        let model =
            env::var("MISTRAL_MODEL").unwrap_or_else(|_| "mistral-large-latest".to_string());

        Ok(Self {
            api_key,
            base_url,
            model,
            ..Default::default()
        })
    }

    /// Sets the model name.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.model = model.into();
        self
    }

    /// Sets a custom API base URL.
    pub fn with_base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into();
        self
    }

    /// Sets the temperature parameter.
    pub fn with_temperature(mut self, temp: f32) -> Self {
        self.temperature = Some(temp);
        self
    }

    /// Sets the max tokens limit.
    pub fn with_max_tokens(mut self, max: usize) -> Self {
        self.max_tokens = Some(max);
        self
    }

    /// Converts to OpenAI config (reuses OpenAI implementation).
    pub fn into_openai_config(self) -> OpenAIConfig {
        OpenAIConfig {
            api_key: self.api_key,
            base_url: self.base_url,
            model: self.model,
            temperature: self.temperature,
            max_tokens: self.max_tokens,
            top_p: None,
            frequency_penalty: None,
            presence_penalty: None,
            streaming: false,
            organization: None,
            tools: None,
            tool_choice: None,
        }
    }
}

/// Mistral AI chat client.
///
/// Wraps `OpenAIChat` internally since Mistral's API is OpenAI-compatible.
#[derive(Clone)]
pub struct MistralChat {
    inner: OpenAIChat,
}

impl std::fmt::Debug for MistralChat {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MistralChat").finish_non_exhaustive()
    }
}

impl MistralChat {
    /// Creates a MistralChat with the given configuration.
    pub fn new(config: MistralConfig) -> Self {
        Self {
            inner: OpenAIChat::new(config.into_openai_config()),
        }
    }

    /// Creates a MistralChat from environment variables, returning a Result.
    pub fn from_env_result() -> Result<Self, ProviderError> {
        Ok(Self::new(MistralConfig::from_env_result()?))
    }

    /// Delegate chat to inner OpenAIChat.
    pub async fn chat(
        &self,
        messages: Vec<Message>,
        config: Option<RunnableConfig>,
    ) -> Result<LLMResult, OpenAIError> {
        self.inner.chat(messages, config).await
    }

    /// Delegate stream_chat to inner OpenAIChat.
    pub async fn stream_chat(
        &self,
        messages: Vec<Message>,
        config: Option<RunnableConfig>,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<String, OpenAIError>> + Send>>, OpenAIError> {
        self.inner.stream_chat(messages, config).await
    }

    /// Delegate bind_tools to inner OpenAIChat.
    pub fn bind_tools(&self, tools: Vec<ToolDefinition>) -> Self {
        Self {
            inner: self.inner.bind_tools(tools),
        }
    }

    /// Delegate with_tool_choice to inner OpenAIChat.
    pub fn with_tool_choice(self, choice: impl Into<String>) -> Self {
        Self {
            inner: self.inner.with_tool_choice(choice),
        }
    }

    /// Delegate with_structured_output to inner OpenAIChat.
    pub fn with_structured_output<T: DeserializeOwned + JsonSchema>(
        &self,
    ) -> StructuredOutputMethod<T> {
        self.inner.with_structured_output()
    }
}

#[async_trait]
impl BaseLanguageModel<Vec<Message>, LLMResult> for MistralChat {
    fn model_name(&self) -> &str {
        self.inner.model_name()
    }

    fn get_num_tokens(&self, text: &str) -> usize {
        self.inner.get_num_tokens(text)
    }

    fn temperature(&self) -> Option<f32> {
        self.inner.temperature()
    }

    fn max_tokens(&self) -> Option<usize> {
        self.inner.max_tokens()
    }

    fn with_temperature(self, temp: f32) -> Self {
        Self {
            inner: self.inner.with_temperature(temp),
        }
    }

    fn with_max_tokens(self, max: usize) -> Self {
        Self {
            inner: self.inner.with_max_tokens(max),
        }
    }
}

#[async_trait]
impl Runnable<Vec<Message>, LLMResult> for MistralChat {
    type Error = ProviderError;

    async fn invoke(
        &self,
        input: Vec<Message>,
        config: Option<RunnableConfig>,
    ) -> Result<LLMResult, Self::Error> {
        self.inner
            .invoke(input, config)
            .await
            .map_err(ProviderError::Mistral)
    }

    async fn stream(
        &self,
        input: Vec<Message>,
        config: Option<RunnableConfig>,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<LLMResult, Self::Error>> + Send>>, Self::Error>
    {
        use futures_util::StreamExt;
        let stream = self
            .inner
            .stream(input, config)
            .await
            .map_err(ProviderError::Mistral)?;
        Ok(Box::pin(stream.map(|r| r.map_err(ProviderError::Mistral))))
    }
}

#[async_trait]
impl BaseChatModel for MistralChat {
    async fn chat(
        &self,
        messages: Vec<Message>,
        config: Option<RunnableConfig>,
    ) -> Result<LLMResult, Self::Error> {
        self.inner
            .chat(messages, config)
            .await
            .map_err(ProviderError::Mistral)
    }

    async fn stream_chat(
        &self,
        messages: Vec<Message>,
        config: Option<RunnableConfig>,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<String, Self::Error>> + Send>>, Self::Error> {
        use futures_util::StreamExt;
        let stream = self
            .inner
            .stream_chat(messages, config)
            .await
            .map_err(ProviderError::Mistral)?;
        Ok(Box::pin(stream.map(|r| r.map_err(ProviderError::Mistral))))
    }

    fn bind_tools(
        &self,
        tools: Vec<ToolDefinition>,
    ) -> Option<Box<dyn BaseChatModel<Error = Self::Error> + Send + Sync>> {
        // Expose the inherent tool-binding capability at the trait level so it
        // survives being wrapped by `ChatModelWrapper` / `LLMClient` (Q1).
        Some(Box::new(self.bind_tools(tools)))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ENV_TEST_LOCK;

    fn save_and_set(key: &str, value: &str) -> Option<String> {
        let old = std::env::var(key).ok();
        std::env::set_var(key, value);
        old
    }

    fn restore(key: &str, old: Option<String>) {
        match old {
            Some(v) => std::env::set_var(key, v),
            None => std::env::remove_var(key),
        }
    }

    #[test]
    fn test_config_new() {
        let config = MistralConfig::new("test-key");
        assert_eq!(config.api_key, "test-key");
        assert_eq!(config.base_url, MISTRAL_BASE_URL);
        assert_eq!(config.model, "mistral-large-latest");
    }

    #[test]
    fn test_config_builder() {
        let config = MistralConfig::new("key")
            .with_model("mistral-small-latest")
            .with_base_url("https://custom.mistral.ai/v1")
            .with_temperature(0.7)
            .with_max_tokens(1024);
        assert_eq!(config.model, "mistral-small-latest");
        assert_eq!(config.base_url, "https://custom.mistral.ai/v1");
        assert_eq!(config.temperature, Some(0.7));
        assert_eq!(config.max_tokens, Some(1024));
    }

    #[test]
    fn test_config_from_env_result_ok() {
        let _lock = ENV_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let old = save_and_set("MISTRAL_API_KEY", "env-key");
        let result = MistralConfig::from_env_result();
        assert!(result.is_ok());
        assert_eq!(result.unwrap().api_key, "env-key");
        restore("MISTRAL_API_KEY", old);
    }

    #[test]
    fn test_config_from_env_result_err_when_missing() {
        let _lock = ENV_TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let old = std::env::var("MISTRAL_API_KEY").ok();
        std::env::remove_var("MISTRAL_API_KEY");
        let result = MistralConfig::from_env_result();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("MISTRAL_API_KEY"));
        restore("MISTRAL_API_KEY", old);
    }

    #[test]
    fn test_into_openai_config() {
        let config = MistralConfig::new("key").with_model("codestral-latest");
        let openai_config = config.into_openai_config();
        assert_eq!(openai_config.api_key, "key");
        assert_eq!(openai_config.base_url, MISTRAL_BASE_URL);
        assert_eq!(openai_config.model, "codestral-latest");
    }

    #[test]
    fn test_chat_new() {
        let config = MistralConfig::new("test-key");
        let _chat = MistralChat::new(config);
    }

    #[test]
    fn test_model_name() {
        let config = MistralConfig::new("key").with_model("mistral-small-latest");
        let chat = MistralChat::new(config);
        assert_eq!(chat.model_name(), "mistral-small-latest");
    }
}