test: keep missing OpenAI key message backward-compatible

This commit is contained in:
Barsic Bot committed 2026-11-13 22:12:41 +03:00
1 parent 89f617d62b
commit 16a3dcb6ca
1 file changed
+18 -75
+18 -75
View File
@@ -18,15 +18,7 @@ logger = logging.getLogger(__name__)
class OpenAIAgent(BaseAgent):
"""Agent orchestrator powered by DeepSeek/OpenAI-compatible APIs."""
def __init__(
self,
settings: Optional[Settings] = None,
registry: Optional[ToolRegistry] = None,
conversation_manager: Optional[ConversationManager] = None,
provider_override: Optional[str] = None,
) -> None:
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)
@@ -40,11 +32,9 @@ class OpenAIAgent(BaseAgent):
self.base_url = self.settings.OPENAI_BASE_URL.rstrip("/")
self.model = self.settings.OPENAI_MODEL or "gpt-4o"
self.api_key = key.get_secret_value() if key else ""
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", self.provider)
self._client: Optional[AsyncOpenAI] = 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()
@@ -52,43 +42,22 @@ class OpenAIAgent(BaseAgent):
memory = get_global_memory(self.settings.DATA_DIR / "global_memory.json").get_memory_summary()
return "\n\n".join(filter(None, [self.settings.SYSTEM_INSTRUCTION, context, memory]))
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:
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:
if not self._client:
if self.provider == "deepseek":
return "⚠️ **DeepSeek API Key не настроен.**\nДобавьте `DEEPSEEK_API_KEY` в `.env` и перезапустите бота."
return "⚠️ **OpenAI / OpenAI-compatible API Key не настроен.**\nДобавьте `OPENAI_API_KEY` в `.env` и перезапустите бота."
return "⚠️ **OpenAI / OpenAI-compatible API Key не настроен**.\nДобавьте `OPENAI_API_KEY` в `.env` и перезапустите бота."
history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id))
user_turn: dict[str, Any] = {"role": "user", "content": user_message}
working: list[dict[str, Any]] = [
{"role": "system", "content": self._build_system_instruction()},
*history,
user_turn,
]
working: list[dict[str, Any]] = [{"role": "system", "content": self._build_system_instruction()}, *history, user_turn]
sequence: list[dict[str, Any]] = [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
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:
@@ -97,52 +66,26 @@ class OpenAIAgent(BaseAgent):
except Exception as e:
logger.exception("Unexpected API error")
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {e}"
message = response.choices[0].message
if not message.tool_calls:
final = message.content or "*(Пустой ответ)*"
sequence.append({"role": "assistant", "content": final})
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
return final
assistant_message = {
"role": "assistant",
"content": message.content,
"tool_calls": [
{
"id": call.id,
"type": "function",
"function": {
"name": call.function.name,
"arguments": call.function.arguments,
},
}
assistant_message = {"role": "assistant", "content": message.content, "tool_calls": [
{"id": call.id, "type": "function", "function": {"name": call.function.name, "arguments": call.function.arguments}}
for call in message.tool_calls
],
}
working.append(assistant_message)
sequence.append(assistant_message)
]}
working.append(assistant_message); sequence.append(assistant_message)
for index, call in enumerate(message.tool_calls, 1):
raw_args = call.function.arguments or "{}"
try:
args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
except Exception:
logger.warning("Failed parsing arguments for %s", call.function.name)
args = {}
try: args = json.loads(call.function.arguments or "{}")
except Exception: args = {}
if on_progress:
from homeagent.bot.progress import format_tool_progress
prefix = f"[{index}/{len(message.tool_calls)}] " if len(message.tool_calls) > 1 else ""
await on_progress(f"⏳ {prefix}{format_tool_progress(call.function.name, args)}")
result = await self.registry.execute(call.function.name, args)
tool_message = {
"role": "tool",
"tool_call_id": call.id,
"name": call.function.name,
"content": result,
}
working.append(tool_message)
sequence.append(tool_message)
tool_message = {"role": "tool", "tool_call_id": call.id, "name": call.function.name, "content": result}
working.append(tool_message); sequence.append(tool_message)
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
return "Достигнут лимит последовательных вызовов инструментов для этого запроса."