319 lines
14 KiB
Python
319 lines
14 KiB
Python
"""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.attachments import (
|
|
OPENAI_IMAGE_MIMES,
|
|
Attachment,
|
|
build_history_user_text,
|
|
format_inline_text_attachments,
|
|
stage_attachments_in_sandbox,
|
|
)
|
|
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)
|
|
|
|
def _build_user_turn(
|
|
self,
|
|
user_message: str,
|
|
attachments: list[Attachment],
|
|
) -> dict[str, Any]:
|
|
"""Build an OpenAI/DeepSeek user message payload supporting images, PDFs, audio, and text files."""
|
|
if not attachments:
|
|
return {"role": "user", "content": user_message}
|
|
|
|
inline_text, binary_attachments = format_inline_text_attachments(attachments)
|
|
text_sections: list[str] = []
|
|
if inline_text:
|
|
text_sections.append(inline_text)
|
|
|
|
multimodal_blocks: list[dict[str, Any]] = []
|
|
notes: list[str] = []
|
|
|
|
if self.provider == "deepseek":
|
|
# DeepSeek Chat Completions API is text-only; avoid sending image_url/file blocks that return HTTP 400
|
|
for att in binary_attachments:
|
|
sandbox_hint = (
|
|
f" Файл сохранён в песочнице: `{att.sandbox_path}` — при необходимости можно обработать его через `code_execute`."
|
|
if att.sandbox_path
|
|
else ""
|
|
)
|
|
notes.append(
|
|
f"- Бинарное вложение {att.to_summary_line()} (активный провайдер DeepSeek текстовый и не принимает "
|
|
f"изображения/PDF/аудио напрямую; для анализа картинок переключитесь на Gemini, OpenAI или Antigravity).{sandbox_hint}"
|
|
)
|
|
else:
|
|
for att in binary_attachments:
|
|
mime = att.mime_type.lower()
|
|
if mime in OPENAI_IMAGE_MIMES:
|
|
multimodal_blocks.append(
|
|
{
|
|
"type": "image_url",
|
|
"image_url": {"url": f"data:{mime};base64,{att.base64_data()}"},
|
|
}
|
|
)
|
|
notes.append(f"- Прикреплено изображение: {att.to_summary_line()}")
|
|
elif att.is_pdf:
|
|
multimodal_blocks.append(
|
|
{
|
|
"type": "file",
|
|
"file": {
|
|
"filename": att.filename,
|
|
"file_data": f"data:application/pdf;base64,{att.base64_data()}",
|
|
},
|
|
}
|
|
)
|
|
notes.append(f"- Прикреплён PDF-документ: {att.to_summary_line()}")
|
|
elif mime in ("audio/wav", "audio/x-wav", "audio/mpeg", "audio/mp3"):
|
|
audio_fmt = "wav" if "wav" in mime else "mp3"
|
|
multimodal_blocks.append(
|
|
{
|
|
"type": "input_audio",
|
|
"input_audio": {
|
|
"data": att.base64_data(),
|
|
"format": audio_fmt,
|
|
},
|
|
}
|
|
)
|
|
notes.append(f"- Прикреплено аудио: {att.to_summary_line()}")
|
|
else:
|
|
sandbox_hint = (
|
|
f" Файл сохранён в песочнице: `{att.sandbox_path}` (можно обработать через `code_execute`)."
|
|
if att.sandbox_path
|
|
else ""
|
|
)
|
|
notes.append(
|
|
f"- Вложение `{att.filename}` ({att.mime_type}, {att.human_size}) не поддерживается напрямую "
|
|
f"форматом OpenAI Chat Completions.{sandbox_hint}"
|
|
)
|
|
|
|
if notes:
|
|
text_sections.append("[Вложения пользователя]:\n" + "\n".join(notes))
|
|
if user_message.strip():
|
|
text_sections.append(user_message)
|
|
|
|
combined_text = "\n\n".join(text_sections) or user_message
|
|
if multimodal_blocks:
|
|
return {
|
|
"role": "user",
|
|
"content": [{"type": "text", "text": combined_text}, *multimodal_blocks],
|
|
}
|
|
return {"role": "user", "content": combined_text}
|
|
|
|
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,
|
|
attachments: Optional[list[Attachment]] = 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. Stage attachments and build current user message
|
|
staged_attachments = stage_attachments_in_sandbox(attachments, self.settings)
|
|
user_turn = self._build_user_turn(user_message, staged_attachments)
|
|
history.append(user_turn)
|
|
|
|
system_instruction = self._build_system_instruction()
|
|
working_messages: list[dict[str, Any]] = [
|
|
{"role": "system", "content": system_instruction},
|
|
*history,
|
|
]
|
|
|
|
# Persist compact text-only turn representation (avoid storing megabyte base64 payloads in session JSON)
|
|
history_user_turn: dict[str, Any] = {
|
|
"role": "user",
|
|
"content": build_history_user_text(user_message, staged_attachments),
|
|
}
|
|
turn_sequence: list[dict[str, Any]] = [history_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
|