DeepSeekAPI.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from __future__ import annotations
  2. import os
  3. import json
  4. import time
  5. from typing import AsyncIterator
  6. import asyncio
  7. from ..base_provider import AsyncAuthedProvider, ProviderModelMixin
  8. from ...providers.helper import get_last_user_message
  9. from ...requests import get_args_from_nodriver, get_nodriver
  10. from ...providers.response import AuthResult, RequestLogin, Reasoning, JsonConversation, FinishReason
  11. from ...typing import AsyncResult, Messages
  12. try:
  13. from dsk.api import DeepSeekAPI as DskAPI
  14. has_dsk = True
  15. except ImportError:
  16. has_dsk = False
  17. class DeepSeekAPI(AsyncAuthedProvider, ProviderModelMixin):
  18. url = "https://chat.deepseek.com"
  19. working = has_dsk
  20. needs_auth = True
  21. use_nodriver = True
  22. _access_token = None
  23. default_model = "deepseek-v3"
  24. models = ["deepseek-v3", "deepseek-r1"]
  25. @classmethod
  26. async def on_auth_async(cls, proxy: str = None, **kwargs) -> AsyncIterator:
  27. if not hasattr(cls, "browser"):
  28. cls.browser, cls.stop_browser = await get_nodriver()
  29. yield RequestLogin(cls.__name__, os.environ.get("G4F_LOGIN_URL") or "")
  30. async def callback(page):
  31. while True:
  32. await asyncio.sleep(1)
  33. cls._access_token = json.loads(await page.evaluate("localStorage.getItem('userToken')") or "{}").get("value")
  34. if cls._access_token:
  35. break
  36. args = await get_args_from_nodriver(cls.url, proxy, callback=callback, browser=cls.browser)
  37. yield AuthResult(
  38. api_key=cls._access_token,
  39. **args
  40. )
  41. @classmethod
  42. async def create_authed(
  43. cls,
  44. model: str,
  45. messages: Messages,
  46. auth_result: AuthResult,
  47. conversation: JsonConversation = None,
  48. web_search: bool = False,
  49. **kwargs
  50. ) -> AsyncResult:
  51. # Initialize with your auth token
  52. api = DskAPI(auth_result.get_dict())
  53. # Create a new chat session
  54. if conversation is None:
  55. chat_id = api.create_chat_session()
  56. conversation = JsonConversation(chat_id=chat_id)
  57. yield conversation
  58. is_thinking = 0
  59. for chunk in api.chat_completion(
  60. conversation.chat_id,
  61. get_last_user_message(messages),
  62. thinking_enabled="deepseek-r1" in model,
  63. search_enabled=web_search
  64. ):
  65. if chunk['type'] == 'thinking':
  66. if not is_thinking:
  67. yield Reasoning(None, "Is thinking...")
  68. is_thinking = time.time()
  69. yield Reasoning(chunk['content'])
  70. elif chunk['type'] == 'text':
  71. if is_thinking:
  72. yield Reasoning(None, f"Thought for {time.time() - is_thinking:.2f}s")
  73. is_thinking = 0
  74. if chunk['content']:
  75. yield chunk['content']
  76. if chunk['finish_reason']:
  77. yield FinishReason(chunk['finish_reason'])