# app/tools.py import importlib import logging from typing import Callable, Dict from .database import SessionLocal from . import models import wikipedia from asteval import Interpreter # Ensure necessary imports are available logger = logging.getLogger(__name__) # Dictionary to store tool functions tools_registry: Dict[str, Callable[[str], str]] = {} def load_tools(): """ Load tools from the database and register them. Assumes that function_code contains the body of the function. """ db = SessionLocal() try: tool_models = db.query(models.ToolModel).all() for tool in tool_models: if tool.name not in tools_registry: # Dynamically create function from code try: namespace = {} exec(tool.function_code, globals(), namespace) func = namespace.get('tool_function') if func: tools_registry[tool.name] = func logger.info(f"Loaded tool: {tool.name}") else: logger.error(f"Function 'tool_function' not defined in tool: {tool.name}") except Exception as e: logger.error(f"Error loading tool {tool.name}: {e}") finally: db.close() def add_tool(tool: models.ToolModel): """ Add a tool to the registry. """ try: namespace = {} exec(tool.function_code, globals(), namespace) func = namespace.get('tool_function') if func: tools_registry[tool.name] = func logger.info(f"Registered new tool: {tool.name}") else: logger.error(f"Function 'tool_function' not defined in tool: {tool.name}") except Exception as e: logger.error(f"Error adding tool {tool.name}: {e}")