From b22297a5d4b2b1ad0c57b205e54a6561fa794e57 Mon Sep 17 00:00:00 2001 From: opencode Date: Mon, 23 Mar 2026 18:01:40 +0100 Subject: [PATCH] fix: usa @tool decorator invece di Tool() per i built-in Il problema era che Tool() senza parametri si lamentava quando invocato con {}. Usando @tool decorator funziona correttamente. --- ollama_agent.py | 137 ++++++++++++++++++------------------------------ 1 file changed, 52 insertions(+), 85 deletions(-) diff --git a/ollama_agent.py b/ollama_agent.py index e456290..3e1a21e 100644 --- a/ollama_agent.py +++ b/ollama_agent.py @@ -14,7 +14,7 @@ from datetime import datetime from pathlib import Path from langchain_core.messages import HumanMessage, AIMessage, SystemMessage, BaseMessage -from langchain_core.tools import Tool +from langchain_core.tools import tool, Tool # ============================================================================= @@ -40,12 +40,46 @@ def get_builtin_tools() -> List[Tool]: """ tools = [] + # Tool: Info sistema - usa @tool decorator + @tool + def system_info() -> str: + """Get system information (OS, Python version, current directory).""" + import platform + import os + info = [] + info.append(f"OS: {platform.system()} {platform.release()}") + info.append(f"Python: {platform.python_version()}") + info.append(f"Current dir: {os.getcwd()}") + info.append(f"User: {os.getenv('USER', 'unknown')}") + return "\n".join(info) + + tools.append(system_info) + + # Tool: Lista file + @tool + def ls(path: str) -> str: + """List files in a directory.""" + try: + dir_path = Path(path).expanduser() + if not dir_path.exists(): + return f"Error: Directory '{path}' not found" + if not dir_path.is_dir(): + return f"Error: '{path}' is not a directory" + + items = [] + for item in sorted(dir_path.iterdir()): + item_type = "DIR" if item.is_dir() else "FILE" + items.append(f"{item_type}: {item.name}") + return "\n".join(items) if items else "Directory is empty" + except Exception as e: + return f"Error listing directory: {str(e)}" + + tools.append(ls) + # Tool: Esegui comando shell - def execute_command(command: str) -> str: - """ - Execute a shell command and return the output. - USE WITH CAUTION - only for safe commands. - """ + @tool + def execute(command: str) -> str: + """Execute a shell command. Use this for file operations, running scripts, git commands, etc.""" try: result = subprocess.run( command, @@ -67,17 +101,12 @@ def get_builtin_tools() -> List[Tool]: except Exception as e: return f"Error: {str(e)}" - tools.append(Tool( - name="execute", - description="Execute a shell command. Use this for file operations, running scripts, git commands, etc. Input is the command string to execute.", - func=execute_command - )) + tools.append(execute) # Tool: Leggi file + @tool def read_file(path: str) -> str: - """ - Read the contents of a file. - """ + """Read the contents of a file.""" try: file_path = Path(path).expanduser() if not file_path.exists(): @@ -88,18 +117,12 @@ def get_builtin_tools() -> List[Tool]: except Exception as e: return f"Error reading file: {str(e)}" - tools.append(Tool( - name="read_file", - description="Read the contents of a file. Input is the file path (can use ~ for home directory).", - func=read_file - )) + tools.append(read_file) # Tool: Scrivi file + @tool def write_file(path: str, content: str) -> str: - """ - Write content to a file. Creates the file if it doesn't exist. - WARNING: This will overwrite existing files! - """ + """Write content to a file. WARNING: overwrites existing files!""" try: file_path = Path(path).expanduser() file_path.parent.mkdir(parents=True, exist_ok=True) @@ -108,45 +131,13 @@ def get_builtin_tools() -> List[Tool]: except Exception as e: return f"Error writing file: {str(e)}" - tools.append(Tool( - name="write_file", - description="Write content to a file. Inputs: 'path' (file path) and 'content' (text to write). WARNING: overwrites existing files!", - func=write_file - )) - - # Tool: Lista file - def list_directory(path: str = ".") -> str: - """ - List files in a directory. - """ - try: - dir_path = Path(path).expanduser() - if not dir_path.exists(): - return f"Error: Directory '{path}' not found" - if not dir_path.is_dir(): - return f"Error: '{path}' is not a directory" - - items = [] - for item in sorted(dir_path.iterdir()): - item_type = "DIR" if item.is_dir() else "FILE" - items.append(f"{item_type}: {item.name}") - return "\n".join(items) if items else "Directory is empty" - except Exception as e: - return f"Error listing directory: {str(e)}" - - tools.append(Tool( - name="ls", - description="List files in a directory. Input is the directory path (default: current directory).", - func=list_directory - )) + tools.append(write_file) # Tool: Cerca file - def search_files(directory: str = ".", pattern: str = "*") -> str: - """ - Search for files matching a pattern in a directory. - """ + @tool + def search(directory: str, pattern: str) -> str: + """Search for files by name pattern.""" try: - from pathlib import Path dir_path = Path(directory).expanduser() if not dir_path.exists(): return f"Error: Directory '{directory}' not found" @@ -156,38 +147,14 @@ def get_builtin_tools() -> List[Tool]: return f"No files matching '{pattern}' found in {directory}" results = [] - for match in matches[:50]: # Limit to 50 results + for match in matches[:50]: results.append(str(match)) return f"Found {len(matches)} matches (showing first 50):\n" + "\n".join(results) except Exception as e: return f"Error searching files: {str(e)}" - tools.append(Tool( - name="search", - description="Search for files by name pattern. Inputs: 'directory' (where to search) and 'pattern' (e.g., '*.py', '*.md').", - func=search_files - )) - - # Tool: Info sistema - def system_info() -> str: - """ - Get system information (OS, Python version, current directory). - """ - import platform - import os - info = [] - info.append(f"OS: {platform.system()} {platform.release()}") - info.append(f"Python: {platform.python_version()}") - info.append(f"Current dir: {os.getcwd()}") - info.append(f"User: {os.getenv('USER', 'unknown')}") - return "\n".join(info) - - tools.append(Tool( - name="system_info", - description="Get system information (OS, Python version, current directory). No input required.", - func=system_info - )) + tools.append(search) return tools