Spaces:
Sleeping
Sleeping
import requests | |
import json | |
import os | |
from datetime import datetime, timedelta | |
def gen_auth_token(): | |
url = "https://ngw.devices.sberbank.ru:9443/api/v2/oauth" | |
payload='scope=GIGACHAT_API_CORP' | |
headers = { | |
'Content-Type': 'application/x-www-form-urlencoded', | |
'Accept': 'application/json', | |
'RqUID': '1b519047-0ee9-4b63-8599-e5ffc9c77e72', | |
'Authorization': os.getenv('GIGACHAT_API_TOKEN') | |
} | |
response = requests.request("POST", url, headers=headers, data=payload, verify=False) | |
with open('auth_token.json', 'w') as f: | |
json.dump(json.loads(response.text), f, ensure_ascii=False) | |
def get_text(content='Привет!', auth_token=None): | |
url = "https://gigachat.devices.sberbank.ru/api/v1/chat/completions" | |
payload = json.dumps({ | |
"model": "GigaChat", | |
"messages": [ | |
{ | |
"role": "user", | |
"content": content | |
} | |
], | |
"temperature": 1, | |
"top_p": 0.1, | |
"n": 1, | |
"stream": False, | |
"max_tokens": 512, | |
"repetition_penalty": 1 | |
}) | |
headers = { | |
'Content-Type': 'application/json', | |
'Accept': 'application/json', | |
'Authorization': f'Bearer {auth_token}' | |
} | |
response = requests.request("POST", url, headers=headers, data=payload, verify=False) | |
return json.loads(response.text) | |
def generate(content='Привет!', auth_file=None): | |
if auth_file is None or not os.path.isfile(auth_file): | |
gen_auth_token() | |
with open(auth_file) as f: | |
auth_token = json.load(f) | |
if datetime.fromtimestamp(auth_token['expires_at']/1000) <= datetime.now() - timedelta(seconds=60): | |
gen_auth_token() | |
with open(auth_file) as f: | |
auth_token = json.load(f) | |
resp = get_text(content, auth_token['access_token']) | |
return resp["choices"][0]["message"]["content"] |