Skip to main content

tool_fn_with_ctx

Function tool_fn_with_ctx 

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

Creates a ToolHandler<Ctx> from a closure that receives context.

The closure receives the tool’s JSON arguments and a reference to the context, and returns a Result<impl Into<ToolOutput>, ToolError>.

§Example

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

struct AppContext {
    db_url: String,
}

let handler = tool_fn_with_ctx(
    ToolDefinition {
        name: "lookup_user".into(),
        description: "Look up a user by ID".into(),
        parameters: JsonSchema::new(json!({
            "type": "object",
            "properties": {
                "user_id": { "type": "string" }
            },
            "required": ["user_id"]
        })),
        retry: None,
    },
    |input: Value, ctx: &AppContext| {
        let user_id = input["user_id"].as_str().unwrap_or("").to_string();
        let db_url = ctx.db_url.clone();
        async move {
            // Use db_url and user_id in async work...
            Ok(ToolOutput::new(format!("Found user {} in {}", user_id, db_url)))
        }
    },
);