Skip to main content

agentai_core/
prompt.rs

1//! # Prompts
2//!
3//! A [`Prompt`] is what you send to the model in a run: text, images or other media, in order.
4//! `Agent::run` and `Agent::run_stream` of `agentai` take anything that implements
5//! [`IntoPrompt`], so plain text works as before:
6//!
7//! ```ignore
8//! use agentai::{Agent, AgentResult, Media, Prompt};
9//!
10//! # async fn example(agent: Agent, png: Vec<u8>) -> Result<(), agentai::AgentError> {
11//! let result: AgentResult<String> = agent.run("Why is the sky blue?").await?;
12//!
13//! // Vision models also accept images
14//! let prompt = Prompt::text("What is in this picture?")
15//!     .with_image_url("https://example.com/cat.jpg")
16//!     .with_media(Media::from_bytes("image/png", &png));
17//! let result: AgentResult<String> = agent.run(prompt).await?;
18//! # Ok(())
19//! # }
20//! ```
21
22use crate::message::{Media, Message, Part, Role};
23
24/// Content of the user message sent in a run: text and media, in order.
25///
26/// Build it with [`Prompt::text`] and the `with_*` methods. Whether the model can read images
27/// or other media depends on the model; `agentai` does not check it, a model without vision
28/// support usually answers with an error.
29#[derive(Debug, Clone, Default, PartialEq)]
30pub struct Prompt {
31    parts: Vec<Part>,
32}
33
34impl Prompt {
35    /// Creates an empty prompt.
36    pub fn new() -> Self {
37        Self::default()
38    }
39
40    /// Returns `true` when the prompt has no parts, or only empty or whitespace text parts.
41    pub fn is_empty(&self) -> bool {
42        self.parts.iter().all(|part| match part {
43            Part::Text(text) => text.trim().is_empty(),
44            _ => false,
45        })
46    }
47
48    /// Creates a prompt with text.
49    pub fn text(text: impl Into<String>) -> Self {
50        Self::new().with_text(text)
51    }
52
53    /// Adds text.
54    pub fn with_text(mut self, text: impl Into<String>) -> Self {
55        self.parts.push(Part::Text(text.into()));
56        self
57    }
58
59    /// Adds an image, audio or other file.
60    pub fn with_media(mut self, media: Media) -> Self {
61        self.parts.push(Part::Media(media));
62        self
63    }
64
65    /// Adds an image the provider downloads from `url`. See [`Media::image_url`].
66    pub fn with_image_url(self, url: impl Into<String>) -> Self {
67        self.with_media(Media::image_url(url))
68    }
69
70    /// Adds an image from its bytes, for example `image/png`. See [`Media::from_bytes`].
71    pub fn with_image_bytes(
72        self,
73        content_type: impl Into<String>,
74        bytes: impl AsRef<[u8]>,
75    ) -> Self {
76        self.with_media(Media::from_bytes(content_type, bytes))
77    }
78
79    /// Returns the parts of the prompt: [`Part::Text`] and [`Part::Media`], in order.
80    pub fn parts(&self) -> &[Part] {
81        &self.parts
82    }
83}
84
85/// The user message sent to the model.
86impl From<Prompt> for Message {
87    fn from(prompt: Prompt) -> Self {
88        Message::new(Role::User, prompt.parts)
89    }
90}
91
92/// Anything that can be sent as a [`Prompt`]: text (`&str`, `String` and every other type that
93/// converts into `String`), a [`Prompt`] or a single [`Media`].
94pub trait IntoPrompt {
95    /// Converts the value into a prompt.
96    fn into_prompt(self) -> Prompt;
97}
98
99impl<T: Into<String>> IntoPrompt for T {
100    fn into_prompt(self) -> Prompt {
101        Prompt::text(self)
102    }
103}
104
105impl IntoPrompt for Prompt {
106    fn into_prompt(self) -> Prompt {
107        self
108    }
109}
110
111impl IntoPrompt for Media {
112    fn into_prompt(self) -> Prompt {
113        Prompt::new().with_media(self)
114    }
115}
116
117#[cfg(test)]
118mod tests {
119    use super::*;
120
121    #[test]
122    fn test_prompt_is_empty() {
123        assert!(Prompt::new().is_empty());
124        assert!(Prompt::text("").is_empty());
125        assert!(Prompt::text("   \n\t  ").is_empty());
126
127        assert!(!Prompt::text("hello").is_empty());
128        assert!(
129            !Prompt::new()
130                .with_media(Media::from_bytes("image/png", b"test"))
131                .is_empty()
132        );
133    }
134}