примитивный ws эндпоинт

This commit is contained in:
Егор Кандрушин 2026-04-01 23:32:13 +03:00
parent 9735069034
commit 04bb17190e
5 changed files with 244 additions and 1 deletions

0
src/api/__init__.py Normal file
View file

45
src/api/external.py Normal file
View file

@ -0,0 +1,45 @@
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
from lambda_agent_api.server import *
from lambda_agent_api.client import *
router = APIRouter()
@router.websocket("/agent_ws/")
async def websocket_endpoint(ws: WebSocket):
await ws.accept()
await ws.send_text(MsgStatus().model_dump_json())
try:
while True:
raw = await ws.receive_text()
msg = ClientMessage.validate_json(raw)
await process_message(ws, msg)
except WebSocketDisconnect:
pass
except Exception as exc:
await ws.send_text(
MsgError(code="INTERNAL_ERROR", details=str(exc)).model_dump_json()
)
async def process_message(ws: WebSocket, msg): # msg должно быть ClientMessage (аннотация не работает из-за TypeAdapter)
match msg:
case MsgUserMessage():
await handle_user_message(ws, msg.text)
async def handle_user_message(ws: WebSocket, text: str):
await ws.send_text(
MsgEventTextChunk(
text="Hello!",
).model_dump_json()
)
await ws.send_text(
MsgEventEnd(
tokens_used=10,
).model_dump_json()
)

8
src/main.py Normal file
View file

@ -0,0 +1,8 @@
from fastapi import FastAPI
from src.api.external import router as ws_router
app = FastAPI()
app.include_router(ws_router)