chat_dialog.py 1.8 KB

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