adk_tool/
stateful_tool.rs1use adk_core::{Result, Tool, ToolContext};
2use async_trait::async_trait;
3use schemars::{
4 JsonSchema,
5 generate::{SchemaGenerator, SchemaSettings},
6};
7use serde::Serialize;
8use serde_json::Value;
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12
13type AsyncStatefulHandler<S> = Box<
14 dyn Fn(
15 Arc<S>,
16 Arc<dyn ToolContext>,
17 Value,
18 ) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>>
19 + Send
20 + Sync,
21>;
22
23pub struct StatefulTool<S: Send + Sync + 'static> {
55 name: String,
56 description: String,
57 state: Arc<S>,
58 handler: AsyncStatefulHandler<S>,
59 long_running: bool,
60 read_only: bool,
61 concurrency_safe: bool,
62 parameters_schema: Option<Value>,
63 arguments: Option<crate::arguments::ArgumentCheck>,
64 lenient_args: bool,
65 response_schema: Option<Value>,
66 scopes: Vec<&'static str>,
67}
68
69impl<S: Send + Sync + 'static> StatefulTool<S> {
70 pub fn new<F, Fut>(
79 name: impl Into<String>,
80 description: impl Into<String>,
81 state: Arc<S>,
82 handler: F,
83 ) -> Self
84 where
85 F: Fn(Arc<S>, Arc<dyn ToolContext>, Value) -> Fut + Send + Sync + 'static,
86 Fut: Future<Output = Result<Value>> + Send + 'static,
87 {
88 Self {
89 name: name.into(),
90 description: description.into(),
91 state,
92 handler: Box::new(move |s, ctx, args| Box::pin(handler(s, ctx, args))),
93 long_running: false,
94 read_only: false,
95 concurrency_safe: false,
96 parameters_schema: None,
97 arguments: None,
98 lenient_args: false,
99 response_schema: None,
100 scopes: Vec::new(),
101 }
102 }
103
104 pub fn with_long_running(mut self, long_running: bool) -> Self {
106 self.long_running = long_running;
107 self
108 }
109
110 pub fn with_read_only(mut self, read_only: bool) -> Self {
112 self.read_only = read_only;
113 self
114 }
115
116 pub fn with_concurrency_safe(mut self, concurrency_safe: bool) -> Self {
118 self.concurrency_safe = concurrency_safe;
119 self
120 }
121
122 pub fn with_parameters_schema<T>(mut self) -> Self
126 where
127 T: JsonSchema + Serialize,
128 {
129 self.parameters_schema = Some(generate_schema::<T>());
130 self.arguments = Some(crate::arguments::ArgumentCheck::for_type::<T>());
131 self
132 }
133
134 pub fn with_lenient_args(mut self, lenient: bool) -> Self {
137 self.lenient_args = lenient;
138 self
139 }
140
141 pub fn with_response_schema<T>(mut self) -> Self
143 where
144 T: JsonSchema + Serialize,
145 {
146 self.response_schema = Some(generate_schema::<T>());
147 self
148 }
149
150 pub fn with_scopes(mut self, scopes: &[&'static str]) -> Self {
155 self.scopes = scopes.to_vec();
156 self
157 }
158
159 pub fn parameters_schema(&self) -> Option<&Value> {
161 self.parameters_schema.as_ref()
162 }
163
164 pub fn response_schema(&self) -> Option<&Value> {
166 self.response_schema.as_ref()
167 }
168}
169
170const LONG_RUNNING_NOTE: &str = "NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.";
172
173#[async_trait]
174impl<S: Send + Sync + 'static> Tool for StatefulTool<S> {
175 fn name(&self) -> &str {
176 &self.name
177 }
178
179 fn description(&self) -> &str {
180 &self.description
181 }
182
183 fn enhanced_description(&self) -> String {
184 if self.long_running {
185 if self.description.is_empty() {
186 LONG_RUNNING_NOTE.to_string()
187 } else {
188 format!("{}\n\n{}", self.description, LONG_RUNNING_NOTE)
189 }
190 } else {
191 self.description.clone()
192 }
193 }
194
195 fn is_long_running(&self) -> bool {
196 self.long_running
197 }
198
199 fn is_read_only(&self) -> bool {
200 self.read_only
201 }
202
203 fn is_concurrency_safe(&self) -> bool {
204 self.concurrency_safe
205 }
206
207 fn parameters_schema(&self) -> Option<Value> {
208 self.parameters_schema.clone()
209 }
210
211 fn response_schema(&self) -> Option<Value> {
212 self.response_schema.clone()
213 }
214
215 fn required_scopes(&self) -> &[&str] {
216 &self.scopes
217 }
218
219 #[adk_telemetry::instrument(
220 skip(self, ctx, args),
221 fields(
222 tool.name = %self.name,
223 tool.description = %self.description,
224 tool.long_running = %self.long_running,
225 function_call.id = %ctx.function_call_id()
226 )
227 )]
228 async fn execute(&self, ctx: Arc<dyn ToolContext>, mut args: Value) -> Result<Value> {
229 adk_telemetry::debug!("Executing stateful tool");
230 if let Some(check) = &self.arguments {
231 check.apply(&self.name, self.lenient_args, &mut args)?;
232 }
233 let state = Arc::clone(&self.state);
234 (self.handler)(state, ctx, args).await
235 }
236}
237
238fn generate_schema<T>() -> Value
239where
240 T: JsonSchema + Serialize,
241{
242 let settings = SchemaSettings::openapi3().with(|s| {
243 s.inline_subschemas = true;
244 s.meta_schema = None;
245 });
246 let generator = SchemaGenerator::new(settings);
247 let mut schema = generator.into_root_schema_for::<T>();
248 if let Some(object) = schema.as_object_mut() {
249 object.remove("title");
250 }
251 serde_json::to_value(schema).unwrap()
252}