llmsdk-mistral 0.1.1

Mistral provider for llmsdk (Rust port of @ai-sdk/mistral)
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
404
405
406
407
408
409
410
411
//! Streaming state machine: Mistral SSE chunks → [`StreamPart`].
//!
//! Mirrors the `TransformStream` body in `mistral-chat-language-model.ts`'s
//! `doStream`. Mistral content arrives as either a string or a list of
//! `text` / `thinking` typed parts. We map `text` deltas to a single text
//! block with id `"0"` and `thinking` deltas to a reasoning block whose id
//! is generated on the fly. When text arrives during an active reasoning
//! block we close the reasoning block first (matches upstream behaviour).
// Rust guideline compliant 2026-05-25

use std::sync::Arc;

use llmsdk_provider::language_model::{
    FinishReason, FinishReasonKind, ResponseMetadata, StreamPart, ToolCallPart,
};
use llmsdk_provider::shared::Warning;
use llmsdk_provider_utils::time::rfc3339_from_unix_seconds;

use super::finish_reason::map as map_finish_reason;
use super::parse_response::collect_thinking_text;
use super::usage;
use super::wire::{ChatChunk, MistralContent, MistralContentPart, WireUsage};
use crate::config::GenerateIdFn;

const TEXT_ID: &str = "0";

/// State machine driving a Mistral Chat Completions stream.
pub(crate) struct StreamState {
    initial_warnings: Option<Vec<Warning>>,
    finish_reason: FinishReason,
    last_usage: Option<WireUsage>,
    metadata_emitted: bool,
    is_first_chunk: bool,
    active_text: bool,
    active_reasoning_id: Option<String>,
    reasoning_id_seq: u64,
    generate_id: Option<Arc<GenerateIdFn>>,
}

impl std::fmt::Debug for StreamState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StreamState")
            .field("initial_warnings", &self.initial_warnings)
            .field("finish_reason", &self.finish_reason)
            .field("last_usage", &self.last_usage)
            .field("metadata_emitted", &self.metadata_emitted)
            .field("is_first_chunk", &self.is_first_chunk)
            .field("active_text", &self.active_text)
            .field("active_reasoning_id", &self.active_reasoning_id)
            .field("reasoning_id_seq", &self.reasoning_id_seq)
            .field("generate_id", &self.generate_id.is_some())
            .finish()
    }
}

impl StreamState {
    /// Build with an optional user-supplied id generator.
    ///
    /// When `generate_id` is `Some`, each new reasoning block id is produced
    /// by invoking the closure; otherwise we fall back to a deterministic
    /// `reasoning-N` counter. Mirrors upstream
    /// `mistral-chat-language-model.ts:75` (`this.generateId = config.generateId ?? generateId`).
    pub(crate) fn with_generate_id(
        warnings: Vec<Warning>,
        generate_id: Option<Arc<GenerateIdFn>>,
    ) -> Self {
        Self {
            initial_warnings: Some(warnings),
            finish_reason: FinishReason::new(FinishReasonKind::Other),
            last_usage: None,
            metadata_emitted: false,
            is_first_chunk: true,
            active_text: false,
            active_reasoning_id: None,
            reasoning_id_seq: 0,
            generate_id,
        }
    }

    fn next_reasoning_id(&mut self) -> String {
        if let Some(f) = self.generate_id.as_ref() {
            return f();
        }
        self.reasoning_id_seq = self.reasoning_id_seq.wrapping_add(1);
        format!("reasoning-{}", self.reasoning_id_seq)
    }

    /// Return the very first frame (`StreamStart` with warnings).
    pub(crate) fn start_frames(&mut self) -> Vec<StreamPart> {
        let warnings = self.initial_warnings.take().unwrap_or_default();
        vec![StreamPart::StreamStart { warnings }]
    }

    /// Handle one decoded SSE chunk; returns the frames to forward.
    #[allow(
        clippy::too_many_lines,
        reason = "single dispatcher mirroring upstream's mistral-chat-language-model.ts TransformStream body"
    )]
    pub(crate) fn on_chunk(&mut self, chunk: ChatChunk) -> Vec<StreamPart> {
        let mut out = Vec::new();

        if self.is_first_chunk {
            self.is_first_chunk = false;
            if !self.metadata_emitted
                && (chunk.id.is_some() || chunk.created.is_some() || chunk.model.is_some())
            {
                self.metadata_emitted = true;
                out.push(StreamPart::ResponseMetadata(ResponseMetadata {
                    id: chunk.id.clone(),
                    timestamp: chunk.created.map(rfc3339_from_unix_seconds),
                    model_id: chunk.model.clone(),
                    headers: None,
                }));
            }
        }

        if let Some(u) = chunk.usage {
            self.last_usage = Some(u);
        }

        let Some(choice) = chunk.choices.into_iter().next() else {
            return out;
        };

        if let Some(reason) = choice.finish_reason.as_deref()
            && !matches!(self.finish_reason.unified, FinishReasonKind::Error)
        {
            self.finish_reason = map_finish_reason(Some(reason));
        }

        let Some(delta) = choice.delta else {
            return out;
        };

        // Reasoning ("thinking") parts come first in the upstream walk because
        // any thinking text might precede the text content within the same
        // chunk; we emit them before opening any text block.
        if let Some(MistralContent::Parts(parts)) = &delta.content {
            for part in parts {
                if let MistralContentPart::Thinking { thinking } = part {
                    let reasoning_delta = collect_thinking_text(thinking);
                    if reasoning_delta.is_empty() {
                        continue;
                    }
                    if self.active_reasoning_id.is_none() {
                        // close any active text block first
                        if self.active_text {
                            out.push(StreamPart::TextEnd {
                                id: TEXT_ID.to_owned(),
                                provider_metadata: None,
                            });
                            self.active_text = false;
                        }
                        let id = self.next_reasoning_id();
                        self.active_reasoning_id = Some(id.clone());
                        out.push(StreamPart::ReasoningStart {
                            id,
                            provider_metadata: None,
                        });
                    }
                    out.push(StreamPart::ReasoningDelta {
                        id: self
                            .active_reasoning_id
                            .clone()
                            .unwrap_or_else(|| "reasoning".to_owned()),
                        delta: reasoning_delta,
                        provider_metadata: None,
                    });
                }
            }
        }

        // Now any text content (either bare string or the text parts inside
        // the array).
        let text_delta = extract_text(delta.content.as_ref());
        if let Some(text) = text_delta
            && !text.is_empty()
        {
            if !self.active_text {
                // close any active reasoning block before starting text
                if let Some(id) = self.active_reasoning_id.take() {
                    out.push(StreamPart::ReasoningEnd {
                        id,
                        provider_metadata: None,
                    });
                }
                out.push(StreamPart::TextStart {
                    id: TEXT_ID.to_owned(),
                    provider_metadata: None,
                });
                self.active_text = true;
            }
            out.push(StreamPart::TextDelta {
                id: TEXT_ID.to_owned(),
                delta: text,
                provider_metadata: None,
            });
        }

        // Tool calls (Mistral emits each tool call complete in one chunk).
        if let Some(tool_calls) = delta.tool_calls {
            for tc in tool_calls {
                let id = tc.id.clone();
                out.push(StreamPart::ToolInputStart {
                    id: id.clone(),
                    tool_name: tc.function.name.clone(),
                    provider_executed: None,
                    dynamic: None,
                    title: None,
                    provider_metadata: None,
                });
                out.push(StreamPart::ToolInputDelta {
                    id: id.clone(),
                    delta: tc.function.arguments.clone(),
                    provider_metadata: None,
                });
                out.push(StreamPart::ToolInputEnd {
                    id: id.clone(),
                    provider_metadata: None,
                });

                let input = serde_json::from_str::<serde_json::Value>(&tc.function.arguments)
                    .unwrap_or(serde_json::Value::String(tc.function.arguments));
                out.push(StreamPart::ToolCall(ToolCallPart {
                    tool_call_id: id,
                    tool_name: tc.function.name,
                    input,
                    provider_executed: None,
                    dynamic: None,
                    provider_options: None,
                }));
            }
        }

        out
    }

    /// Surface a JSON parse failure as an in-stream error.
    pub(crate) fn on_parse_error(&mut self, raw: &str, message: &str) -> Vec<StreamPart> {
        self.finish_reason = FinishReason::new(FinishReasonKind::Error);
        vec![StreamPart::Error {
            error: serde_json::json!({ "message": message, "raw": raw }),
        }]
    }

    /// Final flush: emit any pending `*End` frames, then `Finish`.
    pub(crate) fn flush(self) -> Vec<StreamPart> {
        let mut out = Vec::new();

        if let Some(id) = self.active_reasoning_id {
            out.push(StreamPart::ReasoningEnd {
                id,
                provider_metadata: None,
            });
        }
        if self.active_text {
            out.push(StreamPart::TextEnd {
                id: TEXT_ID.to_owned(),
                provider_metadata: None,
            });
        }

        let usage_value = self
            .last_usage
            .as_ref()
            .map_or_else(usage::zero, usage::convert);

        out.push(StreamPart::Finish {
            usage: usage_value,
            finish_reason: self.finish_reason,
            provider_metadata: None,
        });
        out
    }
}

/// Mirrors `extractTextContent` in upstream — collapses the string / parts
/// union into a single string, skipping non-text parts.
fn extract_text(content: Option<&MistralContent>) -> Option<String> {
    match content? {
        MistralContent::Text(s) => Some(s.clone()),
        MistralContent::Parts(parts) => {
            let mut s = String::new();
            for p in parts {
                if let MistralContentPart::Text { text } = p {
                    s.push_str(text);
                }
            }
            if s.is_empty() { None } else { Some(s) }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::chat::wire::{
        ChatChunkChoice, ChatChunkDelta, MistralThinkingChunk, WireFunctionCall, WireToolCall,
        WireToolCallKind,
    };

    fn text_chunk(text: &str, finish: Option<&str>) -> ChatChunk {
        ChatChunk {
            choices: vec![ChatChunkChoice {
                delta: Some(ChatChunkDelta {
                    content: Some(MistralContent::Text(text.into())),
                    ..Default::default()
                }),
                finish_reason: finish.map(str::to_owned),
                index: 0,
            }],
            ..Default::default()
        }
    }

    fn thinking_chunk(text: &str) -> ChatChunk {
        ChatChunk {
            choices: vec![ChatChunkChoice {
                delta: Some(ChatChunkDelta {
                    content: Some(MistralContent::Parts(vec![MistralContentPart::Thinking {
                        thinking: vec![MistralThinkingChunk::Text { text: text.into() }],
                    }])),
                    ..Default::default()
                }),
                finish_reason: None,
                index: 0,
            }],
            ..Default::default()
        }
    }

    #[test]
    fn start_then_text_then_finish() {
        let mut state = StreamState::with_generate_id(vec![], None);
        let s = state.start_frames();
        assert!(matches!(s[0], StreamPart::StreamStart { .. }));

        let f1 = state.on_chunk(text_chunk("hel", None));
        let f2 = state.on_chunk(text_chunk("lo", None));
        state.on_chunk(text_chunk("", Some("stop")));

        assert!(matches!(&f1[0], StreamPart::TextStart { .. }));
        assert!(matches!(&f1[1], StreamPart::TextDelta { delta, .. } if delta == "hel"));
        assert!(matches!(&f2[0], StreamPart::TextDelta { delta, .. } if delta == "lo"));

        let tail = state.flush();
        assert!(matches!(tail[0], StreamPart::TextEnd { .. }));
        let StreamPart::Finish { finish_reason, .. } = &tail[1] else {
            panic!("expected Finish");
        };
        assert_eq!(finish_reason.unified, FinishReasonKind::Stop);
    }

    #[test]
    fn thinking_then_text_closes_reasoning_first() {
        let mut state = StreamState::with_generate_id(vec![], None);
        let _ = state.start_frames();
        let f1 = state.on_chunk(thinking_chunk("think"));
        assert!(matches!(&f1[0], StreamPart::ReasoningStart { .. }));
        assert!(matches!(&f1[1], StreamPart::ReasoningDelta { .. }));
        let f2 = state.on_chunk(text_chunk("answer", None));
        assert!(matches!(&f2[0], StreamPart::ReasoningEnd { .. }));
        assert!(matches!(&f2[1], StreamPart::TextStart { .. }));
        assert!(matches!(&f2[2], StreamPart::TextDelta { .. }));
    }

    #[test]
    fn tool_call_one_chunk() {
        let mut state = StreamState::with_generate_id(vec![], None);
        let _ = state.start_frames();
        let frames = state.on_chunk(ChatChunk {
            choices: vec![ChatChunkChoice {
                delta: Some(ChatChunkDelta {
                    tool_calls: Some(vec![WireToolCall {
                        id: "call_w".into(),
                        kind: Some(WireToolCallKind::Function),
                        function: WireFunctionCall {
                            name: "weather".into(),
                            arguments: r#"{"city":"NYC"}"#.into(),
                        },
                    }]),
                    ..Default::default()
                }),
                finish_reason: Some("tool_calls".into()),
                index: 0,
            }],
            ..Default::default()
        });
        assert!(matches!(&frames[0], StreamPart::ToolInputStart { .. }));
        assert!(matches!(&frames[1], StreamPart::ToolInputDelta { .. }));
        assert!(matches!(&frames[2], StreamPart::ToolInputEnd { .. }));
        let StreamPart::ToolCall(tc) = &frames[3] else {
            panic!("expected ToolCall");
        };
        assert_eq!(tc.tool_call_id, "call_w");
        assert_eq!(tc.input["city"], "NYC");
    }

    #[test]
    fn parse_error_marks_finish_as_error() {
        let mut state = StreamState::with_generate_id(vec![], None);
        let _ = state.start_frames();
        let frames = state.on_parse_error("not-json", "expected value");
        assert!(matches!(frames[0], StreamPart::Error { .. }));
        let tail = state.flush();
        let StreamPart::Finish { finish_reason, .. } = tail.last().unwrap() else {
            panic!("expected Finish");
        };
        assert_eq!(finish_reason.unified, FinishReasonKind::Error);
    }
}