[ZILANT] Переход на RouterAI
ci/woodpecker/push/woodpecker Pipeline was successful

This commit is contained in:
2026-08-02 16:42:51 +03:00
parent 7c59c0d5e2
commit 9b8b5514b8
2 changed files with 29 additions and 20 deletions
+6 -7
View File
@@ -148,11 +148,10 @@ PUBLISH_SILENTLY = true
USE_SUBSCRIPTION_BOT = true USE_SUBSCRIPTION_BOT = true
LOG_DEBUG_DATA = false LOG_DEBUG_DATA = false
# RouterAI (генерация shortname)
RA_KEY = "sk-7pJxRlbYWUGMNX9y2mHzi2soKDIsZPzp"
RA_MODEL = "moonshotai/kimi-k2-thinking"
# OpenRouter # OpenRouter (не используется, оставлен для справки)
OR_KEY = "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" # OR_KEY = "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"
# OR_MODEL_NAME = "qwen/qwen3-vl-235b-a22b-instruct" # OR_MODEL_NAME = "anthropic/claude-sonnet-5"
OR_MODEL_NAME = "anthropic/claude-sonnet-5"
# OR_MODEL_NAME = "deepseek/deepseek-chat-v3.1"
# OR_MODEL_NAME = "deepseek/deepseek-r1-0528:free"
# OR_MODEL_NAME = "qwen/qwen3-coder:free"
+23 -13
View File
@@ -21,9 +21,10 @@ DB_CONFIG = {
'charset': 'utf8mb4' 'charset': 'utf8mb4'
} }
OPENROUTER_CONFIG = { ROUTERAI_CONFIG = {
'api_key': os.getenv('OR_KEY'), 'api_key': os.getenv('RA_KEY'),
'model': os.getenv('OR_MODEL_NAME') 'model': os.getenv('RA_MODEL'),
'base_url': 'https://routerai.ru/api/v1',
} }
# Настройки журналирования # Настройки журналирования
@@ -59,11 +60,16 @@ def log_message(message, max_retries=5, retry_delay=0.1):
return False return False
def _generate_shortname_by_api(text): def _generate_shortname_by_api(text):
"""Внутренняя функция для генерации краткого названия через OpenRouter API""" """Внутренняя функция для генерации краткого названия через RouterAI API"""
url = "https://openrouter.ai/api/v1/chat/completions" if not ROUTERAI_CONFIG['api_key'] or not ROUTERAI_CONFIG['model']:
log_message("RA_KEY или RA_MODEL не заданы в .env")
print("Ошибка: RA_KEY или RA_MODEL не заданы в .env")
return None
url = f"{ROUTERAI_CONFIG['base_url']}/chat/completions"
headers = { headers = {
"Authorization": f"Bearer {OPENROUTER_CONFIG['api_key']}", "Authorization": f"Bearer {ROUTERAI_CONFIG['api_key']}",
"Content-Type": "application/json" "Content-Type": "application/json",
} }
prompt = f""" prompt = f"""
@@ -78,10 +84,10 @@ def _generate_shortname_by_api(text):
Название:""" Название:"""
data = { data = {
"model": OPENROUTER_CONFIG['model'], "model": ROUTERAI_CONFIG['model'],
"messages": [{"role": "user", "content": prompt}], "messages": [{"role": "user", "content": prompt}],
"max_tokens": 5000, "max_tokens": 5000,
"temperature": 0.3 "temperature": 0.3,
} }
try: try:
@@ -98,7 +104,7 @@ def _generate_shortname_by_api(text):
# Пытаемся распарсить JSON ответ # Пытаемся распарсить JSON ответ
try: try:
error_info["body"] = response.json() error_info["body"] = response.json()
except: except Exception:
pass pass
log_message(f"Ошибка 429: Превышен лимит запросов. Ответ API: {json.dumps(error_info, ensure_ascii=False)}") log_message(f"Ошибка 429: Превышен лимит запросов. Ответ API: {json.dumps(error_info, ensure_ascii=False)}")
@@ -109,7 +115,11 @@ def _generate_shortname_by_api(text):
result = response.json() result = response.json()
# Извлекаем только текст ответа # Извлекаем только текст ответа
shortname = result['choices'][0]['message']['content'].strip() message = result['choices'][0]['message']
shortname = (message.get('content') or '').strip()
if not shortname:
log_message(f"Пустой content в ответе RouterAI: {json.dumps(result, ensure_ascii=False)[:1000]}")
return None
# Удаляем возможные кавычки и лишние символы # Удаляем возможные кавычки и лишние символы
shortname = re.sub(r'^["\']|["\']$', '', shortname) shortname = re.sub(r'^["\']|["\']$', '', shortname)
@@ -118,7 +128,7 @@ def _generate_shortname_by_api(text):
return shortname[:80] return shortname[:80]
except requests.exceptions.HTTPError as e: except requests.exceptions.HTTPError as e:
if e.response.status_code == 429: if e.response is not None and e.response.status_code == 429:
error_info = { error_info = {
"status_code": e.response.status_code, "status_code": e.response.status_code,
"headers": dict(e.response.headers), "headers": dict(e.response.headers),
@@ -128,7 +138,7 @@ def _generate_shortname_by_api(text):
# Пытаемся распарсить JSON ответ # Пытаемся распарсить JSON ответ
try: try:
error_info["body"] = e.response.json() error_info["body"] = e.response.json()
except: except Exception:
pass pass
log_message(f"Ошибка 429: Превышен лимит запросов. Ответ API: {json.dumps(error_info, ensure_ascii=False)}") log_message(f"Ошибка 429: Превышен лимит запросов. Ответ API: {json.dumps(error_info, ensure_ascii=False)}")