Files
site_aegisone/max_bot/app/integrations/yandex_gpt.py
T

81 lines
3.2 KiB
Python

import aiohttp
import logging
from app.settings_cache import SettingsCache
logger = logging.getLogger(__name__)
async def categorize_with_gpt(text: str) -> str:
gpt_key = SettingsCache.get("yandex_gpt_key")
folder_id = SettingsCache.get("yandex_folder_id")
if not gpt_key or not folder_id:
return ""
prompt = (
"Определи категорию обращения клиента из списка: "
"Видеонаблюдение, СКУД, Пожарная сигнализация, IT-инфраструктура, "
"Обслуживание, Консультация, Другое. "
"Ответь только названием категории, без пояснений. "
f"Текст обращения: {text}"
)
url = "https://llm.api.cloud.yandex.net/foundationModels/v1/completion"
headers = {
"Authorization": f"Api-Key {gpt_key}",
"Content-Type": "application/json",
"x-folder-id": folder_id,
}
body = {
"modelUri": f"gpt://{folder_id}/yandexgpt-lite/latest",
"completionOptions": {"stream": False, "temperature": 0.1, "maxTokens": 50},
"messages": [{"role": "user", "text": prompt}],
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=body) as resp:
if resp.status == 200:
data = await resp.json()
return data.get("result", {}).get("alternatives", [{}])[0].get("message", {}).get("text", "").strip()
logger.warning(f"GPT categorize returned {resp.status}")
except Exception as e:
logger.error(f"GPT categorize error: {e}")
return ""
async def analyze_emotion_with_gpt(text: str) -> str:
gpt_key = SettingsCache.get("yandex_gpt_key")
folder_id = SettingsCache.get("yandex_folder_id")
if not gpt_key or not folder_id:
return "neutral"
prompt = (
"Определи эмоциональную окраску текста клиента. "
"Варианты: positive, neutral, negative. "
"Ответь только одним словом. "
f"Текст: {text}"
)
url = "https://llm.api.cloud.yandex.net/foundationModels/v1/completion"
headers = {
"Authorization": f"Api-Key {gpt_key}",
"Content-Type": "application/json",
"x-folder-id": folder_id,
}
body = {
"modelUri": f"gpt://{folder_id}/yandexgpt-lite/latest",
"completionOptions": {"stream": False, "temperature": 0.1, "maxTokens": 10},
"messages": [{"role": "user", "text": prompt}],
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=body) as resp:
if resp.status == 200:
data = await resp.json()
return data.get("result", {}).get("alternatives", [{}])[0].get("message", {}).get("text", "").strip().lower()
logger.warning(f"GPT emotion analysis returned {resp.status}")
except Exception as e:
logger.error(f"GPT emotion analysis error: {e}")
return "neutral"