chat_agent.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import json
  2. # from Log import logger
  3. from app.models.v2.session_model import ChatData
  4. from app.service.v2.app_driver.chat_base import ChatBase
  5. class ChatAgent(ChatBase):
  6. async def chat_completions(self, url, data, headers):
  7. complete_response = ""
  8. async for line in self.http_stream(url, data, headers):
  9. # logger.error(line)
  10. if line.startswith("data:"):
  11. complete_response = line.strip("data:").strip()
  12. elif line.startswith("Error: "):
  13. yield {"event": "error", "message": line}
  14. else:
  15. complete_response += line.strip()
  16. try:
  17. json_data = json.loads(complete_response)
  18. # 处理 JSON 数据
  19. # print(json_data)
  20. complete_response = ""
  21. yield json_data
  22. except json.JSONDecodeError as e:
  23. # logger.info("Invalid JSON data------------------")
  24. print(e)
  25. @staticmethod
  26. async def request_data(query: str, conversation_id: str, user:str, chat_data: ChatData) -> dict:
  27. inputs = []
  28. files = []
  29. if hasattr(chat_data, "inputs"):
  30. inputs = chat_data.inputs
  31. if hasattr(chat_data, "files"):
  32. files = chat_data.files
  33. return {
  34. "inputs":inputs,
  35. "query": query,
  36. "response_mode": "streaming",
  37. "conversation_id": conversation_id,
  38. "user": user,
  39. "files": files
  40. }
  41. if __name__ == "__main__":
  42. async def aa():
  43. chat_id = "16954f6d-c1e6-4a0b-b371-363c28e8a48b"
  44. token = "app-79ndndjNAFSV3qTuDAjDwuSO"
  45. base_url = "http://192.168.20.116"
  46. url = f"{base_url}/v1/chat-messages"
  47. chat = ChatAgent()
  48. data = {
  49. "inputs":{},
  50. "query": "你好,你能做什么?",
  51. "response_mode": "streaming",
  52. "conversation_id": "",
  53. "user": "1",
  54. "files": []
  55. }
  56. headers = {
  57. 'Content-Type': 'application/json',
  58. 'Authorization': f"Bearer {token}"
  59. }
  60. async for ans in chat.chat_completions(url, data, headers):
  61. print(ans)
  62. import asyncio
  63. asyncio.run(aa())