chat_dialog.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. # print(e)
  21. # print(complete_response)
  22. logger.info("Invalid JSON data------------------")
  23. # print(e)
  24. async def chat_sessions(self, url, data, headers):
  25. res = await self.http_post(url, data, headers)
  26. if res.status_code == 200:
  27. return res.json()
  28. else:
  29. return {}
  30. @staticmethod
  31. async def request_data(question, session_id=""):
  32. return {
  33. "question": question,
  34. "stream": True,
  35. "session_id": session_id
  36. }
  37. @staticmethod
  38. async def complex_request_data(question, dataset_ids, session_id=""):
  39. return {
  40. "question": question,
  41. "stream": True,
  42. "session_id": session_id,
  43. "kb_ids": dataset_ids
  44. }
  45. if __name__ == "__main__":
  46. async def aa():
  47. chat_id = "6b8ee426c67511efb1510242ac1b0006"
  48. token = "ragflow-YzMzE1NDRjYzMyZjExZWY5ZjkxMDI0Mm"
  49. base_url = "http://192.168.20.116:11080"
  50. url = f"{base_url}/api/v1/chats/{chat_id}/completions"
  51. chat = ChatDialog(token)
  52. data = {
  53. "question": "电网技术总结300字",
  54. "stream": True,
  55. "session_id": "9969c152cce411ef8a140242ac1b0002"
  56. }
  57. headers = {
  58. 'Content-Type': 'application/json',
  59. 'Authorization': f"Bearer {token}"
  60. }
  61. async for ans in chat.chat_completions(url, data, headers):
  62. print(ans)
  63. import asyncio
  64. asyncio.run(aa())