Skip to main content

gemini_adk_rs/text/
run.rs

1//! One run of a text agent: what goes in ([`RunRequest`]), what comes out
2//! ([`RunResult`]), and a conversation that remembers ([`Chat`]).
3
4use futures_util::StreamExt;
5use futures_util::stream::BoxStream;
6use gemini_genai_rs::prelude::{Content, Part, Role};
7use serde::de::DeserializeOwned;
8
9use super::TextAgent;
10use crate::error::{AgentError, ToolError};
11use crate::llm::TokenUsage;
12use crate::state::State;
13
14/// What to run: the new user turn, the conversation before it, and optionally
15/// the JSON shape the reply must take.
16///
17/// ```
18/// use gemini_adk_rs::text::RunRequest;
19///
20/// let request = RunRequest::new("And in Celsius?")
21///     .history(vec![/* earlier turns, e.g. from `RunResult::messages` */]);
22/// assert_eq!(request.input_text(), "And in Celsius?");
23/// ```
24#[derive(Debug, Clone)]
25#[non_exhaustive]
26pub struct RunRequest {
27    /// The new user turn.
28    pub input: Content,
29    /// Earlier turns, oldest first, sent before `input`.
30    pub history: Vec<Content>,
31    /// A JSON Schema the reply must match; sent as the response schema by
32    /// agents that call a model.
33    pub response_schema: Option<serde_json::Value>,
34}
35
36impl RunRequest {
37    /// A request whose new turn is `text`.
38    pub fn new(text: impl Into<String>) -> Self {
39        Self::from_content(Content::user(text.into()))
40    }
41
42    /// A request whose new turn is `input` — text with images, audio or files.
43    pub fn from_content(input: Content) -> Self {
44        Self {
45            input,
46            history: Vec::new(),
47            response_schema: None,
48        }
49    }
50
51    /// Send `history` before the new turn.
52    pub fn history(mut self, history: Vec<Content>) -> Self {
53        self.history = history;
54        self
55    }
56
57    /// Require the reply to be JSON matching `schema`.
58    pub fn response_schema(mut self, schema: serde_json::Value) -> Self {
59        self.response_schema = Some(schema);
60        self
61    }
62
63    /// The text of the new turn, its text parts joined.
64    pub fn input_text(&self) -> String {
65        text_of(&self.input)
66    }
67}
68
69/// A tool call the model made during a run, and what it returned.
70#[derive(Debug, Clone)]
71#[non_exhaustive]
72pub struct ToolCallRecord {
73    /// The tool's name.
74    pub name: String,
75    /// The arguments the model supplied.
76    pub args: serde_json::Value,
77    /// What the tool returned, or why it did not run.
78    pub outcome: Result<serde_json::Value, ToolError>,
79}
80
81impl ToolCallRecord {
82    /// Record one call.
83    pub fn new(
84        name: impl Into<String>,
85        args: serde_json::Value,
86        outcome: Result<serde_json::Value, ToolError>,
87    ) -> Self {
88        Self {
89            name: name.into(),
90            args,
91            outcome,
92        }
93    }
94}
95
96/// The outcome of a run: the final text, and what it took to get there.
97#[derive(Debug, Clone, Default)]
98#[non_exhaustive]
99pub struct RunResult {
100    /// The final reply.
101    pub text: String,
102    /// The turns this run added, oldest first: the request's input, every
103    /// model turn and every tool response. Append them to the history to
104    /// continue the conversation.
105    pub messages: Vec<Content>,
106    /// Tokens used by this agent's own model calls. Composite agents
107    /// (pipelines, fan-outs) do not add up their children's usage.
108    pub usage: TokenUsage,
109    /// Every tool call, in order.
110    pub tool_calls: Vec<ToolCallRecord>,
111    /// How many times the model was called.
112    pub model_calls: u32,
113}
114
115impl RunResult {
116    /// A result carrying only its final text.
117    pub fn from_text(text: impl Into<String>) -> Self {
118        Self {
119            text: text.into(),
120            ..Self::default()
121        }
122    }
123
124    /// Parse the reply as JSON into `T`.
125    ///
126    /// A reply wrapped in a Markdown code fence is unwrapped first. Fails with
127    /// [`AgentError::InvalidOutput`], which names the type and carries the
128    /// reply.
129    pub fn parse<T: DeserializeOwned>(&self) -> Result<T, AgentError> {
130        serde_json::from_str(crate::utils::text::strip_code_fence(&self.text)).map_err(|e| {
131            AgentError::InvalidOutput {
132                expected: std::any::type_name::<T>(),
133                reason: e.to_string(),
134                text: self.text.clone(),
135            }
136        })
137    }
138}
139
140/// Something that happened during a streamed run; see
141/// [`TextAgent::run_stream`](super::TextAgent::run_stream).
142///
143/// Concatenating every [`TextDelta`](Self::TextDelta) gives the text of the
144/// model's turns; [`Finished`](Self::Finished) is always the last event of a
145/// successful run and carries the same [`RunResult`] `run_with` returns.
146#[derive(Debug, Clone)]
147#[non_exhaustive]
148pub enum RunEvent {
149    /// The next piece of the model's reply.
150    TextDelta(String),
151    /// The model called a tool; it runs next.
152    ToolCall {
153        /// The tool's name.
154        name: String,
155        /// The arguments the model supplied.
156        args: serde_json::Value,
157    },
158    /// A tool finished.
159    ToolResult(ToolCallRecord),
160    /// The run is over.
161    Finished(RunResult),
162}
163
164/// A conversation with an agent: every [`send`](Self::send) carries the turns
165/// before it, and the conversation keeps its own [`State`].
166///
167/// ```
168/// use gemini_adk_rs::llm::{LlmResponse, MockLlm};
169/// use gemini_adk_rs::text::{LlmTextAgent, TextAgent};
170///
171/// # tokio_test::block_on(async {
172/// let llm = MockLlm::script([
173///     LlmResponse::from_text("Nice to meet you, Ada."),
174///     LlmResponse::from_text("Your name is Ada."),
175/// ]);
176/// let agent = LlmTextAgent::new("assistant", llm.clone());
177///
178/// let mut chat = agent.chat();
179/// chat.send("Hi, I'm Ada.").await.unwrap();
180/// assert_eq!(chat.send("What's my name?").await.unwrap(), "Your name is Ada.");
181///
182/// // The second request carried the whole conversation.
183/// assert_eq!(llm.last_request().unwrap().contents.len(), 3);
184/// assert_eq!(chat.history().len(), 4);
185/// # });
186/// ```
187///
188/// `agent.chat()` borrows the agent; `Chat::new(agent)` takes it, for a
189/// conversation that outlives the scope that built the agent.
190pub struct Chat<A> {
191    agent: A,
192    history: Vec<Content>,
193    state: State,
194    usage: TokenUsage,
195}
196
197impl<A: TextAgent> Chat<A> {
198    /// A new conversation with `agent`, with empty history and fresh state.
199    pub fn new(agent: A) -> Self {
200        Self::with_state(agent, State::new())
201    }
202
203    /// A new conversation that reads and writes `state`.
204    pub fn with_state(agent: A, state: State) -> Self {
205        Self {
206            agent,
207            history: Vec::new(),
208            state,
209            usage: TokenUsage::default(),
210        }
211    }
212
213    /// Send a message and get the reply. The turn is added to the history
214    /// only when it succeeds.
215    pub async fn send(&mut self, message: impl Into<String>) -> Result<String, AgentError> {
216        Ok(self.send_request(RunRequest::new(message)).await?.text)
217    }
218
219    /// Send a request (media, a response schema) and get the full result.
220    /// The request's own history is replaced by the conversation's.
221    pub async fn send_request(&mut self, request: RunRequest) -> Result<RunResult, AgentError> {
222        let request = request.history(self.history.clone());
223        let result = self.agent.run_with(request, &self.state).await?;
224        self.history.extend(result.messages.iter().cloned());
225        self.usage += result.usage;
226        Ok(result)
227    }
228
229    /// Send a message and stream the reply; the turn joins the history when
230    /// the stream delivers [`RunEvent::Finished`].
231    pub fn send_stream(
232        &mut self,
233        message: impl Into<String>,
234    ) -> BoxStream<'_, Result<RunEvent, AgentError>> {
235        let request = RunRequest::new(message).history(self.history.clone());
236        let Chat {
237            agent,
238            history,
239            state,
240            usage,
241        } = self;
242        agent
243            .run_stream(request, state.clone())
244            .inspect(move |event| {
245                if let Ok(RunEvent::Finished(result)) = event {
246                    history.extend(result.messages.iter().cloned());
247                    *usage += result.usage;
248                }
249            })
250            .boxed()
251    }
252
253    /// Every turn so far, oldest first.
254    pub fn history(&self) -> &[Content] {
255        &self.history
256    }
257
258    /// Tokens used by the conversation so far.
259    pub fn usage(&self) -> TokenUsage {
260        self.usage
261    }
262
263    /// The conversation's state.
264    pub fn state(&self) -> &State {
265        &self.state
266    }
267
268    /// Forget the history (the state is kept).
269    pub fn clear(&mut self) {
270        self.history.clear();
271    }
272}
273
274/// The text parts of a turn, joined.
275pub(crate) fn text_of(content: &Content) -> String {
276    content
277        .parts
278        .iter()
279        .filter_map(|p| match p {
280            Part::Text { text } => Some(text.as_str()),
281            _ => None,
282        })
283        .collect()
284}
285
286/// A model turn saying `text`.
287pub(crate) fn model_turn(text: impl Into<String>) -> Content {
288    Content {
289        role: Some(Role::Model),
290        parts: vec![Part::Text { text: text.into() }],
291    }
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn parse_reads_plain_and_fenced_json() {
300        #[derive(serde::Deserialize, Debug, PartialEq)]
301        struct City {
302            name: String,
303        }
304        let plain = RunResult::from_text(r#"{"name":"Paris"}"#);
305        assert_eq!(plain.parse::<City>().unwrap().name, "Paris");
306        let fenced = RunResult::from_text("```json\n{\"name\": \"Lyon\"}\n```");
307        assert_eq!(fenced.parse::<City>().unwrap().name, "Lyon");
308        let err = RunResult::from_text("Paris").parse::<City>().unwrap_err();
309        assert!(
310            matches!(&err, AgentError::InvalidOutput { text, expected, .. }
311                if text == "Paris" && expected.ends_with("City")),
312            "{err}"
313        );
314    }
315
316    #[test]
317    fn request_text_joins_text_parts() {
318        let request = RunRequest::from_content(Content {
319            role: Some(Role::User),
320            parts: vec![
321                Part::Text { text: "a".into() },
322                Part::inline_data("image/png", "AAAA"),
323                Part::Text { text: "b".into() },
324            ],
325        });
326        assert_eq!(request.input_text(), "ab");
327    }
328}