chat_dialog.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import json
  2. from Log import logger
  3. from app.service.v2.app_driver.chat_base import ChatBase
  4. class ChatDialog(ChatBase):
  5. async def chat_completions(self, url, data, headers):
  6. complete_response = ""
  7. async for line in self.http_stream(url, data, headers):
  8. print(line)
  9. if line.startswith("data:"):
  10. complete_response = line.strip("data:").strip()
  11. else:
  12. complete_response += line.strip()
  13. try:
  14. json_data = json.loads(complete_response)
  15. # 处理 JSON 数据
  16. # print(json_data)
  17. complete_response = ""
  18. yield json_data
  19. except json.JSONDecodeError as e:
  20. logger.info("Invalid JSON data------------------")
  21. # print(e)
  22. async def chat_sessions(self, url, data, headers):
  23. res = await self.http_post(url, data, headers)
  24. if res.status_code == 200:
  25. return res.json()
  26. else:
  27. return {}
  28. @staticmethod
  29. async def request_data(question, session_id=""):
  30. return {
  31. "question": question,
  32. "stream": True,
  33. "session_id": session_id
  34. }
  35. if __name__ == "__main__":
  36. async def aa():
  37. chat_id = "6b8ee426c67511efb1510242ac1b0006"
  38. token = "ragflow-YzMzE1NDRjYzMyZjExZWY5ZjkxMDI0Mm"
  39. base_url = "http://192.168.20.116:11080"
  40. url = f"{base_url}/api/v1/chats/{chat_id}/completions"
  41. chat = ChatDialog(token)
  42. data = {
  43. "question": "电网技术总结300字",
  44. "stream": True,
  45. "session_id": "9969c152cce411ef8a140242ac1b0002"
  46. }
  47. headers = {
  48. 'Content-Type': 'application/json',
  49. 'Authorization': f"Bearer {token}"
  50. }
  51. async for ans in chat.chat_completions(url, data, headers):
  52. print(ans)
  53. import asyncio
  54. asyncio.run(aa())