Skip to main content

ag_ui/event/
text.rs

1//! Streaming assistant text: `TEXT_MESSAGE_*`.
2
3use serde::{Deserialize, Deserializer, Serialize};
4
5use crate::event::BaseEvent;
6use crate::ids::MessageId;
7
8/// Reads an omitted *or* explicitly null `role` as [`TextMessageRole`]'s
9/// default.
10///
11/// The field is optional on the wire, and a producer that models an optional
12/// field as *nullable* writes the absent case as `null` rather than by leaving
13/// the key out — the same case [`ToolCallStartEvent::parent_message_id`]
14/// documents. Without this, `"role": null` fails to deserialize and takes the
15/// whole event, and so usually the whole run, with it.
16///
17/// [`ToolCallStartEvent::parent_message_id`]: crate::event::ToolCallStartEvent::parent_message_id
18fn null_role_is_the_default<'de, D>(deserializer: D) -> Result<TextMessageRole, D::Error>
19where
20    D: Deserializer<'de>,
21{
22    Ok(Option::<TextMessageRole>::deserialize(deserializer)?.unwrap_or_default())
23}
24
25/// The roles a streamed text message may carry.
26///
27/// Every role except `tool` — a tool result is not streamed as text, it arrives
28/// whole in `TOOL_CALL_RESULT`.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
30#[serde(rename_all = "lowercase")]
31#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
32#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
33pub enum TextMessageRole {
34    /// Out-of-band developer instructions.
35    Developer,
36    /// System prompt.
37    System,
38    /// Model output. The default when a producer omits the field.
39    #[default]
40    Assistant,
41    /// End-user input.
42    User,
43}
44
45impl TextMessageRole {
46    /// The role string as it appears on the wire.
47    pub const fn as_str(&self) -> &'static str {
48        match self {
49            Self::Developer => "developer",
50            Self::System => "system",
51            Self::Assistant => "assistant",
52            Self::User => "user",
53        }
54    }
55}
56
57/// Opens a text message. Every following `TEXT_MESSAGE_CONTENT` with the same
58/// `message_id` appends to it, until `TEXT_MESSAGE_END`.
59#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
60#[serde(rename_all = "camelCase")]
61#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
62#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
63pub struct TextMessageStartEvent {
64    /// Timestamp and raw provider event.
65    #[serde(flatten)]
66    pub base: BaseEvent,
67    /// Id of the message being opened.
68    pub message_id: MessageId,
69    /// Who is speaking. Defaults to `assistant` when omitted, and a JSON `null`
70    /// reads as omitted.
71    #[serde(default, deserialize_with = "null_role_is_the_default")]
72    pub role: TextMessageRole,
73    /// Display name for the author.
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub name: Option<String>,
76}
77
78impl TextMessageStartEvent {
79    /// Opens a message with the given id and role.
80    pub fn new(message_id: impl Into<MessageId>, role: TextMessageRole) -> Self {
81        Self {
82            base: BaseEvent::default(),
83            message_id: message_id.into(),
84            role,
85            name: None,
86        }
87    }
88}
89
90/// Appends a chunk of text to an open message.
91#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
92#[serde(rename_all = "camelCase")]
93#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
94#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
95pub struct TextMessageContentEvent {
96    /// Timestamp and raw provider event.
97    #[serde(flatten)]
98    pub base: BaseEvent,
99    /// The message being appended to.
100    pub message_id: MessageId,
101    /// The text to append.
102    pub delta: String,
103}
104
105impl TextMessageContentEvent {
106    /// Appends `delta` to the message.
107    pub fn new(message_id: impl Into<MessageId>, delta: impl Into<String>) -> Self {
108        Self {
109            base: BaseEvent::default(),
110            message_id: message_id.into(),
111            delta: delta.into(),
112        }
113    }
114}
115
116/// Closes a text message.
117#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
118#[serde(rename_all = "camelCase")]
119#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
120#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
121pub struct TextMessageEndEvent {
122    /// Timestamp and raw provider event.
123    #[serde(flatten)]
124    pub base: BaseEvent,
125    /// The message being closed.
126    pub message_id: MessageId,
127}
128
129impl TextMessageEndEvent {
130    /// Closes the message.
131    pub fn new(message_id: impl Into<MessageId>) -> Self {
132        Self {
133            base: BaseEvent::default(),
134            message_id: message_id.into(),
135        }
136    }
137}
138
139/// A self-contained text update: start, content and end folded into one event.
140///
141/// Producers that cannot bracket a message use this; consumers expand a run of
142/// chunks sharing a `message_id` into the equivalent start/content/end triple.
143#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
144#[serde(rename_all = "camelCase")]
145#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
146#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
147pub struct TextMessageChunkEvent {
148    /// Timestamp and raw provider event.
149    #[serde(flatten)]
150    pub base: BaseEvent,
151    /// The message this chunk belongs to.
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub message_id: Option<MessageId>,
154    /// Who is speaking.
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub role: Option<TextMessageRole>,
157    /// The text to append.
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub delta: Option<String>,
160    /// Display name for the author.
161    #[serde(default, skip_serializing_if = "Option::is_none")]
162    pub name: Option<String>,
163}
164
165impl TextMessageChunkEvent {
166    /// Builds a chunk carrying a message id and a text delta.
167    pub fn new(message_id: Option<MessageId>, delta: Option<String>) -> Self {
168        Self {
169            base: BaseEvent::default(),
170            message_id,
171            role: None,
172            delta,
173            name: None,
174        }
175    }
176}