Files
smart-speaker/ai.py
2026-01-02 20:26:44 +03:00

68 lines
2.3 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.
"""
AI module for Perplexity API integration.
Sends user queries and receives AI responses.
"""
import requests
from config import PERPLEXITY_API_KEY, PERPLEXITY_MODEL, PERPLEXITY_API_URL
# System prompt for the AI
SYSTEM_PROMPT = """Ты — голосовой ассистент умной колонки.
Отвечай кратко, по существу, на русском языке.
Избегай длинных списков и сложного форматирования.
Твои ответы будут озвучены голосом, поэтому пиши естественным разговорным языком."""
def ask_ai(user_message: str) -> str:
"""
Send a message to Perplexity AI and get a response.
Args:
user_message: User's question or command
Returns:
AI response text
"""
if not user_message.strip():
return "Извините, я не расслышал вашу команду."
print(f"🤖 Запрос к AI: {user_message}")
headers = {
"Authorization": f"Bearer {PERPLEXITY_API_KEY}",
"Content-Type": "application/json"
}
payload = {
"model": PERPLEXITY_MODEL,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message}
],
"max_tokens": 500,
"temperature": 0.7
}
try:
response = requests.post(
PERPLEXITY_API_URL,
headers=headers,
json=payload,
timeout=30
)
response.raise_for_status()
data = response.json()
ai_response = data["choices"][0]["message"]["content"]
print(f"💬 Ответ AI: {ai_response[:100]}...")
return ai_response
except requests.exceptions.Timeout:
return "Извините, сервер не отвечает. Попробуйте позже."
except requests.exceptions.RequestException as e:
print(f"❌ Ошибка API: {e}")
return "Произошла ошибка при обращении к AI. Попробуйте ещё раз."
except (KeyError, IndexError) as e:
print(f"❌ Ошибка парсинга ответа: {e}")
return "Не удалось обработать ответ от AI."