AiChatting.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from __future__ import annotations
  2. from urllib.parse import unquote
  3. from ...typing import AsyncResult, Messages
  4. from ..base_provider import BaseProvider
  5. from ...webdriver import WebDriver
  6. from ...requests import Session, get_session_from_browser
  7. class AiChatting(BaseProvider):
  8. url = "https://www.aichatting.net"
  9. supports_gpt_35_turbo = True
  10. _session: Session = None
  11. @classmethod
  12. def create_completion(
  13. cls,
  14. model: str,
  15. messages: Messages,
  16. stream: bool,
  17. proxy: str = None,
  18. timeout: int = 120,
  19. webdriver: WebDriver = None,
  20. **kwargs
  21. ) -> AsyncResult:
  22. if not cls._session:
  23. cls._session = get_session_from_browser(cls.url, webdriver, proxy, timeout)
  24. visitorId = unquote(cls._session.cookies.get("aichatting.website.visitorId"))
  25. headers = {
  26. "accept": "application/json, text/plain, */*",
  27. "lang": "en",
  28. "source": "web"
  29. }
  30. data = {
  31. "roleId": 0,
  32. }
  33. try:
  34. response = cls._session.post("https://aga-api.aichatting.net/aigc/chat/record/conversation/create", json=data, headers=headers)
  35. response.raise_for_status()
  36. conversation_id = response.json()["data"]["conversationId"]
  37. except Exception as e:
  38. cls.reset()
  39. raise e
  40. headers = {
  41. "authority": "aga-api.aichatting.net",
  42. "accept": "text/event-stream,application/json, text/event-stream",
  43. "lang": "en",
  44. "source": "web",
  45. "vtoken": visitorId,
  46. }
  47. data = {
  48. "spaceHandle": True,
  49. "roleId": 0,
  50. "messages": messages,
  51. "conversationId": conversation_id,
  52. }
  53. response = cls._session.post("https://aga-api.aichatting.net/aigc/chat/v2/stream", json=data, headers=headers, stream=True)
  54. response.raise_for_status()
  55. for chunk in response.iter_lines():
  56. if chunk.startswith(b"data:"):
  57. yield chunk[5:].decode().replace("-=- --", " ").replace("-=-n--", "\n").replace("--@DONE@--", "")
  58. @classmethod
  59. def reset(cls):
  60. cls._session = None