This commit is contained in:
+23
-13
@@ -21,9 +21,10 @@ DB_CONFIG = {
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
OPENROUTER_CONFIG = {
|
||||
'api_key': os.getenv('OR_KEY'),
|
||||
'model': os.getenv('OR_MODEL_NAME')
|
||||
ROUTERAI_CONFIG = {
|
||||
'api_key': os.getenv('RA_KEY'),
|
||||
'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
|
||||
|
||||
def _generate_shortname_by_api(text):
|
||||
"""Внутренняя функция для генерации краткого названия через OpenRouter API"""
|
||||
url = "https://openrouter.ai/api/v1/chat/completions"
|
||||
"""Внутренняя функция для генерации краткого названия через RouterAI API"""
|
||||
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 = {
|
||||
"Authorization": f"Bearer {OPENROUTER_CONFIG['api_key']}",
|
||||
"Content-Type": "application/json"
|
||||
"Authorization": f"Bearer {ROUTERAI_CONFIG['api_key']}",
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
|
||||
prompt = f"""
|
||||
@@ -78,10 +84,10 @@ def _generate_shortname_by_api(text):
|
||||
Название:"""
|
||||
|
||||
data = {
|
||||
"model": OPENROUTER_CONFIG['model'],
|
||||
"model": ROUTERAI_CONFIG['model'],
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"max_tokens": 5000,
|
||||
"temperature": 0.3
|
||||
"temperature": 0.3,
|
||||
}
|
||||
|
||||
try:
|
||||
@@ -98,7 +104,7 @@ def _generate_shortname_by_api(text):
|
||||
# Пытаемся распарсить JSON ответ
|
||||
try:
|
||||
error_info["body"] = response.json()
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
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()
|
||||
|
||||
# Извлекаем только текст ответа
|
||||
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)
|
||||
@@ -118,7 +128,7 @@ def _generate_shortname_by_api(text):
|
||||
return shortname[:80]
|
||||
|
||||
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 = {
|
||||
"status_code": e.response.status_code,
|
||||
"headers": dict(e.response.headers),
|
||||
@@ -128,7 +138,7 @@ def _generate_shortname_by_api(text):
|
||||
# Пытаемся распарсить JSON ответ
|
||||
try:
|
||||
error_info["body"] = e.response.json()
|
||||
except:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
log_message(f"Ошибка 429: Превышен лимит запросов. Ответ API: {json.dumps(error_info, ensure_ascii=False)}")
|
||||
|
||||
Reference in New Issue
Block a user