Skip to main content

gemini_adk_rs/llm/
mock.rs

1//! [`MockLlm`]: a scripted, inspectable model for tests.
2
3use std::collections::VecDeque;
4use std::fmt;
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use parking_lot::Mutex;
9
10use super::{BaseLlm, LlmError, LlmRequest, LlmResponse, LlmStream};
11
12type ReplyFn = dyn Fn(&LlmRequest) -> Result<LlmResponse, LlmError> + Send + Sync;
13
14enum Replies {
15    Repeat(LlmResponse),
16    Script(VecDeque<Result<LlmResponse, LlmError>>),
17    Function(Box<ReplyFn>),
18}
19
20struct Inner {
21    replies: Mutex<Replies>,
22    requests: Mutex<Vec<LlmRequest>>,
23}
24
25/// A [`BaseLlm`] that replies from a script or a closure and records every
26/// request, for tests that must not reach a provider.
27///
28/// It replies three ways, one per kind of test:
29///
30/// | Constructor | Replies with | Use it to test |
31/// |---|---|---|
32/// | [`MockLlm::text`] | the same text, every call | wiring, prompts, state flow |
33/// | [`MockLlm::script`] | each response in turn, then an error | tool rounds, retries, multi-turn |
34/// | [`MockLlm::from_fn`] | whatever the closure returns | replies that depend on the request |
35/// | [`MockLlm::echo`] | the request's own text | prompt rendering and interpolation |
36///
37/// Every call's [`LlmRequest`] is recorded, so a test can assert on what the
38/// agent actually sent — instructions, history, tool declarations, sampling —
39/// not only on what came back.
40///
41/// `MockLlm` is a cheap handle: clones share the script and the recording.
42/// Give one clone to the agent and keep one to inspect.
43///
44/// ```
45/// use gemini_adk_rs::llm::{BaseLlm, LlmRequest, LlmResponse, MockLlm};
46///
47/// # tokio_test::block_on(async {
48/// let llm = MockLlm::script([
49///     LlmResponse::tool_call("get_weather", serde_json::json!({ "city": "Paris" })),
50///     LlmResponse::from_text("It is sunny in Paris."),
51/// ]);
52///
53/// let first = llm.generate(LlmRequest::from_text("Weather in Paris?")).await.unwrap();
54/// assert_eq!(first.function_calls()[0].name, "get_weather");
55///
56/// let second = llm.generate(LlmRequest::from_text("…")).await.unwrap();
57/// assert_eq!(second.text(), "It is sunny in Paris.");
58///
59/// // The script is spent: a third call is a test failure, not a silent reply.
60/// assert!(llm.generate(LlmRequest::from_text("again")).await.is_err());
61/// assert_eq!(llm.requests().len(), 3);
62/// # });
63/// ```
64#[derive(Clone)]
65pub struct MockLlm {
66    model_id: String,
67    inner: Arc<Inner>,
68}
69
70impl MockLlm {
71    fn with_replies(replies: Replies) -> Self {
72        Self {
73            model_id: "mock".into(),
74            inner: Arc::new(Inner {
75                replies: Mutex::new(replies),
76                requests: Mutex::new(Vec::new()),
77            }),
78        }
79    }
80
81    /// Reply with `text` to every request.
82    pub fn text(text: impl Into<String>) -> Self {
83        Self::with_replies(Replies::Repeat(LlmResponse::from_text(text)))
84    }
85
86    /// Reply with each response in order.
87    ///
88    /// A call after the script is spent returns an error naming the call, so
89    /// an agent that makes one model call more than the test expected fails
90    /// instead of receiving a plausible reply.
91    pub fn script(responses: impl IntoIterator<Item = LlmResponse>) -> Self {
92        Self::with_replies(Replies::Script(responses.into_iter().map(Ok).collect()))
93    }
94
95    /// Reply by calling `reply` with the request.
96    ///
97    /// This is the programmable mock: branch on the conversation so far, echo
98    /// the prompt, or return an error for a particular input.
99    pub fn from_fn<F>(reply: F) -> Self
100    where
101        F: Fn(&LlmRequest) -> Result<LlmResponse, LlmError> + Send + Sync + 'static,
102    {
103        Self::with_replies(Replies::Function(Box::new(reply)))
104    }
105
106    /// Reply with the text of the request: every text part of every content,
107    /// joined in order. For tests that assert on the prompt an agent built.
108    pub fn echo() -> Self {
109        Self::from_fn(|request| {
110            let text: String = request
111                .contents
112                .iter()
113                .flat_map(|content| &content.parts)
114                .filter_map(|part| match part {
115                    gemini_genai_rs::prelude::Part::Text { text } => Some(text.as_str()),
116                    _ => None,
117                })
118                .collect();
119            Ok(LlmResponse::from_text(text))
120        })
121    }
122
123    /// Append a failure to a script, to test how an agent handles a provider
124    /// error at that point in the conversation.
125    ///
126    /// # Panics
127    ///
128    /// On a mock built with [`text`](Self::text) or [`from_fn`](Self::from_fn):
129    /// those have no sequence to append to, and a closure can return the error
130    /// itself.
131    pub fn then_fail(self, error: LlmError) -> Self {
132        match &mut *self.inner.replies.lock() {
133            Replies::Script(queue) => queue.push_back(Err(error)),
134            _ => panic!("MockLlm::then_fail applies to MockLlm::script only"),
135        }
136        self
137    }
138
139    /// Report `model_id` from [`BaseLlm::model_id`] instead of `"mock"`.
140    pub fn with_model_id(mut self, model_id: impl Into<String>) -> Self {
141        self.model_id = model_id.into();
142        self
143    }
144
145    /// Every request received so far, oldest first.
146    pub fn requests(&self) -> Vec<LlmRequest> {
147        self.inner.requests.lock().clone()
148    }
149
150    /// The most recent request, if any.
151    pub fn last_request(&self) -> Option<LlmRequest> {
152        self.inner.requests.lock().last().cloned()
153    }
154
155    /// How many times the model has been called.
156    pub fn call_count(&self) -> usize {
157        self.inner.requests.lock().len()
158    }
159}
160
161impl fmt::Debug for MockLlm {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        let replies = match &*self.inner.replies.lock() {
164            Replies::Repeat(_) => "repeat".to_string(),
165            Replies::Script(queue) => format!("script({} left)", queue.len()),
166            Replies::Function(_) => "fn".to_string(),
167        };
168        f.debug_struct("MockLlm")
169            .field("model_id", &self.model_id)
170            .field("replies", &replies)
171            .field("calls", &self.call_count())
172            .finish()
173    }
174}
175
176#[async_trait]
177impl BaseLlm for MockLlm {
178    fn model_id(&self) -> &str {
179        &self.model_id
180    }
181
182    /// Streams a text reply one word at a time (usage and the finish reason
183    /// ride on the last chunk), so tests exercise the multi-chunk path; a
184    /// reply with tool calls arrives as one chunk.
185    async fn generate_stream(&self, request: LlmRequest) -> Result<LlmStream, LlmError> {
186        use futures_util::StreamExt;
187
188        let reply = self.generate(request).await?;
189        let words: Vec<String> = reply
190            .text()
191            .split_inclusive(' ')
192            .map(str::to_owned)
193            .collect();
194        if !reply.function_calls().is_empty() || words.len() < 2 {
195            return Ok(futures_util::stream::once(async move { Ok(reply) }).boxed());
196        }
197        let last = words.len() - 1;
198        let chunks: Vec<Result<LlmResponse, LlmError>> = words
199            .into_iter()
200            .enumerate()
201            .map(|(i, word)| {
202                let mut chunk = LlmResponse::from_text(word);
203                chunk.finish_reason = None;
204                if i == last {
205                    chunk.finish_reason = reply.finish_reason.clone();
206                    chunk.usage = reply.usage;
207                }
208                Ok(chunk)
209            })
210            .collect();
211        Ok(futures_util::stream::iter(chunks).boxed())
212    }
213
214    async fn generate(&self, request: LlmRequest) -> Result<LlmResponse, LlmError> {
215        let call = {
216            let mut requests = self.inner.requests.lock();
217            requests.push(request.clone());
218            requests.len()
219        };
220        match &mut *self.inner.replies.lock() {
221            Replies::Repeat(response) => Ok(response.clone()),
222            Replies::Script(queue) => queue.pop_front().unwrap_or_else(|| {
223                Err(LlmError::Other(format!(
224                    "MockLlm script exhausted: call {call} has no scripted reply \
225                     (the agent called the model more times than the test expected)"
226                )))
227            }),
228            Replies::Function(reply) => reply(&request),
229        }
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[tokio::test]
238    async fn text_replies_the_same_to_every_call() {
239        let llm = MockLlm::text("hi");
240        for _ in 0..3 {
241            let reply = llm.generate(LlmRequest::from_text("x")).await.unwrap();
242            assert_eq!(reply.text(), "hi");
243        }
244        assert_eq!(llm.call_count(), 3);
245    }
246
247    #[tokio::test]
248    async fn script_replies_in_order_then_fails_loudly() {
249        let llm = MockLlm::script([LlmResponse::from_text("one"), LlmResponse::from_text("two")]);
250        assert_eq!(
251            llm.generate(LlmRequest::default()).await.unwrap().text(),
252            "one"
253        );
254        assert_eq!(
255            llm.generate(LlmRequest::default()).await.unwrap().text(),
256            "two"
257        );
258        let spent = llm.generate(LlmRequest::default()).await.unwrap_err();
259        assert!(spent.to_string().contains("call 3"), "{spent}");
260    }
261
262    #[tokio::test]
263    async fn then_fail_injects_a_provider_error_at_that_step() {
264        let llm = MockLlm::script([LlmResponse::from_text("ok")]).then_fail(LlmError::RateLimited);
265        assert!(llm.generate(LlmRequest::default()).await.is_ok());
266        assert!(matches!(
267            llm.generate(LlmRequest::default()).await,
268            Err(LlmError::RateLimited)
269        ));
270    }
271
272    #[tokio::test]
273    async fn from_fn_sees_the_request() {
274        let llm = MockLlm::from_fn(|req| {
275            Ok(LlmResponse::from_text(format!(
276                "{} turns",
277                req.contents.len()
278            )))
279        });
280        let reply = llm.generate(LlmRequest::from_text("x")).await.unwrap();
281        assert_eq!(reply.text(), "1 turns");
282    }
283
284    #[tokio::test]
285    async fn echo_replies_with_the_request_text() {
286        let llm = MockLlm::echo();
287        let reply = llm
288            .generate(LlmRequest::from_text("say this"))
289            .await
290            .unwrap();
291        assert_eq!(reply.text(), "say this");
292        let none = llm.generate(LlmRequest::default()).await.unwrap();
293        assert_eq!(none.text(), "");
294    }
295
296    #[tokio::test]
297    async fn clones_share_the_script_and_the_recording() {
298        let llm = MockLlm::script([LlmResponse::from_text("a"), LlmResponse::from_text("b")]);
299        let handed_to_agent = llm.clone();
300        handed_to_agent
301            .generate(LlmRequest::from_text("first"))
302            .await
303            .unwrap();
304        assert_eq!(
305            llm.generate(LlmRequest::default()).await.unwrap().text(),
306            "b"
307        );
308        assert_eq!(llm.call_count(), 2);
309        assert_eq!(llm.requests()[0].contents.len(), 1);
310    }
311
312    #[tokio::test]
313    async fn with_model_id_keeps_the_replies() {
314        let llm = MockLlm::text("hi").with_model_id("gemini-test");
315        assert_eq!(llm.model_id(), "gemini-test");
316        assert_eq!(
317            llm.generate(LlmRequest::default()).await.unwrap().text(),
318            "hi"
319        );
320    }
321
322    #[test]
323    #[should_panic(expected = "script only")]
324    fn then_fail_on_a_repeating_mock_is_a_test_bug() {
325        let _ = MockLlm::text("hi").then_fail(LlmError::RateLimited);
326    }
327}