From aeadee8b0e25fe792f5873d9805ce8ec2aaba9a3 Mon Sep 17 00:00:00 2001 From: Barsic <16+barsic@noreply.localhost> Date: Fri, 13 Nov 2026 22:08:15 +0300 Subject: [PATCH] fix: restore OpenAI agent implementation after validation --- src/homeagent/agent/openai_agent.py | 79 ++++++++++++++++++++--------- 1 file changed, 56 insertions(+), 23 deletions(-) diff --git a/src/homeagent/agent/openai_agent.py b/src/homeagent/agent/openai_agent.py index 9259e6a..e4e6ad7 100644 --- a/src/homeagent/agent/openai_agent.py +++ b/src/homeagent/agent/openai_agent.py @@ -18,6 +18,8 @@ logger = logging.getLogger(__name__) class OpenAIAgent(BaseAgent): + """Agent orchestrator powered by DeepSeek/OpenAI-compatible APIs.""" + def __init__( self, settings: Optional[Settings] = None, @@ -65,13 +67,26 @@ class OpenAIAgent(BaseAgent): history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id)) user_turn: dict[str, Any] = {"role": "user", "content": user_message} - working = [{"role": "system", "content": self._build_system_instruction()}, *history, user_turn] - sequence = [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} + 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: @@ -82,34 +97,52 @@ class OpenAIAgent(BaseAgent): except Exception as e: logger.exception("Unexpected API error") return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {e}" - msg = response.choices[0].message - if not msg.tool_calls: - final = msg.content or "*(Пустой ответ)*" + + 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 = { - "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], + + 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) - sequence.append(assistant) - for idx, tc in enumerate(msg.tool_calls, 1): - raw_args = tc.function.arguments or "{}" + 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", tc.function.name) + logger.warning("Failed parsing arguments for %s", call.function.name) args = {} if on_progress: from homeagent.bot.progress import format_tool_progress - prefix = f"[{idx}/{len(msg.tool_calls)}] " if len(msg.tool_calls) > 1 else "" - await on_progress(f"⏳ {prefix}{format_tool_progress(tc.function.name, 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) + 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) + self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence) return "Достигнут лимит последовательных вызовов инструментов для этого запроса."