Skip to main content

agentai_core/
message.rs

1//! # Conversation messages
2//!
3//! The conversation history is a `Vec<Message>` that you own. Pass it to a run with
4//! `AgentRequest::with_history` in `agentai` and append `AgentResult::new_messages` to it to
5//! continue the conversation.
6//!
7//! Messages implement `Serialize` and `Deserialize` with a format defined by this crate, so a
8//! stored history keeps working when the LLM client used inside `agentai` changes.
9
10use crate::http::{HttpClient, HttpError, HttpRequest};
11use crate::{base64, mime};
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15/// Who wrote a [`Message`].
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
17#[serde(rename_all = "snake_case")]
18#[non_exhaustive]
19pub enum Role {
20    /// The user, or your code speaking for the user.
21    User,
22    /// The model.
23    Assistant,
24    /// Results of tool calls, sent back to the model.
25    Tool,
26}
27
28/// One message of the conversation history.
29///
30/// The system prompt is not a message: the `Agent` of `agentai` sends its own with every
31/// request.
32#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
33#[non_exhaustive]
34pub struct Message {
35    /// Who wrote the message.
36    pub role: Role,
37    /// Content of the message, in order.
38    pub parts: Vec<Part>,
39}
40
41impl Message {
42    /// Creates a message from its parts.
43    pub fn new(role: Role, parts: Vec<Part>) -> Self {
44        Self { role, parts }
45    }
46
47    /// Creates a user message with text.
48    pub fn user(text: impl Into<String>) -> Self {
49        Self::new(Role::User, vec![Part::Text(text.into())])
50    }
51
52    /// Creates an assistant message with text.
53    pub fn assistant(text: impl Into<String>) -> Self {
54        Self::new(Role::Assistant, vec![Part::Text(text.into())])
55    }
56
57    /// Creates a message with the result of a tool call.
58    pub fn tool_response(response: ToolResponse) -> Self {
59        Self::new(Role::Tool, vec![Part::ToolResponse(response)])
60    }
61
62    /// Creates one user message from deferred task notification lines.
63    ///
64    /// Returns `None` when there are no notifications.
65    pub fn deferred_task_notifications(
66        notifications: impl IntoIterator<Item = String>,
67    ) -> Option<Self> {
68        let mut text = String::new();
69        for notification in notifications {
70            if !text.is_empty() {
71                text.push('\n');
72            }
73            text.push_str(&notification);
74        }
75        (!text.is_empty()).then(|| Self::user(text))
76    }
77
78    /// Returns the text parts joined together, or `None` when the message has no text.
79    pub fn text(&self) -> Option<String> {
80        joined_text(&self.parts)
81    }
82
83    /// Returns the tool calls in the message.
84    pub fn tool_calls(&self) -> Vec<&ToolCall> {
85        self.parts
86            .iter()
87            .filter_map(|part| match part {
88                Part::ToolCall(call) => Some(call),
89                _ => None,
90            })
91            .collect()
92    }
93}
94
95/// A piece of a [`Message`].
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[serde(tag = "type", content = "value", rename_all = "snake_case")]
98#[non_exhaustive]
99pub enum Part {
100    /// Text.
101    Text(String),
102    /// A tool call requested by the model.
103    ToolCall(ToolCall),
104    /// The result of a tool call.
105    ToolResponse(ToolResponse),
106    /// Reasoning (thinking) text of the model.
107    Reasoning(String),
108    /// Signature of the model's reasoning. Some providers (Anthropic, Gemini) need it back to
109    /// continue a conversation with reasoning; keep it in the history as it is.
110    ReasoningSignature(String),
111    /// An image, audio or other file.
112    Media(Media),
113    /// Provider-specific data that has to be sent back unchanged, for example reasoning
114    /// details. Keep it in the history as it is.
115    ProviderData(ProviderData),
116}
117
118/// A tool call requested by the model.
119#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
120#[non_exhaustive]
121pub struct ToolCall {
122    /// Id of the call. The matching [`ToolResponse`] has the same id.
123    pub id: String,
124    /// Name of the tool.
125    pub name: String,
126    /// Arguments chosen by the model, as JSON.
127    pub arguments: Value,
128    /// Reasoning signatures some providers attach to the call.
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    pub(crate) signatures: Vec<String>,
131}
132
133impl ToolCall {
134    /// Creates a tool call.
135    pub fn new(id: impl Into<String>, name: impl Into<String>, arguments: Value) -> Self {
136        Self {
137            id: id.into(),
138            name: name.into(),
139            arguments,
140            signatures: Vec::new(),
141        }
142    }
143
144    /// Reasoning signatures some providers attach to the call. Keep them as they are, the
145    /// provider needs them back.
146    pub fn signatures(&self) -> &[String] {
147        &self.signatures
148    }
149
150    /// Sets the reasoning signatures.
151    pub fn with_signatures(mut self, signatures: Vec<String>) -> Self {
152        self.signatures = signatures;
153        self
154    }
155}
156
157/// The result of a tool call, sent back to the model.
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
159#[non_exhaustive]
160pub struct ToolResponse {
161    /// Id of the [`ToolCall`] this result answers.
162    pub call_id: String,
163    /// Name of the tool.
164    pub name: String,
165    /// Result sent to the model: [`Part::Text`] and [`Part::Media`] parts, in order.
166    ///
167    /// Media reaches every vision model, see [`ToolOutput`].
168    #[serde(deserialize_with = "deserialize_tool_content")]
169    pub content: Vec<Part>,
170}
171
172impl ToolResponse {
173    /// Creates the result of `call`.
174    pub fn new(call: &ToolCall, content: impl Into<ToolOutput>) -> Self {
175        Self {
176            call_id: call.id.clone(),
177            name: call.name.clone(),
178            content: content.into().parts,
179        }
180    }
181
182    /// Returns the text parts joined together, or `None` when the result has no text.
183    pub fn text(&self) -> Option<String> {
184        joined_text(&self.content)
185    }
186}
187
188/// Reads `content` as a list of parts, or as a plain string (the format before 0.5.0).
189fn deserialize_tool_content<'de, D>(deserializer: D) -> Result<Vec<Part>, D::Error>
190where
191    D: serde::Deserializer<'de>,
192{
193    #[derive(Deserialize)]
194    #[serde(untagged)]
195    enum Content {
196        Text(String),
197        Parts(Vec<Part>),
198    }
199    Ok(match Content::deserialize(deserializer)? {
200        Content::Text(text) => vec![Part::Text(text)],
201        Content::Parts(parts) => parts,
202    })
203}
204
205/// Joins the text parts, `None` when there are none.
206fn joined_text(parts: &[Part]) -> Option<String> {
207    let texts: Vec<&str> = parts
208        .iter()
209        .filter_map(|part| match part {
210            Part::Text(text) => Some(text.as_str()),
211            _ => None,
212        })
213        .collect();
214    (!texts.is_empty()).then(|| texts.concat())
215}
216
217/// An image, audio or other file in a message.
218#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
219#[non_exhaustive]
220pub struct Media {
221    /// MIME type, for example `image/png`.
222    pub content_type: String,
223    /// Where the bytes are.
224    pub source: MediaSource,
225    /// File name, if known.
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub name: Option<String>,
228}
229
230impl Media {
231    /// Creates media from its MIME type and source.
232    pub fn new(content_type: impl Into<String>, source: MediaSource) -> Self {
233        Self {
234            content_type: content_type.into(),
235            source,
236            name: None,
237        }
238    }
239
240    /// Creates media the provider downloads from `url`. Not every provider accepts URLs; use
241    /// [`Media::from_bytes`] when yours does not.
242    pub fn from_url(content_type: impl Into<String>, url: impl Into<String>) -> Self {
243        Self::new(content_type, MediaSource::Url(url.into()))
244    }
245
246    /// Creates an image the provider downloads from `url`. The MIME type is guessed from the
247    /// file extension with [`mime::from_path`]; URLs without an image extension are sent as
248    /// `image/jpeg`. Use [`Media::from_url`] to set it yourself.
249    pub fn image_url(url: impl Into<String>) -> Self {
250        let url = url.into();
251        let content_type = mime::from_path(&url)
252            .filter(|content_type| content_type.starts_with("image/"))
253            .unwrap_or("image/jpeg");
254        Self::from_url(content_type, url)
255    }
256
257    /// Creates media from its bytes, for example an image read from a file. The bytes are
258    /// sent base64 encoded inside the request.
259    pub fn from_bytes(content_type: impl Into<String>, bytes: impl AsRef<[u8]>) -> Self {
260        Self::from_base64(content_type, base64::encode(bytes))
261    }
262
263    /// Creates media from bytes that are already base64 encoded.
264    pub fn from_base64(content_type: impl Into<String>, data: impl Into<String>) -> Self {
265        Self::new(content_type, MediaSource::Base64(data.into()))
266    }
267
268    /// Sets the file name. Some providers show it to the model.
269    pub fn with_name(mut self, name: impl Into<String>) -> Self {
270        self.name = Some(name.into());
271        self
272    }
273
274    /// Returns `true` when the MIME type is an image type.
275    pub fn is_image(&self) -> bool {
276        self.content_type.starts_with("image/")
277    }
278
279    /// File extension of the MIME type, see [`mime::extension`].
280    pub fn extension(&self) -> &str {
281        mime::extension(&self.content_type)
282    }
283
284    /// A file name for the media: its [`name`](Media::name), else `stem`, with the extension of
285    /// its type unless it already ends in a known one (see [`mime::with_extension`]).
286    ///
287    /// ```rust
288    /// # use agentai_core::message::Media;
289    /// let audio = Media::from_bytes("audio/mpeg", b"ID3");
290    /// assert_eq!(audio.file_name("speech"), "speech.mp3");
291    /// assert_eq!(audio.with_name("intro.wav").file_name("speech"), "intro.wav");
292    /// ```
293    pub fn file_name(&self, stem: &str) -> String {
294        mime::with_extension(self.name.as_deref().unwrap_or(stem), &self.content_type)
295    }
296
297    /// The media as a URL: its own URL, or a `data:` URL with the base64 bytes.
298    pub fn to_url(&self) -> String {
299        match &self.source {
300            MediaSource::Url(url) => url.clone(),
301            MediaSource::Base64(data) => format!("data:{};base64,{data}", self.content_type),
302        }
303    }
304
305    /// Size of the media in bytes. `None` for a URL or invalid base64.
306    pub fn byte_len(&self) -> Option<usize> {
307        match &self.source {
308            MediaSource::Base64(data) => base64::decode(data).ok().map(|bytes| bytes.len()),
309            MediaSource::Url(_) => None,
310        }
311    }
312
313    /// Returns the bytes of the media: decoded base64, or downloaded from its URL with
314    /// `client`.
315    pub async fn bytes(&self, client: &dyn HttpClient) -> Result<Vec<u8>, HttpError> {
316        match &self.source {
317            MediaSource::Base64(data) => base64::decode(data),
318            MediaSource::Url(url) => Ok(client
319                .send(HttpRequest::get(url))
320                .await?
321                .error_for_status()?
322                .body),
323        }
324    }
325}
326
327/// Where the bytes of [`Media`] are.
328#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
329#[serde(rename_all = "snake_case")]
330pub enum MediaSource {
331    /// A URL. Few providers accept it.
332    Url(String),
333    /// The bytes, base64 encoded.
334    Base64(String),
335}
336
337/// Provider-specific data in a message. It has no meaning outside the provider that produced it.
338#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
339#[non_exhaustive]
340pub struct ProviderData {
341    /// Provider that produced the data, if known.
342    #[serde(default, skip_serializing_if = "Option::is_none")]
343    pub provider: Option<String>,
344    /// Model that produced the data, if known.
345    #[serde(default, skip_serializing_if = "Option::is_none")]
346    pub model: Option<String>,
347    /// The data.
348    pub data: Value,
349}
350
351impl ProviderData {
352    /// Creates provider data without the provider and model.
353    pub fn new(data: Value) -> Self {
354        Self {
355            provider: None,
356            model: None,
357            data,
358        }
359    }
360
361    /// Sets the provider.
362    pub fn with_provider(mut self, provider: impl Into<String>) -> Self {
363        self.provider = Some(provider.into());
364        self
365    }
366
367    /// Sets the model.
368    pub fn with_model(mut self, model: impl Into<String>) -> Self {
369        self.model = Some(model.into());
370        self
371    }
372}
373
374/// What a tool sends back to the model: text and media (for example a generated image), in
375/// order.
376///
377/// Text converts into it, so a tool that only returns text can keep returning a `String`.
378/// The model gets the text in the tool result and the media in a user message right after the
379/// tool results, for every provider for now. A later release puts the media in the tool result
380/// itself for the providers that accept it (Anthropic, Gemini, OpenAI Responses, Bedrock and
381/// Ollama).
382///
383/// There is no structured (JSON) output: a tool that produces data converts it to text itself,
384/// for example with `serde_json::to_string`, in the format it wants the model to read.
385///
386/// ```rust
387/// # use agentai_core::message::{Media, ToolOutput};
388/// let png = [0x89, b'P', b'N', b'G'];
389/// let output = ToolOutput::from_text("Here is the chart")
390///     .with_media(Media::from_bytes("image/png", png));
391/// ```
392#[derive(Debug, Clone, Default, PartialEq)]
393#[non_exhaustive]
394pub struct ToolOutput {
395    /// [`Part::Text`] and [`Part::Media`] parts.
396    pub parts: Vec<Part>,
397}
398
399impl ToolOutput {
400    /// Creates an output with text.
401    pub fn from_text(text: impl Into<String>) -> Self {
402        Self::default().with_text(text)
403    }
404
405    /// Creates an output with one media part.
406    pub fn from_media(media: Media) -> Self {
407        Self::default().with_media(media)
408    }
409
410    /// Appends text.
411    pub fn with_text(mut self, text: impl Into<String>) -> Self {
412        self.parts.push(Part::Text(text.into()));
413        self
414    }
415
416    /// Appends media.
417    pub fn with_media(mut self, media: Media) -> Self {
418        self.parts.push(Part::Media(media));
419        self
420    }
421
422    /// Returns the text parts joined together, or `None` when there is no text.
423    pub fn text(&self) -> Option<String> {
424        joined_text(&self.parts)
425    }
426
427    /// Returns the media parts.
428    pub fn media(&self) -> Vec<&Media> {
429        self.parts
430            .iter()
431            .filter_map(|part| match part {
432                Part::Media(media) => Some(media),
433                _ => None,
434            })
435            .collect()
436    }
437}
438
439/// Text parts as they are, media as `[content type]`, for example `[image/png]`.
440impl std::fmt::Display for ToolOutput {
441    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
442        for part in &self.parts {
443            match part {
444                Part::Text(text) => f.write_str(text)?,
445                Part::Media(media) => write!(f, "[{}]", media.content_type)?,
446                _ => {}
447            }
448        }
449        Ok(())
450    }
451}
452
453impl From<String> for ToolOutput {
454    fn from(text: String) -> Self {
455        Self::from_text(text)
456    }
457}
458
459impl From<&str> for ToolOutput {
460    fn from(text: &str) -> Self {
461        Self::from_text(text)
462    }
463}
464
465impl From<Media> for ToolOutput {
466    fn from(media: Media) -> Self {
467        Self::from_media(media)
468    }
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474    use serde_json::json;
475
476    fn every_part() -> Message {
477        let mut call = ToolCall::new("call_1", "echo", json!({"text": "hi"}));
478        call.signatures = vec!["sig".to_string()];
479        Message::new(
480            Role::Assistant,
481            vec![
482                Part::ReasoningSignature("signature".into()),
483                Part::Reasoning("thinking".into()),
484                Part::Text("hello".into()),
485                Part::ToolCall(call.clone()),
486                Part::ToolResponse(ToolResponse::new(&call, "result")),
487                Part::ToolResponse(ToolResponse::new(
488                    &call,
489                    ToolOutput::from_text("an image")
490                        .with_media(Media::new("image/png", MediaSource::Base64("aGk=".into()))),
491                )),
492                Part::Media(Media::new("image/png", MediaSource::Base64("aGk=".into()))),
493                Part::Media(Media::new(
494                    "image/png",
495                    MediaSource::Url("https://example.com/a.png".into()),
496                )),
497                Part::ProviderData(ProviderData {
498                    provider: Some("OpenRouter".into()),
499                    model: Some("m".into()),
500                    data: json!({"type": "reasoning.encrypted"}),
501                }),
502            ],
503        )
504    }
505
506    #[test]
507    fn messages_round_trip_through_json() {
508        let message = every_part();
509        let json = serde_json::to_string(&message).unwrap();
510        assert_eq!(serde_json::from_str::<Message>(&json).unwrap(), message);
511    }
512
513    #[test]
514    fn tool_responses_stored_before_0_5_still_load() {
515        let json = r#"{"role":"tool","parts":[{"type":"tool_response",
516            "value":{"call_id":"call_1","name":"echo","content":"result"}}]}"#;
517        let message: Message = serde_json::from_str(json).unwrap();
518        let call = ToolCall::new("call_1", "echo", json!({}));
519        assert_eq!(
520            message,
521            Message::tool_response(ToolResponse::new(&call, "result"))
522        );
523    }
524
525    #[test]
526    fn image_url_guesses_the_type_from_the_extension() {
527        let types: Vec<String> = [
528            "https://example.com/a.png",
529            "https://example.com/a.PNG?size=2#top",
530            "https://example.com/a.webp",
531            "https://example.com/a.gif",
532            "https://example.com/a.jpeg",
533            "https://example.com/image",
534        ]
535        .into_iter()
536        .map(|url| Media::image_url(url).content_type)
537        .collect();
538        assert_eq!(
539            types,
540            [
541                "image/png",
542                "image/png",
543                "image/webp",
544                "image/gif",
545                "image/jpeg",
546                "image/jpeg"
547            ]
548        );
549        assert_eq!(
550            Media::image_url("https://example.com/a.png").source,
551            MediaSource::Url("https://example.com/a.png".into())
552        );
553    }
554
555    #[test]
556    fn file_name_prefers_the_name_over_the_stem() {
557        let video = Media::from_bytes("video/mp4", b"MP4");
558        assert_eq!(video.file_name("first_frame"), "first_frame.mp4");
559        assert_eq!(video.clone().with_name("clip").file_name("x"), "clip.mp4");
560        assert_eq!(video.with_name("clip.mov").file_name("x"), "clip.mov");
561    }
562
563    #[test]
564    fn to_url_gives_the_url_or_a_data_url() {
565        assert_eq!(
566            Media::from_base64("image/png", "aGk=").to_url(),
567            "data:image/png;base64,aGk="
568        );
569        assert_eq!(
570            Media::image_url("https://example.com/a.png").to_url(),
571            "https://example.com/a.png"
572        );
573    }
574
575    #[test]
576    fn json_format_is_stable() {
577        let message = Message::user("hi");
578        assert_eq!(
579            serde_json::to_value(&message).unwrap(),
580            json!({"role": "user", "parts": [{"type": "text", "value": "hi"}]})
581        );
582    }
583}