Skip to main content

kaeso_kpp/
stream.rs

1use serde::{Deserialize, Serialize};
2
3use crate::audio::{SpeechEvent, TranscriptEvent};
4use crate::block::{Citation, Opaque, RawItem};
5use crate::error::KppError;
6use crate::extras::Extras;
7use crate::image::ImageEvent;
8use crate::response::{StopReason, Usage};
9
10#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12#[non_exhaustive]
13pub enum StreamEvent {
14    ResponseStart(ResponseStart),
15    BlockStart(BlockStart),
16    BlockDelta(BlockDelta),
17    BlockStop(BlockStop),
18    ResponseDelta(ResponseDelta),
19    ResponseStop(ResponseStop),
20    Error(KppError),
21    Extra(RawItem),
22    /// A partial or finished image of a streamed image reply.
23    Image(ImageEvent),
24    /// A piece of streamed audio, or its end.
25    Speech(SpeechEvent),
26    /// A piece of a streamed transcript, a finished segment, or the end.
27    Transcript(TranscriptEvent),
28}
29
30#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
31#[non_exhaustive]
32pub struct ResponseStart {
33    pub id: String,
34    pub model: String,
35    #[serde(default, skip_serializing_if = "Option::is_none")]
36    pub usage: Option<Usage>,
37    #[serde(default, skip_serializing_if = "Extras::is_empty")]
38    pub extras: Extras,
39}
40
41impl ResponseStart {
42    pub fn new(id: impl Into<String>, model: impl Into<String>) -> Self {
43        ResponseStart {
44            id: id.into(),
45            model: model.into(),
46            ..ResponseStart::default()
47        }
48    }
49}
50
51#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
52#[non_exhaustive]
53pub struct BlockStart {
54    pub index: u32,
55    pub block: BlockHeader,
56    #[serde(default, skip_serializing_if = "Extras::is_empty")]
57    pub extras: Extras,
58}
59
60impl BlockStart {
61    pub fn new(index: u32, block: BlockHeader) -> Self {
62        BlockStart {
63            index,
64            block,
65            extras: Extras::default(),
66        }
67    }
68}
69
70#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
71#[non_exhaustive]
72pub struct BlockDelta {
73    pub index: u32,
74    pub delta: Delta,
75    #[serde(default, skip_serializing_if = "Extras::is_empty")]
76    pub extras: Extras,
77}
78
79impl BlockDelta {
80    pub fn new(index: u32, delta: Delta) -> Self {
81        BlockDelta {
82            index,
83            delta,
84            extras: Extras::default(),
85        }
86    }
87}
88
89#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
90#[non_exhaustive]
91pub struct BlockStop {
92    pub index: u32,
93    #[serde(default, skip_serializing_if = "Extras::is_empty")]
94    pub extras: Extras,
95}
96
97impl BlockStop {
98    pub fn new(index: u32) -> Self {
99        BlockStop {
100            index,
101            extras: Extras::default(),
102        }
103    }
104}
105
106#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
107#[non_exhaustive]
108pub struct ResponseDelta {
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub stop: Option<StopReason>,
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub usage: Option<Usage>,
113    #[serde(default, skip_serializing_if = "Extras::is_empty")]
114    pub extras: Extras,
115}
116
117impl ResponseDelta {
118    pub fn new(stop: Option<StopReason>, usage: Option<Usage>) -> Self {
119        ResponseDelta {
120            stop,
121            usage,
122            extras: Extras::default(),
123        }
124    }
125}
126
127#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
128#[non_exhaustive]
129pub struct ResponseStop {
130    #[serde(default, skip_serializing_if = "Extras::is_empty")]
131    pub extras: Extras,
132}
133
134impl ResponseStop {
135    pub fn new() -> Self {
136        ResponseStop::default()
137    }
138}
139
140#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
141#[serde(rename_all = "snake_case")]
142#[non_exhaustive]
143pub enum BlockHeader {
144    Text,
145    ToolCall(ToolCallHeader),
146    Reasoning(ReasoningHeader),
147    Refusal,
148    Audio(AudioHeader),
149    Unknown(RawItem),
150}
151
152#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
153#[non_exhaustive]
154pub struct AudioHeader {
155    pub media_type: String,
156}
157
158impl AudioHeader {
159    pub fn new(media_type: impl Into<String>) -> Self {
160        AudioHeader {
161            media_type: media_type.into(),
162        }
163    }
164}
165
166#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
167#[non_exhaustive]
168pub struct ToolCallHeader {
169    pub id: String,
170    pub name: String,
171}
172
173impl ToolCallHeader {
174    pub fn new(id: impl Into<String>, name: impl Into<String>) -> Self {
175        ToolCallHeader {
176            id: id.into(),
177            name: name.into(),
178        }
179    }
180}
181
182#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
183#[non_exhaustive]
184pub struct ReasoningHeader {
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub origin: Option<crate::Origin>,
187    #[serde(default, skip_serializing_if = "Vec::is_empty")]
188    pub opaque: Vec<Opaque>,
189}
190
191impl ReasoningHeader {
192    pub fn new(origin: impl Into<crate::Origin>) -> Self {
193        ReasoningHeader {
194            origin: Some(origin.into()),
195            opaque: Vec::new(),
196        }
197    }
198}
199
200#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
201#[serde(rename_all = "snake_case")]
202#[non_exhaustive]
203pub enum Delta {
204    Text(String),
205    ToolArguments(String),
206    ReasoningText(String),
207    ReasoningSummary(SummaryDelta),
208    Opaque(Opaque),
209    Citation(Citation),
210    Refusal(String),
211    Audio(AudioDelta),
212    Unknown(RawItem),
213}
214
215#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
216#[non_exhaustive]
217pub struct AudioDelta {
218    #[serde(default, skip_serializing_if = "Option::is_none")]
219    pub data: Option<String>,
220    #[serde(default, skip_serializing_if = "Option::is_none")]
221    pub transcript: Option<String>,
222}
223
224impl AudioDelta {
225    pub fn new(data: Option<String>, transcript: Option<String>) -> Self {
226        AudioDelta { data, transcript }
227    }
228}
229
230#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
231#[non_exhaustive]
232pub struct SummaryDelta {
233    pub summary_index: u32,
234    pub text: String,
235}
236
237impl SummaryDelta {
238    pub fn new(summary_index: u32, text: impl Into<String>) -> Self {
239        SummaryDelta {
240            summary_index,
241            text: text.into(),
242        }
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249    use crate::DialectId;
250
251    #[test]
252    fn stable_json_form_round_trips() {
253        let events = vec![
254            StreamEvent::ResponseStart(ResponseStart::new("msg_1", "m")),
255            StreamEvent::BlockStart(BlockStart::new(
256                0,
257                BlockHeader::ToolCall(ToolCallHeader::new("c", "f")),
258            )),
259            StreamEvent::BlockDelta(BlockDelta::new(0, Delta::ToolArguments("{\"a\"".into()))),
260            StreamEvent::BlockDelta(BlockDelta::new(
261                1,
262                Delta::ReasoningSummary(SummaryDelta::new(0, "x")),
263            )),
264            StreamEvent::BlockStart(BlockStart::new(
265                2,
266                BlockHeader::Reasoning(ReasoningHeader::new(DialectId::AnthropicMessages)),
267            )),
268            StreamEvent::BlockStart(BlockStart::new(
269                3,
270                BlockHeader::Audio(AudioHeader::new("audio/wav")),
271            )),
272            StreamEvent::BlockDelta(BlockDelta::new(
273                3,
274                Delta::Audio(AudioDelta::new(Some("UklGRg==".into()), Some("Hi".into()))),
275            )),
276            StreamEvent::BlockStop(BlockStop::new(0)),
277            StreamEvent::ResponseDelta(ResponseDelta::new(Some(StopReason::ToolUse), None)),
278            StreamEvent::ResponseStop(ResponseStop::new()),
279        ];
280        let json = serde_json::to_string(&events).unwrap();
281        let back: Vec<StreamEvent> = serde_json::from_str(&json).unwrap();
282        assert_eq!(back, events);
283    }
284}