Download scripts/openrouter_free_models.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 7.03 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/scripts/openrouter_free_models.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/scripts/openrouter_free_models.py
-
curl -L -o openrouter_free_models.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/scripts/openrouter_free_models.py
7.03 kB
| import asyncio | |
| import httpx | |
| import json | |
| import os | |
| from pathlib import Path | |
| from dotenv import load_dotenv | |
| load_dotenv() | |
| CONFIG_PATH = Path("D:/Gemini/AI-colab/config/models_config.json") | |
| OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY") | |
| OPENROUTER_API_URL_MODELS = "https://openrouter.ai/api/v1/models" | |
| OPENROUTER_API_URL_CHAT = "https://openrouter.ai/api/v1/chat/completions" | |
| async def fetch_openrouter_models(): | |
| if not OPENROUTER_API_KEY: | |
| print("OPENROUTER_API_KEY not set. Cannot fetch models.") | |
| return [] | |
| headers = { | |
| "Authorization": f"Bearer {OPENROUTER_API_KEY}", | |
| "Content-Type": "application/json", | |
| "HTTP-Referer": "http://localhost:5000", | |
| "X-Title": "AI Colab Laboratory", | |
| } | |
| print(f"Fetching models from {OPENROUTER_API_URL_MODELS}...") | |
| async with httpx.AsyncClient() as client: | |
| try: | |
| response = await client.get(OPENROUTER_API_URL_MODELS, headers=headers, timeout=30.0) | |
| response.raise_for_status() | |
| models_data = response.json().get('data', []) | |
| print(f"Fetched {len(models_data)} models.") | |
| return models_data | |
| except httpx.RequestError as e: | |
| print(f"Error fetching models from OpenRouter: {e}") | |
| return [] | |
| except httpx.HTTPStatusError as e: | |
| print(f"OpenRouter API returned an error {e.response.status_code}: {e.response.text}") | |
| return [] | |
| def update_models_config(new_models_data: list): | |
| if not CONFIG_PATH.exists(): | |
| print(f"Config file not found: {CONFIG_PATH}. Creating a new one with defaults.") | |
| config = { | |
| "model_providers": { | |
| "openrouter": { | |
| "api_key_env": "OPENROUTER_API_KEY", | |
| "api_url": OPENROUTER_API_URL_CHAT | |
| }, | |
| "gptoss": { | |
| "model_path_template": "D:/Gemini/AI-colab/integrations/models/{model_id}", | |
| "n_ctx": 4096, | |
| "n_gpu_layers": 0, | |
| "verbose": False | |
| } | |
| }, | |
| "active_models": { | |
| "chief": { | |
| "name": "Шеф (SmolLM2)", | |
| "provider": "gptoss", | |
| "model_id": "SmolLM2-360M-Instruct-GGUF/smollm2-360m-instruct-q8_0.gguf", | |
| "fallback": None, | |
| "is_local": True, | |
| "prompt_format": "chatml" | |
| }, | |
| "ceo": { | |
| "name": "СЕО (Qwen)", | |
| "provider": "gptoss", | |
| "model_id": "Qwen2.5-1.5B-VibeThinker-heretic-uncensored-abliterated-GGUF/Qwen2.5-1.5B-VibeThinker-heretic-uncensored-abliterated.Q4_K_M.gguf", | |
| "fallback": { | |
| "provider": "openrouter", | |
| "model_id": "meta-llama/llama-3.3-70b-instruct" | |
| }, | |
| "is_local": True, | |
| "prompt_format": "chatml" | |
| }, | |
| "Флик": {"name": "Флик", "provider": "openrouter", "model_id": "x-ai/grok-2-1212", "is_local": False}, | |
| "Флок": {"name": "Флок", "provider": "openrouter", "model_id": "openai/gpt-4o", "is_local": False}, | |
| "Клик": {"name": "Клик", "provider": "openrouter", "model_id": "deepseek/deepseek-chat", "is_local": False}, | |
| "Клак": {"name": "Клак", "provider": "openrouter", "model_id": "meta-llama/llama-3.3-70b-instruct", "is_local": False}, | |
| "Чек": {"name": "Чек", "provider": "openrouter", "model_id": "mistralai/mistral-large", "is_local": False}, | |
| "Чок": {"name": "Чок", "provider": "openrouter", "model_id": "anthropic/claude-3-5-sonnet", "is_local": False}, | |
| "Линк": {"name": "Линк", "provider": "openrouter", "model_id": "nousresearch/hermes-3-llama-3.1-405b", "is_local": False}, | |
| "Синх": {"name": "Синх", "provider": "openrouter", "model_id": "google/gemini-2.0-flash-001", "is_local": False} | |
| }, | |
| "available_openrouter_models": {} # Новый раздел для всех доступных моделей | |
| } | |
| else: | |
| with open(CONFIG_PATH, "r", encoding="utf-8") as f: | |
| config = json.load(f) | |
| # Убедимся, что секции существуют | |
| if "model_providers" not in config: | |
| config["model_providers"] = {} | |
| if "active_models" not in config: | |
| config["active_models"] = {} | |
| if "available_openrouter_models" not in config: | |
| config["available_openrouter_models"] = {} | |
| # Добавляем или обновляем провайдера OpenRouter | |
| config["model_providers"]["openrouter"] = { | |
| "api_key_env": "OPENROUTER_API_KEY", | |
| "api_url": OPENROUTER_API_URL_CHAT | |
| } | |
| # Сохраняем активные (локальные и дружелюбные) модели, чтобы не перезаписать | |
| current_active_models = {k: v for k, v in config["active_models"].items() if v.get("is_local", False) or k in ["chief", "ceo", "Флик", "Флок", "Клик", "Клак", "Чек", "Чок", "Линк", "Синх"]} | |
| # Обновляем раздел available_openrouter_models всеми бесплатными моделями | |
| newly_available_openrouter_models = {} | |
| for model_info in new_models_data: | |
| if model_info.get('free_tier') is True: # Отбираем только бесплатные | |
| model_id = model_info['id'] | |
| newly_available_openrouter_models[model_id] = { | |
| "name": model_info.get('name', model_id), | |
| "provider": "openrouter", | |
| "model_id": model_id, | |
| "is_local": False, | |
| "description": model_info.get('description', '') | |
| } | |
| config["available_openrouter_models"] = newly_available_openrouter_models | |
| # Объединяем активные модели с доступными (при этом активные имеют приоритет) | |
| config["active_models"] = {**newly_available_openrouter_models, **current_active_models} | |
| with open(CONFIG_PATH, "w", encoding="utf-8") as f: | |
| json.dump(config, f, indent=2, ensure_ascii=False) | |
| print(f"Configuration updated at {CONFIG_PATH}") | |
| async def main(): | |
| print("🤖 Запуск парсера и обновлятора моделей OpenRouter") | |
| print("=" * 50) | |
| models_data = await fetch_openrouter_models() | |
| if models_data: | |
| update_models_config(models_data) | |
| print("\n" + "=" * 50) | |
| print("🎉 ГОТОВО! Конфигурация models_config.json обновлена.") | |
| else: | |
| print("\n❌ Не удалось получить список моделей OpenRouter. Конфигурация не обновлена.") | |
| if __name__ == "__main__": | |
| asyncio.run(main()) | |