Files
wiki/tasks/bytik/llm.py
2026-04-15 01:00:01 +03:00

55 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import aiohttp
import logging
from config import OPENROUTER_API_KEY, OPENROUTER_MODEL
logger = logging.getLogger(__name__)
FORBIDDEN_WORDS = [
"мат", "блять", "сука", "хуй", "пизда", "ебать",
"fuck", "shit", "bitch", "asshole",
]
def is_safe_text(text: str) -> bool:
text_lower = text.lower()
for word in FORBIDDEN_WORDS:
if word in text_lower:
logger.warning(f"Обнаружено запрещённое слово: {word}")
return False
return True
async def ask_llm(messages: list) -> str:
url = "https://openrouter.ai/api/v1/chat/completions"
headers = {
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/bytik-bot",
"X-Title": "Bytik Bot",
}
payload = {
"model": OPENROUTER_MODEL,
"messages": messages,
"max_tokens": 500,
"temperature": 0.7,
}
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, json=payload, headers=headers) as resp:
if resp.status != 200:
error_text = await resp.text()
logger.error(f"OpenRouter error: {resp.status} - {error_text}")
return "Ой, я что-то запутался. Попробуй спросить ещё раз! 🤔"
data = await resp.json()
answer = data["choices"][0]["message"]["content"].strip()
if not is_safe_text(answer):
logger.warning("Ответ от LLM содержит запрещённые слова. Блокируем.")
return "Извини, я не могу это обсудить. Давай поговорим о чём-то другом! 😊"
return answer
except Exception as e:
logger.error(f"Ошибка при запросе к LLM: {e}")
return "Извини, я пока не могу ответить. Попробуй позже! 🤖"