PerplexityLabs.py 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. from __future__ import annotations
  2. import random
  3. import json
  4. from ..typing import AsyncResult, Messages
  5. from ..requests import StreamSession, raise_for_status
  6. from ..errors import ResponseError
  7. from ..providers.response import FinishReason, Sources
  8. from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
  9. API_URL = "https://www.perplexity.ai/socket.io/"
  10. WS_URL = "wss://www.perplexity.ai/socket.io/"
  11. class PerplexityLabs(AsyncGeneratorProvider, ProviderModelMixin):
  12. url = "https://labs.perplexity.ai"
  13. working = True
  14. default_model = "r1-1776"
  15. models = [
  16. default_model,
  17. "sonar-pro",
  18. "sonar",
  19. "sonar-reasoning",
  20. "sonar-reasoning-pro",
  21. ]
  22. @classmethod
  23. async def create_async_generator(
  24. cls,
  25. model: str,
  26. messages: Messages,
  27. proxy: str = None,
  28. **kwargs
  29. ) -> AsyncResult:
  30. headers = {
  31. "Origin": cls.url,
  32. "Referer": f"{cls.url}/",
  33. }
  34. async with StreamSession(headers=headers, proxy=proxy, impersonate="chrome") as session:
  35. t = format(random.getrandbits(32), "08x")
  36. async with session.get(
  37. f"{API_URL}?EIO=4&transport=polling&t={t}"
  38. ) as response:
  39. await raise_for_status(response)
  40. text = await response.text()
  41. assert text.startswith("0")
  42. sid = json.loads(text[1:])["sid"]
  43. post_data = '40{"jwt":"anonymous-ask-user"}'
  44. async with session.post(
  45. f"{API_URL}?EIO=4&transport=polling&t={t}&sid={sid}",
  46. data=post_data
  47. ) as response:
  48. await raise_for_status(response)
  49. assert await response.text() == "OK"
  50. async with session.get(
  51. f"{API_URL}?EIO=4&transport=polling&t={t}&sid={sid}",
  52. data=post_data
  53. ) as response:
  54. await raise_for_status(response)
  55. assert (await response.text()).startswith("40")
  56. async with session.ws_connect(f"{WS_URL}?EIO=4&transport=websocket&sid={sid}", autoping=False) as ws:
  57. await ws.send_str("2probe")
  58. assert(await ws.receive_str() == "3probe")
  59. await ws.send_str("5")
  60. assert(await ws.receive_str() == "6")
  61. message_data = {
  62. "version": "2.18",
  63. "source": "default",
  64. "model": model,
  65. "messages": messages,
  66. }
  67. await ws.send_str("42" + json.dumps(["perplexity_labs", message_data]))
  68. last_message = 0
  69. while True:
  70. message = await ws.receive_str()
  71. if message == "2":
  72. if last_message == 0:
  73. raise RuntimeError("Unknown error")
  74. await ws.send_str("3")
  75. continue
  76. try:
  77. if last_message == 0 and model == cls.default_model:
  78. yield "<think>"
  79. data = json.loads(message[2:])[1]
  80. yield data["output"][last_message:]
  81. last_message = len(data["output"])
  82. if data["final"]:
  83. if data["citations"]:
  84. yield Sources(data["citations"])
  85. yield FinishReason("stop")
  86. break
  87. except Exception as e:
  88. raise ResponseError(f"Message: {message}") from e