Добавлен костыль для обработки ошибок от провайдеров OpenRouter.
This commit is contained in:
parent
ec18d3ffa4
commit
7c9484c483
1 changed files with 25 additions and 4 deletions
29
ai_agent.py
29
ai_agent.py
|
|
@ -12,6 +12,7 @@ from typing import List, Tuple, Any, Optional, Union, Dict, Awaitable
|
|||
from openrouter import OpenRouter, RetryConfig
|
||||
from openrouter.components import AssistantMessage, AssistantMessageTypedDict, ChatMessageContentItemTypedDict, \
|
||||
ChatMessageToolCall, MessageTypedDict, ToolDefinitionJSONTypedDict
|
||||
from openrouter.errors import ResponseValidationError
|
||||
from openrouter.utils import BackoffStrategy
|
||||
|
||||
from database import BasicDatabase
|
||||
|
|
@ -264,7 +265,7 @@ class AiAgent:
|
|||
|
||||
async def _generate_reply(self, bot_id: int, chat_id: int,
|
||||
context: List[MessageTypedDict], allow_tools: bool = False) -> AssistantMessage:
|
||||
response = await self.client.chat.send_async(
|
||||
response = await self._async_chat_completion_request(
|
||||
model=self.model_main,
|
||||
messages=context,
|
||||
tools=_get_tools_description() if allow_tools else None,
|
||||
|
|
@ -325,7 +326,7 @@ class AiAgent:
|
|||
context = [{"role": "user", "content": prompt}]
|
||||
|
||||
try:
|
||||
response = await self.client_image.chat.send_async(
|
||||
response = await self._async_chat_completion_request(
|
||||
model=self.model_image,
|
||||
messages=context,
|
||||
user=f'{self.platform}_{bot_id}_{chat_id}',
|
||||
|
|
@ -345,9 +346,29 @@ class AiAgent:
|
|||
image_bytes = output.getvalue()
|
||||
|
||||
return Ok(image_bytes)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Ошибка генерации изображения: {e}")
|
||||
return Err(str(e))
|
||||
# Костыль для модели Seedream 4.5
|
||||
message = str(e)
|
||||
prefix = "Request id:"
|
||||
if prefix in message:
|
||||
message = message.split(prefix)[0].strip()
|
||||
print(f"Ошибка генерации изображения: {message}")
|
||||
return Err(message)
|
||||
|
||||
async def _async_chat_completion_request(self, **kwargs):
|
||||
try:
|
||||
return await self.client_image.chat.send_async(**kwargs)
|
||||
except ResponseValidationError as e:
|
||||
# Костыль для OpenRouter SDK:
|
||||
# https://github.com/OpenRouterTeam/python-sdk/issues/44
|
||||
body = json.loads(e.body)
|
||||
if "error" in body:
|
||||
raw_response = json.loads(body["error"]["metadata"]["raw"])
|
||||
message = str(raw_response["error"]["message"])
|
||||
raise RuntimeError(message)
|
||||
else:
|
||||
raise RuntimeError("Ошибка валидации ответа от провайдера.") from e
|
||||
|
||||
|
||||
agent: AiAgent
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue