llm-chatbot/app/openrouter_client.py
2025-09-14 17:15:48 +00:00

33 lines
1.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.

import os
from openai import OpenAI
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
SITE_URL = os.getenv("WEBAPP_URL", "https://llm.byte-mate.xyz")
SITE_NAME = "Telegram LLM Chat"
# инициализируем клиента
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=OPENROUTER_API_KEY,
)
async def generate_response(messages):
"""
messages: список сообщений [{'role': 'user'|'assistant'|'system', 'content': str}]
"""
try:
completion = client.chat.completions.create(
# дополнительные заголовки для OpenRouter (не обязательно, но полезно)
extra_headers={
"HTTP-Referer": SITE_URL,
"X-Title": SITE_NAME,
},
model="qwen/qwen3-235b-a22b:free", # ✅ используй модель, которая точно доступна твоему APIключу
messages=messages,
)
return completion.choices[0].message.content
except Exception as e:
# Логи и возврат ошибки
print(f"❌ Ошибка вызова OpenRouter API: {e}")
return "Извините, LLM сейчас недоступен. Попробуйте позже."