initial commit heh
This commit is contained in:
78 files changed
+11181
No files matched your search
@@ -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
|
||||
Reference in new issue
Block a user