CopilotAccount.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. from __future__ import annotations
  2. import os
  3. from typing import AsyncIterator
  4. from ..base_provider import AsyncAuthedProvider
  5. from ..Copilot import Copilot, readHAR, has_nodriver, get_access_token_and_cookies
  6. from ...providers.response import AuthResult, RequestLogin
  7. from ...typing import AsyncResult, Messages
  8. from ...errors import NoValidHarFileError
  9. from ... import debug
  10. class CopilotAccount(Copilot, AsyncAuthedProvider):
  11. needs_auth = True
  12. use_nodriver = True
  13. parent = "Copilot"
  14. default_model = "Copilot"
  15. default_vision_model = default_model
  16. @classmethod
  17. async def on_auth_async(cls, proxy: str = None, **kwargs) -> AsyncIterator:
  18. try:
  19. cls._access_token, cls._cookies = readHAR(cls.url)
  20. except NoValidHarFileError as h:
  21. debug.log(f"Copilot: {h}")
  22. if has_nodriver:
  23. yield RequestLogin(cls.label, os.environ.get("G4F_LOGIN_URL", ""))
  24. cls._access_token, cls._cookies = await get_access_token_and_cookies(cls.url, proxy)
  25. else:
  26. raise h
  27. yield AuthResult(
  28. api_key=cls._access_token,
  29. cookies=cls.cookies_to_dict()
  30. )
  31. @classmethod
  32. async def create_authed(
  33. cls,
  34. model: str,
  35. messages: Messages,
  36. auth_result: AuthResult,
  37. **kwargs
  38. ) -> AsyncResult:
  39. cls._access_token = getattr(auth_result, "api_key")
  40. cls._cookies = getattr(auth_result, "cookies")
  41. async for chunk in cls.create_async_generator(model, messages, **kwargs):
  42. yield chunk
  43. auth_result.cookies = cls.cookies_to_dict()
  44. @classmethod
  45. def cookies_to_dict(cls):
  46. return cls._cookies if isinstance(cls._cookies, dict) else {c.name: c.value for c in cls._cookies}