initial commit heh
This commit is contained in:
78 files changed
+11181
No files matched your search
@@ -0,0 +1,13 @@
|
||||
"""Tools package for HomeAgent."""
|
||||
|
||||
from homeagent.tools.base import ToolDefinition, tool
|
||||
from homeagent.tools.loader import load_extensions_from_directory
|
||||
from homeagent.tools.registry import ToolRegistry, get_tool_registry
|
||||
|
||||
__all__ = [
|
||||
"tool",
|
||||
"ToolDefinition",
|
||||
"ToolRegistry",
|
||||
"get_tool_registry",
|
||||
"load_extensions_from_directory",
|
||||
]
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Base classes and decorators for HomeAgent tools and extensions."""
|
||||
|
||||
import inspect
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Callable, Optional, get_args, get_origin
|
||||
|
||||
|
||||
def _python_type_to_schema(py_type: Any) -> dict[str, Any]:
|
||||
"""Map a Python type annotation to a JSON Schema dictionary."""
|
||||
origin = get_origin(py_type)
|
||||
args = get_args(py_type)
|
||||
|
||||
# Check for Optional[T] / Union[T, None]
|
||||
if origin is not None and type(None) in args:
|
||||
non_none_args = [a for a in args if a is not type(None)]
|
||||
if len(non_none_args) == 1:
|
||||
schema = _python_type_to_schema(non_none_args[0])
|
||||
schema["nullable"] = True
|
||||
return schema
|
||||
|
||||
if origin in (list, list):
|
||||
item_type = args[0] if args else str
|
||||
return {"type": "array", "items": _python_type_to_schema(item_type)}
|
||||
|
||||
if origin in (dict, dict) or py_type in (dict,):
|
||||
return {"type": "object"}
|
||||
|
||||
if py_type in (str,):
|
||||
return {"type": "string"}
|
||||
if py_type in (int,):
|
||||
return {"type": "integer"}
|
||||
if py_type in (float,):
|
||||
return {"type": "number"}
|
||||
if py_type in (bool,):
|
||||
return {"type": "boolean"}
|
||||
|
||||
# Default fallback
|
||||
return {"type": "string"}
|
||||
|
||||
|
||||
def _parse_docstring_params(docstring: Optional[str]) -> dict[str, str]:
|
||||
"""Extract parameter descriptions from docstring."""
|
||||
if not docstring:
|
||||
return {}
|
||||
|
||||
param_docs: dict[str, str] = {}
|
||||
|
||||
# Pattern for Sphinx style: :param name: description
|
||||
sphinx_matches = re.findall(r":param\s+([a-zA-Z0-9_]+)\s*:\s*([^\n]+)", docstring)
|
||||
for name, desc in sphinx_matches:
|
||||
param_docs[name] = desc.strip()
|
||||
|
||||
# Pattern for Google style:
|
||||
# Args:
|
||||
# param_name: description
|
||||
lines = docstring.split("\n")
|
||||
in_args_section = False
|
||||
for line in lines:
|
||||
stripped = line.strip()
|
||||
if stripped.lower().startswith("args:"):
|
||||
in_args_section = True
|
||||
continue
|
||||
if in_args_section:
|
||||
if stripped.endswith(":") and not stripped.startswith("-"):
|
||||
# End of args section (e.g. Returns:)
|
||||
in_args_section = False
|
||||
continue
|
||||
google_match = re.match(r"^\s*([a-zA-Z0-9_]+)\s*(?:\([^)]*\))?\s*:\s*(.+)$", line)
|
||||
if google_match:
|
||||
name, desc = google_match.groups()
|
||||
param_docs[name] = desc.strip()
|
||||
|
||||
return param_docs
|
||||
|
||||
|
||||
@dataclass
|
||||
class ToolDefinition:
|
||||
name: str
|
||||
description: str
|
||||
func: Callable[..., Any]
|
||||
parameters_schema: dict[str, Any]
|
||||
is_async: bool
|
||||
|
||||
async def execute(self, **kwargs: Any) -> Any:
|
||||
"""Execute the tool safely, awaiting if async."""
|
||||
if self.is_async:
|
||||
return await self.func(**kwargs)
|
||||
return self.func(**kwargs)
|
||||
|
||||
|
||||
def tool(
|
||||
name: Optional[str] = None,
|
||||
description: Optional[str] = None,
|
||||
) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
||||
"""Decorator to mark a function as an agent tool / extension.
|
||||
|
||||
Example:
|
||||
@tool(description="Search issues in Jira")
|
||||
async def jira_search(jql: str, max_results: int = 10) -> str:
|
||||
\"\"\"Search issues using JQL syntax.
|
||||
|
||||
Args:
|
||||
jql: The JQL query string
|
||||
max_results: Max number of issues to return
|
||||
\"\"\"
|
||||
...
|
||||
"""
|
||||
def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
|
||||
tool_name = name or fn.__name__
|
||||
tool_desc = description or (fn.__doc__ or "").strip().split("\n")[0] or tool_name
|
||||
|
||||
sig = inspect.signature(fn)
|
||||
param_docs = _parse_docstring_params(fn.__doc__)
|
||||
|
||||
properties: dict[str, Any] = {}
|
||||
required: list[str] = []
|
||||
|
||||
for p_name, p in sig.parameters.items():
|
||||
if p_name in ("self", "cls"):
|
||||
continue
|
||||
|
||||
annotation = p.annotation if p.annotation is not inspect.Parameter.empty else str
|
||||
prop_schema = _python_type_to_schema(annotation)
|
||||
|
||||
if p_name in param_docs:
|
||||
prop_schema["description"] = param_docs[p_name]
|
||||
|
||||
properties[p_name] = prop_schema
|
||||
|
||||
if p.default is inspect.Parameter.empty:
|
||||
required.append(p_name)
|
||||
|
||||
parameters_schema = {
|
||||
"type": "object",
|
||||
"properties": properties,
|
||||
}
|
||||
if required:
|
||||
parameters_schema["required"] = required
|
||||
|
||||
tool_def = ToolDefinition(
|
||||
name=tool_name,
|
||||
description=tool_desc,
|
||||
func=fn,
|
||||
parameters_schema=parameters_schema,
|
||||
is_async=inspect.iscoroutinefunction(fn),
|
||||
)
|
||||
|
||||
setattr(fn, "__tool_definition__", tool_def)
|
||||
return fn
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Dynamic extension and tool loader for HomeAgent."""
|
||||
|
||||
import importlib.util
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from homeagent.tools.registry import ToolRegistry, get_tool_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def load_extensions_from_directory(
|
||||
directory: Path,
|
||||
registry: Optional[ToolRegistry] = None,
|
||||
) -> int:
|
||||
"""Scan directory and import all tools from Python files.
|
||||
|
||||
Searches for:
|
||||
- <dir>/*.py
|
||||
- <dir>/*/tools.py
|
||||
- <dir>/*/__init__.py
|
||||
|
||||
Inspects each loaded module for functions decorated with @tool or a setup(registry) hook.
|
||||
"""
|
||||
if registry is None:
|
||||
registry = get_tool_registry()
|
||||
|
||||
if not directory.exists() or not directory.is_dir():
|
||||
logger.warning("Extensions directory '%s' does not exist.", directory)
|
||||
return 0
|
||||
|
||||
registered_count = 0
|
||||
|
||||
# Collect python files
|
||||
py_files: list[Path] = []
|
||||
for path in directory.rglob("*.py"):
|
||||
if path.name.startswith("_") and path.name != "__init__.py":
|
||||
continue
|
||||
py_files.append(path)
|
||||
|
||||
for py_file in py_files:
|
||||
module_name = f"homeagent_ext_{py_file.stem}_{abs(hash(str(py_file)))}"
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location(module_name, py_file)
|
||||
if spec is None or spec.loader is None:
|
||||
continue
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
# Check for explicit setup / register hook
|
||||
if hasattr(module, "register_tools") and callable(module.register_tools):
|
||||
module.register_tools(registry)
|
||||
elif hasattr(module, "setup") and callable(module.setup):
|
||||
module.setup(registry)
|
||||
|
||||
# Auto-discover any @tool functions in the module
|
||||
for attr_name in dir(module):
|
||||
attr = getattr(module, attr_name)
|
||||
if callable(attr) and hasattr(attr, "__tool_definition__"):
|
||||
registry.register(attr)
|
||||
registered_count += 1
|
||||
|
||||
logger.info("Loaded extension module from %s", py_file)
|
||||
except Exception as e:
|
||||
logger.error("Failed to load extension from %s: %s", py_file, e)
|
||||
|
||||
return registered_count
|
||||
@@ -0,0 +1,220 @@
|
||||
"""Tool registry for registering and executing agent tools."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
from google.genai import types
|
||||
from homeagent.memory.global_memory import get_global_memory
|
||||
from homeagent.tools.base import ToolDefinition, tool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ToolRegistry:
|
||||
"""Registry holding all registered tools and providing Gemini conversion."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._tools: dict[str, ToolDefinition] = {}
|
||||
|
||||
def register(self, fn: Callable[..., Any]) -> ToolDefinition:
|
||||
"""Register a function decorated with @tool, or create a definition if needed."""
|
||||
tool_def: Optional[ToolDefinition] = getattr(fn, "__tool_definition__", None)
|
||||
if tool_def is None:
|
||||
# Apply default @tool decorator
|
||||
fn = tool()(fn)
|
||||
tool_def = getattr(fn, "__tool_definition__")
|
||||
|
||||
self._tools[tool_def.name] = tool_def
|
||||
logger.debug("Registered tool: %s (%s)", tool_def.name, tool_def.description)
|
||||
return tool_def
|
||||
|
||||
def unregister(self, name: str) -> bool:
|
||||
if name in self._tools:
|
||||
del self._tools[name]
|
||||
return True
|
||||
return False
|
||||
|
||||
def get(self, name: str) -> Optional[ToolDefinition]:
|
||||
return self._tools.get(name)
|
||||
|
||||
def list_tools(self) -> list[ToolDefinition]:
|
||||
return list(self._tools.values())
|
||||
|
||||
def get_function_declarations(self) -> list[types.FunctionDeclaration]:
|
||||
"""Convert all registered tools into google-genai FunctionDeclaration objects."""
|
||||
declarations: list[types.FunctionDeclaration] = []
|
||||
for tool_def in self._tools.values():
|
||||
fd = types.FunctionDeclaration(
|
||||
name=tool_def.name,
|
||||
description=tool_def.description,
|
||||
parameters=tool_def.parameters_schema,
|
||||
)
|
||||
declarations.append(fd)
|
||||
return declarations
|
||||
|
||||
def get_openai_tools(self, exclude_subagents: bool = False) -> list[dict[str, Any]]:
|
||||
"""Convert registered tools into OpenAI-compatible tools schema.
|
||||
|
||||
Args:
|
||||
exclude_subagents: If True, exclude spawn_subagent tools to prevent recursion in subagents.
|
||||
"""
|
||||
tools: list[dict[str, Any]] = []
|
||||
for tool_def in self._tools.values():
|
||||
if exclude_subagents and tool_def.name in ("spawn_subagent", "spawn_parallel_subagents"):
|
||||
continue
|
||||
tools.append(
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tool_def.name,
|
||||
"description": tool_def.description,
|
||||
"parameters": tool_def.parameters_schema,
|
||||
},
|
||||
}
|
||||
)
|
||||
return tools
|
||||
|
||||
|
||||
async def execute(self, name: str, args: dict[str, Any]) -> str:
|
||||
"""Execute a tool by name with arguments and return result as string."""
|
||||
tool_def = self._tools.get(name)
|
||||
if not tool_def:
|
||||
error_msg = f"Error: Tool '{name}' not found in registry."
|
||||
logger.warning(error_msg)
|
||||
return error_msg
|
||||
|
||||
logger.info("Executing tool '%s' with args: %s", name, args)
|
||||
try:
|
||||
result = await tool_def.execute(**args)
|
||||
if isinstance(result, str):
|
||||
return result
|
||||
if isinstance(result, (dict, list)):
|
||||
return json.dumps(result, ensure_ascii=False, indent=2)
|
||||
return str(result)
|
||||
except Exception as e:
|
||||
logger.exception("Error executing tool '%s': %s", name, e)
|
||||
return f"Error executing tool '{name}': {type(e).__name__}: {str(e)}"
|
||||
|
||||
|
||||
# Global registry singleton
|
||||
_registry_instance: Optional[ToolRegistry] = None
|
||||
|
||||
|
||||
def get_tool_registry() -> ToolRegistry:
|
||||
global _registry_instance
|
||||
if _registry_instance is None:
|
||||
_registry_instance = ToolRegistry()
|
||||
_register_builtins(_registry_instance)
|
||||
return _registry_instance
|
||||
|
||||
|
||||
def _register_builtins(registry: ToolRegistry) -> None:
|
||||
"""Register built-in tools like global memory management."""
|
||||
|
||||
@tool(
|
||||
name="remember_fact",
|
||||
description="Сохранить важный факт, предпочтение или заметку в глобальную память (доступна во всех топиках).",
|
||||
)
|
||||
def remember_fact(fact: str, category: str = "general") -> str:
|
||||
"""Сохранить факт в память.
|
||||
|
||||
Args:
|
||||
fact: Текст факта или предпочтения
|
||||
category: Категория (например: user, project, tech, jira, personal)
|
||||
"""
|
||||
memory = get_global_memory()
|
||||
item = memory.add_fact(fact=fact, category=category)
|
||||
return f"Факт успешно сохранен в категорию '{item.category}' (ID: {item.id}): {item.fact}"
|
||||
|
||||
@tool(
|
||||
name="recall_facts",
|
||||
description="Найти факты и заметки в глобальной памяти по ключевому слову или запросу.",
|
||||
)
|
||||
def recall_facts(query: str) -> str:
|
||||
"""Поиск по глобальной памяти.
|
||||
|
||||
Args:
|
||||
query: Поисковый запрос
|
||||
"""
|
||||
memory = get_global_memory()
|
||||
results = memory.search(query)
|
||||
if not results:
|
||||
return f"В памяти ничего не найдено по запросу '{query}'."
|
||||
lines = [f"Найдено {len(results)} фактов:"]
|
||||
for item in results:
|
||||
lines.append(f"- [{item.id}] ({item.category}): {item.fact}")
|
||||
return "\n".join(lines)
|
||||
|
||||
@tool(
|
||||
name="list_all_facts",
|
||||
description="Показать все сохраненные факты из глобальной памяти, опционально фильтруя по категории.",
|
||||
)
|
||||
def list_all_facts(category: Optional[str] = None) -> str:
|
||||
"""Список всех фактов.
|
||||
|
||||
Args:
|
||||
category: Опциональный фильтр по категории
|
||||
"""
|
||||
memory = get_global_memory()
|
||||
items = memory.list_facts(category=category)
|
||||
if not items:
|
||||
return "Глобальная память пуста."
|
||||
lines = [f"Сохранено фактов ({len(items)}):"]
|
||||
for item in items:
|
||||
lines.append(f"- [{item.id}] ({item.category}): {item.fact}")
|
||||
return "\n".join(lines)
|
||||
|
||||
@tool(
|
||||
name="forget_fact",
|
||||
description="Удалить факт из глобальной памяти по его ID.",
|
||||
)
|
||||
def forget_fact(fact_id: str) -> str:
|
||||
"""Удалить факт по ID.
|
||||
|
||||
Args:
|
||||
fact_id: Идентификатор факта (полученный из recall_facts или list_all_facts)
|
||||
"""
|
||||
memory = get_global_memory()
|
||||
if memory.remove_fact(fact_id.strip()):
|
||||
return f"Факт с ID '{fact_id}' успешно удален."
|
||||
return f"Факт с ID '{fact_id}' не найден в памяти."
|
||||
|
||||
@tool(
|
||||
name="spawn_subagent",
|
||||
description="Запустить автономного быстрого AI-подагента для выполнения отдельной подзадачи (сбор данных, поиск или проверка сервиса).",
|
||||
)
|
||||
async def spawn_subagent(task: str, role: str = "Assistant", context: Optional[str] = None) -> str:
|
||||
"""Запуск одного подагента.
|
||||
|
||||
Args:
|
||||
task: Четкое описание задачи для подагента
|
||||
role: Роль подагента (например: 'Jira Specialist', 'Calendar Assistant')
|
||||
context: Опциональный контекст или указания от главного агента
|
||||
"""
|
||||
from homeagent.agent.subagent import get_subagent_runner
|
||||
|
||||
runner = get_subagent_runner()
|
||||
return await runner.run_task(task=task, role=role, context=context)
|
||||
|
||||
@tool(
|
||||
name="spawn_parallel_subagents",
|
||||
description="Запустить нескольких быстрых AI-подагентов ОДНОВРЕМЕННО (параллельно) для ускорения работы. Идеально для одновременного сбора данных из Календаря и Jira.",
|
||||
)
|
||||
async def spawn_parallel_subagents(tasks: list[dict[str, str]]) -> str:
|
||||
"""Параллельный запуск нескольких подагентов.
|
||||
|
||||
Args:
|
||||
tasks: Список словарей подзадач, например: [{'task': 'Проверить встречи в Календаре', 'role': 'Календарь'}, {'task': 'Проверить активные задачи в Jira', 'role': 'Jira'}]
|
||||
"""
|
||||
from homeagent.agent.subagent import get_subagent_runner
|
||||
|
||||
runner = get_subagent_runner()
|
||||
return await runner.run_parallel(tasks=tasks)
|
||||
|
||||
registry.register(remember_fact)
|
||||
registry.register(recall_facts)
|
||||
registry.register(list_all_facts)
|
||||
registry.register(forget_fact)
|
||||
registry.register(spawn_subagent)
|
||||
registry.register(spawn_parallel_subagents)
|
||||
Reference in new issue
Block a user