cognis-core 0.2.0

Core traits and types for the Cognis LLM framework
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;

use async_trait::async_trait;
use futures::stream;

use crate::error::{CognisError, Result};
use crate::messages::{AIMessage, AIMessageChunk, Message};
use crate::outputs::{ChatGeneration, ChatGenerationChunk, ChatResult, Generation, LLMResult};

use super::base::BaseLanguageModel;
use super::chat_model::{BaseChatModel, ChatStream};
use super::llm::BaseLLM;

// ─── FakeListLLM ───

/// A fake LLM that cycles through a list of predefined responses.
pub struct FakeListLLM {
    pub responses: Vec<String>,
    pub sleep_ms: Option<u64>,
    index: AtomicUsize,
}

impl FakeListLLM {
    pub fn new(responses: Vec<String>) -> Self {
        Self {
            responses,
            sleep_ms: None,
            index: AtomicUsize::new(0),
        }
    }

    pub fn with_sleep(mut self, ms: u64) -> Self {
        self.sleep_ms = Some(ms);
        self
    }

    fn next_response(&self) -> String {
        let idx = self.index.fetch_add(1, Ordering::SeqCst) % self.responses.len();
        self.responses[idx].clone()
    }
}

#[async_trait]
impl BaseLanguageModel for FakeListLLM {
    async fn generate(&self, prompts: &[String]) -> Result<LLMResult> {
        self._generate(prompts, None).await
    }

    async fn generate_chat(&self, _messages: &[Vec<Message>]) -> Result<ChatResult> {
        let response = self.next_response();
        Ok(ChatResult {
            generations: vec![ChatGeneration::new(AIMessage::new(&response))],
            llm_output: None,
        })
    }

    fn model_type(&self) -> &str {
        "fake_list_llm"
    }
}

#[async_trait]
impl BaseLLM for FakeListLLM {
    async fn _generate(&self, prompts: &[String], _stop: Option<&[String]>) -> Result<LLMResult> {
        if let Some(ms) = self.sleep_ms {
            tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
        }
        let generations = prompts
            .iter()
            .map(|_| vec![Generation::new(self.next_response())])
            .collect();
        Ok(LLMResult {
            generations,
            llm_output: None,
            run: None,
        })
    }

    fn llm_type(&self) -> &str {
        "fake_list_llm"
    }
}

// ─── FakeStreamingListLLM ───

/// A fake streaming LLM that streams responses character by character.
///
/// Extends `FakeListLLM` with streaming support — each character
/// of the response is yielded as a separate chunk.
/// Optionally raises an error on a specified chunk number.
pub struct FakeStreamingListLLM {
    pub responses: Vec<String>,
    pub sleep_ms: Option<u64>,
    pub error_on_chunk_number: Option<usize>,
    index: AtomicUsize,
}

impl FakeStreamingListLLM {
    pub fn new(responses: Vec<String>) -> Self {
        Self {
            responses,
            sleep_ms: None,
            error_on_chunk_number: None,
            index: AtomicUsize::new(0),
        }
    }

    pub fn with_sleep(mut self, ms: u64) -> Self {
        self.sleep_ms = Some(ms);
        self
    }

    pub fn with_error_on_chunk(mut self, chunk: usize) -> Self {
        self.error_on_chunk_number = Some(chunk);
        self
    }

    fn next_response(&self) -> String {
        let idx = self.index.fetch_add(1, Ordering::SeqCst) % self.responses.len();
        self.responses[idx].clone()
    }
}

#[async_trait]
impl BaseLanguageModel for FakeStreamingListLLM {
    async fn generate(&self, prompts: &[String]) -> Result<LLMResult> {
        self._generate(prompts, None).await
    }

    async fn generate_chat(&self, _messages: &[Vec<Message>]) -> Result<ChatResult> {
        let response = self.next_response();
        Ok(ChatResult {
            generations: vec![ChatGeneration::new(AIMessage::new(&response))],
            llm_output: None,
        })
    }

    fn model_type(&self) -> &str {
        "fake_streaming_list_llm"
    }
}

#[async_trait]
impl BaseLLM for FakeStreamingListLLM {
    async fn _generate(&self, prompts: &[String], _stop: Option<&[String]>) -> Result<LLMResult> {
        if let Some(ms) = self.sleep_ms {
            tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
        }
        let generations = prompts
            .iter()
            .map(|_| vec![Generation::new(self.next_response())])
            .collect();
        Ok(LLMResult {
            generations,
            llm_output: None,
            run: None,
        })
    }

    async fn _stream(
        &self,
        prompt: &str,
        _stop: Option<&[String]>,
    ) -> Result<crate::runnables::RunnableStream> {
        let _ = prompt;
        let response = self.next_response();
        let error_on = self.error_on_chunk_number;

        let chunks: Vec<(usize, char)> = response.chars().enumerate().collect();
        let stream = stream::iter(chunks.into_iter().map(move |(i, c)| {
            if let Some(err_chunk) = error_on {
                if i == err_chunk {
                    return Err(CognisError::Other(
                        "FakeStreamingListLLM error on chunk".into(),
                    ));
                }
            }
            Ok(serde_json::Value::String(c.to_string()))
        }));

        Ok(Box::pin(stream))
    }

    fn llm_type(&self) -> &str {
        "fake_streaming_list_llm"
    }
}

// ─── FakeListChatModel ───

/// A fake chat model that cycles through a list of predefined string responses.
pub struct FakeListChatModel {
    pub responses: Vec<String>,
    pub sleep_ms: Option<u64>,
    index: AtomicUsize,
}

impl FakeListChatModel {
    pub fn new(responses: Vec<String>) -> Self {
        Self {
            responses,
            sleep_ms: None,
            index: AtomicUsize::new(0),
        }
    }

    pub fn with_sleep(mut self, ms: u64) -> Self {
        self.sleep_ms = Some(ms);
        self
    }

    fn next_response(&self) -> String {
        let idx = self.index.fetch_add(1, Ordering::SeqCst) % self.responses.len();
        self.responses[idx].clone()
    }
}

#[async_trait]
impl BaseChatModel for FakeListChatModel {
    async fn _generate(
        &self,
        _messages: &[Message],
        _stop: Option<&[String]>,
    ) -> Result<ChatResult> {
        if let Some(ms) = self.sleep_ms {
            tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
        }
        let response = self.next_response();
        Ok(ChatResult {
            generations: vec![ChatGeneration::new(AIMessage::new(&response))],
            llm_output: None,
        })
    }

    fn llm_type(&self) -> &str {
        "fake_list_chat_model"
    }

    async fn _stream(&self, _messages: &[Message], _stop: Option<&[String]>) -> Result<ChatStream> {
        if let Some(ms) = self.sleep_ms {
            tokio::time::sleep(std::time::Duration::from_millis(ms)).await;
        }
        let response = self.next_response();
        let chunks: Vec<Result<ChatGenerationChunk>> = response
            .chars()
            .map(|c| Ok(ChatGenerationChunk::new(AIMessageChunk::new(c.to_string()))))
            .collect();
        Ok(Box::pin(stream::iter(chunks)))
    }
}

// ─── FakeMessagesListChatModel ───

/// A fake chat model that cycles through a list of predefined `Message` responses.
pub struct FakeMessagesListChatModel {
    pub responses: Vec<Message>,
    index: AtomicUsize,
}

impl FakeMessagesListChatModel {
    pub fn new(responses: Vec<Message>) -> Self {
        Self {
            responses,
            index: AtomicUsize::new(0),
        }
    }

    fn next_response(&self) -> Message {
        let idx = self.index.fetch_add(1, Ordering::SeqCst) % self.responses.len();
        self.responses[idx].clone()
    }
}

#[async_trait]
impl BaseChatModel for FakeMessagesListChatModel {
    async fn _generate(
        &self,
        _messages: &[Message],
        _stop: Option<&[String]>,
    ) -> Result<ChatResult> {
        let msg = self.next_response();
        let ai_msg = match msg {
            Message::Ai(ai) => ai,
            other => AIMessage::new(other.content().text()),
        };
        Ok(ChatResult {
            generations: vec![ChatGeneration::new(ai_msg)],
            llm_output: None,
        })
    }

    fn llm_type(&self) -> &str {
        "fake_messages_list_chat_model"
    }
}

// ─── ParrotFakeChatModel ───

/// A fake chat model that echoes the last input message.
pub struct ParrotFakeChatModel;

impl ParrotFakeChatModel {
    pub fn new() -> Self {
        Self
    }
}

impl Default for ParrotFakeChatModel {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl BaseChatModel for ParrotFakeChatModel {
    async fn _generate(
        &self,
        messages: &[Message],
        _stop: Option<&[String]>,
    ) -> Result<ChatResult> {
        let last = messages
            .last()
            .ok_or_else(|| CognisError::Other("No messages provided".into()))?;
        let text = last.content().text();
        Ok(ChatResult {
            generations: vec![ChatGeneration::new(AIMessage::new(&text))],
            llm_output: None,
        })
    }

    fn llm_type(&self) -> &str {
        "parrot_fake_chat_model"
    }
}

// ─── FakeChatModel ───

/// A fake chat model that always returns "fake response".
///
/// Useful as a minimal stub for testing pipelines that need a chat model
/// but do not care about the actual output content.
pub struct FakeChatModel;

impl FakeChatModel {
    pub fn new() -> Self {
        Self
    }
}

impl Default for FakeChatModel {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl BaseChatModel for FakeChatModel {
    async fn _generate(
        &self,
        _messages: &[Message],
        _stop: Option<&[String]>,
    ) -> Result<ChatResult> {
        Ok(ChatResult {
            generations: vec![ChatGeneration::new(AIMessage::new("fake response"))],
            llm_output: None,
        })
    }

    fn llm_type(&self) -> &str {
        "fake_chat_model"
    }
}

// ─── GenericFakeChatModel ───

/// A generic fake chat model that draws responses from an iterator.
///
/// Each call to `_generate` pulls the next item from the internal iterator.
/// Items can be `AIMessage` values or plain strings (converted to `AIMessage`).
/// Streaming splits the response content on whitespace boundaries, preserving
/// whitespace tokens, mirroring the Python `GenericFakeChatModel` behaviour.
///
/// # Example
///
/// ```rust
/// use cognis_core::language_models::fake::GenericFakeChatModel;
/// use cognis_core::messages::AIMessage;
///
/// let model = GenericFakeChatModel::from_messages(vec![
///     AIMessage::new("Hello world"),
///     AIMessage::new("Goodbye"),
/// ]);
/// ```
pub struct GenericFakeChatModel {
    messages: Mutex<Box<dyn Iterator<Item = AIMessage> + Send>>,
}

impl GenericFakeChatModel {
    /// Create from a boxed iterator of `AIMessage`.
    pub fn new(iter: Box<dyn Iterator<Item = AIMessage> + Send>) -> Self {
        Self {
            messages: Mutex::new(iter),
        }
    }

    /// Create from a `Vec<AIMessage>`.
    pub fn from_messages(messages: Vec<AIMessage>) -> Self {
        Self::new(Box::new(messages.into_iter()))
    }

    /// Create from a `Vec<String>`, each converted to an `AIMessage`.
    pub fn from_strings(strings: Vec<String>) -> Self {
        Self::new(Box::new(strings.into_iter().map(AIMessage::new)))
    }

    /// Pull the next `AIMessage` from the iterator.
    fn next_message(&self) -> Result<AIMessage> {
        self.messages
            .lock()
            .map_err(|e| CognisError::Other(format!("Lock poisoned: {e}")))?
            .next()
            .ok_or_else(|| CognisError::Other("Iterator exhausted".into()))
    }
}

#[async_trait]
impl BaseChatModel for GenericFakeChatModel {
    async fn _generate(
        &self,
        _messages: &[Message],
        _stop: Option<&[String]>,
    ) -> Result<ChatResult> {
        let ai_msg = self.next_message()?;
        Ok(ChatResult {
            generations: vec![ChatGeneration::new(ai_msg)],
            llm_output: None,
        })
    }

    fn llm_type(&self) -> &str {
        "generic_fake_chat_model"
    }

    /// Stream the next response, splitting on whitespace boundaries.
    ///
    /// Uses a regex-style split that preserves whitespace tokens as separate
    /// chunks (e.g. `"hello world"` becomes `["hello", " ", "world"]`).
    async fn _stream(&self, messages: &[Message], stop: Option<&[String]>) -> Result<ChatStream> {
        let result = self._generate(messages, stop).await?;
        let message = result
            .generations
            .into_iter()
            .next()
            .ok_or_else(|| CognisError::Other("No generations".into()))?
            .message;
        let content = message.content().text();

        let chunks: Vec<Result<ChatGenerationChunk>> = if content.is_empty() {
            Vec::new()
        } else {
            split_preserving_whitespace(&content)
                .into_iter()
                .map(|token| Ok(ChatGenerationChunk::new(AIMessageChunk::new(token))))
                .collect()
        };

        Ok(Box::pin(stream::iter(chunks)))
    }
}

/// Split a string on whitespace boundaries, preserving the whitespace as
/// separate tokens. Equivalent to Python `re.split(r"(\s)", text)`.
///
/// Example: `"hello world"` -> `["hello", " ", "world"]`
fn split_preserving_whitespace(s: &str) -> Vec<String> {
    let mut parts = Vec::new();
    let mut current = String::new();
    let mut in_whitespace = false;

    for ch in s.chars() {
        let is_ws = ch.is_whitespace();
        if current.is_empty() {
            in_whitespace = is_ws;
            current.push(ch);
        } else if is_ws == in_whitespace {
            current.push(ch);
        } else {
            parts.push(std::mem::take(&mut current));
            in_whitespace = is_ws;
            current.push(ch);
        }
    }
    if !current.is_empty() {
        parts.push(current);
    }
    parts
}

// ─── Tests ───

#[cfg(test)]
mod tests {
    use super::*;
    use crate::messages::{HumanMessage, Message, SystemMessage};
    use futures::StreamExt;

    fn human(text: &str) -> Message {
        Message::Human(HumanMessage::new(text))
    }

    // ── FakeListLLM ──

    #[tokio::test]
    async fn test_fake_list_llm_cycles() {
        let llm = FakeListLLM::new(vec!["a".into(), "b".into(), "c".into()]);
        let r1 = llm._generate(&["p".into()], None).await.unwrap();
        assert_eq!(r1.generations[0][0].text, "a");
        let r2 = llm._generate(&["p".into()], None).await.unwrap();
        assert_eq!(r2.generations[0][0].text, "b");
        let r3 = llm._generate(&["p".into()], None).await.unwrap();
        assert_eq!(r3.generations[0][0].text, "c");
        // wraps around
        let r4 = llm._generate(&["p".into()], None).await.unwrap();
        assert_eq!(r4.generations[0][0].text, "a");
    }

    // ── FakeStreamingListLLM ──

    #[tokio::test]
    async fn test_fake_streaming_llm_generate() {
        let llm = FakeStreamingListLLM::new(vec!["hello".into()]);
        let r = llm._generate(&["prompt".into()], None).await.unwrap();
        assert_eq!(r.generations[0][0].text, "hello");
    }

    #[tokio::test]
    async fn test_fake_streaming_llm_stream() {
        let llm = FakeStreamingListLLM::new(vec!["abc".into()]);
        let stream = llm._stream("prompt", None).await.unwrap();
        let chunks: Vec<_> = stream.collect::<Vec<_>>().await;
        assert_eq!(chunks.len(), 3);
        assert_eq!(
            chunks[0].as_ref().unwrap(),
            &serde_json::Value::String("a".into())
        );
        assert_eq!(
            chunks[1].as_ref().unwrap(),
            &serde_json::Value::String("b".into())
        );
        assert_eq!(
            chunks[2].as_ref().unwrap(),
            &serde_json::Value::String("c".into())
        );
    }

    #[tokio::test]
    async fn test_fake_streaming_llm_error_on_chunk() {
        let llm = FakeStreamingListLLM::new(vec!["abc".into()]).with_error_on_chunk(1);
        let stream = llm._stream("prompt", None).await.unwrap();
        let chunks: Vec<_> = stream.collect::<Vec<_>>().await;
        assert!(chunks[0].is_ok());
        assert!(chunks[1].is_err());
        assert!(chunks[2].is_ok());
    }

    // ── FakeListChatModel ──

    #[tokio::test]
    async fn test_fake_list_chat_model_cycles() {
        let model = FakeListChatModel::new(vec!["x".into(), "y".into()]);
        let msgs = vec![human("hi")];
        let r1 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r1.generations[0].message.content().text(), "x");
        let r2 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r2.generations[0].message.content().text(), "y");
        // wraps
        let r3 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r3.generations[0].message.content().text(), "x");
    }

    #[tokio::test]
    async fn test_fake_list_chat_model_stream() {
        let model = FakeListChatModel::new(vec!["abc".into()]);
        let msgs = vec![human("hi")];
        let stream = model._stream(&msgs, None).await.unwrap();
        let chunks: Vec<_> = stream.collect().await;
        assert_eq!(chunks.len(), 3);
        let text: String = chunks
            .into_iter()
            .map(|r| {
                let chunk = r.unwrap();
                chunk.message.base.content.text()
            })
            .collect();
        assert_eq!(text, "abc");
    }

    #[tokio::test]
    async fn test_fake_list_chat_model_llm_type() {
        let model = FakeListChatModel::new(vec!["a".into()]);
        assert_eq!(model.llm_type(), "fake_list_chat_model");
    }

    // ── FakeMessagesListChatModel ──

    #[tokio::test]
    async fn test_fake_messages_list_cycles() {
        let responses = vec![
            Message::Ai(AIMessage::new("first")),
            Message::Ai(AIMessage::new("second")),
        ];
        let model = FakeMessagesListChatModel::new(responses);
        let msgs = vec![human("hello")];

        let r1 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r1.generations[0].message.content().text(), "first");
        let r2 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r2.generations[0].message.content().text(), "second");
        // wraps
        let r3 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r3.generations[0].message.content().text(), "first");
    }

    #[tokio::test]
    async fn test_fake_messages_list_converts_non_ai() {
        let responses = vec![Message::Human(HumanMessage::new("echoed"))];
        let model = FakeMessagesListChatModel::new(responses);
        let r = model._generate(&[human("hi")], None).await.unwrap();
        // Should convert the Human message text into an AIMessage
        assert_eq!(r.generations[0].message.content().text(), "echoed");
    }

    // ── ParrotFakeChatModel ──

    #[tokio::test]
    async fn test_parrot_echoes_last() {
        let model = ParrotFakeChatModel::new();
        let msgs = vec![
            Message::System(SystemMessage::new("system prompt")),
            human("repeat me"),
        ];
        let r = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r.generations[0].message.content().text(), "repeat me");
    }

    #[tokio::test]
    async fn test_parrot_empty_messages_error() {
        let model = ParrotFakeChatModel::new();
        let result = model._generate(&[], None).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_parrot_default() {
        let model = ParrotFakeChatModel::default();
        let r = model._generate(&[human("test")], None).await.unwrap();
        assert_eq!(r.generations[0].message.content().text(), "test");
    }

    // ── FakeChatModel ──

    #[tokio::test]
    async fn test_fake_chat_model_always_returns_fake_response() {
        let model = FakeChatModel::new();
        let msgs = vec![human("anything")];
        let r1 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r1.generations[0].message.content().text(), "fake response");
        // Same output regardless of input
        let r2 = model
            ._generate(&[human("something else")], None)
            .await
            .unwrap();
        assert_eq!(r2.generations[0].message.content().text(), "fake response");
    }

    #[tokio::test]
    async fn test_fake_chat_model_llm_type() {
        let model = FakeChatModel::new();
        assert_eq!(model.llm_type(), "fake_chat_model");
    }

    #[tokio::test]
    async fn test_fake_chat_model_default() {
        let model = FakeChatModel::default();
        let r = model._generate(&[human("hi")], None).await.unwrap();
        assert_eq!(r.generations[0].message.content().text(), "fake response");
    }

    // ── GenericFakeChatModel ──

    #[tokio::test]
    async fn test_generic_fake_generate() {
        let model = GenericFakeChatModel::from_messages(vec![
            AIMessage::new("hello"),
            AIMessage::new("world"),
        ]);
        let msgs = vec![human("test")];
        let r1 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r1.generations[0].message.content().text(), "hello");
        let r2 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r2.generations[0].message.content().text(), "world");
    }

    #[tokio::test]
    async fn test_generic_fake_from_strings() {
        let model = GenericFakeChatModel::from_strings(vec!["alpha".into(), "beta".into()]);
        let msgs = vec![human("go")];
        let r1 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r1.generations[0].message.content().text(), "alpha");
        let r2 = model._generate(&msgs, None).await.unwrap();
        assert_eq!(r2.generations[0].message.content().text(), "beta");
    }

    #[tokio::test]
    async fn test_generic_fake_exhausted_iterator_errors() {
        let model = GenericFakeChatModel::from_messages(vec![AIMessage::new("only")]);
        let msgs = vec![human("hi")];
        let r1 = model._generate(&msgs, None).await;
        assert!(r1.is_ok());
        let r2 = model._generate(&msgs, None).await;
        assert!(r2.is_err());
    }

    #[tokio::test]
    async fn test_generic_fake_stream_splits_on_whitespace() {
        let model = GenericFakeChatModel::from_messages(vec![AIMessage::new("hello world foo")]);
        let msgs = vec![human("go")];
        let stream = model._stream(&msgs, None).await.unwrap();
        let chunks: Vec<_> = stream.collect().await;
        let tokens: Vec<String> = chunks
            .into_iter()
            .map(|r| r.unwrap().message.base.content.text())
            .collect();
        // "hello world foo" splits into ["hello", " ", "world", " ", "foo"]
        assert_eq!(tokens, vec!["hello", " ", "world", " ", "foo"]);
    }

    #[tokio::test]
    async fn test_generic_fake_stream_empty_content() {
        let model = GenericFakeChatModel::from_messages(vec![AIMessage::new("")]);
        let msgs = vec![human("go")];
        let stream = model._stream(&msgs, None).await.unwrap();
        let chunks: Vec<_> = stream.collect().await;
        assert!(chunks.is_empty());
    }

    #[tokio::test]
    async fn test_generic_fake_stream_single_word() {
        let model = GenericFakeChatModel::from_messages(vec![AIMessage::new("hello")]);
        let msgs = vec![human("go")];
        let stream = model._stream(&msgs, None).await.unwrap();
        let chunks: Vec<_> = stream.collect().await;
        assert_eq!(chunks.len(), 1);
        assert_eq!(
            chunks[0].as_ref().unwrap().message.base.content.text(),
            "hello"
        );
    }

    #[tokio::test]
    async fn test_generic_fake_llm_type() {
        let model = GenericFakeChatModel::from_messages(vec![AIMessage::new("x")]);
        assert_eq!(model.llm_type(), "generic_fake_chat_model");
    }

    // ── split_preserving_whitespace ──

    #[test]
    fn test_split_preserving_whitespace_basic() {
        let result = split_preserving_whitespace("hello world");
        assert_eq!(result, vec!["hello", " ", "world"]);
    }

    #[test]
    fn test_split_preserving_whitespace_multiple_spaces() {
        let result = split_preserving_whitespace("a  b");
        assert_eq!(result, vec!["a", "  ", "b"]);
    }

    #[test]
    fn test_split_preserving_whitespace_leading_trailing() {
        let result = split_preserving_whitespace(" hi ");
        assert_eq!(result, vec![" ", "hi", " "]);
    }

    #[test]
    fn test_split_preserving_whitespace_empty() {
        let result = split_preserving_whitespace("");
        assert!(result.is_empty());
    }

    #[test]
    fn test_split_preserving_whitespace_only_spaces() {
        let result = split_preserving_whitespace("   ");
        assert_eq!(result, vec!["   "]);
    }

    #[test]
    fn test_split_preserving_whitespace_tabs_and_newlines() {
        let result = split_preserving_whitespace("a\t\nb");
        assert_eq!(result, vec!["a", "\t\n", "b"]);
    }
}