gpt4free/g4f/Provider/DeepInfra.py

90 lines
3.4 KiB
Python
Raw Normal View History

2023-10-26 19:32:49 +00:00
from __future__ import annotations
2024-01-01 22:23:45 +00:00
import json
import requests
from ..typing import AsyncResult, Messages
from .base_provider import AsyncGeneratorProvider, ProviderModelMixin
from ..requests import StreamSession
2023-10-26 19:32:49 +00:00
class DeepInfra(AsyncGeneratorProvider, ProviderModelMixin):
2024-01-01 22:23:45 +00:00
url = "https://deepinfra.com"
working = True
supports_stream = True
supports_message_history = True
default_model = 'meta-llama/Llama-2-70b-chat-hf'
@classmethod
def get_models(cls):
if not cls.models:
url = 'https://api.deepinfra.com/models/featured'
2024-01-30 03:15:25 +00:00
models = requests.get(url).json()
cls.models = [model['model_name'] for model in models]
return cls.models
@classmethod
2024-01-01 22:23:45 +00:00
async def create_async_generator(
cls,
2024-01-01 22:23:45 +00:00
model: str,
messages: Messages,
stream: bool,
proxy: str = None,
timeout: int = 120,
auth: str = None,
**kwargs
) -> AsyncResult:
2023-10-26 19:32:49 +00:00
headers = {
2024-01-01 22:23:45 +00:00
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US',
2023-11-24 14:16:00 +00:00
'Connection': 'keep-alive',
'Content-Type': 'application/json',
'Origin': 'https://deepinfra.com',
'Referer': 'https://deepinfra.com/',
'Sec-Fetch-Dest': 'empty',
'Sec-Fetch-Mode': 'cors',
'Sec-Fetch-Site': 'same-site',
'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',
'X-Deepinfra-Source': 'web-embed',
'accept': 'text/event-stream',
'sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"macOS"',
2023-10-26 19:32:49 +00:00
}
if auth:
headers['Authorization'] = f"bearer {auth}"
2024-01-01 22:23:45 +00:00
async with StreamSession(headers=headers,
timeout=timeout,
proxies={"https": proxy},
impersonate="chrome110"
) as session:
json_data = {
'model' : cls.get_model(model),
2024-01-01 22:23:45 +00:00
'messages': messages,
'temperature': kwargs.get("temperature", 0.7),
2024-02-24 18:36:42 +00:00
'max_tokens': kwargs.get("max_tokens", 512),
'stop': kwargs.get("stop", []),
2024-01-01 22:23:45 +00:00
'stream' : True
}
async with session.post('https://api.deepinfra.com/v1/openai/chat/completions',
json=json_data) as response:
response.raise_for_status()
first = True
async for line in response.iter_lines():
2024-01-21 04:07:34 +00:00
if not line.startswith(b"data: "):
continue
2024-01-01 22:23:45 +00:00
try:
2024-01-21 08:43:46 +00:00
json_line = json.loads(line[6:])
2024-01-21 04:07:34 +00:00
choices = json_line.get("choices", [{}])
2024-01-21 08:43:46 +00:00
finish_reason = choices[0].get("finish_reason")
2024-01-21 04:07:34 +00:00
if finish_reason:
2024-01-01 22:23:45 +00:00
break
2024-01-21 08:43:46 +00:00
token = choices[0].get("delta", {}).get("content")
2024-01-21 04:07:34 +00:00
if token:
2024-01-01 22:23:45 +00:00
if first:
2024-01-21 04:07:34 +00:00
token = token.lstrip()
if token:
2024-01-21 04:07:34 +00:00
first = False
yield token
2024-01-01 22:23:45 +00:00
except Exception:
2024-01-21 04:07:34 +00:00
raise RuntimeError(f"Response: {line}")