Skip to main content

tiny_agent_rs/tools/
function_factory.rs

1use super::{tool::ToolRegistry, Tool};
2use crate::{AgentError, Result};
3use serde_json::Value;
4
5/// Factory for creating and managing function/tool execution
6#[derive(Debug)]
7pub struct FunctionFactory {
8    registry: ToolRegistry,
9}
10
11impl FunctionFactory {
12    /// Create a new function factory
13    pub fn new() -> Self {
14        Self {
15            registry: ToolRegistry::new(),
16        }
17    }
18
19    /// Register a tool with the factory
20    pub fn register_tool<T: Tool + 'static>(&mut self, tool: T) {
21        self.registry.register(tool);
22    }
23
24    /// Execute a function call by name
25    pub async fn execute_function(&self, function_name: &str, parameters: Value) -> Result<Value> {
26        let tool = self
27            .registry
28            .get(function_name)
29            .ok_or_else(|| AgentError::ToolNotFound(function_name.to_string()))?;
30
31        tool.execute(parameters).await
32    }
33
34    /// Get all available tools for OpenAI function calling
35    pub fn get_openai_tools(&self) -> Vec<Value> {
36        self.registry.to_openai_tools()
37    }
38
39    /// Check if a function exists
40    pub fn has_function(&self, name: &str) -> bool {
41        self.registry.get(name).is_some()
42    }
43}
44
45impl Default for FunctionFactory {
46    fn default() -> Self {
47        Self::new()
48    }
49}