fix: restore OpenAI agent implementation after validation

This commit is contained in:
Barsic Bot committed 2026-11-13 22:08:15 +03:00
1 parent 447fc56e2d
commit aeadee8b0e
1 file changed
+56 -23
+56 -23
View File
@@ -18,6 +18,8 @@ logger = logging.getLogger(__name__)
class OpenAIAgent(BaseAgent): class OpenAIAgent(BaseAgent):
"""Agent orchestrator powered by DeepSeek/OpenAI-compatible APIs."""
def __init__( def __init__(
self, self,
settings: Optional[Settings] = None, settings: Optional[Settings] = None,
@@ -65,13 +67,26 @@ class OpenAIAgent(BaseAgent):
history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id)) history = list(self.conversation_manager.get_openai_messages(chat_id, thread_id))
user_turn: dict[str, Any] = {"role": "user", "content": user_message} user_turn: dict[str, Any] = {"role": "user", "content": user_message}
working = [{"role": "system", "content": self._build_system_instruction()}, *history, user_turn] working: list[dict[str, Any]] = [
sequence = [user_turn] {"role": "system", "content": self._build_system_instruction()},
*history,
user_turn,
]
sequence: list[dict[str, Any]] = [user_turn]
tools = self.registry.get_openai_tools() tools = self.registry.get_openai_tools()
for iteration in range(max_tool_iterations): for iteration in range(max_tool_iterations):
if on_progress: if on_progress:
await on_progress("🤔 Формирую ответ..." if iteration == 0 else f"🧠 Анализирую данные (шаг {iteration + 1})...") await on_progress(
kwargs: dict[str, Any] = {"model": self.model, "messages": working, "temperature": 0.3} "🤔 Формирую ответ..."
if iteration == 0
else f"🧠 Анализирую данные (шаг {iteration + 1})..."
)
kwargs: dict[str, Any] = {
"model": self.model,
"messages": working,
"temperature": 0.3,
}
if tools: if tools:
kwargs["tools"] = tools kwargs["tools"] = tools
try: try:
@@ -82,34 +97,52 @@ class OpenAIAgent(BaseAgent):
except Exception as e: except Exception as e:
logger.exception("Unexpected API error") logger.exception("Unexpected API error")
return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {e}" return f"⚠️ Ошибка запроса к {self.provider.upper()}: {type(e).__name__}: {e}"
msg = response.choices[0].message
if not msg.tool_calls: message = response.choices[0].message
final = msg.content or "*(Пустой ответ)*" if not message.tool_calls:
final = message.content or "*(Пустой ответ)*"
sequence.append({"role": "assistant", "content": final}) sequence.append({"role": "assistant", "content": final})
self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence) self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
return final return final
assistant = {
"role": "assistant", "content": msg.content, assistant_message = {
"tool_calls": [{"id": tc.id, "type": "function", "function": { "role": "assistant",
"name": tc.function.name, "arguments": tc.function.arguments, "content": message.content,
}} for tc in msg.tool_calls], "tool_calls": [
{
"id": call.id,
"type": "function",
"function": {
"name": call.function.name,
"arguments": call.function.arguments,
},
} }
working.append(assistant) for call in message.tool_calls
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: try:
args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args args = json.loads(raw_args) if isinstance(raw_args, str) else raw_args
except Exception: except Exception:
logger.warning("Failed parsing arguments for %s", tc.function.name) logger.warning("Failed parsing arguments for %s", call.function.name)
args = {} args = {}
if on_progress: if on_progress:
from homeagent.bot.progress import format_tool_progress from homeagent.bot.progress import format_tool_progress
prefix = f"[{idx}/{len(msg.tool_calls)}] " if len(msg.tool_calls) > 1 else "" prefix = f"[{index}/{len(message.tool_calls)}] " if len(message.tool_calls) > 1 else ""
await on_progress(f"⏳ {prefix}{format_tool_progress(tc.function.name, args)}") await on_progress(f"⏳ {prefix}{format_tool_progress(call.function.name, args)}")
result = await self.registry.execute(tc.function.name, args) result = await self.registry.execute(call.function.name, args)
tool_msg = {"role": "tool", "tool_call_id": tc.id, "name": tc.function.name, "content": result} tool_message = {
working.append(tool_msg) "role": "tool",
sequence.append(tool_msg) "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) self.conversation_manager.append_openai_turn_sequence(chat_id, thread_id, sequence)
return "Достигнут лимит последовательных вызовов инструментов для этого запроса." return "Достигнут лимит последовательных вызовов инструментов для этого запроса."