Skip to main content

tool_fn

Function tool_fn 

Source
pub fn tool_fn<F, Fut, O>(
    definition: ToolDefinition,
    handler: F,
) -> NoCtxToolHandler<F>
where F: Fn(Value) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<O, ToolError>> + Send + 'static, O: Into<ToolOutput> + Send + 'static,
Expand description

Creates a ToolHandler<()> from a closure (no context).

The closure receives the tool’s JSON arguments and returns a Result<impl Into<ToolOutput>, ToolError>. Returning Result<String, ToolError> also works via the From<String> impl on ToolOutput.

For tools that need shared context, use tool_fn_with_ctx instead.

§Example

use llm_stack::tool::tool_fn;
use llm_stack::{JsonSchema, ToolDefinition};
use serde_json::{json, Value};

let handler = tool_fn(
    ToolDefinition {
        name: "add".into(),
        description: "Add two numbers".into(),
        parameters: JsonSchema::new(json!({
            "type": "object",
            "properties": {
                "a": { "type": "number" },
                "b": { "type": "number" }
            },
            "required": ["a", "b"]
        })),
        retry: None,
    },
    |input: Value| async move {
        let a = input["a"].as_f64().unwrap_or(0.0);
        let b = input["b"].as_f64().unwrap_or(0.0);
        Ok(format!("{}", a + b))
    },
);