Добавил гигачада

This commit is contained in:
maksim 2024-06-11 23:38:00 +04:00
parent 578f6811f4
commit 27148b8638
4 changed files with 77 additions and 1 deletions

63
gigachat.py Normal file
View File

@ -0,0 +1,63 @@
import requests
import json
import base64
import uuid
from password import config
client_id = config.client_id
secret = config.secret
auth = config.auth
credentials = f"{client_id}:{secret}"
encoded_credentials = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
if encoded_credentials != auth:
raise Exception("Credentials do not match")
def get_token(auth_token, scope='GIGACHAT_API_PERS'):
rq_uid = str(uuid.uuid4())
url = "https://ngw.devices.sberbank.ru:9443/api/v2/oauth"
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'application/json',
'RqUID': rq_uid,
'Authorization': f'Basic {auth_token}'
}
payload = {'scope': scope}
try:
response = requests.post(url, headers=headers, data=payload, verify=False)
response.raise_for_status()
return response.json()['access_token']
except requests.RequestException as e:
print(f"Ошибка: {str(e)}")
return None
giga_token = get_token(auth)
def get_chat_completion(auth_token, user_message):
url = "https://gigachat.devices.sberbank.ru/api/v1/chat/completions"
payload = json.dumps({
"model": "GigaChat",
"messages": [
{"role": "user", "content": user_message}
],
"temperature": 1,
"top_p": 0.1,
"n": 1,
"stream": False,
"max_tokens": 512,
"repetition_penalty": 1,
"update_interval": 0
})
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': f'Bearer {auth_token}'
}
try:
response = requests.post(url, headers=headers, data=payload, verify=False)
response.raise_for_status()
return response.json()['choices'][0]['message']['content']
except requests.RequestException as e:
print(f"Произошла ошибка: {str(e)}")
return "Ошибка в запросе к нейронной сети"

View File

@ -2,7 +2,8 @@ from fastapi import FastAPI
import logging
from contextlib import asynccontextmanager
from gigachat import get_token
from password.config import auth
from router_questions import router as questions_router
from router_class import router as class_router
from router_flight import router as flight_router
@ -16,6 +17,10 @@ logger = logging.getLogger(__name__)
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("База данных готова к работе")
global giga_token
giga_token = get_token(auth)
yield
logger.info("Выключение")

Binary file not shown.

View File

@ -3,6 +3,7 @@ from fastapi import APIRouter, Depends
from typing import List
from enums import TypeMood, TypeModel
from gigachat import get_chat_completion, giga_token
from repository import QuestionRepository
from schemas import SQuestionAdd, SQuestion, SQuestionId
@ -31,3 +32,10 @@ async def get_questions_by_email(email_user: str) -> list[SQuestion]:
questions = await QuestionRepository.find_by_email(email_user)
return questions
@router.post("/chat")
async def add_question(question: str):
# Получение ответа от нейронной сети
neural_response = get_chat_completion(giga_token, question)
return {"answer": neural_response}