Skip to main content

adk_code/embedded_python/
host_fn.rs

1//! Host functions callable from Python scripts by bare name.
2//!
3//! A registered [`HostFunction`] becomes a callable Python function visible to
4//! scripts (and to the LLM via the executor's
5//! [`prompt_snippet`](crate::CodeExecutor::prompt_snippet)). The registry is
6//! validated at `build_*()` time — invalid identifiers, duplicates, and
7//! collisions with Monty built-ins are construction errors, not runtime
8//! surprises.
9//!
10//! **Trust note:** host functions run as host code. They are the *user's own*
11//! trust boundary, not Monty's — the interpreter sandbox does not contain
12//! their side effects.
13
14use 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/// Error raised by a [`HostFunction`] implementation.
26///
27/// The message becomes a catchable Python exception at the script's call
28/// site, so make it actionable for the model (what went wrong, what to try
29/// instead).
30#[derive(Debug, Error)]
31#[error("{message}")]
32pub struct HostFunctionError {
33    message: String,
34}
35
36impl HostFunctionError {
37    /// Create an error carrying `message`.
38    ///
39    /// # Example
40    ///
41    /// ```rust
42    /// use adk_code::HostFunctionError;
43    ///
44    /// let err = HostFunctionError::new("city not found; pass an ISO country code");
45    /// assert!(err.to_string().contains("city not found"));
46    /// ```
47    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/// Errors raised by `MontyExecutorBuilder::build_one_shot()` /
65/// `build_repl()` when the configuration is invalid — a bad host-function
66/// registry or a bad filesystem mount.
67#[derive(Debug, Error, Clone, PartialEq, Eq)]
68pub enum MontyBuildError {
69    /// The function name is not a valid Python identifier (or is a keyword).
70    #[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        /// The rejected name.
77        name: String,
78        /// Why it was rejected.
79        reason: String,
80    },
81
82    /// Two registered functions share the same name.
83    #[error("host function name '{0}' is registered more than once; names must be unique")]
84    DuplicateFunctionName(String),
85
86    /// The function name shadows a Monty built-in (e.g. `len`, `print`),
87    /// which the interpreter resolves internally — the host function would
88    /// never be reachable.
89    #[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    /// The function name is reserved by the executor itself.
97    #[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    /// A mount's virtual path is not a normalized absolute path.
104    #[error(
105        "mount path '{path}' is invalid: {reason}. \
106         Use a normalized absolute path such as \"/data\"."
107    )]
108    InvalidMountPath {
109        /// The rejected virtual path.
110        path: String,
111        /// Why it was rejected.
112        reason: String,
113    },
114
115    /// Two mounts share the same virtual path.
116    #[error("mount path '{0}' is registered more than once; virtual paths must be unique")]
117    DuplicateMountPath(String),
118}
119
120/// A Rust function callable from Python scripts executed by a Monty executor.
121///
122/// Register implementations with
123/// [`MontyExecutorBuilder::function`](crate::MontyExecutorBuilder::function),
124/// or use
125/// [`MontyExecutorBuilder::function_fn`](crate::MontyExecutorBuilder::function_fn)
126/// for the closure-based common case.
127///
128/// # Example
129///
130/// ```rust
131/// use adk_code::{HostFunction, HostFunctionError};
132/// use async_trait::async_trait;
133/// use serde_json::{Map, Value, json};
134///
135/// struct GetWeather;
136///
137/// #[async_trait]
138/// impl HostFunction for GetWeather {
139///     fn name(&self) -> &str {
140///         "get_weather"
141///     }
142///
143///     fn description(&self) -> &str {
144///         "Current weather for a city."
145///     }
146///
147///     fn signature(&self) -> String {
148///         "get_weather(city: str) -> dict".to_string()
149///     }
150///
151///     async fn call(
152///         &self,
153///         args: Vec<Value>,
154///         _kwargs: Map<String, Value>,
155///     ) -> Result<Value, HostFunctionError> {
156///         let city = args
157///             .first()
158///             .and_then(Value::as_str)
159///             .ok_or_else(|| HostFunctionError::new("pass the city as the first argument"))?;
160///         Ok(json!({ "city": city, "temp_c": 21 }))
161///     }
162/// }
163/// ```
164#[async_trait]
165pub trait HostFunction: Send + Sync {
166    /// Python-visible function name (must be a valid Python identifier).
167    fn name(&self) -> &str;
168
169    /// One-line description — becomes the Python function's docstring and is
170    /// surfaced to the LLM through the executor's prompt snippet.
171    fn description(&self) -> &str;
172
173    /// Optional signature rendering for the LLM prompt, e.g.
174    /// `"get_weather(city: str, unit: str = \"C\") -> dict"`.
175    /// Defaults to `"{name}(...)"`.
176    fn signature(&self) -> String {
177        format!("{}(...)", self.name())
178    }
179
180    /// Invoke with positional and keyword arguments (JSON-converted).
181    ///
182    /// # Errors
183    ///
184    /// An `Err` becomes a catchable Python exception carrying the message.
185    async fn call(
186        &self,
187        args: Vec<Value>,
188        kwargs: Map<String, Value>,
189    ) -> Result<Value, HostFunctionError>;
190}
191
192/// Future type returned by the closure adapter.
193type HostFnFuture = Pin<Box<dyn Future<Output = Result<Value, HostFunctionError>> + Send>>;
194
195/// Boxed closure stored by the adapter.
196type HostFnClosure = dyn Fn(Vec<Value>, Map<String, Value>) -> HostFnFuture + Send + Sync;
197
198/// Closure adapter created by `MontyExecutorBuilder::function_fn`.
199pub(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
242/// Python keywords (3.x hard keywords) — a host function named after one
243/// could never be called from a script.
244const 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
251/// The name the executor binds the request's JSON input to.
252pub(crate) const INPUT_BINDING: &str = "input";
253
254/// The validated, immutable host-function registry shared by both executor
255/// products. Keyed by Python-visible name.
256#[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    /// Validate and index the registered functions.
271    ///
272    /// # Errors
273    ///
274    /// Returns a [`MontyBuildError`] for an invalid identifier, a duplicate
275    /// name, a built-in collision, or a reserved name.
276    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    /// A corrective message for a failed call, raised into the script as a
309    /// catchable exception: either an unregistered bare name, or a registered
310    /// name invoked as a method (host functions are bare functions only).
311    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    /// A corrective message for a call to an unregistered name, raised into
322    /// the script as a catchable exception.
323    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
335/// Validate a host function name: a valid Python identifier that is not a
336/// keyword, a Monty built-in, or the reserved `input` binding.
337fn 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        // A bare-name miss keeps the unknown-function wording.
436        assert_eq!(
437            registry.call_failure_message("gamma", false),
438            registry.unknown_function_message("gamma")
439        );
440    }
441}