adk_code/embedded_python/
host_fn.rs1use std::collections::BTreeMap;
15use std::fmt;
16use std::future::Future;
17use std::pin::Pin;
18use std::sync::Arc;
19
20use async_trait::async_trait;
21use monty_types::MontyObject;
22use serde_json::{Map, Value};
23use thiserror::Error;
24
25#[derive(Debug, Error)]
31#[error("{message}")]
32pub struct HostFunctionError {
33 message: String,
34}
35
36impl HostFunctionError {
37 pub fn new(message: impl Into<String>) -> Self {
48 Self { message: message.into() }
49 }
50}
51
52impl From<String> for HostFunctionError {
53 fn from(message: String) -> Self {
54 Self::new(message)
55 }
56}
57
58impl From<&str> for HostFunctionError {
59 fn from(message: &str) -> Self {
60 Self::new(message)
61 }
62}
63
64#[derive(Debug, Error, Clone, PartialEq, Eq)]
68pub enum MontyBuildError {
69 #[error(
71 "host function name '{name}' is invalid: {reason}. \
72 Use a valid Python identifier (letters, digits, underscores; \
73 not starting with a digit; not a Python keyword)."
74 )]
75 InvalidFunctionName {
76 name: String,
78 reason: String,
80 },
81
82 #[error("host function name '{0}' is registered more than once; names must be unique")]
84 DuplicateFunctionName(String),
85
86 #[error(
90 "host function name '{0}' collides with a Python built-in; \
91 Monty resolves built-ins internally, so the function would never be called. \
92 Choose a different name."
93 )]
94 BuiltinCollision(String),
95
96 #[error(
98 "host function name '{0}' is reserved: the executor binds the request's \
99 JSON input to the `input` variable. Choose a different name."
100 )]
101 ReservedName(String),
102
103 #[error(
105 "mount path '{path}' is invalid: {reason}. \
106 Use a normalized absolute path such as \"/data\"."
107 )]
108 InvalidMountPath {
109 path: String,
111 reason: String,
113 },
114
115 #[error("mount path '{0}' is registered more than once; virtual paths must be unique")]
117 DuplicateMountPath(String),
118}
119
120#[async_trait]
165pub trait HostFunction: Send + Sync {
166 fn name(&self) -> &str;
168
169 fn description(&self) -> &str;
172
173 fn signature(&self) -> String {
177 format!("{}(...)", self.name())
178 }
179
180 async fn call(
186 &self,
187 args: Vec<Value>,
188 kwargs: Map<String, Value>,
189 ) -> Result<Value, HostFunctionError>;
190}
191
192type HostFnFuture = Pin<Box<dyn Future<Output = Result<Value, HostFunctionError>> + Send>>;
194
195type HostFnClosure = dyn Fn(Vec<Value>, Map<String, Value>) -> HostFnFuture + Send + Sync;
197
198pub(crate) struct ClosureHostFunction {
200 name: String,
201 description: String,
202 func: Arc<HostFnClosure>,
203}
204
205impl ClosureHostFunction {
206 pub(crate) fn new<F, Fut>(
207 name: impl Into<String>,
208 description: impl Into<String>,
209 func: F,
210 ) -> Self
211 where
212 F: Fn(Vec<Value>, Map<String, Value>) -> Fut + Send + Sync + 'static,
213 Fut: Future<Output = Result<Value, HostFunctionError>> + Send + 'static,
214 {
215 Self {
216 name: name.into(),
217 description: description.into(),
218 func: Arc::new(move |args, kwargs| Box::pin(func(args, kwargs))),
219 }
220 }
221}
222
223#[async_trait]
224impl HostFunction for ClosureHostFunction {
225 fn name(&self) -> &str {
226 &self.name
227 }
228
229 fn description(&self) -> &str {
230 &self.description
231 }
232
233 async fn call(
234 &self,
235 args: Vec<Value>,
236 kwargs: Map<String, Value>,
237 ) -> Result<Value, HostFunctionError> {
238 (self.func)(args, kwargs).await
239 }
240}
241
242const PYTHON_KEYWORDS: &[&str] = &[
245 "False", "None", "True", "and", "as", "assert", "async", "await", "break", "class", "continue",
246 "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import",
247 "in", "is", "lambda", "nonlocal", "not", "or", "pass", "raise", "return", "try", "while",
248 "with", "yield",
249];
250
251pub(crate) const INPUT_BINDING: &str = "input";
253
254#[derive(Clone, Default)]
257pub(crate) struct FunctionRegistry {
258 functions: BTreeMap<String, Arc<dyn HostFunction>>,
259}
260
261impl fmt::Debug for FunctionRegistry {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 f.debug_struct("FunctionRegistry")
264 .field("names", &self.functions.keys().collect::<Vec<_>>())
265 .finish()
266 }
267}
268
269impl FunctionRegistry {
270 pub(crate) fn build(functions: Vec<Arc<dyn HostFunction>>) -> Result<Self, MontyBuildError> {
277 let mut map: BTreeMap<String, Arc<dyn HostFunction>> = BTreeMap::new();
278 for function in functions {
279 let name = function.name().to_string();
280 validate_name(&name)?;
281 if map.insert(name.clone(), function).is_some() {
282 return Err(MontyBuildError::DuplicateFunctionName(name));
283 }
284 }
285 Ok(Self { functions: map })
286 }
287
288 pub(crate) fn is_empty(&self) -> bool {
289 self.functions.is_empty()
290 }
291
292 pub(crate) fn contains(&self, name: &str) -> bool {
293 self.functions.contains_key(name)
294 }
295
296 pub(crate) fn get(&self, name: &str) -> Option<&Arc<dyn HostFunction>> {
297 self.functions.get(name)
298 }
299
300 pub(crate) fn names(&self) -> impl Iterator<Item = &str> {
301 self.functions.keys().map(String::as_str)
302 }
303
304 pub(crate) fn iter(&self) -> impl Iterator<Item = &Arc<dyn HostFunction>> {
305 self.functions.values()
306 }
307
308 pub(crate) fn call_failure_message(&self, name: &str, method_call: bool) -> String {
312 if method_call && self.contains(name) {
313 return format!(
314 "'{name}' is a registered host function, not a method; \
315 call {name}(...) as a bare function"
316 );
317 }
318 self.unknown_function_message(name)
319 }
320
321 pub(crate) fn unknown_function_message(&self, name: &str) -> String {
324 if self.is_empty() {
325 format!("'{name}' is not defined and no host functions are registered")
326 } else {
327 format!(
328 "'{name}' is not defined; registered host functions: {}",
329 self.names().collect::<Vec<_>>().join(", ")
330 )
331 }
332 }
333}
334
335fn validate_name(name: &str) -> Result<(), MontyBuildError> {
338 let invalid = |reason: &str| MontyBuildError::InvalidFunctionName {
339 name: name.to_string(),
340 reason: reason.to_string(),
341 };
342 let mut chars = name.chars();
343 match chars.next() {
344 None => return Err(invalid("the name is empty")),
345 Some(first) if !first.is_ascii_alphabetic() && first != '_' => {
346 return Err(invalid("the first character must be a letter or underscore"));
347 }
348 Some(_) => {}
349 }
350 if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
351 return Err(invalid("only letters, digits, and underscores are allowed"));
352 }
353 if PYTHON_KEYWORDS.contains(&name) {
354 return Err(invalid("the name is a Python keyword"));
355 }
356 if name == INPUT_BINDING {
357 return Err(MontyBuildError::ReservedName(name.to_string()));
358 }
359 if MontyObject::builtin_function_from_name(name).is_some() {
360 return Err(MontyBuildError::BuiltinCollision(name.to_string()));
361 }
362 Ok(())
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368 use serde_json::json;
369
370 fn closure_fn(name: &str) -> Arc<dyn HostFunction> {
371 Arc::new(ClosureHostFunction::new(name, "test function", |args, _kwargs| async move {
372 Ok(json!(args.len()))
373 }))
374 }
375
376 #[test]
377 fn valid_names_build() {
378 let registry =
379 FunctionRegistry::build(vec![closure_fn("get_weather"), closure_fn("_private2")])
380 .unwrap();
381 assert!(registry.contains("get_weather"));
382 assert!(registry.contains("_private2"));
383 }
384
385 #[test]
386 fn invalid_identifier_is_rejected() {
387 for bad in ["", "2fast", "has-dash", "has space", "emoji🐍"] {
388 let err = FunctionRegistry::build(vec![closure_fn(bad)]).unwrap_err();
389 assert!(
390 matches!(err, MontyBuildError::InvalidFunctionName { .. }),
391 "expected InvalidFunctionName for {bad:?}, got {err:?}"
392 );
393 }
394 }
395
396 #[test]
397 fn keyword_is_rejected() {
398 let err = FunctionRegistry::build(vec![closure_fn("lambda")]).unwrap_err();
399 assert!(matches!(err, MontyBuildError::InvalidFunctionName { .. }));
400 }
401
402 #[test]
403 fn duplicate_name_is_rejected() {
404 let err = FunctionRegistry::build(vec![closure_fn("dup"), closure_fn("dup")]).unwrap_err();
405 assert_eq!(err, MontyBuildError::DuplicateFunctionName("dup".to_string()));
406 }
407
408 #[test]
409 fn builtin_collision_is_rejected() {
410 let err = FunctionRegistry::build(vec![closure_fn("len")]).unwrap_err();
411 assert_eq!(err, MontyBuildError::BuiltinCollision("len".to_string()));
412 }
413
414 #[test]
415 fn reserved_input_binding_is_rejected() {
416 let err = FunctionRegistry::build(vec![closure_fn("input")]).unwrap_err();
417 assert_eq!(err, MontyBuildError::ReservedName("input".to_string()));
418 }
419
420 #[test]
421 fn unknown_function_message_lists_registered_names() {
422 let registry =
423 FunctionRegistry::build(vec![closure_fn("alpha"), closure_fn("beta")]).unwrap();
424 let msg = registry.unknown_function_message("gamma");
425 assert!(msg.contains("gamma"));
426 assert!(msg.contains("alpha"));
427 assert!(msg.contains("beta"));
428 }
429
430 #[test]
431 fn method_style_call_of_a_registered_name_gets_a_corrective_message() {
432 let registry = FunctionRegistry::build(vec![closure_fn("alpha")]).unwrap();
433 let msg = registry.call_failure_message("alpha", true);
434 assert!(msg.contains("not a method"), "message: {msg}");
435 assert_eq!(
437 registry.call_failure_message("gamma", false),
438 registry.unknown_function_message("gamma")
439 );
440 }
441}