excel_talk.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import asyncio
  2. import json
  3. from enum import Enum
  4. from fastapi import APIRouter, Depends
  5. from sqlalchemy.orm import Session
  6. from starlette.websockets import WebSocket, WebSocketDisconnect
  7. from app.api import get_current_user_websocket
  8. from app.config.config import settings
  9. from app.models import UserModel, AgentModel
  10. from app.models.base_model import get_db
  11. from app.service.basic import BasicService
  12. router = APIRouter()
  13. # class CompletionRequest(BaseModel):
  14. # id: Optional[str] = None
  15. # app_id: str
  16. # message: str
  17. #
  18. # class DownloadRequest(BaseModel):
  19. # file_id: str
  20. # app_id: str
  21. # file_type: Optional[str] = None
  22. class AdvancedAgentID(Enum):
  23. EXCEL_TALK = "excel_talk"
  24. QUESTIONS_TALK = "questions_talk"
  25. @router.websocket("/ws/{agent_id}/{chat_id}")
  26. async def handle_client(websocket: WebSocket,
  27. agent_id: str,
  28. chat_id: str,
  29. current_user: UserModel = Depends(get_current_user_websocket),
  30. db: Session = Depends(get_db)):
  31. await websocket.accept()
  32. print(f"Client {agent_id} connected")
  33. service = BasicService(base_url=settings.basic_base_url)
  34. agent = db.query(AgentModel).filter(AgentModel.id == agent_id).first()
  35. if not agent:
  36. ret = {"message": "Agent not found", "type": "close"}
  37. await websocket.send_json(ret)
  38. return
  39. try:
  40. while True:
  41. # 接收前端消息
  42. message = await websocket.receive_json()
  43. question = message.get("message")
  44. if not question:
  45. await websocket.send_json({"message": "Invalid request", "type": "error"})
  46. continue
  47. # 调用 excel_talk 方法
  48. result = await service.excel_talk(question, chat_id)
  49. # 将结果发送回前端
  50. await websocket.send_json({"message": result, "type": "response"})
  51. except Exception as e:
  52. await websocket.send_json({"message": str(e), "type": "error"})
  53. finally:
  54. await websocket.close()
  55. print(f"Client {agent_id} disconnected")