diff --git a/gigachat.py b/gigachat.py new file mode 100644 index 0000000..9e1b2f6 --- /dev/null +++ b/gigachat.py @@ -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 "Ошибка в запросе к нейронной сети" diff --git a/main.py b/main.py index f9bff10..ef14e78 100644 --- a/main.py +++ b/main.py @@ -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("Выключение") diff --git a/requirements.txt b/requirements.txt index 74bc0cf..b15852a 100644 Binary files a/requirements.txt and b/requirements.txt differ diff --git a/router_questions.py b/router_questions.py index a055694..d63e06d 100644 --- a/router_questions.py +++ b/router_questions.py @@ -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}