после решения проблемы с падежами и добавления памяти
This commit is contained in:
52
ai.py
52
ai.py
@@ -2,6 +2,7 @@
|
||||
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
|
||||
|
||||
@@ -12,53 +13,56 @@ SYSTEM_PROMPT = """Ты — Александр, умный голосовой а
|
||||
Твоя главная цель — помогать пользователю и поддерживать интересный диалог.
|
||||
Отвечай кратко и по существу, на русском языке.
|
||||
Избегай длинных списков, сложного форматирования и спецсимволов, так как твои ответы озвучиваются голосом.
|
||||
Пиши в разговорном стиле, как при живом общении."""
|
||||
Пиши в разговорном стиле, как при живом общении, но не забывай о вежливости и правильности твоих ответов."""
|
||||
|
||||
|
||||
def ask_ai(user_message: str) -> str:
|
||||
def ask_ai(messages_history: list) -> str:
|
||||
"""
|
||||
Send a message to Perplexity AI and get a response.
|
||||
|
||||
Send a message history to Perplexity AI and get a response.
|
||||
|
||||
Args:
|
||||
user_message: User's question or command
|
||||
|
||||
messages_history: List of dictionaries with role and content
|
||||
e.g., [{"role": "user", "content": "Hi"}]
|
||||
|
||||
Returns:
|
||||
AI response text
|
||||
"""
|
||||
if not user_message.strip():
|
||||
if not messages_history:
|
||||
return "Извините, я не расслышал вашу команду."
|
||||
|
||||
print(f"🤖 Запрос к AI: {user_message}")
|
||||
|
||||
|
||||
# Extract the last user message for logging
|
||||
last_user_message = next(
|
||||
(m["content"] for m in reversed(messages_history) if m["role"] == "user"),
|
||||
"Unknown",
|
||||
)
|
||||
print(f"🤖 Запрос к AI: {last_user_message}")
|
||||
|
||||
headers = {
|
||||
"Authorization": f"Bearer {PERPLEXITY_API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
|
||||
# Prepend system prompt to the history
|
||||
messages = [{"role": "system", "content": SYSTEM_PROMPT}] + list(messages_history)
|
||||
|
||||
payload = {
|
||||
"model": PERPLEXITY_MODEL,
|
||||
"messages": [
|
||||
{"role": "system", "content": SYSTEM_PROMPT},
|
||||
{"role": "user", "content": user_message}
|
||||
],
|
||||
"messages": messages,
|
||||
"max_tokens": 500,
|
||||
"temperature": 0.7
|
||||
"temperature": 1.0,
|
||||
}
|
||||
|
||||
|
||||
try:
|
||||
response = requests.post(
|
||||
PERPLEXITY_API_URL,
|
||||
headers=headers,
|
||||
json=payload,
|
||||
timeout=30
|
||||
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:
|
||||
|
||||
Reference in New Issue
Block a user