dynamo-llm 1.0.2

Dynamo LLM Library
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
// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! A module for parsing Server-Sent Events (SSE) streams according to the SSE specification.
//!
//! This module provides `SseLineCodec<T>`, a codec for decoding SSE streams into typed messages.
//! It handles parsing of `id`, `event`, `data`, and comments, and attempts to deserialize
//! the `data` field into the specified type `T`.
//!

// TODO: Determine if we should use an External EventSource crate. There appear to be several
// potential candidates.

use std::{io::Cursor, pin::Pin};

use bytes::BytesMut;
use futures::Stream;
use serde::Deserialize;
use tokio_util::codec::{Decoder, FramedRead, LinesCodec};

use super::Annotated;

/// An error that occurs when decoding an SSE stream.
#[derive(Debug, thiserror::Error)]
pub enum SseCodecError {
    #[error("SseLineCodec decode error: {0}")]
    DecodeError(String),

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

/// A codec for decoding SSE streams into `Message<T>` instances.
///
/// This codec parses SSE streams according to the SSE specification and attempts to deserialize
/// the `data` field into the specified type `T`.
///
/// # Type Parameters
///
/// * `T` - The type to deserialize the `data` field into.
pub struct SseLineCodec {
    lines_codec: LinesCodec,
    data_buffer: String,
    event_type_buffer: String,
    last_event_id_buffer: String,
    comments_buffer: Vec<String>,
}

/// Represents a parsed SSE message.
///
/// The `Message` struct contains optional fields for `id`, `event`, `data`, and a vector of `comments`.
///
/// # Type Parameters
///
/// * `T` - The type to deserialize the `data` field into.
#[derive(Debug)]
pub struct Message {
    pub id: Option<String>,
    pub event: Option<String>,
    pub data: Option<String>,
    pub comments: Option<Vec<String>>,
}

impl Message {
    /// Deserializes the `data` field into the specified type `T`.
    ///
    /// # Errors
    ///
    /// Returns an error if the `data` field is empty or if deserialization fails.
    pub fn decode_data<T>(&self) -> Result<T, SseCodecError>
    where
        T: for<'de> Deserialize<'de>,
    {
        serde_json::from_str(self.data.as_ref().ok_or(SseCodecError::DecodeError(
            "no data: message to decode".to_string(),
        ))?)
        .map_err(|e| SseCodecError::DecodeError(format!("failed to deserialized data: {}", e)))
    }
}

impl<T> TryFrom<Message> for Annotated<T>
where
    T: for<'de> Deserialize<'de>,
{
    type Error = String;

    fn try_from(value: Message) -> Result<Annotated<T>, Self::Error> {
        // determine if the message had an error
        if let Some(event) = value.event.as_ref()
            && event == "error"
        {
            let message = match &value.comments {
                Some(comments) => comments.join("\n"),
                None => "`event: error` detected, but no error message found".to_string(),
            };
            return Err(message);
        }

        // try to deserialize the data to T

        let data: Option<T> = match &value.data {
            Some(_) => value.decode_data().map_err(|e| e.to_string())?,
            None => None,
        };

        Ok(Annotated {
            data,
            id: value.id,
            event: value.event,
            comment: value.comments,
            error: None,
        })
    }
}

impl SseLineCodec {
    /// Creates a new `SseLineCodec<T>`.
    pub fn new() -> Self {
        Self::default()
    }
}

impl Default for SseLineCodec {
    fn default() -> Self {
        Self {
            lines_codec: LinesCodec::new(),
            data_buffer: String::new(),
            event_type_buffer: String::new(),
            last_event_id_buffer: String::new(),
            comments_buffer: Vec::new(),
        }
    }
}

impl Decoder for SseLineCodec {
    type Item = Message;
    type Error = SseCodecError;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        loop {
            match self
                .lines_codec
                .decode(src)
                .map_err(|e| SseCodecError::DecodeError(e.to_string()))?
            {
                Some(line) => {
                    let line = line.trim_end_matches(&['\r', '\n'][..]);
                    if line.is_empty() {
                        // End of event; dispatch
                        if !self.data_buffer.is_empty()
                            || !self.event_type_buffer.is_empty()
                            || !self.last_event_id_buffer.is_empty()
                            || !self.comments_buffer.is_empty()
                        {
                            // Remove the last '\n' if present in data_buffer
                            if self.data_buffer.ends_with('\n') {
                                self.data_buffer.pop();
                            }

                            let data = if !self.data_buffer.is_empty() {
                                Some(std::mem::take(&mut self.data_buffer))
                            } else {
                                None
                            };

                            let message = Message {
                                id: if self.last_event_id_buffer.is_empty() {
                                    None
                                } else {
                                    Some(std::mem::take(&mut self.last_event_id_buffer))
                                },
                                event: if self.event_type_buffer.is_empty() {
                                    None
                                } else {
                                    Some(std::mem::take(&mut self.event_type_buffer))
                                },
                                data,
                                comments: if self.comments_buffer.is_empty() {
                                    None
                                } else {
                                    Some(std::mem::take(&mut self.comments_buffer))
                                },
                            };
                            // No need to clear the buffers; they've been replaced with empty values
                            return Ok(Some(message));
                        } else {
                            // No data to dispatch; continue
                            continue;
                        }
                    } else if let Some(comment) = line.strip_prefix(':') {
                        self.comments_buffer.push(comment.trim().into());
                    } else {
                        let (field_name, field_value) = if let Some(idx) = line.find(':') {
                            let (name, value) = line.split_at(idx);
                            let value = value[1..].trim_start_matches(' ');
                            (name, value)
                        } else {
                            (line, "")
                        };

                        match field_name {
                            "event" => {
                                self.event_type_buffer = field_value.to_string();
                            }
                            "data" => {
                                if field_value != "[DONE]" {
                                    if !self.data_buffer.is_empty() {
                                        self.data_buffer.push('\n');
                                    }
                                    self.data_buffer.push_str(field_value);
                                }
                            }
                            "id" => {
                                if !field_value.contains('\0') {
                                    self.last_event_id_buffer = field_value.to_string();
                                }
                            }
                            "retry" => {
                                // For simplicity, we'll ignore retry in this implementation
                            }
                            _ => {
                                // Ignore unknown fields
                            }
                        }
                    }
                }
                None => {
                    // No more data available at the moment
                    return Ok(None);
                }
            }
        }
    }

    fn decode_eof(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        // Attempt to process any remaining data
        let result = self.decode(src)?;
        if result.is_some() {
            return Ok(result);
        }
        // If there's no data left to process, return None
        if self.data_buffer.is_empty()
            && self.event_type_buffer.is_empty()
            && self.last_event_id_buffer.is_empty()
            && self.comments_buffer.is_empty()
        {
            Ok(None)
        } else {
            // Dispatch any remaining data as an event
            if self.data_buffer.ends_with('\n') {
                self.data_buffer.pop();
            }

            let data = if !self.data_buffer.is_empty() {
                Some(std::mem::take(&mut self.data_buffer))
            } else {
                None
            };

            let message = Message {
                id: if self.last_event_id_buffer.is_empty() {
                    None
                } else {
                    Some(std::mem::take(&mut self.last_event_id_buffer))
                },
                event: if self.event_type_buffer.is_empty() {
                    None
                } else {
                    Some(std::mem::take(&mut self.event_type_buffer))
                },
                data,
                comments: if self.comments_buffer.is_empty() {
                    None
                } else {
                    Some(std::mem::take(&mut self.comments_buffer))
                },
            };
            // No need to clear the buffers; they've been replaced with empty values
            Ok(Some(message))
        }
    }
}

/// Creates a stream of `Message` instances from a text stream of SSE events.
pub fn create_message_stream(
    text: &str,
) -> Pin<Box<dyn Stream<Item = Result<Message, SseCodecError>> + Send + Sync>> {
    let cursor = Cursor::new(text.to_string());
    let framed = FramedRead::new(cursor, SseLineCodec::new());
    Box::pin(framed)
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use futures::stream::StreamExt;
    use tokio_util::codec::FramedRead;

    use super::*;

    #[derive(Deserialize, Debug, PartialEq)]
    struct TestData {
        message: String,
    }

    #[tokio::test]
    async fn test_message_with_all_fields() {
        let sample_data = r#"id: 123
event: test
data: {"message": "Hello World"}
: This is a comment

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(Ok(message)) = framed.next().await {
            assert_eq!(message.id, Some("123".to_string()));
            assert_eq!(message.event, Some("test".to_string()));
            assert_eq!(
                message.comments,
                Some(vec!["This is a comment".to_string()])
            );
            let data: TestData = message.decode_data().unwrap();
            assert_eq!(data.message, "Hello World".to_string());
        } else {
            panic!("Expected a message");
        }
    }

    #[tokio::test]
    async fn test_message_with_only_data() {
        let sample_data = r#"data: {"message": "Just some data"}

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(Ok(message)) = framed.next().await {
            assert!(message.id.is_none());
            assert!(message.event.is_none());
            assert!(message.comments.is_none());
            let data: TestData = message.decode_data().unwrap();
            assert_eq!(data.message, "Just some data".to_string());
        } else {
            panic!("Expected a message");
        }
    }

    #[tokio::test]
    async fn test_message_with_only_comment() {
        let sample_data = r#": This is a comment

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(Ok(message)) = framed.next().await {
            assert!(message.id.is_none());
            assert!(message.event.is_none());
            assert!(message.data.is_none());
            assert_eq!(
                message.comments,
                Some(vec!["This is a comment".to_string()])
            );
        } else {
            panic!("Expected a message");
        }
    }

    #[tokio::test]
    async fn test_message_with_multiple_comments() {
        let sample_data = r#": First comment
: Second comment

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(Ok(message)) = framed.next().await {
            assert!(message.id.is_none());
            assert!(message.event.is_none());
            assert!(message.data.is_none());
            assert_eq!(
                message.comments,
                Some(vec![
                    "First comment".to_string(),
                    "Second comment".to_string()
                ])
            );
        } else {
            panic!("Expected a message");
        }
    }

    #[tokio::test]
    async fn test_message_with_partial_fields() {
        let sample_data = r#"id: 456
data: {"message": "Partial data"}

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(Ok(message)) = framed.next().await {
            assert_eq!(message.id, Some("456".to_string()));
            assert!(message.event.is_none());
            assert!(message.comments.is_none());
            let data: TestData = message.decode_data().unwrap();
            assert_eq!(data.message, "Partial data".to_string());
        } else {
            panic!("Expected a message");
        }
    }

    #[tokio::test]
    async fn test_message_with_invalid_json_data() {
        let sample_data = r#"data: {"message": "Invalid JSON

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(result) = framed.next().await {
            match result {
                Ok(message) => {
                    // got a message, but it has invalid json
                    let data = message.decode_data::<TestData>();
                    assert!(data.is_err(), "Expected an error; got {:?}", data);
                }
                _ => panic!("Expected a message"),
            }
        } else {
            panic!("Expected an error");
        }
    }

    #[tokio::test]
    async fn test_message_with_missing_data_field() {
        let sample_data = r#"id: 789
event: test_event

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(Ok(message)) = framed.next().await {
            assert_eq!(message.id, Some("789".to_string()));
            assert_eq!(message.event, Some("test_event".to_string()));
            assert!(message.data.is_none());
            assert!(message.comments.is_none());
        } else {
            panic!("Expected a message");
        }
    }

    #[tokio::test]
    async fn test_message_with_empty_data_field() {
        let sample_data = r#"data:

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(result) = framed.next().await {
            match result {
                Ok(_) => {
                    panic!("Expected no message");
                }
                Err(e) => panic!("Unexpected error: {}", e),
            }
        } else {
            // no message is emitted
        }
    }

    #[tokio::test]
    async fn test_message_with_multiple_data_lines() {
        let sample_data = r#"data: {"message": "Line1"}
data: {"message": "Line2"}

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(result) = framed.next().await {
            match result {
                Ok(message) => {
                    // got a message with data, but the data is junk
                    let data = message.decode_data::<TestData>();
                    assert!(data.is_err(), "Expected an error; got {:?}", data);
                }
                _ => panic!("Expected a message"),
            }
        } else {
            panic!("Expected an error");
        }
    }

    #[tokio::test]
    async fn test_message_with_unrecognized_field() {
        let sample_data = r#"unknown: value
data: {"message": "Hello"}

"#;
        let cursor = Cursor::new(sample_data);
        let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        if let Some(Ok(message)) = framed.next().await {
            // Unrecognized fields are ignored
            assert!(message.id.is_none());
            assert!(message.event.is_none());
            assert!(message.comments.is_none());
            let data: TestData = message.decode_data().unwrap();
            assert_eq!(data.message, "Hello".to_string());
        } else {
            panic!("Expected a message");
        }
    }

    // data recorded on 2024-09-30 from
    // + curl https://integrate.api.nvidia.com/v1/chat/completions -H 'Content-Type: application/json' \
    //     -H 'Authorization: Bearer nvapi-<redacted>' -d '{
    //     "model": "mistralai/mixtral-8x22b-instruct-v0.1",
    //     "messages": [{"role":"user","content":"Write a limerick about the wonders of GPU computing."}],
    //     "temperature": 0.5,
    //     "top_p": 1,
    //     "max_tokens": 64,
    //     "stream": true
    //   }'
    const SAMPLE_CHAT_DATA: &str = r#"
data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":"assistant","content":null},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"A"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" GPU"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" so"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" swift"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" and"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" so"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" clever"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":","},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"\n"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"In"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" comput"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"ations"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" it"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"'"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"s"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" quite"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" the"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" ende"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"avor"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"."},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"\n"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"With"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" its"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" thousands"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" of"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" co"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"res"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":","},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"\n"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"On"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" complex"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" tasks"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" it"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" ro"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"ars"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":","},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"\n"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"S"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"olving"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" problems"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" like"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" never"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":","},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":" forever"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":"!"},"logprobs":null,"finish_reason":null}]}

data: {"id":"chat-e135180178ae4fe6a7a301aa65aaeea5","object":"chat.completion.chunk","created":1727750141,"model":"mistralai/mixtral-8x22b-instruct-v0.1","choices":[{"index":0,"delta":{"role":null,"content":""},"logprobs":null,"finish_reason":"stop","stop_reason":null}]}

data: [DONE]

"#;

    #[tokio::test]
    async fn test_openai_chat_stream() {
        use crate::protocols::openai::chat_completions::NvCreateChatCompletionStreamResponse;

        // let cursor = Cursor::new(SAMPLE_CHAT_DATA);
        // let mut framed = FramedRead::new(cursor, SseLineCodec::new());

        let mut stream = create_message_stream(SAMPLE_CHAT_DATA);

        let mut counter = 0;

        loop {
            match stream.next().await {
                Some(Ok(message)) => {
                    let delta: NvCreateChatCompletionStreamResponse =
                        serde_json::from_str(&message.data.unwrap()).unwrap();
                    counter += 1;
                    println!("counter: {}", counter);
                    println!("delta: {:?}", delta);
                }
                Some(Err(e)) => {
                    panic!("Error: {:?}", e);
                }
                None => {
                    break;
                }
            }
        }

        assert_eq!(counter, 47);
    }

    #[test]
    fn test_successful_conversion() {
        let message = Message {
            id: Some("123".to_string()),
            event: Some("update".to_string()),
            data: Some(r#"{"message": "Hello World"}"#.to_string()),
            comments: Some(vec!["Some comment".to_string()]),
        };

        let annotated: Annotated<TestData> = message.try_into().unwrap();

        assert_eq!(annotated.id, Some("123".to_string()));
        assert_eq!(annotated.event, Some("update".to_string()));
        assert_eq!(annotated.comment, Some(vec!["Some comment".to_string()]));
        assert_eq!(
            annotated.data,
            Some(TestData {
                message: "Hello World".to_string()
            })
        );
    }

    #[test]
    fn test_error_event_with_comments() {
        let message = Message {
            id: Some("456".to_string()),
            event: Some("error".to_string()),
            data: Some("Error data".to_string()),
            comments: Some(vec!["An error occurred".to_string()]),
        };

        let result: Result<Annotated<TestData>, _> = message.try_into();

        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "An error occurred".to_string());
    }

    #[test]
    fn test_error_event_without_comments() {
        let message = Message {
            id: Some("789".to_string()),
            event: Some("error".to_string()),
            data: Some("Error data".to_string()),
            comments: None,
        };

        let result: Result<Annotated<TestData>, _> = message.try_into();

        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_json_data() {
        let message = Message {
            id: None,
            event: Some("update".to_string()),
            data: Some("Invalid JSON".to_string()),
            comments: None,
        };

        let result: Result<Annotated<TestData>, _> = message.try_into();

        assert!(result.is_err());
    }

    #[test]
    fn test_missing_data_field() {
        let message = Message {
            id: None,
            event: Some("update".to_string()),
            data: None,
            comments: None,
        };

        let result: Result<Annotated<TestData>, _> = message.try_into();

        assert!(result.is_ok());
        let annotated = result.unwrap();
        assert!(annotated.data.is_none());
        assert_eq!(annotated.event, Some("update".to_string()));
    }
}