|
2 | 2 | import json |
3 | 3 | import os |
4 | 4 | from pathlib import Path |
| 5 | +from urllib.request import urlopen |
5 | 6 |
|
6 | 7 | from fastapi import APIRouter |
7 | 8 | from pydantic.v1 import BaseModel |
@@ -51,31 +52,88 @@ class Model(BaseModel): |
51 | 52 | MODELS: list[Model] = [] |
52 | 53 |
|
53 | 54 |
|
| 55 | +def fetch_openrouter_models(source_filter: str | None = None) -> list[dict]: |
| 56 | + """Fetches model information from OpenRouter API.""" |
| 57 | + base_url = os.getenv("BASE_URL", "https://openrouter.ai/api/v1") |
| 58 | + |
| 59 | + try: |
| 60 | + with urlopen(f"{base_url}/models") as response: |
| 61 | + data = json.loads(response.read().decode("utf-8")) |
| 62 | + |
| 63 | + models_data: list[dict] = [] |
| 64 | + for model in data.get("data", []): |
| 65 | + model_id = model.get("id", "") |
| 66 | + |
| 67 | + if source_filter: |
| 68 | + source_prefix = f"{source_filter}/" |
| 69 | + if not model_id.startswith(source_prefix): |
| 70 | + continue |
| 71 | + |
| 72 | + model = dict(model) |
| 73 | + model["id"] = model_id[len(source_prefix) :] |
| 74 | + model_id = model["id"] |
| 75 | + |
| 76 | + if ( |
| 77 | + "(free)" in model.get("name", "") |
| 78 | + or model_id == "openrouter/auto" |
| 79 | + or model_id == "google/gemini-2.5-pro-exp-03-25" |
| 80 | + ): |
| 81 | + continue |
| 82 | + |
| 83 | + models_data.append(model) |
| 84 | + |
| 85 | + return models_data |
| 86 | + except Exception as e: |
| 87 | + print(f"Error fetching models from OpenRouter API: {e}") |
| 88 | + return [] |
| 89 | + |
| 90 | + |
54 | 91 | def load_models() -> list[Model]: |
55 | | - """Load model definitions from a JSON file. |
| 92 | + """Load model definitions from a JSON file or auto-generate from OpenRouter API. |
56 | 93 |
|
57 | 94 | The file path can be specified via the ``MODELS_PATH`` environment variable. |
58 | | - If ``models.json`` is not found, the bundled ``models.example.json`` is used |
59 | | - as a fallback. If neither file exists or an error occurs while loading, an |
60 | | - empty list is returned. |
| 95 | + If a user-provided models.json exists, it will be used. Otherwise, models are |
| 96 | + automatically fetched from OpenRouter API in memory. If the example file exists |
| 97 | + and no user file is provided, it will be used as a fallback. |
61 | 98 | """ |
62 | 99 |
|
63 | 100 | models_path = Path(os.environ.get("MODELS_PATH", "models.json")) |
64 | | - if not models_path.exists(): |
65 | | - example = Path(__file__).resolve().parent.parent / "models.example.json" |
66 | | - if example.exists(): |
67 | | - models_path = example |
68 | | - else: |
69 | | - return [] |
70 | 101 |
|
71 | | - try: |
72 | | - with models_path.open("r") as f: |
73 | | - data = json.load(f) |
74 | | - except Exception as e: # pragma: no cover - log and continue |
75 | | - print(f"Error loading models from {models_path}: {e}") |
| 102 | + # Check if user has actively provided a models.json file |
| 103 | + if models_path.exists(): |
| 104 | + print(f"Loading models from user-provided file: {models_path}") |
| 105 | + try: |
| 106 | + with models_path.open("r") as f: |
| 107 | + data = json.load(f) |
| 108 | + return [Model(**model) for model in data.get("models", [])] |
| 109 | + except Exception as e: |
| 110 | + print(f"Error loading models from {models_path}: {e}") |
| 111 | + # Fall through to auto-generation |
| 112 | + |
| 113 | + # Check for example file as fallback |
| 114 | + example = Path(__file__).resolve().parent.parent.parent / "models.example.json" |
| 115 | + if example.exists(): |
| 116 | + print(f"Loading models from example file: {example}") |
| 117 | + try: |
| 118 | + with example.open("r") as f: |
| 119 | + data = json.load(f) |
| 120 | + return [Model(**model) for model in data.get("models", [])] |
| 121 | + except Exception as e: |
| 122 | + print(f"Error loading models from {example}: {e}") |
| 123 | + # Fall through to auto-generation |
| 124 | + |
| 125 | + # Auto-generate models from OpenRouter API |
| 126 | + print("Auto-generating models from OpenRouter API") |
| 127 | + source_filter = os.getenv("SOURCE") |
| 128 | + source_filter = source_filter if source_filter and source_filter.strip() else None |
| 129 | + |
| 130 | + models_data = fetch_openrouter_models(source_filter=source_filter) |
| 131 | + if not models_data: |
| 132 | + print("Failed to fetch models from OpenRouter API") |
76 | 133 | return [] |
77 | 134 |
|
78 | | - return [Model(**model) for model in data.get("models", [])] |
| 135 | + print(f"Successfully fetched {len(models_data)} models from OpenRouter API") |
| 136 | + return [Model(**model) for model in models_data] |
79 | 137 |
|
80 | 138 |
|
81 | 139 | MODELS = load_models() |
|
0 commit comments