rig-core 0.47.0

An opinionated library for building LLM powered applications.
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
//! The events of a completion stream. A completion decoder never builds one:
//! it writes through the reply's part handles
//! ([`Out`](crate::wire::Out)), and the writer emits each part's start, its
//! fragments and its end, in that order. A [`Part`] is a part's position in
//! the response's `choice`. A stream transform that splits or adds parts
//! (reasoning a model wrote inside its text, tool calls written as text)
//! numbers its own with [`Part::new`]. An item also reads back from its
//! serialized form on its own, unchecked, so a client can decode a relayed
//! stream as it arrives; [`StreamRecord::parse`] is the one place a sequence
//! is checked.
//!
//! ```
//! use rig_core::streaming::{PartKind, StreamEvent, StreamRecord};
//!
//! let transcript = StreamRecord::parse(serde_json::json!([
//!     {"item": "event", "value": {"event": "start", "part": 0, "kind": "text"}},
//!     {"item": "event", "value": {"event": "text", "part": 0, "text": "Hello"}},
//!     {"item": "event", "value": {"event": "end", "part": 0,
//!         "content": {"type": "text", "text": "Hello"}}},
//! ]))?;
//! assert!(matches!(
//!     transcript.events().next(),
//!     Some(StreamEvent::Start { kind: PartKind::Text, .. })
//! ));
//! # Ok::<(), rig_core::streaming::SequenceError>(())
//! ```

use std::collections::btree_map::Entry;

use serde::{Deserialize, Serialize};

use crate::message::{AssistantContent, ToolName};

use super::UnknownPayload;

/// A part's position in the response's `choice`. A transform that rewrites
/// a stream numbers the parts it emits with [`Self::new`], and keeps the
/// order [`StreamRecord::parse`] checks: each part starts, grows and ends, and
/// parts are numbered in the order they start.
///
/// ```
/// use rig_core::streaming::Part;
///
/// assert_eq!(Part::new(2).index(), 2);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Part(u32);

impl Part {
    /// The part at position `index` of the response's `choice`.
    pub const fn new(index: u32) -> Self {
        Self(index)
    }

    /// The part's position in the response's `choice`.
    pub const fn index(self) -> usize {
        self.0 as usize
    }
}

/// What kind of part a [`StreamEvent::Start`] opened.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PartKind {
    /// Answer text.
    Text,
    /// Reasoning.
    Reasoning,
    /// A tool call.
    ToolCall,
    /// An image.
    Image,
    /// A provider item with no canonical meaning.
    Opaque,
}

/// One event of a completion stream: a part starts, grows, or ends with the
/// content it finalized. Deserializing one event checks nothing about its
/// order; read a sequence through [`StreamRecord::parse`] to check it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "event", rename_all = "snake_case")]
pub enum StreamEvent {
    /// A part opened. A tool call opens once its tool is named, so a call
    /// streams its arguments under a known tool.
    Start {
        /// The part.
        part: Part,
        /// What it holds.
        kind: PartKind,
        /// The tool a [`PartKind::ToolCall`] names as it opens; `None` for
        /// every other kind. The call's end states the name it settled on.
        #[serde(default, skip_serializing_if = "Option::is_none")]
        name: Option<ToolName>,
    },
    /// A text part grew.
    Text {
        /// The part.
        part: Part,
        /// The fragment.
        text: String,
    },
    /// A reasoning part grew.
    Reasoning {
        /// The part.
        part: Part,
        /// The fragment.
        text: String,
    },
    /// A tool call's arguments grew. The fragments of one call, joined,
    /// are the argument JSON the provider sent; read an incomplete prefix
    /// with [`parse_partial_arguments`](super::parse_partial_arguments).
    Arguments {
        /// The part.
        part: Part,
        /// The fragment of raw argument JSON.
        json: String,
    },
    /// A part ended with the content it finalized.
    End {
        /// The part.
        part: Part,
        /// The finalized content.
        content: AssistantContent,
    },
}

impl StreamEvent {
    /// The part this event is about.
    pub const fn part(&self) -> Part {
        match self {
            Self::Start { part, .. }
            | Self::Text { part, .. }
            | Self::Reasoning { part, .. }
            | Self::Arguments { part, .. }
            | Self::End { part, .. } => *part,
        }
    }

    /// A stable variant name that exposes no payload to logs.
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Start { .. } => "Start",
            Self::Text { .. } => "Text",
            Self::Reasoning { .. } => "Reasoning",
            Self::Arguments { .. } => "Arguments",
            Self::End { .. } => "End",
        }
    }

    /// The events a stream writes for `content` arriving whole as the part
    /// at `part`: its start, its text, reasoning or argument text as one
    /// fragment, and its end holding `content`. Empty text writes no
    /// fragment. A call's fragment is its
    /// [`raw_arguments`](crate::message::ToolFunction::raw_arguments): the
    /// text the model sent when it was not an object, else the object.
    ///
    /// ```
    /// use rig_core::message::AssistantContent;
    /// use rig_core::streaming::{Part, StreamEvent};
    ///
    /// let events = StreamEvent::whole(Part::new(0), &AssistantContent::text("Hi"));
    /// let names: Vec<_> = events.iter().map(StreamEvent::name).collect();
    /// assert_eq!(names, ["Start", "Text", "End"]);
    /// ```
    pub fn whole(part: Part, content: &AssistantContent) -> Vec<Self> {
        let name = content
            .as_tool_call()
            .map(|call| call.function.name.clone());
        let start = Self::Start {
            part,
            kind: PartKind::of(content),
            name,
        };
        let end = Self::End {
            part,
            content: content.clone(),
        };
        [start]
            .into_iter()
            .chain(Self::fragment(part, content))
            .chain([end])
            .collect()
    }

    /// `content`'s whole text, reasoning or argument text as one fragment
    /// of `part`, or `None` when it is empty or `content` has none.
    pub(crate) fn fragment(part: Part, content: &AssistantContent) -> Option<Self> {
        match content {
            AssistantContent::Text(text) if !text.text.is_empty() => Some(Self::Text {
                part,
                text: text.text.clone(),
            }),
            AssistantContent::Reasoning(reasoning) if !reasoning.text.is_empty() => {
                Some(Self::Reasoning {
                    part,
                    text: reasoning.text.clone(),
                })
            }
            AssistantContent::ToolCall(call) => {
                let json = call.function.raw_arguments();
                (!json.is_empty()).then_some(Self::Arguments { part, json })
            }
            _ => None,
        }
    }
}

impl PartKind {
    /// The kind of part that holds `content`.
    pub(crate) const fn of(content: &AssistantContent) -> Self {
        match content {
            AssistantContent::Text(_) => Self::Text,
            AssistantContent::Reasoning(_) => Self::Reasoning,
            AssistantContent::ToolCall(_) => Self::ToolCall,
            AssistantContent::Image(_) => Self::Image,
            AssistantContent::Opaque(_) => Self::Opaque,
        }
    }
}

/// One item of a stream: an event of the operation, or a payload the
/// provider sent that the decoder does not model. An unmodeled payload
/// always reaches the consumer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "item", content = "value", rename_all = "snake_case")]
pub enum Item<E> {
    /// An event of the operation.
    Event(E),
    /// A payload the decoder does not model.
    Unknown(UnknownPayload),
}

/// A completion stream's items read back from their serialized form, in an
/// order the writer could have produced: each part starts once, at a
/// position no part took before, grows only while open and with its own
/// kind of fragment, and ends once. Positions follow the order provider
/// items opened, so a dropped item leaves a gap. Unmodeled payloads may come
/// anywhere.
#[derive(Debug, Clone, Default)]
pub struct StreamRecord {
    items: Vec<Item<StreamEvent>>,
    /// Each started part's kind, and whether it ended.
    parts: std::collections::BTreeMap<usize, (PartKind, bool)>,
}

impl PartialEq for StreamRecord {
    fn eq(&self, other: &Self) -> bool {
        self.items == other.items
    }
}

impl Serialize for StreamRecord {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.items.serialize(serializer)
    }
}

/// Why a serialized event sequence is not one the writer could produce.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum SequenceError {
    /// The value is not a list of stream items.
    #[error("not a list of stream items: {0}")]
    Shape(String),
    /// An event names a part that has not started, or a start reuses a
    /// position.
    #[error("item {0} names a part that has not started, or starts one twice")]
    UnknownPart(usize),
    /// A part ended twice, or grew after its end.
    #[error("item {0} touches a part that already ended")]
    EndedTwice(usize),
    /// A fragment or end does not match the part's kind, or a start names a
    /// tool for a part that is not a call, or none for one that is.
    #[error("item {0} does not match its part's kind")]
    WrongKind(usize),
    /// A part started and never ended.
    #[error("part {0} never ended")]
    Unclosed(usize),
}

impl StreamRecord {
    /// Read a serialized item sequence, refusing one the writer could not
    /// have produced. Every part must have ended.
    pub fn parse(value: serde_json::Value) -> Result<Self, SequenceError> {
        let transcript = Self::parse_prefix(value)?;
        transcript.check_closed()?;
        Ok(transcript)
    }

    /// [`Self::parse`] for a stream that stopped early (an error or a
    /// cancellation): parts may still be open at its end.
    pub fn parse_prefix(value: serde_json::Value) -> Result<Self, SequenceError> {
        let items: Vec<Item<StreamEvent>> = crate::json_utils::from_value(&value)
            .map_err(|error| SequenceError::Shape(error.to_string()))?;
        Self::from_items(items)
    }

    /// Append the next item a stream yielded, refusing one the writer could
    /// not have produced after the items so far.
    pub fn push(&mut self, item: Item<StreamEvent>) -> Result<(), SequenceError> {
        let position = self.items.len();
        if let Item::Event(event) = &item {
            let index = event.part().index();
            let kind = match event {
                StreamEvent::Start { kind, name, .. } => {
                    if (*kind == PartKind::ToolCall) != name.is_some() {
                        return Err(SequenceError::WrongKind(position));
                    }
                    let Entry::Vacant(part) = self.parts.entry(index) else {
                        return Err(SequenceError::UnknownPart(position));
                    };
                    part.insert((*kind, false));
                    None
                }
                StreamEvent::Text { .. } => Some(PartKind::Text),
                StreamEvent::Reasoning { .. } => Some(PartKind::Reasoning),
                StreamEvent::Arguments { .. } => Some(PartKind::ToolCall),
                StreamEvent::End { content, .. } => Some(PartKind::of(content)),
            };
            if let Some(kind) = kind {
                match self.parts.get_mut(&index) {
                    None => return Err(SequenceError::UnknownPart(position)),
                    Some((_, true)) => return Err(SequenceError::EndedTwice(position)),
                    Some((open, false)) if *open != kind => {
                        return Err(SequenceError::WrongKind(position));
                    }
                    Some((_, ended)) => *ended = matches!(event, StreamEvent::End { .. }),
                }
            }
        }
        self.items.push(item);
        Ok(())
    }

    fn check_closed(&self) -> Result<(), SequenceError> {
        match self.parts.iter().find(|(_, (_, ended))| !ended) {
            Some((part, _)) => Err(SequenceError::Unclosed(*part)),
            None => Ok(()),
        }
    }

    /// Items a stream yielded, checked as [`Self::push`] checks them: a
    /// stream that stopped early may leave parts open.
    pub fn from_items(items: Vec<Item<StreamEvent>>) -> Result<Self, SequenceError> {
        let mut transcript = Self::default();
        for item in items {
            transcript.push(item)?;
        }
        Ok(transcript)
    }

    /// The number of items.
    pub fn len(&self) -> usize {
        self.items.len()
    }

    /// Whether there are no items.
    pub fn is_empty(&self) -> bool {
        self.items.is_empty()
    }

    /// The items, in order.
    pub fn items(&self) -> &[Item<StreamEvent>] {
        &self.items
    }

    /// The items, in order.
    pub fn into_items(self) -> Vec<Item<StreamEvent>> {
        self.items
    }

    /// The events, in order, without the unmodeled payloads.
    pub fn events(&self) -> impl Iterator<Item = &StreamEvent> {
        self.items.iter().filter_map(|item| match item {
            Item::Event(event) => Some(event),
            Item::Unknown(_) => None,
        })
    }
}

impl From<StreamRecord> for Vec<Item<StreamEvent>> {
    fn from(transcript: StreamRecord) -> Self {
        transcript.items
    }
}

/// Read as the item list it is, with no `Value` tree between.
impl<'de> Deserialize<'de> for StreamRecord {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let items = Vec::<Item<StreamEvent>>::deserialize(deserializer)
            .map_err(|error| serde::de::Error::custom(SequenceError::Shape(error.to_string())))?;
        Self::from_items(items).map_err(serde::de::Error::custom)
    }
}

// The stream vocabulary crosses threads on every target: a handler sends it
// over a channel, the effect log records it, and a client reads it back.
const _: fn() = || {
    fn assert_wire<T: Clone + Send + Sync + 'static + Serialize + serde::de::DeserializeOwned>() {}
    assert_wire::<StreamEvent>();
    assert_wire::<StreamRecord>();
    assert_wire::<Item<StreamEvent>>();
};

#[cfg(test)]
mod tests;