File size: 3,701 Bytes
0b2210a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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)}