initial commit heh
This commit is contained in:
78 files changed
+11181
No files matched your search
@@ -0,0 +1,3 @@
|
||||
"""HomeAgent - Personal AI Agent for Telegram."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Agent package for HomeAgent."""
|
||||
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.agent.gemini import GeminiAgent
|
||||
|
||||
__all__ = ["GeminiAgent", "ConversationManager"]
|
||||
@@ -0,0 +1,31 @@
|
||||
"""Base agent interface for HomeAgent."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Any, Awaitable, Callable, Optional
|
||||
|
||||
|
||||
class BaseAgent(ABC):
|
||||
"""Abstract base class for all LLM agents."""
|
||||
|
||||
@abstractmethod
|
||||
async def chat(
|
||||
self,
|
||||
chat_id: int,
|
||||
thread_id: Optional[int],
|
||||
user_message: str,
|
||||
max_tool_iterations: int = 8,
|
||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
||||
) -> str:
|
||||
"""Process user message within chat topic and execute tools as needed.
|
||||
|
||||
Args:
|
||||
chat_id: Telegram Chat ID
|
||||
thread_id: Optional Telegram Forum Topic ID
|
||||
user_message: Incoming user prompt
|
||||
max_tool_iterations: Safety cap on consecutive tool call loops
|
||||
on_progress: Optional async callback for reporting status updates to the user
|
||||
|
||||
Returns:
|
||||
Final markdown response text for the user
|
||||
"""
|
||||
pass
|
||||
@@ -0,0 +1,391 @@
|
||||
"""Topic-isolated conversation history management supporting multiple LLM formats."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
|
||||
from google.genai import types
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _session_file(data_dir: Path, chat_id: int, thread_id: Optional[int]) -> Path:
|
||||
thread_suffix = f"thread_{thread_id}" if thread_id is not None else "main"
|
||||
return data_dir / "sessions" / f"session_{chat_id}_{thread_suffix}.json"
|
||||
|
||||
|
||||
def _sanitize_openai_messages(raw_messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Sanitize message chain to strictly conform to OpenAI/DeepSeek API specifications.
|
||||
|
||||
Ensures that:
|
||||
1. Every assistant message with tool_calls is immediately followed by tool messages for ALL tool_call_ids.
|
||||
2. Tool responses matching call IDs are properly aligned.
|
||||
3. Dangling tool calls or orphan tool messages are safely cleaned up.
|
||||
"""
|
||||
sanitized: list[dict[str, Any]] = []
|
||||
i = 0
|
||||
n = len(raw_messages)
|
||||
|
||||
while i < n:
|
||||
msg = dict(raw_messages[i])
|
||||
role = msg.get("role")
|
||||
|
||||
if role == "tool":
|
||||
# Orphan tool response without preceding assistant tool_calls -> drop it
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if role == "assistant" and msg.get("tool_calls"):
|
||||
tool_calls = [dict(tc) for tc in msg["tool_calls"]]
|
||||
# Look ahead for following tool messages
|
||||
j = i + 1
|
||||
tool_responses: list[dict[str, Any]] = []
|
||||
while j < n and raw_messages[j].get("role") == "tool":
|
||||
tool_responses.append(dict(raw_messages[j]))
|
||||
j += 1
|
||||
|
||||
if not tool_responses:
|
||||
# No tool responses followed this assistant message!
|
||||
# Strip tool_calls to prevent API 400 error.
|
||||
if msg.get("content"):
|
||||
sanitized.append({"role": "assistant", "content": msg["content"]})
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# Ensure 1-to-1 matching tool_call_id
|
||||
if len(tool_calls) == len(tool_responses):
|
||||
for tc, tr in zip(tool_calls, tool_responses):
|
||||
tr["tool_call_id"] = tc["id"]
|
||||
sanitized.append({
|
||||
"role": "assistant",
|
||||
"content": msg.get("content"),
|
||||
"tool_calls": tool_calls,
|
||||
})
|
||||
sanitized.extend(tool_responses)
|
||||
else:
|
||||
# Different counts: match by name or existing ID
|
||||
matched_pairs = []
|
||||
remaining_responses = list(tool_responses)
|
||||
for tc in tool_calls:
|
||||
tc_id = tc.get("id")
|
||||
tc_name = tc.get("function", {}).get("name")
|
||||
found_idx = None
|
||||
for idx, tr in enumerate(remaining_responses):
|
||||
if tr.get("tool_call_id") == tc_id or tr.get("name") == tc_name:
|
||||
found_idx = idx
|
||||
break
|
||||
if found_idx is not None:
|
||||
tr = remaining_responses.pop(found_idx)
|
||||
tr["tool_call_id"] = tc_id
|
||||
matched_pairs.append((tc, tr))
|
||||
|
||||
if matched_pairs:
|
||||
valid_tool_calls = [pair[0] for pair in matched_pairs]
|
||||
valid_tool_responses = [pair[1] for pair in matched_pairs]
|
||||
sanitized.append({
|
||||
"role": "assistant",
|
||||
"content": msg.get("content"),
|
||||
"tool_calls": valid_tool_calls,
|
||||
})
|
||||
sanitized.extend(valid_tool_responses)
|
||||
elif msg.get("content"):
|
||||
sanitized.append({"role": "assistant", "content": msg["content"]})
|
||||
|
||||
i = j
|
||||
continue
|
||||
|
||||
# Normal user or assistant message
|
||||
sanitized.append(msg)
|
||||
i += 1
|
||||
|
||||
return sanitized
|
||||
|
||||
|
||||
class ConversationManager:
|
||||
"""Manages chat and topic history with disk persistence and multi-provider format support."""
|
||||
|
||||
def __init__(self, data_dir: Path, max_turns: int = 20) -> None:
|
||||
self.data_dir = data_dir
|
||||
self.max_turns = max_turns
|
||||
self._cache: dict[tuple[int, Optional[int]], list[dict[str, Any]]] = {}
|
||||
(self.data_dir / "sessions").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def _get_key(self, chat_id: int, thread_id: Optional[int]) -> tuple[int, Optional[int]]:
|
||||
return (chat_id, thread_id)
|
||||
|
||||
def _load_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]:
|
||||
"""Load and normalize messages from disk into universal dictionary format."""
|
||||
key = self._get_key(chat_id, thread_id)
|
||||
if key in self._cache:
|
||||
return self._cache[key]
|
||||
|
||||
file_path = _session_file(self.data_dir, chat_id, thread_id)
|
||||
if not file_path.exists():
|
||||
self._cache[key] = []
|
||||
return self._cache[key]
|
||||
|
||||
try:
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
raw_data = json.load(f)
|
||||
|
||||
normalized: list[dict[str, Any]] = []
|
||||
pending_tool_call_ids: dict[str, list[str]] = {}
|
||||
|
||||
for turn_idx, item in enumerate(raw_data):
|
||||
# 1. Check if legacy Gemini format with "parts"
|
||||
if "parts" in item:
|
||||
role = item.get("role", "user")
|
||||
parts = item.get("parts", [])
|
||||
if role == "user":
|
||||
# Check for function_response
|
||||
fr_parts = [p for p in parts if "function_response" in p]
|
||||
if fr_parts:
|
||||
for p in fr_parts:
|
||||
fr = p["function_response"]
|
||||
fn_name = fr.get("name", "tool")
|
||||
if fn_name in pending_tool_call_ids and pending_tool_call_ids[fn_name]:
|
||||
call_id = pending_tool_call_ids[fn_name].pop(0)
|
||||
else:
|
||||
call_id = f"call_{turn_idx}_{fn_name}"
|
||||
|
||||
resp = fr.get("response", {})
|
||||
res_val = resp.get("result", json.dumps(resp, ensure_ascii=False))
|
||||
normalized.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": call_id,
|
||||
"name": fn_name,
|
||||
"content": str(res_val),
|
||||
})
|
||||
else:
|
||||
text = "".join(p.get("text", "") for p in parts)
|
||||
normalized.append({"role": "user", "content": text})
|
||||
elif role == "model":
|
||||
fc_parts = [p for p in parts if "function_call" in p]
|
||||
if fc_parts:
|
||||
tcs = []
|
||||
for idx, p in enumerate(fc_parts):
|
||||
fc = p["function_call"]
|
||||
fn_name = fc.get("name", "tool")
|
||||
call_id = f"call_{turn_idx}_{idx}_{fn_name}"
|
||||
pending_tool_call_ids.setdefault(fn_name, []).append(call_id)
|
||||
args = fc.get("args", {})
|
||||
tcs.append({
|
||||
"id": call_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": fn_name,
|
||||
"arguments": json.dumps(args, ensure_ascii=False) if isinstance(args, dict) else str(args),
|
||||
},
|
||||
})
|
||||
normalized.append({"role": "assistant", "content": None, "tool_calls": tcs})
|
||||
else:
|
||||
text = "".join(p.get("text", "") for p in parts)
|
||||
normalized.append({"role": "assistant", "content": text})
|
||||
else:
|
||||
# 2. Already normalized message format
|
||||
normalized.append(item)
|
||||
|
||||
self._cache[key] = normalized
|
||||
return normalized
|
||||
except Exception as e:
|
||||
logger.error("Failed to load session history from %s: %s", file_path, e)
|
||||
self._cache[key] = []
|
||||
return self._cache[key]
|
||||
|
||||
def _save_raw_messages(self, chat_id: int, thread_id: Optional[int]) -> None:
|
||||
key = self._get_key(chat_id, thread_id)
|
||||
messages = self._cache.get(key, [])
|
||||
file_path = _session_file(self.data_dir, chat_id, thread_id)
|
||||
|
||||
try:
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
json.dump(messages, f, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
logger.error("Failed to persist session to %s: %s", file_path, e)
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Gemini Compatibility API
|
||||
# --------------------------------------------------------------------------
|
||||
def get_history(self, chat_id: int, thread_id: Optional[int]) -> list[types.Content]:
|
||||
"""Retrieve conversation history converted into Gemini types.Content objects."""
|
||||
messages = self._load_raw_messages(chat_id, thread_id)
|
||||
gemini_history: list[types.Content] = []
|
||||
|
||||
for msg in messages:
|
||||
role = msg.get("role", "user")
|
||||
content = msg.get("content")
|
||||
tool_calls = msg.get("tool_calls")
|
||||
|
||||
if role == "user":
|
||||
gemini_history.append(
|
||||
types.Content(
|
||||
role="user",
|
||||
parts=[types.Part.from_text(text=str(content or ""))],
|
||||
)
|
||||
)
|
||||
elif role == "assistant":
|
||||
if tool_calls:
|
||||
parts = []
|
||||
for tc in tool_calls:
|
||||
fn = tc.get("function", {})
|
||||
fn_name = fn.get("name", "")
|
||||
raw_args = fn.get("arguments", "{}")
|
||||
if isinstance(raw_args, str):
|
||||
try:
|
||||
args = json.loads(raw_args)
|
||||
except Exception:
|
||||
args = {}
|
||||
elif isinstance(raw_args, dict):
|
||||
args = raw_args
|
||||
else:
|
||||
args = {}
|
||||
parts.append(types.Part.from_function_call(name=fn_name, args=args))
|
||||
gemini_history.append(types.Content(role="model", parts=parts))
|
||||
else:
|
||||
gemini_history.append(
|
||||
types.Content(
|
||||
role="model",
|
||||
parts=[types.Part.from_text(text=str(content or ""))],
|
||||
)
|
||||
)
|
||||
elif role == "tool":
|
||||
tool_name = msg.get("name") or "tool"
|
||||
gemini_history.append(
|
||||
types.Content(
|
||||
role="user",
|
||||
parts=[
|
||||
types.Part.from_function_response(
|
||||
name=tool_name,
|
||||
response={"result": str(content or "")},
|
||||
)
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
return gemini_history
|
||||
|
||||
def append_turn_sequence(
|
||||
self, chat_id: int, thread_id: Optional[int], contents: list[types.Content]
|
||||
) -> None:
|
||||
"""Append multiple Gemini types.Content objects to conversation history."""
|
||||
key = self._get_key(chat_id, thread_id)
|
||||
messages = self._load_raw_messages(chat_id, thread_id)
|
||||
pending_tool_call_ids: dict[str, list[str]] = {}
|
||||
|
||||
for content in contents:
|
||||
role = content.role
|
||||
parts = content.parts or []
|
||||
if role == "user":
|
||||
fr_parts = [p for p in parts if p.function_response]
|
||||
if fr_parts:
|
||||
for p in fr_parts:
|
||||
fr = p.function_response
|
||||
fn_name = fr.name
|
||||
if fn_name in pending_tool_call_ids and pending_tool_call_ids[fn_name]:
|
||||
call_id = pending_tool_call_ids[fn_name].pop(0)
|
||||
else:
|
||||
call_id = f"call_{len(messages)}_{fn_name}"
|
||||
|
||||
resp = dict(fr.response) if fr.response else {}
|
||||
res_val = resp.get("result", json.dumps(resp, ensure_ascii=False))
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": call_id,
|
||||
"name": fn_name,
|
||||
"content": str(res_val),
|
||||
})
|
||||
else:
|
||||
text = "".join(p.text for p in parts if p.text)
|
||||
messages.append({"role": "user", "content": text})
|
||||
elif role == "model":
|
||||
fc_parts = [p for p in parts if p.function_call]
|
||||
if fc_parts:
|
||||
tcs = []
|
||||
for idx, p in enumerate(fc_parts):
|
||||
fc = p.function_call
|
||||
fn_name = fc.name
|
||||
call_id = f"call_{len(messages)}_{idx}_{fn_name}"
|
||||
pending_tool_call_ids.setdefault(fn_name, []).append(call_id)
|
||||
args = dict(fc.args) if fc.args else {}
|
||||
tcs.append({
|
||||
"id": call_id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": fn_name,
|
||||
"arguments": json.dumps(args, ensure_ascii=False),
|
||||
},
|
||||
})
|
||||
messages.append({"role": "assistant", "content": None, "tool_calls": tcs})
|
||||
else:
|
||||
text = "".join(p.text for p in parts if p.text)
|
||||
messages.append({"role": "assistant", "content": text})
|
||||
|
||||
if len(messages) > self.max_turns * 2:
|
||||
messages = messages[-self.max_turns * 2 :]
|
||||
|
||||
self._cache[key] = messages
|
||||
self._save_raw_messages(chat_id, thread_id)
|
||||
|
||||
def append_content(self, chat_id: int, thread_id: Optional[int], content: types.Content) -> None:
|
||||
"""Add a single content turn (Gemini compatibility)."""
|
||||
self.append_turn_sequence(chat_id, thread_id, [content])
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# OpenAI / DeepSeek Compatibility API
|
||||
# --------------------------------------------------------------------------
|
||||
def get_openai_messages(self, chat_id: int, thread_id: Optional[int]) -> list[dict[str, Any]]:
|
||||
"""Retrieve conversation history in sanitized standard OpenAI messages list format."""
|
||||
raw_messages = self._load_raw_messages(chat_id, thread_id)
|
||||
openai_msgs: list[dict[str, Any]] = []
|
||||
|
||||
for msg in raw_messages:
|
||||
role = msg.get("role", "user")
|
||||
out: dict[str, Any] = {"role": role}
|
||||
|
||||
if role == "user":
|
||||
out["content"] = str(msg.get("content") or "")
|
||||
elif role == "assistant":
|
||||
out["content"] = msg.get("content")
|
||||
if msg.get("tool_calls"):
|
||||
out["tool_calls"] = msg["tool_calls"]
|
||||
elif role == "tool":
|
||||
out["tool_call_id"] = msg.get("tool_call_id", "call_default")
|
||||
out["name"] = msg.get("name", "tool")
|
||||
out["content"] = str(msg.get("content") or "")
|
||||
|
||||
openai_msgs.append(out)
|
||||
|
||||
# Apply strict DeepSeek/OpenAI tool call chain sanitizer
|
||||
sanitized = _sanitize_openai_messages(openai_msgs)
|
||||
return sanitized
|
||||
|
||||
def append_openai_turn_sequence(
|
||||
self, chat_id: int, thread_id: Optional[int], new_messages: list[dict[str, Any]]
|
||||
) -> None:
|
||||
"""Append messages generated in an OpenAI-compatible turn sequence."""
|
||||
key = self._get_key(chat_id, thread_id)
|
||||
messages = self._load_raw_messages(chat_id, thread_id)
|
||||
|
||||
for m in new_messages:
|
||||
if m.get("role") == "system":
|
||||
continue
|
||||
messages.append(m)
|
||||
|
||||
if len(messages) > self.max_turns * 2:
|
||||
messages = messages[-self.max_turns * 2 :]
|
||||
|
||||
self._cache[key] = messages
|
||||
self._save_raw_messages(chat_id, thread_id)
|
||||
|
||||
# --------------------------------------------------------------------------
|
||||
# Common Utilities
|
||||
# --------------------------------------------------------------------------
|
||||
def clear(self, chat_id: int, thread_id: Optional[int]) -> None:
|
||||
"""Clear the history for this topic."""
|
||||
key = self._get_key(chat_id, thread_id)
|
||||
self._cache[key] = []
|
||||
file_path = _session_file(self.data_dir, chat_id, thread_id)
|
||||
if file_path.exists():
|
||||
file_path.unlink()
|
||||
logger.info("Cleared conversation history for chat=%s, thread=%s", chat_id, thread_id)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Agent factory creating the appropriate LLM provider agent."""
|
||||
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from homeagent.agent.base import BaseAgent
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.agent.gemini import GeminiAgent
|
||||
from homeagent.agent.openai_agent import OpenAIAgent
|
||||
from homeagent.config import Settings, get_settings
|
||||
from homeagent.tools.registry import ToolRegistry, get_tool_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_agent(
|
||||
settings: Optional[Settings] = None,
|
||||
registry: Optional[ToolRegistry] = None,
|
||||
conversation_manager: Optional[ConversationManager] = None,
|
||||
) -> BaseAgent:
|
||||
"""Create and return an agent configured for the active LLM_PROVIDER."""
|
||||
settings = settings or get_settings()
|
||||
registry = registry or get_tool_registry()
|
||||
conversation_manager = conversation_manager or ConversationManager(settings.DATA_DIR)
|
||||
|
||||
provider = settings.LLM_PROVIDER.lower().strip()
|
||||
logger.info("Initializing Agent with LLM provider: '%s'", provider)
|
||||
|
||||
if provider == "deepseek":
|
||||
return OpenAIAgent(
|
||||
settings=settings,
|
||||
registry=registry,
|
||||
conversation_manager=conversation_manager,
|
||||
provider_override="deepseek",
|
||||
)
|
||||
elif provider in ("openai", "openai_compatible"):
|
||||
return OpenAIAgent(
|
||||
settings=settings,
|
||||
registry=registry,
|
||||
conversation_manager=conversation_manager,
|
||||
provider_override="openai",
|
||||
)
|
||||
elif provider == "gemini":
|
||||
return GeminiAgent(
|
||||
settings=settings,
|
||||
registry=registry,
|
||||
conversation_manager=conversation_manager,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"Unknown LLM_PROVIDER '%s'. Falling back to 'gemini'.",
|
||||
provider,
|
||||
)
|
||||
return GeminiAgent(
|
||||
settings=settings,
|
||||
registry=registry,
|
||||
conversation_manager=conversation_manager,
|
||||
)
|
||||
@@ -0,0 +1,172 @@
|
||||
"""Gemini AI Studio Agent with multi-turn tool calling and global memory integration."""
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any, Awaitable, Callable, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
from homeagent.agent.base import BaseAgent
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.config import Settings, get_settings
|
||||
from homeagent.memory.global_memory import get_global_memory
|
||||
from homeagent.tools.registry import ToolRegistry, get_tool_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class GeminiAgent(BaseAgent):
|
||||
"""Agent orchestrator powered by Google AI Studio (Gemini)."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Optional[Settings] = None,
|
||||
registry: Optional[ToolRegistry] = None,
|
||||
conversation_manager: Optional[ConversationManager] = None,
|
||||
) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self.registry = registry or get_tool_registry()
|
||||
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
||||
|
||||
api_key = self.settings.GEMINI_API_KEY.get_secret_value()
|
||||
self._client: Optional[genai.Client] = None
|
||||
if api_key:
|
||||
self._client = genai.Client(api_key=api_key)
|
||||
else:
|
||||
logger.warning("GEMINI_API_KEY is not set. Agent will return configuration prompts.")
|
||||
|
||||
def _build_system_instruction(self) -> str:
|
||||
now = datetime.now()
|
||||
dt_context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
||||
memory_summary = get_global_memory().get_memory_summary()
|
||||
|
||||
parts = [
|
||||
self.settings.SYSTEM_INSTRUCTION,
|
||||
dt_context,
|
||||
]
|
||||
if memory_summary:
|
||||
parts.append(memory_summary)
|
||||
|
||||
return "\n\n".join(parts)
|
||||
|
||||
def _get_tools_config(self) -> Optional[list[types.Tool]]:
|
||||
declarations = self.registry.get_function_declarations()
|
||||
if not declarations:
|
||||
return None
|
||||
return [types.Tool(function_declarations=declarations)]
|
||||
|
||||
async def chat(
|
||||
self,
|
||||
chat_id: int,
|
||||
thread_id: Optional[int],
|
||||
user_message: str,
|
||||
max_tool_iterations: int = 8,
|
||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
||||
) -> str:
|
||||
"""Process a user message within the topic context, running tools as requested by Gemini."""
|
||||
if not self._client:
|
||||
return (
|
||||
"⚠️ **Google AI Studio API Key не настроен.**\n"
|
||||
"Пожалуйста, добавьте `GEMINI_API_KEY=your_key` в файл `.env` и перезапустите бота.\n"
|
||||
"Получить ключ можно бесплатно в [Google AI Studio](https://aistudio.google.com/)."
|
||||
)
|
||||
|
||||
# 1. Fetch current conversation history
|
||||
history = list(self.conversation_manager.get_history(chat_id, thread_id))
|
||||
|
||||
# 2. Add current user message
|
||||
user_content = types.Content(
|
||||
role="user",
|
||||
parts=[types.Part.from_text(text=user_message)],
|
||||
)
|
||||
history.append(user_content)
|
||||
|
||||
turn_contents: list[types.Content] = [user_content]
|
||||
system_instruction = self._build_system_instruction()
|
||||
tools_config = self._get_tools_config()
|
||||
|
||||
config = types.GenerateContentConfig(
|
||||
system_instruction=system_instruction,
|
||||
tools=tools_config,
|
||||
temperature=0.4,
|
||||
)
|
||||
|
||||
for iteration in range(max_tool_iterations):
|
||||
logger.debug(
|
||||
"Gemini request turn: chat=%d, thread=%s, iteration=%d, history_len=%d",
|
||||
chat_id,
|
||||
thread_id,
|
||||
iteration,
|
||||
len(history),
|
||||
)
|
||||
|
||||
if on_progress:
|
||||
if iteration == 0:
|
||||
await on_progress("🤔 Формирую ответ...")
|
||||
else:
|
||||
await on_progress(f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
||||
|
||||
try:
|
||||
response = await self._client.aio.models.generate_content(
|
||||
model=self.settings.GEMINI_MODEL,
|
||||
contents=history,
|
||||
config=config,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("Error calling Gemini API: %s", e)
|
||||
return f"⚠️ Ошибка обращения к Google Gemini API: {type(e).__name__}: {str(e)}"
|
||||
|
||||
# Check if model requested function calls
|
||||
function_calls = response.function_calls
|
||||
if not function_calls:
|
||||
# Final response reached
|
||||
final_text = response.text or "*(Пустой ответ)*"
|
||||
model_content = types.Content(
|
||||
role="model",
|
||||
parts=[types.Part.from_text(text=final_text)],
|
||||
)
|
||||
turn_contents.append(model_content)
|
||||
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
||||
return final_text
|
||||
|
||||
# Model produced function calls
|
||||
# Save the model's message with function calls
|
||||
candidate = response.candidates[0] if response.candidates else None
|
||||
model_parts = candidate.content.parts if (candidate and candidate.content) else []
|
||||
model_content = types.Content(role="model", parts=model_parts)
|
||||
history.append(model_content)
|
||||
turn_contents.append(model_content)
|
||||
|
||||
# Execute all function calls requested by the model in this step
|
||||
response_parts: list[types.Part] = []
|
||||
for idx, fc in enumerate(function_calls, 1):
|
||||
fc_name = fc.name
|
||||
fc_args = dict(fc.args) if fc.args else {}
|
||||
|
||||
if on_progress:
|
||||
from homeagent.bot.progress import format_tool_progress
|
||||
|
||||
step_info = f"[{idx}/{len(function_calls)}] " if len(function_calls) > 1 else ""
|
||||
desc = format_tool_progress(fc_name, fc_args)
|
||||
await on_progress(f"⏳ {step_info}{desc}")
|
||||
|
||||
logger.info("Executing function call: %s(%s)", fc_name, fc_args)
|
||||
tool_result = await self.registry.execute(fc_name, fc_args)
|
||||
|
||||
response_parts.append(
|
||||
types.Part.from_function_response(
|
||||
name=fc_name,
|
||||
response={"result": tool_result},
|
||||
)
|
||||
)
|
||||
|
||||
tool_response_content = types.Content(role="user", parts=response_parts)
|
||||
history.append(tool_response_content)
|
||||
turn_contents.append(tool_response_content)
|
||||
|
||||
# If exceeded max iterations, return warning
|
||||
warning_msg = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
||||
self.conversation_manager.append_turn_sequence(chat_id, thread_id, turn_contents)
|
||||
return warning_msg
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
"""OpenAI-compatible Agent supporting DeepSeek, OpenRouter, Ollama, and OpenAI."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Any, Awaitable, Callable, Optional
|
||||
|
||||
import openai
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from homeagent.agent.base import BaseAgent
|
||||
from homeagent.agent.conversation import ConversationManager
|
||||
from homeagent.config import Settings, get_settings
|
||||
from homeagent.memory.global_memory import get_global_memory
|
||||
from homeagent.tools.registry import ToolRegistry, get_tool_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class OpenAIAgent(BaseAgent):
|
||||
"""Agent orchestrator for DeepSeek and OpenAI-compatible models."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Optional[Settings] = None,
|
||||
registry: Optional[ToolRegistry] = None,
|
||||
conversation_manager: Optional[ConversationManager] = None,
|
||||
provider_override: Optional[str] = None,
|
||||
) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self.registry = registry or get_tool_registry()
|
||||
self.conversation_manager = conversation_manager or ConversationManager(self.settings.DATA_DIR)
|
||||
self.provider = provider_override or self.settings.LLM_PROVIDER
|
||||
|
||||
# Resolve configuration based on provider
|
||||
if self.provider == "deepseek":
|
||||
api_key_secret = self.settings.DEEPSEEK_API_KEY or self.settings.OPENAI_API_KEY
|
||||
self.api_key = api_key_secret.get_secret_value() if api_key_secret else ""
|
||||
self.base_url = self.settings.DEEPSEEK_BASE_URL.rstrip("/")
|
||||
self.model = self.settings.DEEPSEEK_MODEL or "deepseek-chat"
|
||||
else:
|
||||
api_key_secret = self.settings.OPENAI_API_KEY
|
||||
self.api_key = api_key_secret.get_secret_value() if api_key_secret else ""
|
||||
self.base_url = self.settings.OPENAI_BASE_URL.rstrip("/")
|
||||
self.model = self.settings.OPENAI_MODEL or "gpt-4o"
|
||||
|
||||
self._client: Optional[AsyncOpenAI] = None
|
||||
if self.api_key:
|
||||
self._client = AsyncOpenAI(
|
||||
api_key=self.api_key,
|
||||
base_url=self.base_url,
|
||||
timeout=60.0,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
"API key for %s is not set. OpenAIAgent will return configuration prompt.",
|
||||
self.provider.upper(),
|
||||
)
|
||||
|
||||
def _build_system_instruction(self) -> str:
|
||||
now = datetime.now()
|
||||
dt_context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
||||
memory_summary = get_global_memory().get_memory_summary()
|
||||
|
||||
parts = [
|
||||
self.settings.SYSTEM_INSTRUCTION,
|
||||
dt_context,
|
||||
]
|
||||
if memory_summary:
|
||||
parts.append(memory_summary)
|
||||
|
||||
return "\n\n".join(parts)
|
||||
|
||||
async def chat(
|
||||
self,
|
||||
chat_id: int,
|
||||
thread_id: Optional[int],
|
||||
user_message: str,
|
||||
max_tool_iterations: int = 100,
|
||||
on_progress: Optional[Callable[[str], Awaitable[None]]] = None,
|
||||
) -> str:
|
||||
"""Process user message within topic context using DeepSeek / OpenAI API."""
|
||||
if not self._client:
|
||||
if self.provider == "deepseek":
|
||||
return (
|
||||
"⚠️ **DeepSeek API Key не настроен.**\n\n"
|
||||
"Пожалуйста, добавьте ваш ключ в `.env`:\n"
|
||||
"```env\n"
|
||||
"LLM_PROVIDER=deepseek\n"
|
||||
"DEEPSEEK_API_KEY=sk-...\n"
|
||||
"DEEPSEEK_MODEL=deepseek-chat\n"
|
||||
"```\n"
|
||||
"Получить ключ можно на платформе [DeepSeek Platform](https://platform.deepseek.com)."
|
||||
)
|
||||
else:
|
||||
return (
|
||||
"⚠️ **OpenAI / OpenAI-compatible API Key не настроен.**\n\n"
|
||||
"Пожалуйста, добавьте ваш ключ в `.env`:\n"
|
||||
"```env\n"
|
||||
"LLM_PROVIDER=openai\n"
|
||||
"OPENAI_API_KEY=sk-...\n"
|
||||
"OPENAI_BASE_URL=https://api.openai.com/v1\n"
|
||||
"OPENAI_MODEL=gpt-4o\n"
|
||||
"```"
|
||||
)
|
||||
|
||||
# 1. Fetch current conversation history
|
||||
history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id))
|
||||
|
||||
# 2. Add current user message
|
||||
user_turn: dict[str, Any] = {"role": "user", "content": user_message}
|
||||
history.append(user_turn)
|
||||
|
||||
system_instruction = self._build_system_instruction()
|
||||
working_messages: list[dict[str, Any]] = [
|
||||
{"role": "system", "content": system_instruction},
|
||||
*history,
|
||||
]
|
||||
|
||||
turn_sequence: list[dict[str, Any]] = [user_turn]
|
||||
tools = self.registry.get_openai_tools()
|
||||
|
||||
for iteration in range(max_tool_iterations):
|
||||
logger.debug(
|
||||
"OpenAI/DeepSeek request turn: chat=%d, thread=%s, iteration=%d, model=%s",
|
||||
chat_id,
|
||||
thread_id,
|
||||
iteration,
|
||||
self.model,
|
||||
)
|
||||
|
||||
if on_progress:
|
||||
if iteration == 0:
|
||||
await on_progress("🤔 Формирую ответ...")
|
||||
else:
|
||||
await on_progress(f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
||||
|
||||
kwargs: dict[str, Any] = {
|
||||
"model": self.model,
|
||||
"messages": working_messages,
|
||||
"temperature": 0.3,
|
||||
}
|
||||
if tools:
|
||||
kwargs["tools"] = tools
|
||||
|
||||
try:
|
||||
response = await self._client.chat.completions.create(**kwargs)
|
||||
except openai.APIError as e:
|
||||
logger.exception("OpenAI/DeepSeek API error: %s", e)
|
||||
return f"⚠️ Ошибка обращения к {self.provider.upper()} API ({e.code or 'Error'}): {e.message}"
|
||||
except Exception as e:
|
||||
logger.exception("Unexpected error calling %s: %s", self.provider, e)
|
||||
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {str(e)}"
|
||||
|
||||
choice = response.choices[0]
|
||||
choice_message = choice.message
|
||||
|
||||
# Check if model requested function calls
|
||||
tool_calls = choice_message.tool_calls
|
||||
if not tool_calls:
|
||||
final_text = choice_message.content or "*(Пустой ответ)*"
|
||||
model_turn = {"role": "assistant", "content": final_text}
|
||||
turn_sequence.append(model_turn)
|
||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, turn_sequence)
|
||||
return final_text
|
||||
|
||||
# Model produced tool calls
|
||||
assistant_turn: dict[str, Any] = {
|
||||
"role": "assistant",
|
||||
"content": choice_message.content,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": tc.id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.function.name,
|
||||
"arguments": tc.function.arguments,
|
||||
},
|
||||
}
|
||||
for tc in tool_calls
|
||||
],
|
||||
}
|
||||
working_messages.append(assistant_turn)
|
||||
turn_sequence.append(assistant_turn)
|
||||
|
||||
# Execute all tool calls
|
||||
for idx, tc in enumerate(tool_calls, 1):
|
||||
fn_name = tc.function.name
|
||||
raw_args = tc.function.arguments or "{}"
|
||||
try:
|
||||
fn_args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
|
||||
except Exception as parse_err:
|
||||
logger.warning("Failed parsing arguments for %s: %s", fn_name, parse_err)
|
||||
fn_args = {}
|
||||
|
||||
if on_progress:
|
||||
from homeagent.bot.progress import format_tool_progress
|
||||
|
||||
step_info = f"[{idx}/{len(tool_calls)}] " if len(tool_calls) > 1 else ""
|
||||
desc = format_tool_progress(fn_name, fn_args)
|
||||
await on_progress(f"⏳ {step_info}{desc}")
|
||||
|
||||
logger.info("Executing OpenAI/DeepSeek tool call: %s(%s)", fn_name, fn_args)
|
||||
tool_result = await self.registry.execute(fn_name, fn_args)
|
||||
|
||||
tool_response_msg: dict[str, Any] = {
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": fn_name,
|
||||
"content": tool_result,
|
||||
}
|
||||
working_messages.append(tool_response_msg)
|
||||
turn_sequence.append(tool_response_msg)
|
||||
|
||||
warning_msg = "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, turn_sequence)
|
||||
return warning_msg
|
||||
@@ -0,0 +1,297 @@
|
||||
"""Subagent execution runner for parallel and specialized subtasks across LLM providers."""
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Optional
|
||||
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
from openai import AsyncOpenAI
|
||||
|
||||
from homeagent.config import Settings, get_settings
|
||||
from homeagent.tools.registry import ToolRegistry, get_tool_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SubagentRunner:
|
||||
"""Orchestrates fast, autonomous subagent executions with independent tool calling across providers."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
settings: Optional[Settings] = None,
|
||||
registry: Optional[ToolRegistry] = None,
|
||||
) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self.registry = registry or get_tool_registry()
|
||||
|
||||
# 1. Gemini client initialization
|
||||
self._gemini_client: Optional[genai.Client] = None
|
||||
gemini_api_key = self.settings.GEMINI_API_KEY.get_secret_value()
|
||||
if gemini_api_key:
|
||||
self._gemini_client = genai.Client(api_key=gemini_api_key)
|
||||
|
||||
# 2. OpenAI / DeepSeek client initialization
|
||||
self._openai_client: Optional[AsyncOpenAI] = None
|
||||
provider = self.settings.LLM_PROVIDER
|
||||
if provider == "deepseek":
|
||||
secret = self.settings.DEEPSEEK_API_KEY or self.settings.OPENAI_API_KEY
|
||||
api_key = secret.get_secret_value() if secret else ""
|
||||
base_url = self.settings.DEEPSEEK_BASE_URL.rstrip("/")
|
||||
else:
|
||||
secret = self.settings.OPENAI_API_KEY
|
||||
api_key = secret.get_secret_value() if secret else ""
|
||||
base_url = self.settings.OPENAI_BASE_URL.rstrip("/")
|
||||
|
||||
if api_key:
|
||||
self._openai_client = AsyncOpenAI(
|
||||
api_key=api_key,
|
||||
base_url=base_url,
|
||||
timeout=45.0,
|
||||
)
|
||||
|
||||
@property
|
||||
def _client(self) -> Optional[genai.Client]:
|
||||
"""Backward-compatible access to underlying Gemini client."""
|
||||
return self._gemini_client
|
||||
|
||||
@_client.setter
|
||||
def _client(self, client: Optional[genai.Client]) -> None:
|
||||
self._gemini_client = client
|
||||
|
||||
def _get_subagent_tools_config(self) -> Optional[list[types.Tool]]:
|
||||
"""Backward-compatible alias for _get_gemini_subagent_tools_config."""
|
||||
return self._get_gemini_subagent_tools_config()
|
||||
|
||||
def _get_gemini_subagent_tools_config(self) -> Optional[list[types.Tool]]:
|
||||
"""Get tools declarations excluding subagent tools to avoid recursion."""
|
||||
declarations = []
|
||||
for tool_def in self.registry.list_tools():
|
||||
if tool_def.name in ("spawn_subagent", "spawn_parallel_subagents"):
|
||||
continue
|
||||
declarations.append(
|
||||
types.FunctionDeclaration(
|
||||
name=tool_def.name,
|
||||
description=tool_def.description,
|
||||
parameters=tool_def.parameters_schema,
|
||||
)
|
||||
)
|
||||
if not declarations:
|
||||
return None
|
||||
return [types.Tool(function_declarations=declarations)]
|
||||
|
||||
async def _run_task_gemini(
|
||||
self,
|
||||
task: str,
|
||||
role: str,
|
||||
context: Optional[str] = None,
|
||||
max_tool_iterations: int = 6,
|
||||
) -> str:
|
||||
if not self._gemini_client:
|
||||
return "Ошибка: GEMINI_API_KEY не установлен для подагента."
|
||||
|
||||
logger.info("[SUBAGENT GEMINI START] Role='%s', Task='%s'", role, task)
|
||||
|
||||
system_instruction = (
|
||||
f"Ты — быстрый автономный AI-подагент с ролью '{role}'.\n"
|
||||
f"Твоя цель: максимально быстро и точно выполнить поставленную задачу: '{task}'.\n"
|
||||
"Используй доступные инструменты (Jira, Google Календарь, память, Gitea, поиск в интернете web_search/web_fetch_page, безопасное выполнение кода code_execute/sandbox_run_command), чтобы получить актуальные данные или выполнить действие.\n"
|
||||
"После выполнения предоставь четкую, емкую выжимку в Markdown главному агенту-координатору."
|
||||
)
|
||||
if context:
|
||||
system_instruction += f"\nДополнительный контекст от главного агента:\n{context}"
|
||||
|
||||
tools_config = self._get_gemini_subagent_tools_config()
|
||||
config = types.GenerateContentConfig(
|
||||
system_instruction=system_instruction,
|
||||
tools=tools_config,
|
||||
temperature=0.2,
|
||||
)
|
||||
|
||||
history: list[types.Content] = [
|
||||
types.Content(role="user", parts=[types.Part.from_text(text=task)])
|
||||
]
|
||||
model = self.settings.GEMINI_SUBAGENT_MODEL or "gemini-2.5-flash"
|
||||
|
||||
for iteration in range(max_tool_iterations):
|
||||
try:
|
||||
response = await self._gemini_client.aio.models.generate_content(
|
||||
model=model,
|
||||
contents=history,
|
||||
config=config,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("[SUBAGENT ERROR] in role='%s': %s", role, e)
|
||||
return f"Ошибка подагента ({role}): {type(e).__name__}: {str(e)}"
|
||||
|
||||
function_calls = response.function_calls
|
||||
if not function_calls:
|
||||
final_text = response.text or "(Подагент завершил работу без вывода)"
|
||||
logger.info("[SUBAGENT DONE] Role='%s'", role)
|
||||
return final_text
|
||||
|
||||
candidate = response.candidates[0] if response.candidates else None
|
||||
model_parts = candidate.content.parts if (candidate and candidate.content) else []
|
||||
history.append(types.Content(role="model", parts=model_parts))
|
||||
|
||||
response_parts: list[types.Part] = []
|
||||
for fc in function_calls:
|
||||
fc_name = fc.name
|
||||
fc_args = dict(fc.args) if fc.args else {}
|
||||
logger.info("[SUBAGENT TOOL CALL] %s(%s)", fc_name, fc_args)
|
||||
|
||||
tool_result = await self.registry.execute(fc_name, fc_args)
|
||||
response_parts.append(
|
||||
types.Part.from_function_response(
|
||||
name=fc_name,
|
||||
response={"result": tool_result},
|
||||
)
|
||||
)
|
||||
|
||||
history.append(types.Content(role="user", parts=response_parts))
|
||||
|
||||
return f"Подагент ({role}) достиг лимита итераций без итогового ответа."
|
||||
|
||||
async def _run_task_openai(
|
||||
self,
|
||||
task: str,
|
||||
role: str,
|
||||
context: Optional[str] = None,
|
||||
max_tool_iterations: int = 6,
|
||||
) -> str:
|
||||
provider = self.settings.LLM_PROVIDER.upper()
|
||||
if not self._openai_client:
|
||||
return f"Ошибка: API ключ для {provider} не установлен для подагента."
|
||||
|
||||
logger.info("[SUBAGENT %s START] Role='%s', Task='%s'", provider, role, task)
|
||||
|
||||
system_instruction = (
|
||||
f"Ты — быстрый автономный AI-подагент с ролью '{role}'.\n"
|
||||
f"Твоя цель: максимально быстро и точно выполнить поставленную задачу: '{task}'.\n"
|
||||
"Используй доступные инструменты (Jira, Google Календарь, память, Gitea, поиск в интернете web_search/web_fetch_page, безопасное выполнение кода code_execute/sandbox_run_command), чтобы получить актуальные данные или выполнить действие.\n"
|
||||
"После выполнения предоставь четкую, емкую выжимку в Markdown главному агенту-координатору."
|
||||
)
|
||||
if context:
|
||||
system_instruction += f"\nДополнительный контекст от главного агента:\n{context}"
|
||||
|
||||
messages: list[dict[str, Any]] = [
|
||||
{"role": "system", "content": system_instruction},
|
||||
{"role": "user", "content": task},
|
||||
]
|
||||
|
||||
tools = self.registry.get_openai_tools(exclude_subagents=True)
|
||||
model = self.settings.get_active_subagent_model()
|
||||
|
||||
for iteration in range(max_tool_iterations):
|
||||
kwargs: dict[str, Any] = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"temperature": 0.2,
|
||||
}
|
||||
if tools:
|
||||
kwargs["tools"] = tools
|
||||
|
||||
try:
|
||||
response = await self._openai_client.chat.completions.create(**kwargs)
|
||||
except Exception as e:
|
||||
logger.exception("[SUBAGENT %s ERROR] in role='%s': %s", provider, role, e)
|
||||
return f"Ошибка подагента ({role}): {type(e).__name__}: {str(e)}"
|
||||
|
||||
choice_message = response.choices[0].message
|
||||
tool_calls = choice_message.tool_calls
|
||||
if not tool_calls:
|
||||
final_text = choice_message.content or "(Подагент завершил работу без вывода)"
|
||||
logger.info("[SUBAGENT DONE] Role='%s'", role)
|
||||
return final_text
|
||||
|
||||
assistant_msg: dict[str, Any] = {
|
||||
"role": "assistant",
|
||||
"content": choice_message.content,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": tc.id,
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": tc.function.name,
|
||||
"arguments": tc.function.arguments,
|
||||
},
|
||||
}
|
||||
for tc in tool_calls
|
||||
],
|
||||
}
|
||||
messages.append(assistant_msg)
|
||||
|
||||
for tc in tool_calls:
|
||||
fn_name = tc.function.name
|
||||
raw_args = tc.function.arguments or "{}"
|
||||
try:
|
||||
fn_args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
|
||||
except Exception:
|
||||
fn_args = {}
|
||||
|
||||
logger.info("[SUBAGENT TOOL CALL] %s(%s)", fn_name, fn_args)
|
||||
tool_result = await self.registry.execute(fn_name, fn_args)
|
||||
messages.append({
|
||||
"role": "tool",
|
||||
"tool_call_id": tc.id,
|
||||
"name": fn_name,
|
||||
"content": tool_result,
|
||||
})
|
||||
|
||||
return f"Подагент ({role}) достиг лимита итераций без итогового ответа."
|
||||
|
||||
async def run_task(
|
||||
self,
|
||||
task: str,
|
||||
role: str = "Specialist",
|
||||
context: Optional[str] = None,
|
||||
max_tool_iterations: int = 6,
|
||||
) -> str:
|
||||
"""Run a single subagent task to completion using the active provider's fast subagent model."""
|
||||
if self.settings.LLM_PROVIDER == "gemini":
|
||||
return await self._run_task_gemini(
|
||||
task=task, role=role, context=context, max_tool_iterations=max_tool_iterations
|
||||
)
|
||||
else:
|
||||
return await self._run_task_openai(
|
||||
task=task, role=role, context=context, max_tool_iterations=max_tool_iterations
|
||||
)
|
||||
|
||||
async def run_parallel(self, tasks: list[dict[str, Any]]) -> str:
|
||||
"""Run multiple subagents concurrently across providers using asyncio.gather."""
|
||||
if not tasks:
|
||||
return "Нет задач для выполнения подагентами."
|
||||
|
||||
logger.info("[PARALLEL SUBAGENTS] Launching %d concurrent subagents...", len(tasks))
|
||||
|
||||
coros = []
|
||||
task_roles = []
|
||||
for idx, t in enumerate(tasks, 1):
|
||||
task_desc = t.get("task", "")
|
||||
role = t.get("role", f"Подагент #{idx}")
|
||||
context = t.get("context")
|
||||
task_roles.append((role, task_desc))
|
||||
coros.append(self.run_task(task=task_desc, role=role, context=context))
|
||||
|
||||
results = await asyncio.gather(*coros, return_exceptions=True)
|
||||
|
||||
lines = [f"📊 **Результаты работы параллельных подагентов ({len(tasks)}):**\n"]
|
||||
for (role, desc), res in zip(task_roles, results):
|
||||
if isinstance(res, Exception):
|
||||
lines.append(f"### ❌ {role} (Задача: {desc})\nОшибка: {res}\n")
|
||||
else:
|
||||
lines.append(f"### ✅ {role} (Задача: {desc})\n{res}\n")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# Singleton container
|
||||
_subagent_runner_instance: Optional[SubagentRunner] = None
|
||||
|
||||
|
||||
def get_subagent_runner() -> SubagentRunner:
|
||||
global _subagent_runner_instance
|
||||
if _subagent_runner_instance is None:
|
||||
_subagent_runner_instance = SubagentRunner()
|
||||
return _subagent_runner_instance
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Bot package for HomeAgent."""
|
||||
|
||||
from homeagent.bot.middlewares import WhitelistMiddleware
|
||||
from homeagent.bot.telegram_app import TelegramAgentApp
|
||||
|
||||
__all__ = ["TelegramAgentApp", "WhitelistMiddleware"]
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Message and command handlers for HomeAgent Telegram bot with strict Rich Messages support."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from aiogram import Router
|
||||
from aiogram.enums import ChatAction
|
||||
from aiogram.filters import Command
|
||||
from aiogram.types import InputRichMessage, Message
|
||||
|
||||
from homeagent.agent.base import BaseAgent
|
||||
from homeagent.bot.progress import ProgressReporter
|
||||
from homeagent.bot.utils import split_message
|
||||
from homeagent.config import Settings
|
||||
from homeagent.memory.global_memory import get_global_memory
|
||||
from homeagent.skills.manager import SkillManager
|
||||
from homeagent.tools.registry import ToolRegistry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def create_bot_router(
|
||||
settings: Settings,
|
||||
agent: BaseAgent,
|
||||
skill_manager: SkillManager,
|
||||
tool_registry: ToolRegistry,
|
||||
) -> Router:
|
||||
"""Create and configure the main Aiogram Router."""
|
||||
router = Router(name="main_router")
|
||||
|
||||
@router.message(Command("start", "help"))
|
||||
async def handle_start(message: Message) -> None:
|
||||
user_id = message.from_user.id if message.from_user else 0
|
||||
thread_id = message.message_thread_id
|
||||
is_topic = message.is_topic_message or (thread_id is not None)
|
||||
|
||||
skills = skill_manager.list_skills()
|
||||
tools = tool_registry.list_tools()
|
||||
|
||||
greeting = (
|
||||
f"👋 **Привет! Я твой персональный AI-ассистент.**\n\n"
|
||||
f"⚙️ **Текущий статус:**\n"
|
||||
f"- Твой Telegram ID: `{user_id}`\n"
|
||||
f"- Режим топика форума: {'Да (ID топика: ' + str(thread_id) + ')' if is_topic else 'Основной чат / ЛС'}\n"
|
||||
f"- LLM Провайдер: `{settings.get_active_provider_name()}`\n"
|
||||
f"- Главная модель (Orchestrator): `{settings.get_active_model()}`\n"
|
||||
f"- Модель быстрых подагентов: `{settings.get_active_subagent_model()}`\n"
|
||||
f"- Доступно скиллов: **{len(skills)}** (введите `/skills`)\n"
|
||||
f"- Доступно инструментов: **{len(tools)}**\n\n"
|
||||
f"📋 **Полезные команды:**\n"
|
||||
f"• `/skills` — список готовых скиллов и триггеров\n"
|
||||
f"• `/skill <название>` — запустить конкретный скилл\n"
|
||||
f"• `/memory` — посмотреть факты в глобальной памяти\n"
|
||||
f"• `/reset` — очистить контекст диалога в текущем топике\n"
|
||||
f"• `/help` — показать это сообщение\n\n"
|
||||
f"Просто напиши мне любой вопрос или команду, например:\n"
|
||||
f"_«Какие у меня созвоны на сегодня?»_ или _«Сделай утренний план»_."
|
||||
)
|
||||
await _send_reply(message, greeting)
|
||||
|
||||
@router.message(Command("skills"))
|
||||
async def handle_list_skills(message: Message) -> None:
|
||||
skills = skill_manager.list_skills()
|
||||
if not skills:
|
||||
await _send_reply(
|
||||
message,
|
||||
"В папке `skills/` пока нет скиллов. Добавьте файлы `.md` согласно `docs/SKILLS.md`.",
|
||||
)
|
||||
return
|
||||
|
||||
lines = ["🎯 **Доступные скиллы:**\n"]
|
||||
for s in skills:
|
||||
triggers_str = ", ".join([f"`{t}`" for t in s.triggers]) if s.triggers else f"`/skill {s.name}`"
|
||||
lines.append(f"• **{s.title}** (`{s.name}`)\n _{s.description}_\n Запуск: {triggers_str}\n")
|
||||
|
||||
lines.append("\nВы можете вызвать любой скилл напрямую командой `/skill <имя>` или написав один из триггеров.")
|
||||
await _send_reply(message, "\n".join(lines))
|
||||
|
||||
@router.message(Command("memory"))
|
||||
async def handle_memory(message: Message) -> None:
|
||||
memory = get_global_memory()
|
||||
items = memory.list_facts()
|
||||
if not items:
|
||||
await _send_reply(
|
||||
message,
|
||||
"Глобальная память пуста. Скажите боту, например: _«Запомни, что мой основной проект — KAN»_, "
|
||||
"и он сохранит это в память для всех топиков.",
|
||||
)
|
||||
return
|
||||
|
||||
lines = [f"🧠 **Глобальная память ({len(items)} фактов):**\n"]
|
||||
for item in items:
|
||||
lines.append(f"- `[{item.id}]` ({item.category}): {item.fact}")
|
||||
|
||||
lines.append("\n_Эти данные автоматически подмешиваются в системный промпт во всех топиках._")
|
||||
await _send_reply(message, "\n".join(lines))
|
||||
|
||||
@router.message(Command("reset"))
|
||||
async def handle_reset(message: Message) -> None:
|
||||
chat_id = message.chat.id
|
||||
thread_id = message.message_thread_id
|
||||
agent.conversation_manager.clear(chat_id, thread_id)
|
||||
topic_info = f"в топике #{thread_id}" if thread_id else "в этом чате"
|
||||
await _send_reply(
|
||||
message,
|
||||
f"🧹 Контекст диалога {topic_info} успешно очищен. Глобальная память сохранена.",
|
||||
)
|
||||
|
||||
@router.message()
|
||||
async def handle_message(message: Message) -> None:
|
||||
text = message.text or message.caption or ""
|
||||
if not text.strip():
|
||||
return
|
||||
|
||||
chat_id = message.chat.id
|
||||
thread_id = message.message_thread_id
|
||||
|
||||
# 1. Check if the message triggers a skill
|
||||
matched = skill_manager.match_trigger(text)
|
||||
if matched:
|
||||
skill, extra_args = matched
|
||||
prompt_to_run = skill.render(extra_instructions=extra_args)
|
||||
logger.info("Executing skill '%s' for chat=%d, thread=%s", skill.name, chat_id, thread_id)
|
||||
else:
|
||||
prompt_to_run = text
|
||||
|
||||
# 2. Show typing indicator and dynamic progress message while agent is working
|
||||
typing_task = asyncio.create_task(_keep_typing(message))
|
||||
progress = ProgressReporter(bot=message.bot, chat_id=chat_id, thread_id=thread_id)
|
||||
await progress.start("⏳ Думаю...")
|
||||
|
||||
try:
|
||||
response_text = await agent.chat(
|
||||
chat_id=chat_id,
|
||||
thread_id=thread_id,
|
||||
user_message=prompt_to_run,
|
||||
on_progress=progress.update,
|
||||
)
|
||||
finally:
|
||||
typing_task.cancel()
|
||||
await progress.finish()
|
||||
|
||||
# 3. Split and send chunks strictly as Rich Messages (up to 32K chars)
|
||||
chunks = split_message(response_text)
|
||||
for chunk in chunks:
|
||||
await _send_reply(message, chunk)
|
||||
|
||||
return router
|
||||
|
||||
|
||||
async def _send_reply(message: Message, text: str) -> None:
|
||||
"""Send reply strictly using Telegram sendRichMessage API with InputRichMessage."""
|
||||
rich_msg = InputRichMessage(markdown=text)
|
||||
try:
|
||||
await message.bot.send_rich_message(
|
||||
chat_id=message.chat.id,
|
||||
rich_message=rich_msg,
|
||||
message_thread_id=message.message_thread_id,
|
||||
reply_parameters=message.as_reply_parameters(),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Failed sending markdown rich message, trying html/plain rich message: %s", e)
|
||||
try:
|
||||
# Fallback within rich message: if Markdown had syntax parsing issues
|
||||
await message.bot.send_rich_message(
|
||||
chat_id=message.chat.id,
|
||||
rich_message=InputRichMessage(html=text),
|
||||
message_thread_id=message.message_thread_id,
|
||||
reply_parameters=message.as_reply_parameters(),
|
||||
)
|
||||
except Exception as e2:
|
||||
logger.error("Failed sending rich message via sendRichMessage: %s", e2)
|
||||
# Final safety fallback to standard send_message if rich message endpoint is unavailable
|
||||
try:
|
||||
await message.bot.send_message(
|
||||
chat_id=message.chat.id,
|
||||
text=text,
|
||||
message_thread_id=message.message_thread_id,
|
||||
reply_parameters=message.as_reply_parameters(),
|
||||
)
|
||||
except Exception as final_err:
|
||||
logger.error("Failed sending message completely: %s", final_err)
|
||||
|
||||
|
||||
async def _keep_typing(message: Message) -> None:
|
||||
"""Send typing action periodically while agent executes."""
|
||||
try:
|
||||
while True:
|
||||
await message.bot.send_chat_action(
|
||||
chat_id=message.chat.id,
|
||||
action=ChatAction.TYPING,
|
||||
message_thread_id=message.message_thread_id,
|
||||
)
|
||||
await asyncio.sleep(4.5)
|
||||
except asyncio.CancelledError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.debug("Typing action error: %s", e)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Telegram Bot middlewares for HomeAgent."""
|
||||
|
||||
import logging
|
||||
from typing import Any, Awaitable, Callable, Dict
|
||||
|
||||
from aiogram import BaseMiddleware
|
||||
from aiogram.types import TelegramObject, User
|
||||
|
||||
from homeagent.config import Settings, get_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class WhitelistMiddleware(BaseMiddleware):
|
||||
"""Middleware enforcing strict user whitelist.
|
||||
|
||||
If the user's Telegram ID is not in ALLOWED_TELEGRAM_USER_IDS, the update is dropped silently.
|
||||
"""
|
||||
|
||||
def __init__(self, settings: Settings) -> None:
|
||||
self.settings = settings
|
||||
super().__init__()
|
||||
|
||||
async def __call__(
|
||||
self,
|
||||
handler: Callable[[TelegramObject, Dict[str, Any]], Awaitable[Any]],
|
||||
event: TelegramObject,
|
||||
data: Dict[str, Any],
|
||||
) -> Any:
|
||||
user: User | None = data.get("event_from_user")
|
||||
if not user:
|
||||
# Events without a user (e.g. system status updates) are ignored
|
||||
return None
|
||||
|
||||
allowed_ids = self.settings.ALLOWED_TELEGRAM_USER_IDS
|
||||
if not allowed_ids:
|
||||
logger.warning(
|
||||
"ALLOWED_TELEGRAM_USER_IDS is empty! Dropping message from user %d (@%s). "
|
||||
"Add your Telegram ID to ALLOWED_TELEGRAM_USER_IDS in .env to allow access.",
|
||||
user.id,
|
||||
user.username,
|
||||
)
|
||||
return None
|
||||
|
||||
if user.id not in allowed_ids:
|
||||
logger.warning(
|
||||
"Unauthorized access attempt blocked: user_id=%d, username=@%s",
|
||||
user.id,
|
||||
user.username,
|
||||
)
|
||||
# Silent drop: do not reply, do not leak presence
|
||||
return None
|
||||
|
||||
return await handler(event, data)
|
||||
@@ -0,0 +1,211 @@
|
||||
"""Progress reporter for real-time Telegram status updates."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, Optional
|
||||
|
||||
from aiogram import Bot
|
||||
from aiogram.types import Message
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def format_tool_progress(name: str, args: dict[str, Any]) -> str:
|
||||
"""Format tool invocation into a human-readable progress status."""
|
||||
if name == "web_search":
|
||||
q = str(args.get("query", "")).strip()
|
||||
short_q = f"«{q[:35]}...»" if len(q) > 35 else f"«{q}»" if q else ""
|
||||
return f"🔍 Ищу в интернете {short_q}..."
|
||||
|
||||
if name == "web_fetch_page":
|
||||
url = str(args.get("url", "")).strip()
|
||||
short_url = f"{url[:40]}..." if len(url) > 40 else url
|
||||
return f"🌐 Читаю веб-страницу: {short_url}..."
|
||||
|
||||
if name == "code_execute":
|
||||
lang = str(args.get("language", "python")).strip()
|
||||
return f"⚙️ Выполняю код ({lang}) в изолированной песочнице..."
|
||||
|
||||
if name == "sandbox_run_command":
|
||||
cmd = str(args.get("command", "")).strip()
|
||||
short_cmd = f"`{cmd[:30]}...`" if len(cmd) > 30 else f"`{cmd}`" if cmd else ""
|
||||
return f"💻 Выполняю команду в песочнице: {short_cmd}..."
|
||||
|
||||
if name == "sandbox_file_write":
|
||||
fn = str(args.get("filename", "")).strip()
|
||||
return f"📝 Записываю файл в песочнице: `{fn}`..."
|
||||
|
||||
if name == "sandbox_file_read":
|
||||
fn = str(args.get("filename", "")).strip()
|
||||
return f"📄 Читаю файл из песочницы: `{fn}`..."
|
||||
|
||||
if name == "sandbox_reset":
|
||||
return "🧹 Очищаю рабочую песочницу..."
|
||||
|
||||
if name == "calendar_today_schedule":
|
||||
return "📅 Проверяю расписание на сегодня..."
|
||||
|
||||
if name == "calendar_tomorrow_schedule":
|
||||
return "📅 Проверяю расписание на завтра..."
|
||||
|
||||
if name == "calendar_date_schedule":
|
||||
d = str(args.get("date_str", "")).strip()
|
||||
return f"📅 Проверяю расписание на {d}..." if d else "📅 Проверяю расписание..."
|
||||
|
||||
if name == "calendar_list_events":
|
||||
days = args.get("days_ahead", 7)
|
||||
return f"📅 Загружаю события из календарей (на {days} дн.)..."
|
||||
|
||||
if name == "calendar_create_event":
|
||||
s = str(args.get("summary", "")).strip()
|
||||
short_s = f"«{s[:30]}...»" if len(s) > 30 else f"«{s}»" if s else ""
|
||||
return f"📅 Создаю событие в календаре {short_s}..."
|
||||
|
||||
if name == "calendar_delete_event":
|
||||
return "📅 Удаляю событие из календаря..."
|
||||
|
||||
if name == "calendar_list_calendars":
|
||||
return "📅 Запрашиваю список Google Календарей..."
|
||||
|
||||
if name == "jira_search":
|
||||
return "📋 Ищу задачи в Jira..."
|
||||
|
||||
if name == "jira_my_issues":
|
||||
return "📋 Загружаю назначенные задачи в Jira..."
|
||||
|
||||
if name == "jira_get_issue":
|
||||
key = str(args.get("issue_key", "")).strip()
|
||||
return f"📋 Читаю задачу Jira {key}..." if key else "📋 Читаю задачу Jira..."
|
||||
|
||||
if name == "jira_create_issue":
|
||||
s = str(args.get("summary", "")).strip()
|
||||
return f"📋 Создаю задачу в Jira: «{s[:30]}»..." if s else "📋 Создаю задачу в Jira..."
|
||||
|
||||
if name == "jira_update_issue":
|
||||
key = str(args.get("issue_key", "")).strip()
|
||||
return f"📋 Обновляю задачу Jira {key}..." if key else "📋 Обновляю задачу в Jira..."
|
||||
|
||||
if name == "gitea_list_repos":
|
||||
return "🐙 Загружаю список репозиториев Gitea..."
|
||||
|
||||
if name == "gitea_get_repo_details":
|
||||
repo = str(args.get("repo", "")).strip()
|
||||
return f"🐙 Загружаю детали репозитория {repo}..."
|
||||
|
||||
if name == "gitea_get_directory_contents":
|
||||
return "🐙 Просматриваю файлы в репозитории Gitea..."
|
||||
|
||||
if name == "gitea_get_file_contents":
|
||||
path = str(args.get("filepath", "")).strip()
|
||||
return f"🐙 Читаю файл `{path}` из Gitea..." if path else "🐙 Читаю файл из Gitea..."
|
||||
|
||||
if name == "gitea_save_file_vibecoding":
|
||||
path = str(args.get("filepath", "")).strip()
|
||||
return f"🐙 Сохраняю изменения в `{path}` (Gitea)..." if path else "🐙 Сохраняю файл в Gitea..."
|
||||
|
||||
if name == "gitea_list_branches":
|
||||
return "🐙 Проверяю ветки репозитория Gitea..."
|
||||
|
||||
if name == "gitea_create_branch":
|
||||
branch = str(args.get("branch_name", "")).strip()
|
||||
return f"🐙 Создаю ветку `{branch}` в Gitea..."
|
||||
|
||||
if name == "gitea_list_issues":
|
||||
return "🐙 Загружаю issues и PR в Gitea..."
|
||||
|
||||
if name == "gitea_create_issue":
|
||||
title = str(args.get("title", "")).strip()
|
||||
return f"🐙 Создаю issue «{title[:30]}» в Gitea..."
|
||||
|
||||
if name == "remember_fact":
|
||||
return "🧠 Запоминаю факт в долговременную память..."
|
||||
|
||||
if name == "recall_facts":
|
||||
return "🧠 Ищу информацию в памяти..."
|
||||
|
||||
if name == "list_all_facts":
|
||||
return "🧠 Просматриваю базу памяти..."
|
||||
|
||||
if name == "save_note":
|
||||
title = str(args.get("title", "")).strip()
|
||||
return f"📝 Сохраняю заметку «{title[:30]}»..."
|
||||
|
||||
if name == "get_note":
|
||||
title = str(args.get("title", "")).strip()
|
||||
return f"📝 Читаю заметку «{title[:30]}»..."
|
||||
|
||||
if name == "spawn_subagent":
|
||||
role = str(args.get("role", "помощник")).strip()
|
||||
return f"🤖 Запускаю подагента [{role}]..."
|
||||
|
||||
if name == "spawn_parallel_subagents":
|
||||
tasks = args.get("tasks", [])
|
||||
cnt = len(tasks) if isinstance(tasks, list) else ""
|
||||
return f"👥 Запускаю {cnt} параллельных подагентов..."
|
||||
|
||||
return f"🔧 Выполняю `{name}`..."
|
||||
|
||||
|
||||
class ProgressReporter:
|
||||
"""Manages an ephemeral Telegram progress message during agent processing."""
|
||||
|
||||
def __init__(self, bot: Bot, chat_id: int, thread_id: Optional[int] = None) -> None:
|
||||
self.bot = bot
|
||||
self.chat_id = chat_id
|
||||
self.thread_id = thread_id
|
||||
self.message: Optional[Message] = None
|
||||
self._last_text: str = ""
|
||||
self._last_edit_time: float = 0.0
|
||||
self._lock = asyncio.Lock()
|
||||
self._min_interval: float = 0.7 # Rate limit for message edits
|
||||
|
||||
async def start(self, initial_text: str = "⏳ Думаю...") -> None:
|
||||
"""Send the initial progress message."""
|
||||
try:
|
||||
kwargs: dict[str, Any] = {
|
||||
"chat_id": self.chat_id,
|
||||
"text": initial_text,
|
||||
}
|
||||
if self.thread_id is not None:
|
||||
kwargs["message_thread_id"] = self.thread_id
|
||||
|
||||
self.message = await self.bot.send_message(**kwargs)
|
||||
self._last_text = initial_text
|
||||
self._last_edit_time = time.monotonic()
|
||||
except Exception as e:
|
||||
logger.debug("Failed sending initial progress message: %s", e)
|
||||
self.message = None
|
||||
|
||||
async def update(self, text: str) -> None:
|
||||
"""Update the progress message text, respecting Telegram rate limits."""
|
||||
if not self.message or text == self._last_text:
|
||||
return
|
||||
|
||||
async with self._lock:
|
||||
now = time.monotonic()
|
||||
elapsed = now - self._last_edit_time
|
||||
if elapsed < self._min_interval:
|
||||
await asyncio.sleep(self._min_interval - elapsed)
|
||||
|
||||
try:
|
||||
await self.message.edit_text(text=text)
|
||||
self._last_text = text
|
||||
self._last_edit_time = time.monotonic()
|
||||
except Exception as e:
|
||||
err_str = str(e).lower()
|
||||
if "message is not modified" not in err_str and "message to edit not found" not in err_str:
|
||||
logger.debug("Failed updating progress message: %s", e)
|
||||
|
||||
async def finish(self) -> None:
|
||||
"""Delete the ephemeral progress message when processing finishes."""
|
||||
if not self.message:
|
||||
return
|
||||
|
||||
msg_to_delete = self.message
|
||||
self.message = None
|
||||
|
||||
try:
|
||||
await msg_to_delete.delete()
|
||||
except Exception as e:
|
||||
logger.debug("Could not delete progress message: %s", e)
|
||||
@@ -0,0 +1,105 @@
|
||||
"""Main Telegram application and bot runner for HomeAgent."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
from aiogram import Bot, Dispatcher
|
||||
from aiogram.client.default import DefaultBotProperties
|
||||
from aiogram.enums import ParseMode
|
||||
from aiogram.types import BotCommand
|
||||
|
||||
from homeagent.agent.base import BaseAgent
|
||||
from homeagent.agent.factory import create_agent
|
||||
from homeagent.bot.handlers import create_bot_router
|
||||
from homeagent.bot.middlewares import WhitelistMiddleware
|
||||
from homeagent.config import Settings, get_settings
|
||||
from homeagent.skills.manager import SkillManager
|
||||
from homeagent.tools.loader import load_extensions_from_directory
|
||||
from homeagent.tools.registry import get_tool_registry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TelegramAgentApp:
|
||||
"""Orchestrates Telegram bot lifecycle, middlewares, and agent components."""
|
||||
|
||||
def __init__(self, settings: Optional[Settings] = None) -> None:
|
||||
self.settings = settings or get_settings()
|
||||
self.registry = get_tool_registry()
|
||||
|
||||
# Load dynamic extensions from directory
|
||||
load_extensions_from_directory(self.settings.EXTENSIONS_DIR, self.registry)
|
||||
|
||||
# Initialize skills
|
||||
self.skill_manager = SkillManager(self.settings.SKILLS_DIR)
|
||||
|
||||
# Initialize LLM agent according to active provider (Gemini, DeepSeek, or OpenAI)
|
||||
self.agent: BaseAgent = create_agent(
|
||||
settings=self.settings,
|
||||
registry=self.registry,
|
||||
)
|
||||
|
||||
token = self.settings.TELEGRAM_BOT_TOKEN.get_secret_value().strip()
|
||||
self.bot: Optional[Bot] = None
|
||||
self.dp = Dispatcher()
|
||||
|
||||
if token:
|
||||
try:
|
||||
self.bot = Bot(
|
||||
token=token,
|
||||
default=DefaultBotProperties(parse_mode=ParseMode.MARKDOWN),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning("Could not initialize Telegram Bot with provided token: %s", e)
|
||||
|
||||
# Enforce strict whitelist middleware on all message events
|
||||
self.dp.message.middleware(WhitelistMiddleware(self.settings))
|
||||
|
||||
# Register router
|
||||
router = create_bot_router(
|
||||
settings=self.settings,
|
||||
agent=self.agent,
|
||||
skill_manager=self.skill_manager,
|
||||
tool_registry=self.registry,
|
||||
)
|
||||
self.dp.include_router(router)
|
||||
|
||||
async def _setup_commands(self) -> None:
|
||||
"""Register command menu in Telegram UI."""
|
||||
if not self.bot:
|
||||
return
|
||||
|
||||
commands = [
|
||||
BotCommand(command="start", description="Запустить бота / статус"),
|
||||
BotCommand(command="skills", description="Список доступных скиллов"),
|
||||
BotCommand(command="memory", description="Глобальная память фактов"),
|
||||
BotCommand(command="reset", description="Очистить контекст текущего топика"),
|
||||
BotCommand(command="help", description="Справка по командам"),
|
||||
]
|
||||
try:
|
||||
await self.bot.set_my_commands(commands)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to set bot commands menu: %s", e)
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Start Telegram bot polling."""
|
||||
if not self.bot:
|
||||
raise ValueError("Cannot start bot: TELEGRAM_BOT_TOKEN is missing or invalid.")
|
||||
|
||||
logger.info("Starting HomeAgent Telegram Bot...")
|
||||
logger.info("Allowed User IDs: %s", self.settings.ALLOWED_TELEGRAM_USER_IDS)
|
||||
logger.info("LLM Provider: %s", self.settings.get_active_provider_name())
|
||||
logger.info("Orchestrator Model: %s", self.settings.get_active_model())
|
||||
logger.info("Subagent Model: %s", self.settings.get_active_subagent_model())
|
||||
logger.info("Registered Tools (%d): %s", len(self.registry.list_tools()), [t.name for t in self.registry.list_tools()])
|
||||
logger.info("Loaded Skills (%d): %s", len(self.skill_manager.list_skills()), [s.name for s in self.skill_manager.list_skills()])
|
||||
|
||||
await self._setup_commands()
|
||||
|
||||
try:
|
||||
# Delete any webhooks and start polling
|
||||
await self.bot.delete_webhook(drop_pending_updates=True)
|
||||
await self.dp.start_polling(self.bot)
|
||||
finally:
|
||||
await self.bot.session.close()
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Formatting and message splitting utilities for Telegram."""
|
||||
|
||||
|
||||
def split_message(text: str, max_length: int = 30000) -> list[str]:
|
||||
"""Split long text into chunks that fit within Telegram Rich Messages 32768 character limit."""
|
||||
if len(text) <= max_length:
|
||||
return [text]
|
||||
|
||||
chunks: list[str] = []
|
||||
lines = text.split("\n")
|
||||
current_chunk: list[str] = []
|
||||
current_length = 0
|
||||
in_code_block = False
|
||||
code_block_lang = ""
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1 # newline char
|
||||
|
||||
# Check for code fence
|
||||
if line.strip().startswith("```"):
|
||||
if in_code_block:
|
||||
in_code_block = False
|
||||
code_block_lang = ""
|
||||
else:
|
||||
in_code_block = True
|
||||
code_block_lang = line.strip()[3:]
|
||||
|
||||
if current_length + line_len > max_length:
|
||||
if in_code_block:
|
||||
# Close code block in current chunk
|
||||
current_chunk.append("```")
|
||||
chunks.append("\n".join(current_chunk))
|
||||
# Reopen code block in next chunk
|
||||
current_chunk = [f"```{code_block_lang}", line]
|
||||
current_length = len(current_chunk[0]) + 1 + line_len
|
||||
else:
|
||||
chunks.append("\n".join(current_chunk))
|
||||
current_chunk = [line]
|
||||
current_length = line_len
|
||||
else:
|
||||
current_chunk.append(line)
|
||||
current_length += line_len
|
||||
|
||||
if current_chunk:
|
||||
chunks.append("\n".join(current_chunk))
|
||||
|
||||
return chunks
|
||||
@@ -0,0 +1,222 @@
|
||||
"""Configuration management for HomeAgent using pydantic-settings."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Literal, Optional
|
||||
from pydantic import Field, SecretStr, field_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
extra="ignore",
|
||||
)
|
||||
|
||||
# Telegram Bot
|
||||
TELEGRAM_BOT_TOKEN: SecretStr = Field(
|
||||
default=SecretStr(""),
|
||||
description="Telegram bot token obtained from @BotFather",
|
||||
)
|
||||
ALLOWED_TELEGRAM_USER_IDS: list[int] | str = Field(
|
||||
default_factory=list,
|
||||
description="List of Telegram User IDs allowed to interact with the bot. Whitelist only.",
|
||||
)
|
||||
|
||||
# LLM Provider selection: 'gemini', 'deepseek', or 'openai' (compatible)
|
||||
LLM_PROVIDER: Literal["gemini", "deepseek", "openai"] = Field(
|
||||
default="gemini",
|
||||
description="Active LLM provider: 'gemini', 'deepseek', or 'openai'",
|
||||
)
|
||||
|
||||
# Google AI Studio (Gemini)
|
||||
GEMINI_API_KEY: SecretStr = Field(
|
||||
default=SecretStr(""),
|
||||
description="Google AI Studio API Key",
|
||||
)
|
||||
GEMINI_MODEL: str = Field(
|
||||
default="gemini-2.5-pro",
|
||||
description="Gemini orchestrator model name (e.g. gemini-3.1-pro, gemini-2.5-pro)",
|
||||
)
|
||||
GEMINI_SUBAGENT_MODEL: str = Field(
|
||||
default="gemini-2.5-flash",
|
||||
description="Fast Gemini model used for subagent tasks (e.g. gemini-2.5-flash)",
|
||||
)
|
||||
|
||||
# DeepSeek API (https://api.deepseek.com)
|
||||
DEEPSEEK_API_KEY: Optional[SecretStr] = Field(
|
||||
default=None,
|
||||
description="DeepSeek API Key (https://platform.deepseek.com)",
|
||||
)
|
||||
DEEPSEEK_BASE_URL: str = Field(
|
||||
default="https://api.deepseek.com",
|
||||
description="DeepSeek base URL (default: https://api.deepseek.com)",
|
||||
)
|
||||
DEEPSEEK_MODEL: str = Field(
|
||||
default="deepseek-chat",
|
||||
description="DeepSeek model name (e.g. deepseek-chat, deepseek-reasoner)",
|
||||
)
|
||||
DEEPSEEK_SUBAGENT_MODEL: str = Field(
|
||||
default="deepseek-chat",
|
||||
description="Fast DeepSeek model for subagents",
|
||||
)
|
||||
|
||||
# OpenAI-Compatible API (OpenAI, OpenRouter, Groq, Ollama, vLLM, etc.)
|
||||
OPENAI_API_KEY: Optional[SecretStr] = Field(
|
||||
default=None,
|
||||
description="OpenAI or OpenAI-compatible API Key",
|
||||
)
|
||||
OPENAI_BASE_URL: str = Field(
|
||||
default="https://api.openai.com/v1",
|
||||
description="Base URL for OpenAI-compatible endpoint (e.g. https://openrouter.ai/api/v1, http://localhost:11434/v1)",
|
||||
)
|
||||
OPENAI_MODEL: str = Field(
|
||||
default="gpt-4o",
|
||||
description="Model name for OpenAI-compatible endpoint",
|
||||
)
|
||||
OPENAI_SUBAGENT_MODEL: str = Field(
|
||||
default="gpt-4o-mini",
|
||||
description="Fast model for subagents on OpenAI-compatible endpoint",
|
||||
)
|
||||
|
||||
SYSTEM_INSTRUCTION: str = Field(
|
||||
default=(
|
||||
"Ты — умный персональный AI-ассистент и главный координатор (Orchestrator), интегрированный в Telegram. "
|
||||
"Ты помогаешь пользователю управлять задачами в Jira, расписанием в Google Календаре, репозиториями в Gitea, "
|
||||
"искать актуальную информацию в интернете (web_search, web_fetch_page), безопасно выполнять код и вычисления в песочнице (code_execute, sandbox_run_command), "
|
||||
"помнить важные факты и выполнять специализированные скиллы. "
|
||||
"Для быстрого и эффективного сбора данных из нескольких источников ты можешь запускать быстрых подагентов параллельно "
|
||||
"через spawn_parallel_subagents (например, один подагент проверяет Календарь, второй — задачи в Jira, третий ищет информацию в интернете). "
|
||||
"Отвечай емко, красиво и структурированно, используя Markdown для списков, жирного шрифта и таблиц. "
|
||||
"Всегда выполняй действия через доступные инструменты (tools), если требуется проверить актуальные данные или совершить действие."
|
||||
),
|
||||
description="Default system instruction for Gemini",
|
||||
)
|
||||
|
||||
# Jira Integration
|
||||
JIRA_ENABLED: bool = Field(default=True, description="Enable or disable Jira tools")
|
||||
JIRA_URL: Optional[str] = Field(default=None, description="Base Jira URL, e.g. https://your-domain.atlassian.net")
|
||||
JIRA_EMAIL: Optional[str] = Field(default=None, description="Jira user email")
|
||||
JIRA_API_TOKEN: Optional[SecretStr] = Field(default=None, description="Jira Atlassian API Token")
|
||||
JIRA_PERSONAL_ACCESS_TOKEN: Optional[SecretStr] = Field(default=None, description="Jira PAT (for Server/Data Center)")
|
||||
|
||||
# Gitea Integration
|
||||
GITEA_ENABLED: bool = Field(default=True, description="Enable or disable Gitea tools")
|
||||
GITEA_URL: str = Field(default="https://git.timka.su", description="Base Gitea URL (e.g. https://git.timka.su)")
|
||||
GITEA_TOKEN: Optional[SecretStr] = Field(default=None, description="Gitea Personal Access Token")
|
||||
|
||||
# Web Search Integration
|
||||
WEB_SEARCH_ENABLED: bool = Field(default=True, description="Enable or disable web search tools")
|
||||
WEB_SEARCH_PROVIDER: Literal["duckduckgo", "tavily", "searxng"] = Field(
|
||||
default="duckduckgo",
|
||||
description="Search provider: 'duckduckgo', 'tavily', or 'searxng'",
|
||||
)
|
||||
TAVILY_API_KEY: Optional[SecretStr] = Field(default=None, description="Tavily API Key (optional)")
|
||||
SEARXNG_URL: Optional[str] = Field(default=None, description="SearXNG instance URL (optional)")
|
||||
|
||||
# Code Sandbox Integration
|
||||
SANDBOX_ENABLED: bool = Field(default=True, description="Enable or disable isolated code execution sandbox")
|
||||
SANDBOX_BACKEND: Literal["auto", "bwrap", "docker", "process"] = Field(
|
||||
default="auto",
|
||||
description="Sandbox backend: 'auto' (bwrap -> docker -> process), 'bwrap', 'docker', or 'process'",
|
||||
)
|
||||
SANDBOX_TIMEOUT_SECONDS: int = Field(default=30, description="Max execution time in seconds")
|
||||
SANDBOX_MEMORY_LIMIT_MB: int = Field(default=512, description="Max RAM allowed for sandbox process in MB")
|
||||
SANDBOX_CPU_LIMIT: float = Field(default=1.0, description="CPU cores limit")
|
||||
SANDBOX_ALLOW_NETWORK: bool = Field(default=False, description="Allow outbound network in sandbox (disabled by default)")
|
||||
SANDBOX_DOCKER_IMAGE: str = Field(default="python:3.12-slim", description="Docker image used if docker backend is active")
|
||||
|
||||
# Google Calendar Integration
|
||||
GOOGLE_CALENDAR_ENABLED: bool = Field(default=True, description="Enable or disable Google Calendar tools")
|
||||
GOOGLE_CALENDAR_ID: str = Field(default="primary", description="Primary calendar ID or user email (default 'primary')")
|
||||
GOOGLE_ADDITIONAL_CALENDAR_IDS: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="List of additional Google Calendar IDs to always monitor",
|
||||
)
|
||||
GOOGLE_AUTH_TYPE: Literal["auto", "service_account", "oauth2"] = Field(
|
||||
default="auto",
|
||||
description="Authentication method for Google Calendar: 'auto', 'service_account', or 'oauth2'",
|
||||
)
|
||||
GOOGLE_SERVICE_ACCOUNT_FILE: Optional[str] = Field(
|
||||
default="service_account.json",
|
||||
description="Path to service account JSON credentials",
|
||||
)
|
||||
GOOGLE_OAUTH_CREDENTIALS_FILE: Optional[str] = Field(
|
||||
default="credentials.json",
|
||||
description="Path to OAuth2 client credentials JSON file",
|
||||
)
|
||||
GOOGLE_OAUTH_TOKEN_FILE: str = Field(
|
||||
default="data/calendar_token.json",
|
||||
description="Path where OAuth2 refresh token is saved",
|
||||
)
|
||||
|
||||
# Storage and paths
|
||||
DATA_DIR: Path = Field(default=Path("data"), description="Directory for storing sessions and memory")
|
||||
SKILLS_DIR: Path = Field(default=Path("skills"), description="Directory with skills markdown files")
|
||||
EXTENSIONS_DIR: Path = Field(default=Path("extensions"), description="Directory with dynamic extensions")
|
||||
LOG_LEVEL: str = Field(default="INFO", description="Logging level")
|
||||
|
||||
def get_active_provider_name(self) -> str:
|
||||
if self.LLM_PROVIDER == "deepseek":
|
||||
return "DeepSeek"
|
||||
if self.LLM_PROVIDER == "openai":
|
||||
return "OpenAI-Compatible"
|
||||
return "Google Gemini"
|
||||
|
||||
def get_active_model(self) -> str:
|
||||
if self.LLM_PROVIDER == "deepseek":
|
||||
return self.DEEPSEEK_MODEL
|
||||
if self.LLM_PROVIDER == "openai":
|
||||
return self.OPENAI_MODEL
|
||||
return self.GEMINI_MODEL
|
||||
|
||||
def get_active_subagent_model(self) -> str:
|
||||
if self.LLM_PROVIDER == "deepseek":
|
||||
return self.DEEPSEEK_SUBAGENT_MODEL
|
||||
if self.LLM_PROVIDER == "openai":
|
||||
return self.OPENAI_SUBAGENT_MODEL
|
||||
return self.GEMINI_SUBAGENT_MODEL
|
||||
|
||||
@field_validator("ALLOWED_TELEGRAM_USER_IDS", mode="after")
|
||||
@classmethod
|
||||
def parse_allowed_user_ids(cls, v: object) -> list[int]:
|
||||
if isinstance(v, str):
|
||||
v = v.strip()
|
||||
if not v:
|
||||
return []
|
||||
# Supports "123, 456" or "[123, 456]"
|
||||
clean = v.replace("[", "").replace("]", "")
|
||||
return [int(item.strip()) for item in clean.split(",") if item.strip()]
|
||||
if isinstance(v, (int, float)):
|
||||
return [int(v)]
|
||||
if isinstance(v, (list, tuple, set)):
|
||||
return [int(item) for item in v]
|
||||
return []
|
||||
|
||||
@field_validator("GOOGLE_ADDITIONAL_CALENDAR_IDS", mode="after")
|
||||
@classmethod
|
||||
def parse_calendar_ids(cls, v: object) -> list[str]:
|
||||
if isinstance(v, str):
|
||||
v = v.strip()
|
||||
if not v:
|
||||
return []
|
||||
if v.startswith("[") and v.endswith("]"):
|
||||
import json
|
||||
try:
|
||||
parsed = json.loads(v)
|
||||
if isinstance(parsed, list):
|
||||
return [str(item).strip() for item in parsed if str(item).strip()]
|
||||
except Exception:
|
||||
clean = v.replace("[", "").replace("]", "").replace('"', "").replace("'", "")
|
||||
return [item.strip() for item in clean.split(",") if item.strip()]
|
||||
return [item.strip() for item in v.split(",") if item.strip()]
|
||||
if isinstance(v, (list, tuple, set)):
|
||||
return [str(item).strip() for item in v if str(item).strip()]
|
||||
return []
|
||||
|
||||
|
||||
def get_settings() -> Settings:
|
||||
"""Retrieve application settings."""
|
||||
settings = Settings()
|
||||
settings.DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
return settings
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Memory package for HomeAgent."""
|
||||
|
||||
from homeagent.memory.global_memory import GlobalMemory, MemoryItem, get_global_memory
|
||||
|
||||
__all__ = ["GlobalMemory", "MemoryItem", "get_global_memory"]
|
||||
@@ -0,0 +1,110 @@
|
||||
"""Global shared memory across all topics and chats."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import uuid
|
||||
from dataclasses import asdict, dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class MemoryItem:
|
||||
id: str
|
||||
fact: str
|
||||
category: str = "general"
|
||||
created_at: str = field(default_factory=lambda: datetime.now().isoformat())
|
||||
|
||||
|
||||
class GlobalMemory:
|
||||
"""Persistent global memory store shared across all forum topics."""
|
||||
|
||||
def __init__(self, storage_path: Path):
|
||||
self.storage_path = storage_path
|
||||
self._items: dict[str, MemoryItem] = {}
|
||||
self._load()
|
||||
|
||||
def _load(self) -> None:
|
||||
if not self.storage_path.exists():
|
||||
return
|
||||
try:
|
||||
with open(self.storage_path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
for item_data in data:
|
||||
item = MemoryItem(**item_data)
|
||||
self._items[item.id] = item
|
||||
logger.info("Loaded %d items into global memory from %s", len(self._items), self.storage_path)
|
||||
except Exception as e:
|
||||
logger.error("Failed to load global memory from %s: %s", self.storage_path, e)
|
||||
|
||||
def _save(self) -> None:
|
||||
try:
|
||||
self.storage_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(self.storage_path, "w", encoding="utf-8") as f:
|
||||
json.dump([asdict(item) for item in self._items.values()], f, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
logger.error("Failed to save global memory to %s: %s", self.storage_path, e)
|
||||
|
||||
def add_fact(self, fact: str, category: str = "general") -> MemoryItem:
|
||||
"""Add a new fact or preference to global memory."""
|
||||
item_id = str(uuid.uuid4())[:8]
|
||||
item = MemoryItem(id=item_id, fact=fact.strip(), category=category.strip().lower())
|
||||
self._items[item_id] = item
|
||||
self._save()
|
||||
logger.info("Added fact [%s] in category '%s': %s", item_id, item.category, item.fact)
|
||||
return item
|
||||
|
||||
def remove_fact(self, fact_id: str) -> bool:
|
||||
"""Remove a fact by its ID."""
|
||||
if fact_id in self._items:
|
||||
del self._items[fact_id]
|
||||
self._save()
|
||||
return True
|
||||
return False
|
||||
|
||||
def list_facts(self, category: Optional[str] = None) -> list[MemoryItem]:
|
||||
"""List all facts, optionally filtered by category."""
|
||||
if category:
|
||||
cat = category.strip().lower()
|
||||
return [item for item in self._items.values() if item.category == cat]
|
||||
return list(self._items.values())
|
||||
|
||||
def search(self, query: str) -> list[MemoryItem]:
|
||||
"""Search memory for keywords in query."""
|
||||
q = query.lower()
|
||||
return [
|
||||
item for item in self._items.values()
|
||||
if q in item.fact.lower() or q in item.category.lower()
|
||||
]
|
||||
|
||||
def clear(self) -> None:
|
||||
"""Clear all stored memory."""
|
||||
self._items.clear()
|
||||
self._save()
|
||||
|
||||
def get_memory_summary(self, max_items: int = 30) -> str:
|
||||
"""Produce a formatted summary of remembered facts for the system prompt."""
|
||||
if not self._items:
|
||||
return ""
|
||||
|
||||
lines = ["\n[ГЛОБАЛЬНАЯ ПАМЯТЬ / ФАКТЫ О ПОЛЬЗОВАТЕЛЕ И ПРОЕКТЕ]:"]
|
||||
items = list(self._items.values())[-max_items:]
|
||||
for item in items:
|
||||
lines.append(f"- (id: {item.id}, категория: {item.category}) {item.fact}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# Singleton instance container
|
||||
_global_memory_instance: Optional[GlobalMemory] = None
|
||||
|
||||
|
||||
def get_global_memory(storage_path: Optional[Path] = None) -> GlobalMemory:
|
||||
global _global_memory_instance
|
||||
if _global_memory_instance is None:
|
||||
if storage_path is None:
|
||||
storage_path = Path("data") / "global_memory.json"
|
||||
_global_memory_instance = GlobalMemory(storage_path)
|
||||
return _global_memory_instance
|
||||
@@ -0,0 +1,6 @@
|
||||
"""Skills package for HomeAgent."""
|
||||
|
||||
from homeagent.skills.loader import Skill, load_skills_from_directory, parse_skill_file
|
||||
from homeagent.skills.manager import SkillManager
|
||||
|
||||
__all__ = ["Skill", "parse_skill_file", "load_skills_from_directory", "SkillManager"]
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Skill definition and loader for HomeAgent."""
|
||||
|
||||
import logging
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Optional
|
||||
import yaml
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@dataclass
|
||||
class Skill:
|
||||
name: str
|
||||
title: str
|
||||
description: str
|
||||
prompt_template: str
|
||||
triggers: list[str] = field(default_factory=list)
|
||||
metadata: dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
def render(self, extra_instructions: str = "") -> str:
|
||||
"""Render the skill prompt with current date/time variables."""
|
||||
now = datetime.now()
|
||||
rendered = self.prompt_template
|
||||
rendered = rendered.replace("{date}", now.strftime("%Y-%m-%d"))
|
||||
rendered = rendered.replace("{time}", now.strftime("%H:%M:%S"))
|
||||
rendered = rendered.replace("{weekday}", now.strftime("%A"))
|
||||
rendered = rendered.replace("{datetime}", now.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
|
||||
if extra_instructions.strip():
|
||||
rendered += f"\n\nДополнительные указания пользователя:\n{extra_instructions.strip()}"
|
||||
|
||||
return rendered
|
||||
|
||||
|
||||
def parse_skill_file(file_path: Path) -> Optional[Skill]:
|
||||
"""Parse a Markdown file with YAML frontmatter into a Skill object."""
|
||||
try:
|
||||
content = file_path.read_text(encoding="utf-8")
|
||||
if not content.startswith("---"):
|
||||
# Plain markdown file without frontmatter
|
||||
name = file_path.stem
|
||||
return Skill(
|
||||
name=name,
|
||||
title=name.replace("_", " ").title(),
|
||||
description=f"Skill from {file_path.name}",
|
||||
prompt_template=content.strip(),
|
||||
triggers=[f"/{name}"],
|
||||
)
|
||||
|
||||
parts = content.split("---", 2)
|
||||
if len(parts) < 3:
|
||||
logger.warning("Invalid frontmatter format in %s", file_path)
|
||||
return None
|
||||
|
||||
frontmatter_raw = parts[1]
|
||||
body = parts[2].strip()
|
||||
|
||||
meta = yaml.safe_load(frontmatter_raw) or {}
|
||||
name = str(meta.get("name", file_path.stem))
|
||||
title = str(meta.get("title", name.replace("_", " ").title()))
|
||||
description = str(meta.get("description", ""))
|
||||
triggers = meta.get("triggers", [])
|
||||
if isinstance(triggers, str):
|
||||
triggers = [triggers]
|
||||
|
||||
return Skill(
|
||||
name=name,
|
||||
title=title,
|
||||
description=description,
|
||||
prompt_template=body,
|
||||
triggers=[t.strip().lower() for t in triggers],
|
||||
metadata=meta,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("Error parsing skill file %s: %s", file_path, e)
|
||||
return None
|
||||
|
||||
|
||||
def load_skills_from_directory(directory: Path) -> dict[str, Skill]:
|
||||
"""Load all skill definitions from markdown files in directory."""
|
||||
skills: dict[str, Skill] = {}
|
||||
if not directory.exists():
|
||||
logger.warning("Skills directory %s does not exist.", directory)
|
||||
return skills
|
||||
|
||||
for file_path in directory.glob("*.md"):
|
||||
skill = parse_skill_file(file_path)
|
||||
if skill:
|
||||
skills[skill.name] = skill
|
||||
logger.info("Loaded skill '%s' (%s) with triggers %s", skill.name, skill.title, skill.triggers)
|
||||
|
||||
return skills
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Skills manager to find, match, and render skills."""
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from homeagent.skills.loader import Skill, load_skills_from_directory
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SkillManager:
|
||||
"""Manages skill discovery, trigger matching, and execution rendering."""
|
||||
|
||||
def __init__(self, skills_dir: Path) -> None:
|
||||
self.skills_dir = skills_dir
|
||||
self._skills: dict[str, Skill] = {}
|
||||
self.reload()
|
||||
|
||||
def reload(self) -> None:
|
||||
"""Reload all skills from disk."""
|
||||
self._skills = load_skills_from_directory(self.skills_dir)
|
||||
logger.info("Loaded %d skills from %s", len(self._skills), self.skills_dir)
|
||||
|
||||
def get_skill(self, name: str) -> Optional[Skill]:
|
||||
return self._skills.get(name.lower().strip())
|
||||
|
||||
def list_skills(self) -> list[Skill]:
|
||||
return list(self._skills.values())
|
||||
|
||||
def match_trigger(self, text: str) -> Optional[tuple[Skill, str]]:
|
||||
"""Check if message matches a skill trigger or command.
|
||||
|
||||
Returns (skill, user_arguments) if matched, else None.
|
||||
"""
|
||||
clean_text = text.strip()
|
||||
lower_text = clean_text.lower()
|
||||
|
||||
# Check explicit /skill <name> command
|
||||
if lower_text.startswith("/skill "):
|
||||
parts = clean_text.split(maxsplit=2)
|
||||
skill_name = parts[1].lower()
|
||||
extra = parts[2] if len(parts) > 2 else ""
|
||||
skill = self.get_skill(skill_name)
|
||||
if skill:
|
||||
return skill, extra
|
||||
|
||||
# Check skill triggers (e.g. "/briefing", "утренняя сводка", etc.)
|
||||
for skill in self._skills.values():
|
||||
for trigger in skill.triggers:
|
||||
t = trigger.lower()
|
||||
if lower_text == t or lower_text.startswith(t + " "):
|
||||
extra = clean_text[len(trigger):].strip()
|
||||
return skill, extra
|
||||
|
||||
return None
|
||||
@@ -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