1use 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
13pub const SCRIPT_EXHAUSTED_CODE: &str = "model.scripted.exhausted";
15
16#[derive(Debug)]
38pub struct ScriptedResponse {
39 responses: Vec<LlmResponse>,
40 stream_error: Option<AdkError>,
41 call_error: Option<AdkError>,
42}
43
44impl ScriptedResponse {
45 pub fn text(text: impl Into<String>) -> Self {
47 Self::response(final_response(vec![Part::Text { text: text.into() }]))
48 }
49
50 pub fn function_call(name: impl Into<String>, args: Value) -> Self {
54 Self::function_calls([(name, args)])
55 }
56
57 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 pub fn response(response: LlmResponse) -> Self {
73 Self::stream([response])
74 }
75
76 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 pub fn error(error: AdkError) -> Self {
83 Self { responses: Vec::new(), stream_error: None, call_error: Some(error) }
84 }
85
86 pub fn then_error(mut self, error: AdkError) -> Self {
88 self.stream_error = Some(error);
89 self
90 }
91
92 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
120pub 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 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 pub fn with_native_web_search(mut self, search: NativeWebSearch) -> Self {
205 self.native_web_search = Some(search);
206 self
207 }
208
209 pub fn with_data_locality(mut self, locality: adk_core::DataLocality) -> Self {
226 self.data_locality = locality;
227 self
228 }
229
230 pub fn with_data_destination(mut self, destination: adk_core::DataDestination) -> Self {
244 self.data_destinations.push(destination);
245 self
246 }
247
248 pub fn push(&self, reply: impl Into<ScriptedResponse>) {
250 lock(&self.script).push_back(reply.into());
251 }
252
253 pub fn requests(&self) -> Vec<LlmRequest> {
255 lock(&self.requests).clone()
256 }
257
258 pub fn last_request(&self) -> Option<LlmRequest> {
260 lock(&self.requests).last().cloned()
261 }
262
263 pub fn remaining(&self) -> usize {
265 lock(&self.script).len()
266 }
267}
268
269fn 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}