chat_agent.py 2.7 KB

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