use std::any::Any;
use std::collections::BTreeMap;
use std::sync::Arc;
use async_trait::async_trait;
use gadk_agent::{Context, RunnableTool, Tool, ToolError};
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{Map, Value};
use crate::tool::{FunctionTool, FunctionToolConfig};
#[derive(Deserialize, JsonSchema)]
struct ExitLoopArgs {}
pub fn exit_loop() -> Arc<dyn Tool> {
let built = FunctionTool::new(
FunctionToolConfig::new(
"exit_loop",
"Exits the loop.\n\nCall this function only when you are instructed to do so.\n",
),
|ctx: Context, _args: ExitLoopArgs| async move {
ctx.update_actions(|a| {
a.escalate = true;
a.skip_summarization = true;
});
Ok::<_, ToolError>(BTreeMap::<String, String>::new())
},
);
match built {
Ok(t) => t,
Err(e) => Arc::new(UnavailableExitLoop(format!(
"error creating exit loop tool: {e}"
))),
}
}
struct UnavailableExitLoop(String);
impl Tool for UnavailableExitLoop {
fn name(&self) -> &str {
"exit_loop"
}
fn description(&self) -> &str {
&self.0
}
fn as_runnable(&self) -> Option<&dyn RunnableTool> {
Some(self)
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[async_trait]
impl RunnableTool for UnavailableExitLoop {
async fn run(&self, _ctx: Context, _args: Value) -> Result<Map<String, Value>, ToolError> {
Err(ToolError::Execution(self.0.clone().into()))
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
use super::*;
use serde_json::json;
#[tokio::test]
async fn exit_loop_sets_escalate_and_skip_summarization() {
let t = exit_loop();
assert_eq!(t.name(), "exit_loop");
assert_eq!(
t.description(),
"Exits the loop.\n\nCall this function only when you are instructed to do so.\n"
);
let ctx = Context::builder()
.build()
.with_delta(gadk_agent::ContextDelta {
function_call_id: Some("call".into()),
..Default::default()
});
let out = t
.as_runnable()
.unwrap()
.run(ctx.clone(), json!({}))
.await
.unwrap();
assert!(out.is_empty());
let actions = ctx.actions();
assert!(actions.escalate && actions.skip_summarization);
}
}