gadk_engine/tool/
exit_loop.rs1use std::any::Any;
19use std::collections::BTreeMap;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use gadk_agent::{Context, RunnableTool, Tool, ToolError};
24use schemars::JsonSchema;
25use serde::Deserialize;
26use serde_json::{Map, Value};
27
28use crate::tool::{FunctionTool, FunctionToolConfig};
29
30#[derive(Deserialize, JsonSchema)]
33struct ExitLoopArgs {}
34
35pub fn exit_loop() -> Arc<dyn Tool> {
42 let built = FunctionTool::new(
43 FunctionToolConfig::new(
44 "exit_loop",
45 "Exits the loop.\n\nCall this function only when you are instructed to do so.\n",
46 ),
47 |ctx: Context, _args: ExitLoopArgs| async move {
48 ctx.update_actions(|a| {
49 a.escalate = true;
50 a.skip_summarization = true;
51 });
52 Ok::<_, ToolError>(BTreeMap::<String, String>::new())
55 },
56 );
57 match built {
58 Ok(t) => t,
59 Err(e) => Arc::new(UnavailableExitLoop(format!(
60 "error creating exit loop tool: {e}"
61 ))),
62 }
63}
64
65struct UnavailableExitLoop(String);
68
69impl Tool for UnavailableExitLoop {
70 fn name(&self) -> &str {
71 "exit_loop"
72 }
73
74 fn description(&self) -> &str {
75 &self.0
76 }
77
78 fn as_runnable(&self) -> Option<&dyn RunnableTool> {
79 Some(self)
80 }
81
82 fn as_any(&self) -> &dyn Any {
83 self
84 }
85}
86
87#[async_trait]
88impl RunnableTool for UnavailableExitLoop {
89 async fn run(&self, _ctx: Context, _args: Value) -> Result<Map<String, Value>, ToolError> {
90 Err(ToolError::Execution(self.0.clone().into()))
91 }
92}
93
94#[cfg(test)]
95#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
96mod tests {
97 use super::*;
98 use serde_json::json;
99
100 #[tokio::test]
101 async fn exit_loop_sets_escalate_and_skip_summarization() {
102 let t = exit_loop();
103 assert_eq!(t.name(), "exit_loop");
104 assert_eq!(
105 t.description(),
106 "Exits the loop.\n\nCall this function only when you are instructed to do so.\n"
107 );
108 let ctx = Context::builder()
111 .build()
112 .with_delta(gadk_agent::ContextDelta {
113 function_call_id: Some("call".into()),
114 ..Default::default()
115 });
116 let out = t
117 .as_runnable()
118 .unwrap()
119 .run(ctx.clone(), json!({}))
120 .await
121 .unwrap();
122 assert!(out.is_empty());
123 let actions = ctx.actions();
124 assert!(actions.escalate && actions.skip_summarization);
125 }
126}