DeepInfra.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from __future__ import annotations
  2. import json
  3. from ..typing import AsyncResult, Messages
  4. from .base_provider import AsyncGeneratorProvider
  5. from ..requests import StreamSession
  6. class DeepInfra(AsyncGeneratorProvider):
  7. url = "https://deepinfra.com"
  8. working = True
  9. supports_stream = True
  10. supports_message_history = True
  11. @staticmethod
  12. async def create_async_generator(
  13. model: str,
  14. messages: Messages,
  15. stream: bool,
  16. proxy: str = None,
  17. timeout: int = 120,
  18. auth: str = None,
  19. **kwargs
  20. ) -> AsyncResult:
  21. if not model:
  22. model = 'meta-llama/Llama-2-70b-chat-hf'
  23. headers = {
  24. 'Accept-Encoding': 'gzip, deflate, br',
  25. 'Accept-Language': 'en-US',
  26. 'Connection': 'keep-alive',
  27. 'Content-Type': 'application/json',
  28. 'Origin': 'https://deepinfra.com',
  29. 'Referer': 'https://deepinfra.com/',
  30. 'Sec-Fetch-Dest': 'empty',
  31. 'Sec-Fetch-Mode': 'cors',
  32. 'Sec-Fetch-Site': 'same-site',
  33. 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
  34. 'X-Deepinfra-Source': 'web-embed',
  35. 'accept': 'text/event-stream',
  36. 'sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
  37. 'sec-ch-ua-mobile': '?0',
  38. 'sec-ch-ua-platform': '"macOS"',
  39. }
  40. if auth:
  41. headers['Authorization'] = f"bearer {auth}"
  42. async with StreamSession(headers=headers,
  43. timeout=timeout,
  44. proxies={"https": proxy},
  45. impersonate="chrome110"
  46. ) as session:
  47. json_data = {
  48. 'model' : model,
  49. 'messages': messages,
  50. 'stream' : True
  51. }
  52. async with session.post('https://api.deepinfra.com/v1/openai/chat/completions',
  53. json=json_data) as response:
  54. response.raise_for_status()
  55. first = True
  56. async for line in response.iter_lines():
  57. try:
  58. if line.startswith(b"data: [DONE]"):
  59. break
  60. elif line.startswith(b"data: "):
  61. chunk = json.loads(line[6:])["choices"][0]["delta"].get("content")
  62. if chunk:
  63. if first:
  64. chunk = chunk.lstrip()
  65. if chunk:
  66. first = False
  67. yield chunk
  68. except Exception:
  69. raise RuntimeError(f"Response: {line}")