From 146dcdf21d800668d7d521e199f8866ab120c024 Mon Sep 17 00:00:00 2001 From: MrKan Date: Sun, 19 Apr 2026 21:00:34 +0300 Subject: [PATCH 1/7] =?UTF-8?q?=D0=BC=D0=BE=D0=B4=D0=B5=D0=BB=D1=8C=20MsgE?= =?UTF-8?q?ventSendFile=20=D0=B4=D0=BB=D1=8F=20=D0=BF=D0=BE=D0=BB=D1=83?= =?UTF-8?q?=D1=87=D0=B5=D0=BD=D0=B8=D1=8F=20=D1=84=D0=B0=D0=B9=D0=BB=D0=BE?= =?UTF-8?q?=D0=B2=20=D0=BE=D1=82=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lambda_agent_api/server.py | 99 ++++++++++++++++++++++++++------------ 1 file changed, 68 insertions(+), 31 deletions(-) diff --git a/lambda_agent_api/server.py b/lambda_agent_api/server.py index e5882f7..c0f01df 100644 --- a/lambda_agent_api/server.py +++ b/lambda_agent_api/server.py @@ -4,10 +4,18 @@ from typing import Literal, Annotated, Union, Any, Dict, Optional __all__ = [ - 'EServerMessage', 'MsgStatus', 'MsgError', 'MsgGracefulDisconnect', - 'MsgEventTextChunk', 'MsgEventToolCallChunk', 'MsgEventToolResult', - 'MsgEventCustomUpdate', 'MsgEventEnd', - 'AgentEventUnion', 'ServerMessage' + "EServerMessage", + "MsgStatus", + "MsgError", + "MsgGracefulDisconnect", + "MsgEventTextChunk", + "MsgEventToolCallChunk", + "MsgEventToolResult", + "MsgEventCustomUpdate", + "MsgEventSendFile", + "MsgEventEnd", + "AgentEventUnion", + "ServerMessage", ] @@ -19,18 +27,21 @@ class EServerMessage(str, Enum): # Ивенты агента AGENT_EVENT_TEXT_CHUNK = "AGENT_EVENT_TEXT_CHUNK" AGENT_EVENT_TOOL_CALL_CHUNK = "AGENT_EVENT_TOOL_CALL_CHUNK" # Новое - AGENT_EVENT_TOOL_RESULT = "AGENT_EVENT_TOOL_RESULT" # Новоеы - AGENT_EVENT_CUSTOM_UPDATE = "AGENT_EVENT_CUSTOM_UPDATE" # Новое + AGENT_EVENT_TOOL_RESULT = "AGENT_EVENT_TOOL_RESULT" # Новоеы + AGENT_EVENT_CUSTOM_UPDATE = "AGENT_EVENT_CUSTOM_UPDATE" # Новое + AGENT_EVENT_SEND_FILE = "AGENT_EVENT_SEND_FILE" # Новое AGENT_EVENT_END = "AGENT_EVENT_END" class MsgStatus(BaseModel): """Отправляется сервером при открытии соединения с клиентом.""" + type: Literal[EServerMessage.STATUS] = EServerMessage.STATUS class MsgError(BaseModel): """Неопределенная ошибка в работе агента.""" + type: Literal[EServerMessage.ERROR] = EServerMessage.ERROR code: str details: str @@ -38,16 +49,23 @@ class MsgError(BaseModel): class MsgGracefulDisconnect(BaseModel): """Отправляется перед завершением работы контейнера с агентом.""" - type: Literal[EServerMessage.GRACEFUL_DISCONNECT] = EServerMessage.GRACEFUL_DISCONNECT + + type: Literal[EServerMessage.GRACEFUL_DISCONNECT] = ( + EServerMessage.GRACEFUL_DISCONNECT + ) # ------------------------------------------------------------------ # AGENT EVENTS (События генерации) # ------------------------------------------------------------------ + class MsgEventTextChunk(BaseModel): """Чанк текста ответа агента.""" - type: Literal[EServerMessage.AGENT_EVENT_TEXT_CHUNK] = EServerMessage.AGENT_EVENT_TEXT_CHUNK + + type: Literal[EServerMessage.AGENT_EVENT_TEXT_CHUNK] = ( + EServerMessage.AGENT_EVENT_TEXT_CHUNK + ) text: str # Новое: "main" (главный агент) или "tools:..." (субагент, если будем использовать) source: str = "main" # пока везде будет main @@ -55,17 +73,23 @@ class MsgEventTextChunk(BaseModel): class MsgEventToolCallChunk(BaseModel): """Агент решил использовать инструмент и генерирует аргументы.""" - type: Literal[EServerMessage.AGENT_EVENT_TOOL_CALL_CHUNK] = EServerMessage.AGENT_EVENT_TOOL_CALL_CHUNK + + type: Literal[EServerMessage.AGENT_EVENT_TOOL_CALL_CHUNK] = ( + EServerMessage.AGENT_EVENT_TOOL_CALL_CHUNK + ) tool_name: Optional[str] = Field( - None, description="Имя инструмента (приходит обычно в первом чанке)") - args_chunk: Optional[str] = Field( - None, description="Кусок JSON-аргументов") + None, description="Имя инструмента (приходит обычно в первом чанке)" + ) + args_chunk: Optional[str] = Field(None, description="Кусок JSON-аргументов") source: str = "main" class MsgEventToolResult(BaseModel): """Инструмент отработал и вернул результат.""" - type: Literal[EServerMessage.AGENT_EVENT_TOOL_RESULT] = EServerMessage.AGENT_EVENT_TOOL_RESULT + + type: Literal[EServerMessage.AGENT_EVENT_TOOL_RESULT] = ( + EServerMessage.AGENT_EVENT_TOOL_RESULT + ) tool_name: str result: Any # Может быть строкой, словарем или списком source: str = "main" @@ -73,14 +97,28 @@ class MsgEventToolResult(BaseModel): class MsgEventCustomUpdate(BaseModel): """Кастомный прогресс (например, скачивание файла) изнутри инструмента.""" - type: Literal[EServerMessage.AGENT_EVENT_CUSTOM_UPDATE] = EServerMessage.AGENT_EVENT_CUSTOM_UPDATE + + type: Literal[EServerMessage.AGENT_EVENT_CUSTOM_UPDATE] = ( + EServerMessage.AGENT_EVENT_CUSTOM_UPDATE + ) payload: Dict[str, Any] = Field( - ..., description="Любые данные о прогрессе (status, progress и т.д.)") + ..., description="Любые данные о прогрессе (status, progress и т.д.)" + ) source: str = "main" +class MsgEventSendFile(BaseModel): + """Агент отправляет файл пользователю.""" + + type: Literal[EServerMessage.AGENT_EVENT_SEND_FILE] = ( + EServerMessage.AGENT_EVENT_SEND_FILE + ) + path: str = Field(..., description="Путь к файлу относительно /workspace") + + class MsgEventEnd(BaseModel): """Агент закончил генерацию ответа.""" + type: Literal[EServerMessage.AGENT_EVENT_END] = EServerMessage.AGENT_EVENT_END tokens_used: int @@ -95,25 +133,24 @@ AgentEventUnion = Union[ MsgEventToolCallChunk, MsgEventToolResult, MsgEventCustomUpdate, - MsgEventEnd + MsgEventSendFile, + MsgEventEnd, ] -# Обновлено: добавили новые модели в Union адаптера -ServerMessage = TypeAdapter(Annotated[ - Union[ - MsgStatus, - MsgError, - MsgGracefulDisconnect, - MsgEventTextChunk, - MsgEventToolCallChunk, - MsgEventToolResult, - MsgEventCustomUpdate, - MsgEventEnd - ], - Field(discriminator="type") -]) +# ServerMessage использует AgentEventUnion + остальные типы +ServerMessage = TypeAdapter( + Annotated[ + Union[ + MsgStatus, + MsgError, + MsgGracefulDisconnect, + AgentEventUnion, + ], + Field(discriminator="type"), + ] +) """ -Объединяет все типы исходящих сообщений в одно для удобной автоматической десериализации. +TypeAdapter для десериализации всех входящих сообщений (от сервера). Pydantic сам определит нужный тип в зависимости от поля `type`. Использование: msg = ServerMessage.validate_json(json_str) From 9ac4ef1ba165289c7b3d5b5350622617385b5386 Mon Sep 17 00:00:00 2001 From: MrKan Date: Sun, 19 Apr 2026 11:58:45 +0300 Subject: [PATCH 2/7] =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D0=B4=D0=B5=D1=80=D0=B6?= =?UTF-8?q?=D0=BA=D0=B0=20chat=5Fid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lambda_agent_api/agent_api.py | 7 +++++-- tests/manual.py | 3 ++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lambda_agent_api/agent_api.py b/lambda_agent_api/agent_api.py index d130bcf..e2e5346 100644 --- a/lambda_agent_api/agent_api.py +++ b/lambda_agent_api/agent_api.py @@ -2,6 +2,7 @@ import logging from typing import Callable, Optional, AsyncIterator import aiohttp import asyncio +from urllib.parse import urljoin from lambda_agent_api.server import * from lambda_agent_api.client import * @@ -27,10 +28,12 @@ class AgentApi: agent_id: str, url: str, callback: Optional[Callable[[ServerMessage], None]] = None, - on_disconnect: Optional[Callable[['AgentApi'], None]] = None + on_disconnect: Optional[Callable[['AgentApi'], None]] = None, + chat_id: int = 0 # значение по умолчанию для обратной совместимости ): self.id = agent_id # ID агента для словаря - self.url = url + self.chat_id = chat_id + self.url = urljoin(url, f"{chat_id}/") self.callback = callback self.on_disconnect = on_disconnect diff --git a/tests/manual.py b/tests/manual.py index a39802b..b801a2d 100644 --- a/tests/manual.py +++ b/tests/manual.py @@ -7,7 +7,8 @@ from lambda_agent_api.server import MsgEventTextChunk, MsgEventToolCallChunk, Ms async def main(): - api = AgentApi("agent-1", "ws://localhost:8000/agent_ws/") + chat_id = input("Chat id: ") or 0 + api = AgentApi("agent-1", "ws://localhost:8000/agent_ws/", chat_id=chat_id) await api.connect() while True: From 1b8efdb4a44803fe0c4fc4eb464400b19e1aa934 Mon Sep 17 00:00:00 2001 From: MrKan Date: Sun, 19 Apr 2026 14:41:48 +0300 Subject: [PATCH 3/7] =?UTF-8?q?=D0=BA=D0=BE=D1=80=D1=80=D0=B5=D0=BA=D1=82?= =?UTF-8?q?=D0=BD=D0=B0=D1=8F=20=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BA=D0=B8,=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=B3=D0=B4=D0=B0=20=D1=87=D0=B0=D1=82=20=D0=B7=D0=B0?= =?UTF-8?q?=D0=BD=D1=8F=D1=82=20=D0=B4=D1=80=D1=83=D0=B3=D0=B8=D0=BC=20?= =?UTF-8?q?=D0=BA=D0=BB=D0=B8=D0=B5=D0=BD=D1=82=D0=BE=D0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lambda_agent_api/agent_api.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/lambda_agent_api/agent_api.py b/lambda_agent_api/agent_api.py index e2e5346..cc25416 100644 --- a/lambda_agent_api/agent_api.py +++ b/lambda_agent_api/agent_api.py @@ -4,6 +4,8 @@ import aiohttp import asyncio from urllib.parse import urljoin +from aiohttp import WSServerHandshakeError + from lambda_agent_api.server import * from lambda_agent_api.client import * @@ -46,7 +48,11 @@ class AgentApi: self._listen_task: asyncio.Task | None = None async def connect(self): - """Явное подключение к агенту.""" + """Явное подключение к агенту. + + :raise AgentBusyException: Чат занят другим клиентом. + :raise AgentException: Непредвиденная ошибка протокола, см. code и details + """ self._session = aiohttp.ClientSession() try: self._ws = await self._session.ws_connect(self.url, heartbeat=30) @@ -88,6 +94,25 @@ class AgentApi: await self._session.close() raise + except WSServerHandshakeError as e: # если при открытии подключения сервер вернул какую-то ошибку + if self._session and not self._session.closed: + await self._session.close() + + # во-первых, aiohttp зачем-то приводит WS коды ошибок к HTTP. + # во-вторых, делает он это некорректно. Любой неизвестный код WS ошибки становится 403 HTTP + # в-третьих, он не передает оригинальное сообщение об ошибке. + # Т. е. какое бы сообщение сервер не отправлял, тут всегда будет "Invalid response status" + # см. site-packages\aiohttp\client.py, line 1104, in _ws_connect + # итого понять реальную причину ошибки почти невозможно. Нужно менять библиотеку + # сейчас сервер специально кидает только ошибку с WS кодом 1008 Policy Violation, когда внутри ловит ChatBusyError + # поэтому скорее всего, если мы получили WSServerHandshakeError с 403, то это внутренний ChatBusyError + if e.status != 403: + # обрабатываем как обычную ошибку WS по примеру except блока ниже + raise AgentException(code="CONNECTION_ERROR", + details=f"Failed to connect agent {self.id}: {e}") from e + + raise AgentBusyException(f"Chat {self.chat_id} is already in use by other client") + except Exception as e: # Обработка всех остальных ошибок (например, aiohttp.ClientConnectionError) if self._ws and not self._ws.closed: From 8256453bbf3381b62ee73bca77e9711444446f46 Mon Sep 17 00:00:00 2001 From: MrKan Date: Sun, 19 Apr 2026 15:12:07 +0300 Subject: [PATCH 4/7] =?UTF-8?q?=D0=B0=D0=BA=D1=82=D1=83=D0=B0=D0=BB=D0=B8?= =?UTF-8?q?=D0=B7=D0=B0=D1=86=D0=B8=D1=8F=20=D0=B4=D0=BE=D0=BA=D1=83=D0=BC?= =?UTF-8?q?=D0=B5=D0=BD=D1=82=D0=B0=D1=86=D0=B8=D0=B8=20=D0=B8=20manual=20?= =?UTF-8?q?=D1=82=D0=B5=D1=81=D1=82=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 41 +++++++---------------------------------- tests/manual.py | 9 +++++++-- 2 files changed, 14 insertions(+), 36 deletions(-) diff --git a/README.md b/README.md index 496c876..470317e 100644 --- a/README.md +++ b/README.md @@ -4,6 +4,11 @@ from lambda_agent_api import AgentApi WebSocket API SDK для взаимодействия с AI-агентом. +## Release Notes +# v1.1 +- Добавлен параметр `chat_id` в конструктор `AgentAPI`. Нужен для разделения истории сообщений по чатам/веткам. +- `AgentAPI.connect()` вызывает `AgentBusyException`, если выбранный чат уже занят другим API клиентом. + ## Установка В `master` всегда будет актуальная рабочая версия. ```bash @@ -14,42 +19,10 @@ pip install git+https://git.lambda.coredump.ru/platform/agent_api.git ## Быстрый старт (с использованием AgentApi) -```python -import asyncio - -from lambda_agent_api.agent_api import AgentApi -from lambda_agent_api.server import MsgEventTextChunk +**Рабочий REPL пример: [tests/manual.py](tests/manual.py).** -async def main(): - api = AgentApi("agent-1", "ws://localhost:8000/ws") - - await api.connect() - try: - response = await api.send_message("Привет, агент!") - - async for chunk in response: - if isinstance(chunk, MsgEventTextChunk): - print(chunk.text, end="", flush=True) - elif isinstance(chunk, MsgEventToolCallChunk): - print(f"Tool call started: {chunk.tool_name}") - elif isinstance(chunk, MsgEventToolResult): - print(f"Tool result: {chunk.result}") - elif isinstance(chunk, MsgEventCustomUpdate): - print(f"Progress update: {chunk.payload}") - elif isinstance(chunk, MsgEventEnd): - print(f"Generation ended, tokens used: {chunk.tokens_used}") - - finally: - await api.close() - - -asyncio.run(main()) -``` - -> `AgentApi.send_message()` возвращает стриминг-итерируемый объект, который может выдавать не только текстовые чанки, но и события инструментов (`MsgEventToolCallChunk`, `MsgEventToolResult`, `MsgEventCustomUpdate`) и финальный `MsgEventEnd`. - -## Предполагаемое использование +## Предполагаемое управление подключениями ```python from lambda_agent_api.agent_api import AgentApi diff --git a/tests/manual.py b/tests/manual.py index b801a2d..0ba6e0a 100644 --- a/tests/manual.py +++ b/tests/manual.py @@ -1,7 +1,7 @@ import asyncio import traceback -from lambda_agent_api.agent_api import AgentApi +from lambda_agent_api.agent_api import AgentApi, AgentBusyException from lambda_agent_api.server import MsgEventTextChunk, MsgEventToolCallChunk, MsgEventToolResult @@ -10,7 +10,12 @@ async def main(): chat_id = input("Chat id: ") or 0 api = AgentApi("agent-1", "ws://localhost:8000/agent_ws/", chat_id=chat_id) - await api.connect() + try: + await api.connect() + except AgentBusyException: + print(f"Чат {chat_id} занят другим клиентом") + return + while True: try: prompt = await asyncio.get_event_loop().run_in_executor(None, input, ">>> ") From 4c3e7253c71fed9efcf6feee41d0f5f7ccd6a035 Mon Sep 17 00:00:00 2001 From: MrKan Date: Sun, 19 Apr 2026 15:24:14 +0300 Subject: [PATCH 5/7] =?UTF-8?q?AgentAPI=20=D0=BF=D1=80=D0=B8=D0=BD=D0=B8?= =?UTF-8?q?=D0=BC=D0=B0=D0=B5=D1=82=20base=5Furl=20(=D0=BF=D0=BE=20=D0=B8?= =?UTF-8?q?=D0=B4=D0=B5=D0=B5=20ws://host:port)=20=D0=B8=20=D1=81=D0=B0?= =?UTF-8?q?=D0=BC=20=D0=B4=D0=BE=D0=BF=D0=B8=D1=81=D1=8B=D0=B2=D0=B0=D0=B5?= =?UTF-8?q?=D1=82=20=D0=BD=D1=83=D0=B6=D0=BD=D1=8B=D0=B9=20=D1=8D=D0=BD?= =?UTF-8?q?=D0=B4=D0=BF=D0=BE=D0=B8=D0=BD=D1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 ++-- lambda_agent_api/agent_api.py | 4 ++-- tests/manual.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 470317e..23841e6 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ -from lambda_agent_api import AgentApi - # Lambda Agent API WebSocket API SDK для взаимодействия с AI-агентом. ## Release Notes # v1.1 +- **CRITICAL**: `AgentAPI` вместо `url` принимает `base_url` и сам дописывает нужный эндпоинт. +Раньше: `AgentAPI(url="ws://localhost:8000/agent_ws/")`. Сейчас: `AgentAPI(base_url="ws://localhost:8000/")` - Добавлен параметр `chat_id` в конструктор `AgentAPI`. Нужен для разделения истории сообщений по чатам/веткам. - `AgentAPI.connect()` вызывает `AgentBusyException`, если выбранный чат уже занят другим API клиентом. diff --git a/lambda_agent_api/agent_api.py b/lambda_agent_api/agent_api.py index cc25416..e22a0b8 100644 --- a/lambda_agent_api/agent_api.py +++ b/lambda_agent_api/agent_api.py @@ -28,14 +28,14 @@ class AgentApi: def __init__( self, agent_id: str, - url: str, + base_url: str, callback: Optional[Callable[[ServerMessage], None]] = None, on_disconnect: Optional[Callable[['AgentApi'], None]] = None, chat_id: int = 0 # значение по умолчанию для обратной совместимости ): self.id = agent_id # ID агента для словаря self.chat_id = chat_id - self.url = urljoin(url, f"{chat_id}/") + self.url = urljoin(base_url, f"/v1/agent_ws/{chat_id}/") self.callback = callback self.on_disconnect = on_disconnect diff --git a/tests/manual.py b/tests/manual.py index 0ba6e0a..10f3005 100644 --- a/tests/manual.py +++ b/tests/manual.py @@ -8,7 +8,7 @@ from lambda_agent_api.server import MsgEventTextChunk, MsgEventToolCallChunk, Ms async def main(): chat_id = input("Chat id: ") or 0 - api = AgentApi("agent-1", "ws://localhost:8000/agent_ws/", chat_id=chat_id) + api = AgentApi("agent-1", "ws://localhost:8000/", chat_id=chat_id) try: await api.connect() From 0cf3117fde29a328a8de9adb830e1d3f9fec0834 Mon Sep 17 00:00:00 2001 From: MrKan Date: Sun, 19 Apr 2026 21:14:19 +0300 Subject: [PATCH 6/7] =?UTF-8?q?=D0=BE=D0=B1=D1=80=D0=B0=D0=B1=D0=BE=D1=82?= =?UTF-8?q?=D0=BA=D0=B0=20=D0=BD=D0=BE=D0=B2=D0=BE=D0=B9=20=D0=BC=D0=BE?= =?UTF-8?q?=D0=B4=D0=B5=D0=BB=D0=B8,=20=D0=B0=D0=BA=D1=82=D1=83=D0=B0?= =?UTF-8?q?=D0=BB=D1=8C=D0=BD=D1=8B=D0=B9=20manual.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lambda_agent_api/agent_api.py | 95 ++++++++++++++++++++--------------- tests/manual.py | 18 +++++-- 2 files changed, 68 insertions(+), 45 deletions(-) diff --git a/lambda_agent_api/agent_api.py b/lambda_agent_api/agent_api.py index e22a0b8..9a82992 100644 --- a/lambda_agent_api/agent_api.py +++ b/lambda_agent_api/agent_api.py @@ -30,8 +30,8 @@ class AgentApi: agent_id: str, base_url: str, callback: Optional[Callable[[ServerMessage], None]] = None, - on_disconnect: Optional[Callable[['AgentApi'], None]] = None, - chat_id: int = 0 # значение по умолчанию для обратной совместимости + on_disconnect: Optional[Callable[["AgentApi"], None]] = None, + chat_id: int = 0, # значение по умолчанию для обратной совместимости ): self.id = agent_id # ID агента для словаря self.chat_id = chat_id @@ -67,10 +67,12 @@ class AgentApi: logger.info(f"Agent {self.id} is ready") else: raise AgentException( - "INVALID_STATUS", f"Expected SM.Status, got {status_msg.type}") + "INVALID_STATUS", f"Expected SM.Status, got {status_msg.type}" + ) else: - raise AgentException("UNEXPECTED_MSG_TYPE", - f"Unexpected message type: {msg.type}") + raise AgentException( + "UNEXPECTED_MSG_TYPE", f"Unexpected message type: {msg.type}" + ) self._connected = True self._listen_task = asyncio.create_task(self._listen()) @@ -83,7 +85,8 @@ class AgentApi: await self._session.close() raise AgentException( - "TIMEOUT", "Agent did not send initial Status message within 5 seconds") from e + "TIMEOUT", "Agent did not send initial Status message within 5 seconds" + ) from e except AgentException: # Перехватываем наши собственные ошибки (INVALID_STATUS, UNEXPECTED_MSG_TYPE), @@ -94,7 +97,9 @@ class AgentApi: await self._session.close() raise - except WSServerHandshakeError as e: # если при открытии подключения сервер вернул какую-то ошибку + except ( + WSServerHandshakeError + ) as e: # если при открытии подключения сервер вернул какую-то ошибку if self._session and not self._session.closed: await self._session.close() @@ -108,10 +113,14 @@ class AgentApi: # поэтому скорее всего, если мы получили WSServerHandshakeError с 403, то это внутренний ChatBusyError if e.status != 403: # обрабатываем как обычную ошибку WS по примеру except блока ниже - raise AgentException(code="CONNECTION_ERROR", - details=f"Failed to connect agent {self.id}: {e}") from e + raise AgentException( + code="CONNECTION_ERROR", + details=f"Failed to connect agent {self.id}: {e}", + ) from e - raise AgentBusyException(f"Chat {self.chat_id} is already in use by other client") + raise AgentBusyException( + f"Chat {self.chat_id} is already in use by other client" + ) except Exception as e: # Обработка всех остальных ошибок (например, aiohttp.ClientConnectionError) @@ -121,8 +130,10 @@ class AgentApi: await self._session.close() # Можно оставить RuntimeError, а можно тоже завернуть в AgentException - raise AgentException(code="CONNECTION_ERROR", - details=f"Failed to connect agent {self.id}: {e}") from e + raise AgentException( + code="CONNECTION_ERROR", + details=f"Failed to connect agent {self.id}: {e}", + ) from e async def close(self): """Явное ручное закрытие соединения.""" @@ -161,17 +172,17 @@ class AgentApi: async def send_message(self, text: str) -> AsyncIterator[AgentEventUnion]: """ - Нативный асинхронный генератор. + Нативный асинхронный генератор. Не требует отдельного класса ResponseIterator. Гарантированно освобождает блокировку. """ if not self._connected or not self._ws: - raise AgentException(code="NOT_CONNECTED", - details="Not connected. Call connect() first.") + raise AgentException( + code="NOT_CONNECTED", details="Not connected. Call connect() first." + ) if self._request_lock.locked(): - raise AgentBusyException( - "Agent is currently processing another request") + raise AgentBusyException("Agent is currently processing another request") # Блокируем параллельные запросы # если идет стриминг ответа, то при попытки отправить новое сообщение будет ошибка - ее рейзим(делаем AgentBusyError) @@ -180,10 +191,7 @@ class AgentApi: try: self._current_queue = asyncio.Queue() - message = MsgUserMessage( - type=EClientMessage.USER_MESSAGE, - text=text - ) + message = MsgUserMessage(type=EClientMessage.USER_MESSAGE, text=text) await self._ws.send_str(message.model_dump_json()) logger.debug(f"[{self.id}] Sent message: {text[:50]}...") @@ -226,7 +234,8 @@ class AgentApi: # Если это исключение, просто логируем, в коллбек его кидать не стоит if isinstance(orphan_msg, Exception): logger.debug( - f"[{self.id}] Dropped exception from queue during cleanup: {orphan_msg}") + f"[{self.id}] Dropped exception from queue during cleanup: {orphan_msg}" + ) continue # 3. Отправляем "мусорные/осиротевшие" куски в callback @@ -234,7 +243,8 @@ class AgentApi: self.callback(orphan_msg) else: logger.debug( - f"[{self.id}] Dropped orphaned message during cleanup") + f"[{self.id}] Dropped orphaned message during cleanup" + ) except asyncio.QueueEmpty: break @@ -244,34 +254,41 @@ class AgentApi: self._request_lock.release() async def _listen(self): - """" + """ " Прослушивание вебсокета. """ try: async for msg in self._ws: if msg.type == aiohttp.WSMsgType.TEXT: try: - outgoing_msg = ServerMessage.validate_json( - msg.data) + outgoing_msg = ServerMessage.validate_json(msg.data) - if isinstance(outgoing_msg, (MsgEventTextChunk, - MsgEventToolCallChunk, - MsgEventToolResult, - MsgEventCustomUpdate, - MsgEventEnd)): + if isinstance( + outgoing_msg, + ( + MsgEventTextChunk, + MsgEventToolCallChunk, + MsgEventToolResult, + MsgEventCustomUpdate, + MsgEventSendFile, + MsgEventEnd, + ), + ): if self._current_queue: await self._current_queue.put(outgoing_msg) elif self.callback: self.callback(outgoing_msg) else: logger.warning( - f"[{self.id}] AgentEvent without active request") + f"[{self.id}] AgentEvent without active request" + ) elif isinstance(outgoing_msg, MsgError): if self.callback: self.callback(outgoing_msg) error = AgentException( - outgoing_msg.code, outgoing_msg.details) + outgoing_msg.code, outgoing_msg.details + ) logger.error(f"[{self.id}] Agent error: {error}") if self._current_queue: await self._current_queue.put(error) @@ -279,8 +296,7 @@ class AgentApi: elif isinstance(outgoing_msg, MsgGracefulDisconnect): if self.callback: self.callback(outgoing_msg) - logger.info( - f"[{self.id}] Gracefully disconnecting") + logger.info(f"[{self.id}] Gracefully disconnecting") break # Выход из цикла приведет к finally -> _cleanup else: @@ -292,17 +308,14 @@ class AgentApi: self.callback(outgoing_msg) except Exception as e: - logger.error( - f"[{self.id}] Failed to deserialize message: {e}") + logger.error(f"[{self.id}] Failed to deserialize message: {e}") if self._current_queue: await self._current_queue.put( - AgentException( - "PARSE_ERROR", f"Validation failed: {e}") + AgentException("PARSE_ERROR", f"Validation failed: {e}") ) elif msg.type in (aiohttp.WSMsgType.ERROR, aiohttp.WSMsgType.CLOSED): - logger.error( - f"[{self.id}] WebSocket closed/error: {msg.type}") + logger.error(f"[{self.id}] WebSocket closed/error: {msg.type}") break except asyncio.CancelledError: diff --git a/tests/manual.py b/tests/manual.py index 10f3005..44adea2 100644 --- a/tests/manual.py +++ b/tests/manual.py @@ -2,8 +2,12 @@ import asyncio import traceback from lambda_agent_api.agent_api import AgentApi, AgentBusyException -from lambda_agent_api.server import MsgEventTextChunk, MsgEventToolCallChunk, MsgEventToolResult - +from lambda_agent_api.server import ( + MsgEventTextChunk, + MsgEventToolCallChunk, + MsgEventToolResult, + MsgEventSendFile, +) async def main(): @@ -28,12 +32,18 @@ async def main(): print(chunk.text, end="", flush=True) case MsgEventToolCallChunk(): if not is_tool: - print(f"\n\n### TOOL CALL: ({chunk.tool_name}) ", end="", flush=True) + print( + f"\n\n### TOOL CALL: ({chunk.tool_name}) ", + end="", + flush=True, + ) is_tool = True print(chunk.args_chunk, end="", flush=True) case MsgEventToolResult(): is_tool = False print(f"\nResult: {chunk.result}\n\n", end="", flush=True) + case MsgEventSendFile(): + print(f"\n[SEND FILE] {chunk.path}\n", end="", flush=True) print("\n") except KeyboardInterrupt: @@ -44,4 +54,4 @@ async def main(): await api.close() -asyncio.run(main()) \ No newline at end of file +asyncio.run(main()) From 700f7fa0e7fecd2675873437555663fecd89d012 Mon Sep 17 00:00:00 2001 From: MrKan Date: Sun, 19 Apr 2026 21:42:49 +0300 Subject: [PATCH 7/7] =?UTF-8?q?=D0=B0=D0=BA=D1=82=D1=83=D0=B0=D0=BB=D1=8C?= =?UTF-8?q?=D0=BD=D1=8B=D0=B9=20README?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 21 +++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 23841e6..ccc0115 100644 --- a/README.md +++ b/README.md @@ -3,11 +3,12 @@ WebSocket API SDK для взаимодействия с AI-агентом. ## Release Notes -# v1.1 +# v1.1 - **CRITICAL**: `AgentAPI` вместо `url` принимает `base_url` и сам дописывает нужный эндпоинт. -Раньше: `AgentAPI(url="ws://localhost:8000/agent_ws/")`. Сейчас: `AgentAPI(base_url="ws://localhost:8000/")` + Раньше: `AgentAPI(url="ws://localhost:8000/agent_ws/")`. Сейчас: `AgentAPI(base_url="ws://localhost:8000/")` - Добавлен параметр `chat_id` в конструктор `AgentAPI`. Нужен для разделения истории сообщений по чатам/веткам. - `AgentAPI.connect()` вызывает `AgentBusyException`, если выбранный чат уже занят другим API клиентом. +- Добавлен новый тип события `MsgEventSendFile` для отправки файлов пользователю. Поле `path` — путь к файлу относительно `/workspace`. ## Установка В `master` всегда будет актуальная рабочая версия. @@ -164,6 +165,22 @@ async def on_telegram_message(from_user: int, text: str): | payload | object | Любые данные о прогрессе | | source | string | Источник события (по умолчанию "main") | +#### AGENT_EVENT_SEND_FILE + +Агент отправляет файл пользователю. Путь к файлу относительно `/workspace`. + +```json +{ + "type": "AGENT_EVENT_SEND_FILE", + "path": "reports/2024/report.pdf" +} +``` + +| Поле | Тип | Описание | +|--------|--------|-----------------------------------------------| +| type | string | Всегда `AGENT_EVENT_SEND_FILE` | +| path | string | Путь к файлу относительно `/workspace` | + #### AGENT_EVENT_END Агент закончил генерацию ответа.