chat_agent.py 2.7 KB

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