Skip to main content

adk_model/
scripted.rs

1//! A scripted [`Llm`](adk_core::Llm) for tests: one scripted reply per call, with every request recorded.
2
3use std::collections::VecDeque;
4use std::sync::Mutex;
5
6use adk_core::{
7    AdkError, Content, ErrorCategory, ErrorComponent, FinishReason, Llm, LlmRequest, LlmResponse,
8    LlmResponseStream, NativeWebSearch, Part, Result, UsageMetadata,
9};
10use async_trait::async_trait;
11use serde_json::Value;
12
13/// The error code [`ScriptedLlm`] fails a call with once its script is used up.
14pub const SCRIPT_EXHAUSTED_CODE: &str = "model.scripted.exhausted";
15
16/// What a [`ScriptedLlm`] answers to one `generate_content` call.
17///
18/// A reply is a stream of responses, optionally followed by a stream error, or a call that
19/// fails outright. Build one with [`text`](Self::text), [`function_call`](Self::function_call),
20/// [`stream`](Self::stream) or [`error`](Self::error); an [`LlmResponse`] converts into a
21/// one-response reply.
22///
23/// # Example
24///
25/// ```rust
26/// use adk_core::{AdkError, UsageMetadata};
27/// use adk_model::ScriptedResponse;
28/// use serde_json::json;
29///
30/// let call = ScriptedResponse::function_call("get_weather", json!({ "city": "Nairobi" }));
31/// let answer = ScriptedResponse::text("It is sunny.")
32///     .with_usage(UsageMetadata { prompt_token_count: 12, ..Default::default() });
33/// let cut = ScriptedResponse::text("It is").then_error(AdkError::model("stream reset"));
34/// let refused = ScriptedResponse::error(AdkError::model("rate limited"));
35/// # let _ = (call, answer, cut, refused);
36/// ```
37#[derive(Debug)]
38pub struct ScriptedResponse {
39    responses: Vec<LlmResponse>,
40    stream_error: Option<AdkError>,
41    call_error: Option<AdkError>,
42}
43
44impl ScriptedResponse {
45    /// A final model response with one text part.
46    pub fn text(text: impl Into<String>) -> Self {
47        Self::response(final_response(vec![Part::Text { text: text.into() }]))
48    }
49
50    /// A final model response with one function call.
51    ///
52    /// The call has no ID; [`ScriptedLlm`] assigns one when it replies.
53    pub fn function_call(name: impl Into<String>, args: Value) -> Self {
54        Self::function_calls([(name, args)])
55    }
56
57    /// A final model response with several function calls, in order.
58    pub fn function_calls<N: Into<String>>(calls: impl IntoIterator<Item = (N, Value)>) -> Self {
59        let parts = calls
60            .into_iter()
61            .map(|(name, args)| Part::FunctionCall {
62                name: name.into(),
63                args,
64                id: None,
65                thought_signature: None,
66            })
67            .collect();
68        Self::response(final_response(parts))
69    }
70
71    /// A reply of exactly `response`.
72    pub fn response(response: LlmResponse) -> Self {
73        Self::stream([response])
74    }
75
76    /// A reply that streams `responses` in order, as given.
77    pub fn stream(responses: impl IntoIterator<Item = LlmResponse>) -> Self {
78        Self { responses: responses.into_iter().collect(), stream_error: None, call_error: None }
79    }
80
81    /// A call that fails: `generate_content` returns `error` instead of a stream.
82    pub fn error(error: AdkError) -> Self {
83        Self { responses: Vec::new(), stream_error: None, call_error: Some(error) }
84    }
85
86    /// Ends the stream with `error` after its responses, as a provider whose stream breaks.
87    pub fn then_error(mut self, error: AdkError) -> Self {
88        self.stream_error = Some(error);
89        self
90    }
91
92    /// Reports `usage` on the reply's last response.
93    pub fn with_usage(mut self, usage: UsageMetadata) -> Self {
94        if let Some(last) = self.responses.last_mut() {
95            last.usage_metadata = Some(usage);
96        }
97        self
98    }
99}
100
101impl From<LlmResponse> for ScriptedResponse {
102    fn from(response: LlmResponse) -> Self {
103        Self::response(response)
104    }
105}
106
107impl From<AdkError> for ScriptedResponse {
108    fn from(error: AdkError) -> Self {
109        Self::error(error)
110    }
111}
112
113fn final_response(parts: Vec<Part>) -> LlmResponse {
114    let mut response = LlmResponse::new(Content { role: "model".to_string(), parts });
115    response.finish_reason = Some(FinishReason::Stop);
116    response.turn_complete = true;
117    response
118}
119
120/// A test double for [`Llm`] that answers each call with the next scripted reply and records
121/// every request.
122///
123/// Script one [`ScriptedResponse`] per model call: a tool loop that calls one tool and then
124/// answers is two replies, a function call and a text. [`requests`](Self::requests) returns
125/// what the agent sent on each call, so a test can assert on the history, tool declarations,
126/// and configuration the model received. A call past the end of the script fails with
127/// [`SCRIPT_EXHAUSTED_CODE`], so a test that runs more model turns than it expects fails
128/// instead of passing on a made-up reply.
129///
130/// A function call scripted without an ID is given `scripted_tc_{call}_{index}`, where `call`
131/// counts `generate_content` calls from 0 and `index` counts the reply's function calls.
132///
133/// [`MockLlm`](crate::MockLlm) replays its whole response list on every call; use
134/// `ScriptedLlm` to script more than one turn.
135///
136/// # Example
137///
138/// ```rust
139/// use adk_core::Llm;
140/// use adk_model::{ScriptedLlm, ScriptedResponse};
141/// use futures::StreamExt;
142/// use serde_json::json;
143///
144/// # #[tokio::main(flavor = "current_thread")]
145/// # async fn main() -> Result<(), adk_core::AdkError> {
146/// let llm = ScriptedLlm::new(
147///     "scripted",
148///     [
149///         ScriptedResponse::function_call("get_weather", json!({ "city": "Nairobi" })),
150///         ScriptedResponse::text("It is sunny in Nairobi."),
151///     ],
152/// );
153///
154/// let request = adk_core::LlmRequest::new("scripted", vec![]);
155/// let first = llm.generate_content(request, false).await?.next().await.unwrap()?;
156/// assert!(first.content.unwrap().has_function_calls());
157/// assert_eq!(llm.requests().len(), 1);
158/// assert_eq!(llm.remaining(), 1);
159/// # Ok(())
160/// # }
161/// ```
162pub struct ScriptedLlm {
163    name: String,
164    script: Mutex<VecDeque<ScriptedResponse>>,
165    requests: Mutex<Vec<LlmRequest>>,
166    native_web_search: Option<NativeWebSearch>,
167    data_locality: adk_core::DataLocality,
168    data_destinations: Vec<adk_core::DataDestination>,
169}
170
171impl ScriptedLlm {
172    /// Creates a model named `name` that answers its calls with `script`, in order.
173    ///
174    /// Each item is anything that converts into a [`ScriptedResponse`], such as an
175    /// [`LlmResponse`].
176    pub fn new<R: Into<ScriptedResponse>>(
177        name: impl Into<String>,
178        script: impl IntoIterator<Item = R>,
179    ) -> Self {
180        Self {
181            name: name.into(),
182            script: Mutex::new(script.into_iter().map(Into::into).collect()),
183            requests: Mutex::new(Vec::new()),
184            native_web_search: None,
185            data_locality: adk_core::DataLocality::Remote,
186            data_destinations: Vec::new(),
187        }
188    }
189
190    /// Reports `search` from [`Llm::native_web_search`], so a test stands in for a client
191    /// whose transport serves that provider's built-in search (spec 3.1 ยง7.20).
192    ///
193    /// # Example
194    ///
195    /// ```rust
196    /// use adk_core::{Llm, NativeWebSearch, NativeWebSearchTool};
197    /// use adk_model::{ScriptedLlm, ScriptedResponse};
198    ///
199    /// let search = NativeWebSearch::new("gemini", NativeWebSearchTool::GoogleSearch, false);
200    /// let llm = ScriptedLlm::new("gemini-3.5-flash-lite", Vec::<ScriptedResponse>::new())
201    ///     .with_native_web_search(search);
202    /// assert_eq!(llm.native_web_search(), Some(search));
203    /// ```
204    pub fn with_native_web_search(mut self, search: NativeWebSearch) -> Self {
205        self.native_web_search = Some(search);
206        self
207    }
208
209    /// Reports `locality` from [`Llm::data_locality`], so a test stands in for a local or
210    /// loopback model. The default is [`DataLocality::Remote`](adk_core::DataLocality::Remote),
211    /// as for any hosted provider.
212    ///
213    /// # Example
214    ///
215    /// ```rust
216    /// use adk_core::{DataLocality, Llm};
217    /// use adk_model::{ScriptedLlm, ScriptedResponse};
218    ///
219    /// let remote = ScriptedLlm::new("claude-sonnet-5-5", Vec::<ScriptedResponse>::new());
220    /// assert_eq!(remote.data_locality(), DataLocality::Remote);
221    /// let local = ScriptedLlm::new("qwen3-vl-8b", Vec::<ScriptedResponse>::new())
222    ///     .with_data_locality(DataLocality::InProcess);
223    /// assert_eq!(local.data_locality(), DataLocality::InProcess);
224    /// ```
225    pub fn with_data_locality(mut self, locality: adk_core::DataLocality) -> Self {
226        self.data_locality = locality;
227        self
228    }
229
230    /// Reports `destination` from [`Llm::data_destinations`], so a test stands in for a
231    /// hosted provider's client. None by default.
232    ///
233    /// # Example
234    ///
235    /// ```rust
236    /// use adk_core::{DataDestination, Llm};
237    /// use adk_model::{ScriptedLlm, ScriptedResponse};
238    ///
239    /// let claude = ScriptedLlm::new("claude-sonnet-5-5", Vec::<ScriptedResponse>::new())
240    ///     .with_data_destination(DataDestination::new("anthropic", ["api.anthropic.com"]));
241    /// assert_eq!(claude.data_destinations()[0].hosts, ["api.anthropic.com"]);
242    /// ```
243    pub fn with_data_destination(mut self, destination: adk_core::DataDestination) -> Self {
244        self.data_destinations.push(destination);
245        self
246    }
247
248    /// Appends a reply to the end of the script.
249    pub fn push(&self, reply: impl Into<ScriptedResponse>) {
250        lock(&self.script).push_back(reply.into());
251    }
252
253    /// Every request received so far, in call order.
254    pub fn requests(&self) -> Vec<LlmRequest> {
255        lock(&self.requests).clone()
256    }
257
258    /// The most recent request, if any.
259    pub fn last_request(&self) -> Option<LlmRequest> {
260        lock(&self.requests).last().cloned()
261    }
262
263    /// How many scripted replies have not been used yet.
264    pub fn remaining(&self) -> usize {
265        lock(&self.script).len()
266    }
267}
268
269/// A poisoned lock only means another test thread panicked; the data is still usable.
270fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
271    mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
272}
273
274impl std::fmt::Debug for ScriptedLlm {
275    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
276        f.debug_struct("ScriptedLlm")
277            .field("name", &self.name)
278            .field("remaining", &self.remaining())
279            .field("requests", &lock(&self.requests).len())
280            .finish()
281    }
282}
283
284#[async_trait]
285impl Llm for ScriptedLlm {
286    fn name(&self) -> &str {
287        &self.name
288    }
289
290    fn native_web_search(&self) -> Option<NativeWebSearch> {
291        self.native_web_search
292    }
293
294    fn data_locality(&self) -> adk_core::DataLocality {
295        self.data_locality
296    }
297
298    fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
299        self.data_destinations.clone()
300    }
301
302    async fn generate_content(
303        &self,
304        request: LlmRequest,
305        _stream: bool,
306    ) -> Result<LlmResponseStream> {
307        let call = {
308            let mut requests = lock(&self.requests);
309            requests.push(request);
310            requests.len() - 1
311        };
312        let Some(reply) = lock(&self.script).pop_front() else {
313            return Err(AdkError::new(
314                ErrorComponent::Model,
315                ErrorCategory::Internal,
316                SCRIPT_EXHAUSTED_CODE,
317                format!(
318                    "ScriptedLlm '{}' has no reply scripted for call {}; script one more reply \
319                     or expect fewer model calls.",
320                    self.name,
321                    call + 1
322                ),
323            ));
324        };
325        if let Some(error) = reply.call_error {
326            return Err(error);
327        }
328
329        let mut index = 0;
330        let mut items: Vec<Result<LlmResponse>> = reply
331            .responses
332            .into_iter()
333            .map(|mut response| {
334                let parts =
335                    response.content.iter_mut().flat_map(|content| content.parts.iter_mut());
336                for part in parts {
337                    if let Part::FunctionCall { id, .. } = part {
338                        if id.is_none() {
339                            *id = Some(format!("scripted_tc_{call}_{index}"));
340                        }
341                        index += 1;
342                    }
343                }
344                Ok(response)
345            })
346            .collect();
347        items.extend(reply.stream_error.map(Err));
348        Ok(Box::pin(futures::stream::iter(items)))
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355    use futures::StreamExt;
356    use serde_json::json;
357
358    async fn call(llm: &ScriptedLlm, text: &str) -> Result<Vec<Result<LlmResponse>>> {
359        let request = LlmRequest::new("m", vec![Content::new("user").with_text(text)]);
360        Ok(llm.generate_content(request, true).await?.collect().await)
361    }
362
363    #[tokio::test]
364    async fn each_call_gets_the_next_reply_and_is_recorded() {
365        let llm = ScriptedLlm::new(
366            "m",
367            [
368                ScriptedResponse::function_calls([("a", json!({ "x": 1 })), ("b", json!({}))]),
369                ScriptedResponse::text("done"),
370            ],
371        );
372
373        let first = call(&llm, "one").await.unwrap();
374        assert_eq!(first.len(), 1);
375        let parts = &first[0].as_ref().unwrap().content.as_ref().unwrap().parts;
376        let ids: Vec<_> = parts
377            .iter()
378            .map(|part| match part {
379                Part::FunctionCall { id, .. } => id.clone(),
380                other => panic!("expected a function call, got {other:?}"),
381            })
382            .collect();
383        assert_eq!(ids, [Some("scripted_tc_0_0".to_string()), Some("scripted_tc_0_1".to_string())]);
384
385        let second = call(&llm, "two").await.unwrap();
386        let reply = second[0].as_ref().unwrap();
387        assert_eq!(reply.content.as_ref().unwrap().parts[0].text(), Some("done"));
388        assert!(reply.turn_complete);
389        assert_eq!(reply.finish_reason, Some(FinishReason::Stop));
390
391        let texts: Vec<_> = llm
392            .requests()
393            .iter()
394            .map(|request| request.contents[0].parts[0].text().unwrap().to_string())
395            .collect();
396        assert_eq!(texts, ["one", "two"]);
397        assert_eq!(llm.remaining(), 0);
398    }
399
400    #[tokio::test]
401    async fn an_exhausted_script_fails_the_call() {
402        let llm = ScriptedLlm::new("m", [ScriptedResponse::text("only")]);
403        call(&llm, "one").await.unwrap();
404        let err = call(&llm, "two").await.unwrap_err();
405        assert_eq!(err.code, SCRIPT_EXHAUSTED_CODE);
406        assert!(err.message.contains("call 2"), "{}", err.message);
407        assert_eq!(llm.requests().len(), 2, "the unanswered request is still recorded");
408    }
409
410    #[tokio::test]
411    async fn errors_usage_and_streams_are_scripted() {
412        let mut chunk = LlmResponse::new(Content::new("model").with_text("par"));
413        chunk.partial = true;
414        let llm = ScriptedLlm::new(
415            "m",
416            [
417                ScriptedResponse::error(AdkError::model("rate limited")),
418                ScriptedResponse::stream([
419                    chunk,
420                    final_response(vec![Part::Text { text: "partial".into() }]),
421                ])
422                .with_usage(UsageMetadata { total_token_count: 7, ..Default::default() })
423                .then_error(AdkError::model("stream reset")),
424            ],
425        );
426        assert_eq!(call(&llm, "a").await.unwrap_err().message, "rate limited");
427
428        let items = call(&llm, "b").await.unwrap();
429        assert_eq!(items.len(), 3);
430        assert!(items[0].as_ref().unwrap().partial);
431        assert_eq!(
432            items[1].as_ref().unwrap().usage_metadata.as_ref().unwrap().total_token_count,
433            7
434        );
435        assert_eq!(items[2].as_ref().unwrap_err().message, "stream reset");
436    }
437
438    #[tokio::test]
439    async fn scripted_ids_are_kept_and_replies_can_be_pushed() {
440        let mut response = final_response(vec![Part::FunctionCall {
441            name: "a".into(),
442            args: json!({}),
443            id: Some("call_mine".into()),
444            thought_signature: None,
445        }]);
446        response.model = Some("scripted".into());
447        let llm = ScriptedLlm::new("m", Vec::<ScriptedResponse>::new());
448        llm.push(response);
449        let items = call(&llm, "x").await.unwrap();
450        let reply = items[0].as_ref().unwrap();
451        assert!(matches!(
452            &reply.content.as_ref().unwrap().parts[0],
453            Part::FunctionCall { id: Some(id), .. } if id == "call_mine"
454        ));
455        assert_eq!(llm.last_request().unwrap().contents[0].parts[0].text(), Some("x"));
456    }
457}