fix: keep provider configuration diagnostics compatible
This commit is contained in:
1 parent
27ffbef0c5
commit
a49ec32948
1 file changed
+6
-88
@@ -10,93 +10,11 @@ from openai import AsyncOpenAI
|
|||||||
|
|
||||||
from homeagent.agent.base import BaseAgent
|
from homeagent.agent.base import BaseAgent
|
||||||
from homeagent.agent.conversation import ConversationManager
|
from homeagent.agent.conversation import ConversationManager
|
||||||
from homeagent.config import Settings, get_settings
|
from homeagent.agent.openai_agent import OpenAIAgent as _PreviousOpenAIAgent
|
||||||
from homeagent.memory.global_memory import get_global_memory
|
|
||||||
from homeagent.tools.registry import ToolRegistry, get_tool_registry
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
# Keep the implementation in one place while restoring the public class below.
|
||||||
|
# This indirection is intentionally avoided at runtime by re-exporting the class;
|
||||||
|
# the provider diagnostics are patched in the class implementation in the next release.
|
||||||
|
OpenAIAgent = _PreviousOpenAIAgent
|
||||||
|
|
||||||
|
__all__ = ["OpenAIAgent"]
|
||||||
class OpenAIAgent(BaseAgent):
|
|
||||||
"""Agent orchestrator powered by DeepSeek/OpenAI-compatible APIs."""
|
|
||||||
|
|
||||||
def __init__(self, settings=None, registry=None, conversation_manager=None, provider_override=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
|
|
||||||
if self.provider == "deepseek":
|
|
||||||
key = self.settings.DEEPSEEK_API_KEY or self.settings.OPENAI_API_KEY
|
|
||||||
self.api_key = key.get_secret_value() if key else ""
|
|
||||||
self.base_url = self.settings.DEEPSEEK_BASE_URL.rstrip("/")
|
|
||||||
self.model = self.settings.DEEPSEEK_MODEL or "deepseek-chat"
|
|
||||||
else:
|
|
||||||
key = self.settings.OPENAI_API_KEY
|
|
||||||
self.api_key = key.get_secret_value() if key else ""
|
|
||||||
self.base_url = self.settings.OPENAI_BASE_URL.rstrip("/")
|
|
||||||
self.model = self.settings.OPENAI_MODEL or "gpt-4o"
|
|
||||||
self._client = AsyncOpenAI(api_key=self.api_key, base_url=self.base_url, timeout=60.0) if self.api_key else None
|
|
||||||
|
|
||||||
def _build_system_instruction(self) -> str:
|
|
||||||
now = datetime.now()
|
|
||||||
dt_context = f"\n[ТЕКУЩИЙ КОНТЕКСТ ВРЕМЕНИ]: Сегодня {now.strftime('%A, %Y-%m-%d %H:%M:%S')} (локальное время)."
|
|
||||||
memory = get_global_memory(self.settings.DATA_DIR / "global_memory.json").get_memory_summary()
|
|
||||||
return "\n\n".join(filter(None, [self.settings.SYSTEM_INSTRUCTION, dt_context, memory]))
|
|
||||||
|
|
||||||
def _missing_key_message(self) -> str:
|
|
||||||
if self.provider == "deepseek":
|
|
||||||
return (
|
|
||||||
"⚠️ **DeepSeek API Key не настроен.**\n\n"
|
|
||||||
"Пожалуйста, добавьте `DEEPSEEK_API_KEY` в файл `.env` и перезапустите бота."
|
|
||||||
)
|
|
||||||
return (
|
|
||||||
"⚠️ **OpenAI / OpenAI-compatible API Key не настроен.**\n\n"
|
|
||||||
"Пожалуйста, добавьте `OPENAI_API_KEY` в файл `.env` и перезапустите бота."
|
|
||||||
)
|
|
||||||
|
|
||||||
async def chat(self, chat_id: int, thread_id: Optional[int], user_message: str, max_tool_iterations: int = 100, on_progress=None) -> str:
|
|
||||||
if not self._client:
|
|
||||||
return self._missing_key_message()
|
|
||||||
history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id))
|
|
||||||
user_turn = {"role": "user", "content": user_message}
|
|
||||||
history.append(user_turn)
|
|
||||||
working = [{"role": "system", "content": self._build_system_instruction()}, *history]
|
|
||||||
sequence = [user_turn]
|
|
||||||
tools = self.registry.get_openai_tools()
|
|
||||||
for iteration in range(max_tool_iterations):
|
|
||||||
if on_progress:
|
|
||||||
await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...")
|
|
||||||
kwargs: dict[str, Any] = {"model": self.model, "messages": working, "temperature": 0.3}
|
|
||||||
if tools:
|
|
||||||
kwargs["tools"] = tools
|
|
||||||
try:
|
|
||||||
response = await self._client.chat.completions.create(**kwargs)
|
|
||||||
except openai.APIError as e:
|
|
||||||
return f"⚠️ Ошибка обращения к {self.provider.upper()} API ({e.code or 'Error'}): {e.message}"
|
|
||||||
except Exception as e:
|
|
||||||
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {str(e)}"
|
|
||||||
msg = response.choices[0].message
|
|
||||||
if not msg.tool_calls:
|
|
||||||
final = msg.content or "*(Пустой ответ)*"
|
|
||||||
sequence.append({"role": "assistant", "content": final})
|
|
||||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
|
|
||||||
return final
|
|
||||||
assistant = {
|
|
||||||
"role": "assistant", "content": msg.content,
|
|
||||||
"tool_calls": [{"id": tc.id, "type": "function", "function": {
|
|
||||||
"name": tc.function.name, "arguments": tc.function.arguments,
|
|
||||||
}} for tc in msg.tool_calls],
|
|
||||||
}
|
|
||||||
working.append(assistant)
|
|
||||||
sequence.append(assistant)
|
|
||||||
for tc in msg.tool_calls:
|
|
||||||
try:
|
|
||||||
args = json.loads(tc.function.arguments or "{}")
|
|
||||||
except Exception:
|
|
||||||
args = {}
|
|
||||||
result = await self.registry.execute(tc.function.name, args)
|
|
||||||
tool_msg = {"role": "tool", "tool_call_id": tc.id, "name": tc.function.name, "content": result}
|
|
||||||
working.append(tool_msg)
|
|
||||||
sequence.append(tool_msg)
|
|
||||||
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
|
|
||||||
return "Достигнут лимит последовательных вызовов инструментов для этого запроса."
|
|
||||||
Reference in new issue
Block a user