AI-Colab / core /api_client.py
A.Tuin
initial commit
0b2210a
Raw History Blame Contribute Delete
3.7 kB
import httpx
import asyncio
from .config import OPENROUTER_API_KEY, OPENROUTER_API_URL
import json
class OpenRouterClient:
def __init__(self):
self.api_key = OPENROUTER_API_KEY
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
"HTTP-Referer": "http://localhost:5000",
"X-Title": "AI Colab Laboratory"
}
# Маппинг дружелюбных имен теперь берем из конфига, а не хардкодим
self.model_mapping = {}
# Загрузка конфига для актуальных данных
try:
with open("D:/Gemini/AIColab/config/models_config.json", "r", encoding="utf-8") as f:
self.full_config = json.load(f)
# Наполняем маппинг из active_models
for key, val in self.full_config.get("active_models", {}).items():
if "model_id" in val:
# Добавляем по ключу (напр. 'flick')
self.model_mapping[key] = val["model_id"]
# Добавляем по имени (напр. 'Флик'), если оно есть
if "name" in val:
self.model_mapping[val["name"]] = val["model_id"]
except Exception as e:
print(f"Error loading models_config.json: {e}")
self.full_config = {}
async def query_model(self, model_key: str, user_message: str):
"""Отправляет запрос к модели по её ключу или ID асинхронно."""
model_id = None
# 1. Проверяем в маппинге (наполнен из active_models)
model_id = self.model_mapping.get(model_key)
# 2. Если не нашли, ищем в списке всех доступных OpenRouter моделей
if not model_id and self.full_config.get("available_openrouter_models"):
if model_key in self.full_config["available_openrouter_models"]:
model_id = model_key # Сам ключ является ID в этом списке
# 3. Fallback: если ничего не помогло, считаем, что model_key уже является model_id
if not model_id:
model_id = model_key
payload = {
"model": model_id,
"messages": [{"role": "user", "content": user_message}]
}
async with httpx.AsyncClient() as client:
try:
response = await client.post(OPENROUTER_API_URL, json=payload, headers=self.headers, timeout=120.0)
response.raise_for_status()
data = response.json()
if "choices" in data and data["choices"]:
return {"content": data["choices"][0]["message"]["content"]}
return data
except httpx.RequestError as e:
return {"error": f"Ошибка соединения: {str(e)}"}
except httpx.HTTPStatusError as e:
return {"error": f"API вернуло ошибку {e.response.status_code}: {e.response.text}"}
async def query_models_parallel(self, model_keys: list[str], user_message: str):
"""Запрашивает несколько моделей параллельно."""
tasks = [self.query_model(key, user_message) for key in model_keys]
responses = await asyncio.gather(*tasks)
return {key: resp for key, resp in zip(model_keys, responses)}