Skip to main content

ag_ui/
message.rs

1//! The message union and its multimodal content parts.
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use crate::JsonObject;
7use crate::ids::{MessageId, ToolCallId};
8use crate::tool::ToolCall;
9
10/// Every role the protocol defines.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
12#[serde(rename_all = "lowercase")]
13#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
14#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
15pub enum Role {
16    /// Out-of-band instructions from the application developer.
17    Developer,
18    /// System prompt.
19    System,
20    /// Model output.
21    Assistant,
22    /// End-user input.
23    User,
24    /// The result of a tool call.
25    Tool,
26    /// A structured progress update rendered by the client.
27    Activity,
28    /// Model reasoning / chain-of-thought.
29    Reasoning,
30}
31
32impl Role {
33    /// The role string as it appears on the wire.
34    pub const fn as_str(&self) -> &'static str {
35        match self {
36            Self::Developer => "developer",
37            Self::System => "system",
38            Self::Assistant => "assistant",
39            Self::User => "user",
40            Self::Tool => "tool",
41            Self::Activity => "activity",
42            Self::Reasoning => "reasoning",
43        }
44    }
45}
46
47impl std::fmt::Display for Role {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.write_str(self.as_str())
50    }
51}
52
53/// Where the bytes of a multimodal part live.
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
55#[serde(tag = "type", rename_all = "lowercase")]
56#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
57#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
58pub enum InputContentSource {
59    /// Inline data, typically base64.
60    Data {
61        /// The encoded payload.
62        value: String,
63        /// MIME type of the payload, for example `image/png`.
64        #[serde(rename = "mimeType")]
65        mime_type: String,
66    },
67    /// A URL the consumer fetches itself.
68    Url {
69        /// The URL.
70        value: String,
71        /// MIME type, when the producer knows it.
72        #[serde(rename = "mimeType", default, skip_serializing_if = "Option::is_none")]
73        mime_type: Option<String>,
74    },
75}
76
77/// A plain-text content part.
78#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
79#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
80#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
81pub struct TextInputContent {
82    /// The text.
83    pub text: String,
84}
85
86/// An image, audio, video or document content part.
87///
88/// The four modalities share a shape, so they share a struct; which one it is
89/// is carried by the [`InputContent`] variant.
90#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
91#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
92#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
93pub struct MediaInputContent {
94    /// Where the bytes are.
95    pub source: InputContentSource,
96    /// Producer-defined extras (dimensions, page counts, alt text, …).
97    #[serde(default, skip_serializing_if = "Option::is_none")]
98    pub metadata: Option<Value>,
99}
100
101impl MediaInputContent {
102    /// Builds a media part from a source, with no metadata.
103    pub fn new(source: InputContentSource) -> Self {
104        Self {
105            source,
106            metadata: None,
107        }
108    }
109}
110
111/// The legacy `binary` content part.
112///
113/// Superseded by the modality-specific parts, but still accepted: at least one
114/// of `id`, `url` or `data` must be set. That constraint is a runtime rule in
115/// the upstream schema and is not encoded in this type — see
116/// [`BinaryInputContent::has_payload`].
117#[derive(Clone, Debug, Default, PartialEq, Eq, 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 BinaryInputContent {
122    /// MIME type of the payload.
123    pub mime_type: String,
124    /// Reference to a previously uploaded blob.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub id: Option<String>,
127    /// URL to fetch the payload from.
128    #[serde(default, skip_serializing_if = "Option::is_none")]
129    pub url: Option<String>,
130    /// Inline payload, typically base64.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub data: Option<String>,
133    /// Original file name, for display.
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub filename: Option<String>,
136}
137
138impl BinaryInputContent {
139    /// Whether the part carries a payload in any of the three accepted forms.
140    pub fn has_payload(&self) -> bool {
141        self.id.is_some() || self.url.is_some() || self.data.is_some()
142    }
143}
144
145/// One part of a multimodal user message.
146#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
147#[serde(tag = "type", rename_all = "lowercase")]
148#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
149#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
150pub enum InputContent {
151    /// Text.
152    Text(TextInputContent),
153    /// An image.
154    Image(MediaInputContent),
155    /// An audio clip.
156    Audio(MediaInputContent),
157    /// A video clip.
158    Video(MediaInputContent),
159    /// A document, for example a PDF.
160    Document(MediaInputContent),
161    /// The legacy catch-all binary part.
162    Binary(BinaryInputContent),
163}
164
165impl InputContent {
166    /// Builds a text part.
167    pub fn text(text: impl Into<String>) -> Self {
168        Self::Text(TextInputContent { text: text.into() })
169    }
170}
171
172/// The body of a user message: either a bare string or an ordered list of
173/// multimodal parts.
174#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
175#[serde(untagged)]
176#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
177#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
178pub enum UserContent {
179    /// Plain text.
180    Text(String),
181    /// Multimodal parts.
182    Parts(Vec<InputContent>),
183}
184
185impl UserContent {
186    /// The text, when the content is a plain string.
187    ///
188    /// `None` for multimodal content, even when every part of it happens to be
189    /// text: this borrows, and joining parts cannot. Reach for
190    /// [`UserContent::to_text`] when any text will do.
191    pub fn as_text(&self) -> Option<&str> {
192        match self {
193            Self::Text(text) => Some(text),
194            Self::Parts(_) => None,
195        }
196    }
197
198    /// Every text part, in order, joined with newlines.
199    ///
200    /// Non-text parts are dropped rather than described: an agent that does not
201    /// handle images wants the caption, not a placeholder it has to strip.
202    ///
203    /// ```
204    /// use ag_ui::{InputContent, InputContentSource, MediaInputContent, UserContent};
205    ///
206    /// let plain = UserContent::from("what is the weather?");
207    /// assert_eq!(plain.as_text(), Some("what is the weather?"));
208    /// assert_eq!(plain.to_text(), "what is the weather?");
209    ///
210    /// let image = MediaInputContent::new(InputContentSource::Url {
211    ///     value: "https://example.com/cat.png".into(),
212    ///     mime_type: None,
213    /// });
214    /// let mixed = UserContent::from(vec![
215    ///     InputContent::text("what is this?"),
216    ///     InputContent::Image(image),
217    ///     InputContent::text("be brief"),
218    /// ]);
219    /// assert_eq!(mixed.as_text(), None);
220    /// assert_eq!(mixed.to_text(), "what is this?\nbe brief");
221    /// ```
222    pub fn to_text(&self) -> String {
223        match self {
224            Self::Text(text) => text.clone(),
225            Self::Parts(parts) => parts
226                .iter()
227                .filter_map(|part| match part {
228                    InputContent::Text(part) => Some(part.text.as_str()),
229                    _ => None,
230                })
231                .collect::<Vec<_>>()
232                .join("\n"),
233        }
234    }
235}
236
237impl Default for UserContent {
238    fn default() -> Self {
239        Self::Text(String::new())
240    }
241}
242
243impl From<String> for UserContent {
244    fn from(value: String) -> Self {
245        Self::Text(value)
246    }
247}
248
249impl From<&str> for UserContent {
250    fn from(value: &str) -> Self {
251        Self::Text(value.to_owned())
252    }
253}
254
255impl From<Vec<InputContent>> for UserContent {
256    fn from(value: Vec<InputContent>) -> Self {
257        Self::Parts(value)
258    }
259}
260
261/// Out-of-band instructions from the application developer.
262#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
263#[serde(rename_all = "camelCase")]
264#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
265#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
266pub struct DeveloperMessage {
267    /// Message id.
268    pub id: MessageId,
269    /// The instructions.
270    pub content: String,
271    /// Optional display name for the author.
272    #[serde(default, skip_serializing_if = "Option::is_none")]
273    pub name: Option<String>,
274    /// Opaque provider payload for zero-data-retention modes.
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub encrypted_value: Option<String>,
277}
278
279/// The system prompt.
280#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(rename_all = "camelCase")]
282#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
283#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
284pub struct SystemMessage {
285    /// Message id.
286    pub id: MessageId,
287    /// The prompt.
288    pub content: String,
289    /// Optional display name for the author.
290    #[serde(default, skip_serializing_if = "Option::is_none")]
291    pub name: Option<String>,
292    /// Opaque provider payload for zero-data-retention modes.
293    #[serde(default, skip_serializing_if = "Option::is_none")]
294    pub encrypted_value: Option<String>,
295}
296
297/// Model output, optionally requesting tool calls.
298#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
299#[serde(rename_all = "camelCase")]
300#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
301#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
302pub struct AssistantMessage {
303    /// Message id.
304    pub id: MessageId,
305    /// The reply text. Absent when the turn is tool calls only.
306    #[serde(default, skip_serializing_if = "Option::is_none")]
307    pub content: Option<String>,
308    /// Optional display name for the author.
309    #[serde(default, skip_serializing_if = "Option::is_none")]
310    pub name: Option<String>,
311    /// Opaque provider payload for zero-data-retention modes.
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    pub encrypted_value: Option<String>,
314    /// Tool calls the assistant wants executed.
315    #[serde(default, skip_serializing_if = "Option::is_none")]
316    pub tool_calls: Option<Vec<ToolCall>>,
317}
318
319/// End-user input, possibly multimodal.
320#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
321#[serde(rename_all = "camelCase")]
322#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
323#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
324pub struct UserMessage {
325    /// Message id.
326    pub id: MessageId,
327    /// Text or multimodal parts.
328    pub content: UserContent,
329    /// Optional display name for the author.
330    #[serde(default, skip_serializing_if = "Option::is_none")]
331    pub name: Option<String>,
332    /// Opaque provider payload for zero-data-retention modes.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub encrypted_value: Option<String>,
335}
336
337/// The result of a tool call, fed back to the model.
338#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
339#[serde(rename_all = "camelCase")]
340#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
341#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
342pub struct ToolMessage {
343    /// Message id.
344    pub id: MessageId,
345    /// The result, already rendered to a string.
346    pub content: String,
347    /// The call this result answers.
348    pub tool_call_id: ToolCallId,
349    /// Set when the tool failed; `content` then holds whatever partial output
350    /// there was.
351    #[serde(default, skip_serializing_if = "Option::is_none")]
352    pub error: Option<String>,
353    /// Opaque provider payload for zero-data-retention modes.
354    #[serde(default, skip_serializing_if = "Option::is_none")]
355    pub encrypted_value: Option<String>,
356}
357
358/// A structured progress update the client renders as it likes.
359#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
360#[serde(rename_all = "camelCase")]
361#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
362#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
363pub struct ActivityMessage {
364    /// Message id.
365    pub id: MessageId,
366    /// Client-defined activity discriminator, for example `"web_search"`.
367    pub activity_type: String,
368    /// The activity payload.
369    #[cfg_attr(
370        feature = "schemars",
371        schemars(with = "std::collections::BTreeMap<String, serde_json::Value>")
372    )]
373    #[cfg_attr(feature = "utoipa", schema(value_type = Object))]
374    pub content: JsonObject,
375}
376
377/// Model reasoning, shown separately from the reply.
378#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(rename_all = "camelCase")]
380#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
381#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
382pub struct ReasoningMessage {
383    /// Message id.
384    pub id: MessageId,
385    /// The reasoning text. Empty when the provider only returns an encrypted
386    /// blob.
387    pub content: String,
388    /// Opaque provider payload for zero-data-retention modes.
389    #[serde(default, skip_serializing_if = "Option::is_none")]
390    pub encrypted_value: Option<String>,
391}
392
393/// A message in a thread, discriminated by its `role`.
394#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
395#[serde(tag = "role", rename_all = "lowercase")]
396#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
397#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
398pub enum Message {
399    /// See [`DeveloperMessage`].
400    Developer(DeveloperMessage),
401    /// See [`SystemMessage`].
402    System(SystemMessage),
403    /// See [`AssistantMessage`].
404    Assistant(AssistantMessage),
405    /// See [`UserMessage`].
406    User(UserMessage),
407    /// See [`ToolMessage`].
408    Tool(ToolMessage),
409    /// See [`ActivityMessage`].
410    Activity(ActivityMessage),
411    /// See [`ReasoningMessage`].
412    Reasoning(ReasoningMessage),
413}
414
415impl Message {
416    /// Builds a user message carrying plain text.
417    pub fn user(id: impl Into<MessageId>, content: impl Into<UserContent>) -> Self {
418        Self::User(UserMessage {
419            id: id.into(),
420            content: content.into(),
421            ..Default::default()
422        })
423    }
424
425    /// Builds an assistant message carrying plain text.
426    pub fn assistant(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
427        Self::Assistant(AssistantMessage {
428            id: id.into(),
429            content: Some(content.into()),
430            ..Default::default()
431        })
432    }
433
434    /// Builds a system message.
435    pub fn system(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
436        Self::System(SystemMessage {
437            id: id.into(),
438            content: content.into(),
439            ..Default::default()
440        })
441    }
442
443    /// Builds a developer message.
444    pub fn developer(id: impl Into<MessageId>, content: impl Into<String>) -> Self {
445        Self::Developer(DeveloperMessage {
446            id: id.into(),
447            content: content.into(),
448            ..Default::default()
449        })
450    }
451
452    /// Builds a tool result message.
453    pub fn tool(
454        id: impl Into<MessageId>,
455        tool_call_id: impl Into<ToolCallId>,
456        content: impl Into<String>,
457    ) -> Self {
458        Self::Tool(ToolMessage {
459            id: id.into(),
460            content: content.into(),
461            tool_call_id: tool_call_id.into(),
462            ..Default::default()
463        })
464    }
465
466    /// The message id, whatever the role.
467    pub const fn id(&self) -> &MessageId {
468        match self {
469            Self::Developer(m) => &m.id,
470            Self::System(m) => &m.id,
471            Self::Assistant(m) => &m.id,
472            Self::User(m) => &m.id,
473            Self::Tool(m) => &m.id,
474            Self::Activity(m) => &m.id,
475            Self::Reasoning(m) => &m.id,
476        }
477    }
478
479    /// The role, whatever the variant.
480    pub const fn role(&self) -> Role {
481        match self {
482            Self::Developer(_) => Role::Developer,
483            Self::System(_) => Role::System,
484            Self::Assistant(_) => Role::Assistant,
485            Self::User(_) => Role::User,
486            Self::Tool(_) => Role::Tool,
487            Self::Activity(_) => Role::Activity,
488            Self::Reasoning(_) => Role::Reasoning,
489        }
490    }
491}
492
493macro_rules! message_from {
494    ($($ty:ident => $variant:ident),* $(,)?) => {
495        $(
496            impl From<$ty> for Message {
497                fn from(value: $ty) -> Self {
498                    Self::$variant(value)
499                }
500            }
501        )*
502    };
503}
504
505message_from! {
506    DeveloperMessage => Developer,
507    SystemMessage => System,
508    AssistantMessage => Assistant,
509    UserMessage => User,
510    ToolMessage => Tool,
511    ActivityMessage => Activity,
512    ReasoningMessage => Reasoning,
513}