use std::collections::VecDeque;
use std::sync::Mutex;
use adk_core::{
AdkError, Content, ErrorCategory, ErrorComponent, FinishReason, Llm, LlmRequest, LlmResponse,
LlmResponseStream, NativeWebSearch, Part, Result, UsageMetadata,
};
use async_trait::async_trait;
use serde_json::Value;
pub const SCRIPT_EXHAUSTED_CODE: &str = "model.scripted.exhausted";
#[derive(Debug)]
pub struct ScriptedResponse {
responses: Vec<LlmResponse>,
stream_error: Option<AdkError>,
call_error: Option<AdkError>,
}
impl ScriptedResponse {
pub fn text(text: impl Into<String>) -> Self {
Self::response(final_response(vec![Part::Text { text: text.into() }]))
}
pub fn function_call(name: impl Into<String>, args: Value) -> Self {
Self::function_calls([(name, args)])
}
pub fn function_calls<N: Into<String>>(calls: impl IntoIterator<Item = (N, Value)>) -> Self {
let parts = calls
.into_iter()
.map(|(name, args)| Part::FunctionCall {
name: name.into(),
args,
id: None,
thought_signature: None,
})
.collect();
Self::response(final_response(parts))
}
pub fn response(response: LlmResponse) -> Self {
Self::stream([response])
}
pub fn stream(responses: impl IntoIterator<Item = LlmResponse>) -> Self {
Self { responses: responses.into_iter().collect(), stream_error: None, call_error: None }
}
pub fn error(error: AdkError) -> Self {
Self { responses: Vec::new(), stream_error: None, call_error: Some(error) }
}
pub fn then_error(mut self, error: AdkError) -> Self {
self.stream_error = Some(error);
self
}
pub fn with_usage(mut self, usage: UsageMetadata) -> Self {
if let Some(last) = self.responses.last_mut() {
last.usage_metadata = Some(usage);
}
self
}
}
impl From<LlmResponse> for ScriptedResponse {
fn from(response: LlmResponse) -> Self {
Self::response(response)
}
}
impl From<AdkError> for ScriptedResponse {
fn from(error: AdkError) -> Self {
Self::error(error)
}
}
fn final_response(parts: Vec<Part>) -> LlmResponse {
let mut response = LlmResponse::new(Content { role: "model".to_string(), parts });
response.finish_reason = Some(FinishReason::Stop);
response.turn_complete = true;
response
}
pub struct ScriptedLlm {
name: String,
script: Mutex<VecDeque<ScriptedResponse>>,
requests: Mutex<Vec<LlmRequest>>,
native_web_search: Option<NativeWebSearch>,
data_locality: adk_core::DataLocality,
data_destinations: Vec<adk_core::DataDestination>,
}
impl ScriptedLlm {
pub fn new<R: Into<ScriptedResponse>>(
name: impl Into<String>,
script: impl IntoIterator<Item = R>,
) -> Self {
Self {
name: name.into(),
script: Mutex::new(script.into_iter().map(Into::into).collect()),
requests: Mutex::new(Vec::new()),
native_web_search: None,
data_locality: adk_core::DataLocality::Remote,
data_destinations: Vec::new(),
}
}
pub fn with_native_web_search(mut self, search: NativeWebSearch) -> Self {
self.native_web_search = Some(search);
self
}
pub fn with_data_locality(mut self, locality: adk_core::DataLocality) -> Self {
self.data_locality = locality;
self
}
pub fn with_data_destination(mut self, destination: adk_core::DataDestination) -> Self {
self.data_destinations.push(destination);
self
}
pub fn push(&self, reply: impl Into<ScriptedResponse>) {
lock(&self.script).push_back(reply.into());
}
pub fn requests(&self) -> Vec<LlmRequest> {
lock(&self.requests).clone()
}
pub fn last_request(&self) -> Option<LlmRequest> {
lock(&self.requests).last().cloned()
}
pub fn remaining(&self) -> usize {
lock(&self.script).len()
}
}
fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
impl std::fmt::Debug for ScriptedLlm {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScriptedLlm")
.field("name", &self.name)
.field("remaining", &self.remaining())
.field("requests", &lock(&self.requests).len())
.finish()
}
}
#[async_trait]
impl Llm for ScriptedLlm {
fn name(&self) -> &str {
&self.name
}
fn native_web_search(&self) -> Option<NativeWebSearch> {
self.native_web_search
}
fn data_locality(&self) -> adk_core::DataLocality {
self.data_locality
}
fn data_destinations(&self) -> Vec<adk_core::DataDestination> {
self.data_destinations.clone()
}
async fn generate_content(
&self,
request: LlmRequest,
_stream: bool,
) -> Result<LlmResponseStream> {
let call = {
let mut requests = lock(&self.requests);
requests.push(request);
requests.len() - 1
};
let Some(reply) = lock(&self.script).pop_front() else {
return Err(AdkError::new(
ErrorComponent::Model,
ErrorCategory::Internal,
SCRIPT_EXHAUSTED_CODE,
format!(
"ScriptedLlm '{}' has no reply scripted for call {}; script one more reply \
or expect fewer model calls.",
self.name,
call + 1
),
));
};
if let Some(error) = reply.call_error {
return Err(error);
}
let mut index = 0;
let mut items: Vec<Result<LlmResponse>> = reply
.responses
.into_iter()
.map(|mut response| {
let parts =
response.content.iter_mut().flat_map(|content| content.parts.iter_mut());
for part in parts {
if let Part::FunctionCall { id, .. } = part {
if id.is_none() {
*id = Some(format!("scripted_tc_{call}_{index}"));
}
index += 1;
}
}
Ok(response)
})
.collect();
items.extend(reply.stream_error.map(Err));
Ok(Box::pin(futures::stream::iter(items)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use futures::StreamExt;
use serde_json::json;
async fn call(llm: &ScriptedLlm, text: &str) -> Result<Vec<Result<LlmResponse>>> {
let request = LlmRequest::new("m", vec![Content::new("user").with_text(text)]);
Ok(llm.generate_content(request, true).await?.collect().await)
}
#[tokio::test]
async fn each_call_gets_the_next_reply_and_is_recorded() {
let llm = ScriptedLlm::new(
"m",
[
ScriptedResponse::function_calls([("a", json!({ "x": 1 })), ("b", json!({}))]),
ScriptedResponse::text("done"),
],
);
let first = call(&llm, "one").await.unwrap();
assert_eq!(first.len(), 1);
let parts = &first[0].as_ref().unwrap().content.as_ref().unwrap().parts;
let ids: Vec<_> = parts
.iter()
.map(|part| match part {
Part::FunctionCall { id, .. } => id.clone(),
other => panic!("expected a function call, got {other:?}"),
})
.collect();
assert_eq!(ids, [Some("scripted_tc_0_0".to_string()), Some("scripted_tc_0_1".to_string())]);
let second = call(&llm, "two").await.unwrap();
let reply = second[0].as_ref().unwrap();
assert_eq!(reply.content.as_ref().unwrap().parts[0].text(), Some("done"));
assert!(reply.turn_complete);
assert_eq!(reply.finish_reason, Some(FinishReason::Stop));
let texts: Vec<_> = llm
.requests()
.iter()
.map(|request| request.contents[0].parts[0].text().unwrap().to_string())
.collect();
assert_eq!(texts, ["one", "two"]);
assert_eq!(llm.remaining(), 0);
}
#[tokio::test]
async fn an_exhausted_script_fails_the_call() {
let llm = ScriptedLlm::new("m", [ScriptedResponse::text("only")]);
call(&llm, "one").await.unwrap();
let err = call(&llm, "two").await.unwrap_err();
assert_eq!(err.code, SCRIPT_EXHAUSTED_CODE);
assert!(err.message.contains("call 2"), "{}", err.message);
assert_eq!(llm.requests().len(), 2, "the unanswered request is still recorded");
}
#[tokio::test]
async fn errors_usage_and_streams_are_scripted() {
let mut chunk = LlmResponse::new(Content::new("model").with_text("par"));
chunk.partial = true;
let llm = ScriptedLlm::new(
"m",
[
ScriptedResponse::error(AdkError::model("rate limited")),
ScriptedResponse::stream([
chunk,
final_response(vec![Part::Text { text: "partial".into() }]),
])
.with_usage(UsageMetadata { total_token_count: 7, ..Default::default() })
.then_error(AdkError::model("stream reset")),
],
);
assert_eq!(call(&llm, "a").await.unwrap_err().message, "rate limited");
let items = call(&llm, "b").await.unwrap();
assert_eq!(items.len(), 3);
assert!(items[0].as_ref().unwrap().partial);
assert_eq!(
items[1].as_ref().unwrap().usage_metadata.as_ref().unwrap().total_token_count,
7
);
assert_eq!(items[2].as_ref().unwrap_err().message, "stream reset");
}
#[tokio::test]
async fn scripted_ids_are_kept_and_replies_can_be_pushed() {
let mut response = final_response(vec![Part::FunctionCall {
name: "a".into(),
args: json!({}),
id: Some("call_mine".into()),
thought_signature: None,
}]);
response.model = Some("scripted".into());
let llm = ScriptedLlm::new("m", Vec::<ScriptedResponse>::new());
llm.push(response);
let items = call(&llm, "x").await.unwrap();
let reply = items[0].as_ref().unwrap();
assert!(matches!(
&reply.content.as_ref().unwrap().parts[0],
Part::FunctionCall { id: Some(id), .. } if id == "call_mine"
));
assert_eq!(llm.last_request().unwrap().contents[0].parts[0].text(), Some("x"));
}
}