File size: 14,322 Bytes
7c06aef
a32a92f
 
 
 
da6e1bc
 
3ed02d5
da6e1bc
 
 
338dc9b
3ed02d5
da6e1bc
98c6811
9002fc2
da6e1bc
 
 
b311dd5
8941a67
 
 
 
260c1a3
98c6811
260c1a3
8941a67
 
e51c770
98c6811
e51c770
8941a67
02f927b
8941a67
9983b5f
 
f3a09a2
260c1a3
8941a67
98c6811
 
 
8941a67
260c1a3
 
 
8941a67
9983b5f
260c1a3
8941a67
 
da6e1bc
 
52abc5b
f3a09a2
 
 
 
 
 
 
 
e51c770
52abc5b
 
da6e1bc
 
 
 
 
 
 
a32a92f
 
 
 
9983b5f
 
 
c9e9db6
 
9983b5f
a73f888
 
 
 
 
 
 
b311dd5
941d5c5
f840423
b311dd5
9983b5f
 
 
 
6878a71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9983b5f
6878a71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9983b5f
 
338dc9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
da6e1bc
 
 
 
 
 
 
 
 
338dc9b
da6e1bc
 
 
f840423
7c06aef
 
 
 
 
 
 
 
 
 
 
da6e1bc
913253a
7c06aef
 
 
 
98c6811
 
 
 
7c06aef
 
 
da6e1bc
 
913253a
da6e1bc
a73f888
7c06aef
 
 
 
 
 
 
 
 
 
 
 
 
338dc9b
 
 
 
7c06aef
338dc9b
7c06aef
338dc9b
 
 
 
 
da6e1bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ed02d5
 
9002fc2
 
c29b8da
9002fc2
 
 
 
3ed02d5
 
9002fc2
d91b022
9002fc2
 
 
 
 
 
ebaf279
9002fc2
 
a32a92f
 
 
9002fc2
 
3ed02d5
 
7c06aef
 
 
 
 
 
 
 
3ed02d5
 
 
a32a92f
ebaf279
3ed02d5
 
 
9002fc2
3ed02d5
9002fc2
 
6878a71
 
 
 
 
 
 
 
9002fc2
 
b311dd5
 
f840423
52abc5b
f840423
 
 
7c06aef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b311dd5
 
 
 
 
 
 
 
a73f888
 
 
b311dd5
 
 
 
 
 
 
 
7c06aef
 
338dc9b
98c6811
338dc9b
 
b311dd5
 
 
a73f888
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import asyncio
import json
import re
from collections import defaultdict
from datetime import date
from os import getenv

import pandas as pd
from aiolimiter import AsyncLimiter
from dotenv import load_dotenv
from elevenlabs import AsyncElevenLabs
from google.cloud import translate_v2 as translate
from huggingface_hub import AsyncInferenceClient, HfApi
from joblib.memory import Memory
from openai import AsyncOpenAI, BadRequestError
from requests import HTTPError, get

# for development purposes, all languages will be evaluated on the fast models
# and only a sample of languages will be evaluated on all models
important_models = [
    "meta-llama/llama-4-maverick",  # 0.6$
    "meta-llama/llama-3.3-70b-instruct",  # 0.3$
    "meta-llama/llama-3.1-70b-instruct",  # 0.3$
    "meta-llama/llama-3-70b-instruct",  # 0.4$
    # "meta-llama/llama-2-70b-chat", # 0.9$; not properly supported by OpenRouter
    "openai/gpt-4.1",  # 8$
    "openai/gpt-4.1-mini",  # 1.6$
    "openai/gpt-4.1-nano",  # 0.4$
    "openai/gpt-4o-mini",  # 0.6$
    "openai/gpt-4o-2024-11-20", # 10$
    "openai/gpt-3.5-turbo-0613",  # 2$
    "openai/gpt-3.5-turbo",  # 1.5$
    # "anthropic/claude-3.5-haiku", # 4$ -> too expensive for dev
    "anthropic/claude-sonnet-4",
    "mistralai/mistral-small-3.1-24b-instruct",  # 0.3$
    "mistralai/mistral-saba",  # 0.6$
    "mistralai/mistral-nemo",  # 0.08$
    "google/gemini-2.5-flash",  # 0.6$
    "google/gemini-2.0-flash-lite-001",  # 0.3$
    "google/gemma-3-27b-it",  # 0.2$
    "qwen/qwen3-32b",
    "qwen/qwen3-235b-a22b",
    "qwen/qwen3-30b-a3b",  # 0.29$
    # "qwen/qwen-turbo", # 0.2$; recognizes "inappropriate content"
    # "qwen/qwq-32b",  # 0.2$
    # "qwen/qwen-2.5-72b-instruct",  # 0.39$
    # "qwen/qwen-2-72b-instruct",  # 0.9$
    "deepseek/deepseek-chat-v3-0324",  # 1.1$
    "deepseek/deepseek-chat",  # 0.89$
    "microsoft/phi-4",  # 0.07$
    "microsoft/phi-4-multimodal-instruct",  # 0.1$
    "amazon/nova-micro-v1",  # 0.09$
]

blocklist = [
    "google/gemini-2.5-pro-preview",
    "google/gemini-2.5-flash-preview",
    "google/gemini-2.5-flash-lite-preview",
    "google/gemini-2.5-flash-preview-04-17",
    "google/gemini-2.5-flash-preview-05-20",
    "google/gemini-2.5-flash-lite-preview-06-17",
    "google/gemini-2.5-pro-preview-06-05",
    "google/gemini-2.5-pro-preview-05-06",
    "perplexity/sonar-deep-research"
]

transcription_models = [
    "elevenlabs/scribe_v1",
    "openai/whisper-large-v3",
    # "openai/whisper-small",
    # "facebook/seamless-m4t-v2-large",
]

cache = Memory(location=".cache", verbose=0).cache


@cache
def get_models(date: date):
    return get("https://openrouter.ai/api/frontend/models").json()["data"]


def get_model(permaslug):
    models = get_models(date.today())
    slugs = [
        m
        for m in models
        if m["permaslug"] == permaslug
        and m["endpoint"]
        and not m["endpoint"]["is_free"]
    ]
    if len(slugs) == 0:
        # the problem is that free models typically have very high rate-limiting
        print(f"no non-free model found for {permaslug}")
    return slugs[0] if len(slugs) >= 1 else None


@cache
def get_historical_popular_models(date: date):
    try:
        raw = get("https://openrouter.ai/rankings").text
        
        # Extract model data from rankingData using regex
        import re
        import json
        
        # Find all count and model_permaslug pairs in the data
        # Format: "count":number,"model_permaslug":"model/name"
        pattern = r'\\\"count\\\":([\d.]+).*?\\\"model_permaslug\\\":\\\"([^\\\"]+)\\\"'
        matches = re.findall(pattern, raw)
        
        if matches:
            # Aggregate model counts
            model_counts = {}
            for count_str, model_slug in matches:
                count = float(count_str)
                if not model_slug.startswith('openrouter') and model_slug != 'Others':
                    # Remove variant suffixes for aggregation
                    base_model = model_slug.split(':')[0]
                    model_counts[base_model] = model_counts.get(base_model, 0) + count
            
            # Sort by popularity and return top models
            sorted_models = sorted(model_counts.items(), key=lambda x: x[1], reverse=True)
            result = []
            for model_slug, count in sorted_models[:20]:  # Top 20
                result.append({"slug": model_slug, "count": int(count)})
            
            print(f"βœ… Historical OpenRouter models: {len(result)} models fetched")
            if result:
                print(f"   Top 5: {[m['slug'] for m in result[:5]]}")
                print(f"   Sample counts: {[m['count'] for m in result[:3]]}")
            return result
        else:
            print("⚠️ Could not find model ranking data in OpenRouter response")
            return []
        
    except Exception as e:
        print(f"⚠️ Error fetching OpenRouter historical rankings: {e}")
        print("πŸ”„ Falling back to static model list")
        return []


@cache  
def get_current_popular_models(date: date):
    try:
        raw = get("https://openrouter.ai/rankings?view=day").text
        
        # Extract model data from daily rankings
        import re
        import json
        
        # Find all count and model_permaslug pairs in the daily data
        pattern = r'\\\"count\\\":([\d.]+).*?\\\"model_permaslug\\\":\\\"([^\\\"]+)\\\"'
        matches = re.findall(pattern, raw)
        
        if matches:
            # Aggregate model counts
            model_counts = {}
            for count_str, model_slug in matches:
                count = float(count_str)
                if not model_slug.startswith('openrouter') and model_slug != 'Others':
                    # Remove variant suffixes for aggregation
                    base_model = model_slug.split(':')[0]
                    model_counts[base_model] = model_counts.get(base_model, 0) + count
            
            # Sort by popularity and return top models
            sorted_models = sorted(model_counts.items(), key=lambda x: x[1], reverse=True)
            result = []
            for model_slug, count in sorted_models[:10]:  # Top 10
                result.append({"slug": model_slug, "count": int(count)})
            
            print(f"βœ… Current OpenRouter models: {len(result)} models fetched")
            if result:
                print(f"   Top 5: {[m['slug'] for m in result[:5]]}")
                print(f"   Sample counts: {[m['count'] for m in result[:3]]}")
            return result
        else:
            print("⚠️ Could not find daily ranking data in OpenRouter response")
            return []
        
    except Exception as e:
        print(f"⚠️ Error fetching OpenRouter current rankings: {e}")
        print("πŸ”„ Falling back to static model list")
        return []


def get_translation_models():
    return pd.DataFrame(
        [
            {
                "id": "google/translate-v2",
                "name": "Google Translate",
                "provider_name": "Google",
                "cost": 20.0,
                "size": None,
                "type": "closed-source",
                "license": None,
                "tasks": ["translation_from", "translation_to"],
            }
        ]
    )


load_dotenv()
client = AsyncOpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=getenv("OPENROUTER_API_KEY"),
)

openrouter_rate_limit = AsyncLimiter(max_rate=20, time_period=1)
elevenlabs_rate_limit = AsyncLimiter(max_rate=2, time_period=1)
huggingface_rate_limit = AsyncLimiter(max_rate=5, time_period=1)
google_rate_limit = AsyncLimiter(max_rate=10, time_period=1)


@cache
async def complete(**kwargs) -> str | None:
    # Add longer timeout for slower, premium, or reasoning-focused models
    model_id = kwargs.get('model', '')
    slow_model_keywords = [
        'claude-3.5', 'claude-3.7', 'claude-4', 'sonnet-4', # Claude
        'gpt-4', 'o1', 'o3', # OpenAI
        'gemini-2.5', 'gemini-pro', # Google
        'llama-4', # Meta
        'reasoning', 'thinking' # General
    ]
    timeout = 120 if any(keyword in model_id for keyword in slow_model_keywords) else 60
    
    async with openrouter_rate_limit:
        try:
            response = await asyncio.wait_for(
                client.chat.completions.create(**kwargs),
                timeout=timeout
            )
        except BadRequestError as e:
            if "filtered" in e.message:
                return None
            raise e
        except asyncio.TimeoutError:
            print(f"⏰ Timeout after {timeout}s for model {model}")
            return None
    if not response.choices:
        raise Exception(response)
    return response.choices[0].message.content.strip()


translate_client = None


def get_google_translate_client():
    global translate_client
    if translate_client is None:
        translate_client = translate.Client()
    return translate_client


def get_google_supported_languages():
    client = get_google_translate_client()
    return [l["language"] for l in client.get_languages()]


@cache
async def translate_google(text, source_language, target_language):
    client = get_google_translate_client()
    async with google_rate_limit:
        response = client.translate(
            text, source_language=source_language, target_language=target_language
        )
    return response["translatedText"]


@cache
async def transcribe_elevenlabs(path, model):
    modelname = model.split("/")[-1]
    client = AsyncElevenLabs(api_key=getenv("ELEVENLABS_API_KEY"))
    async with elevenlabs_rate_limit:
        with open(path, "rb") as file:
            response = await client.speech_to_text.convert(
                model_id=modelname, file=file
            )
    return response.text


@cache
async def transcribe_huggingface(path, model):
    client = AsyncInferenceClient(api_key=getenv("HUGGINGFACE_ACCESS_TOKEN"))
    async with huggingface_rate_limit:
        output = await client.automatic_speech_recognition(model=model, audio=path)
    return output.text


async def transcribe(path, model="elevenlabs/scribe_v1"):
    provider, modelname = model.split("/")
    match provider:
        case "elevenlabs":
            return await transcribe_elevenlabs(path, modelname)
        case "openai" | "facebook":
            return await transcribe_huggingface(path, model)
        case _:
            raise ValueError(f"Model {model} not supported")


def get_or_metadata(id):
    # get metadata from OpenRouter
    models = get_models(date.today())
    metadata = next((m for m in models if m["slug"] == id), None)
    return metadata


api = HfApi()


@cache
def get_hf_metadata(row):
    # get metadata from the HuggingFace API
    empty = {
        "hf_id": None,
        "creation_date": None,
        "size": None,
        "type": "closed-source",
        "license": None,
    }
    if not row:
        return empty
    id = row["hf_slug"] or row["slug"].split(":")[0]
    if not id:
        return empty
    try:
        info = api.model_info(id)
        license = ""
        if info.card_data and hasattr(info.card_data, 'license') and info.card_data.license:
            license = (
                info.card_data.license
                .replace("-", " ")
                .replace("mit", "MIT")
                .title()
            )
        return {
            "hf_id": info.id,
            "creation_date": info.created_at,
            "size": info.safetensors.total if info.safetensors else None,
            "type": "open-source",
            "license": license,
        }
    except HTTPError:
        return empty


def get_cost(row):
    """
    row: a row from the OpenRouter models dataframe
    """
    try:
        cost = float(row["endpoint"]["pricing"]["completion"])
        return round(cost * 1_000_000, 2)
    except (TypeError, KeyError):
        return None


@cache
def load_models(date: date):
    popular_models = (
        get_historical_popular_models(date.today())[:20]
        + get_current_popular_models(date.today())[:10]
    )
    popular_models = [m["slug"] for m in popular_models]
    all_model_candidates = set(important_models + popular_models) - set(blocklist)
    
    # Validate models exist on OpenRouter before including them
    print(f"πŸ” Validating {len(all_model_candidates)} model candidates...")
    valid_models = []
    invalid_models = []
    
    for model_id in all_model_candidates:
        metadata = get_or_metadata(model_id)
        if metadata is not None:
            valid_models.append(model_id)
        else:
            invalid_models.append(model_id)
    
    if invalid_models:
        print(f"⚠️ Excluded {len(invalid_models)} invalid models:")
        for model in sorted(invalid_models)[:5]:  # Show first 5
            print(f"   - {model}")
        if len(invalid_models) > 5:
            print(f"   ... and {len(invalid_models) - 5} more")
    
    print(f"βœ… Using {len(valid_models)} valid models for evaluation")
    
    models = pd.DataFrame(sorted(valid_models), columns=["id"])
    or_metadata = models["id"].apply(get_or_metadata)
    hf_metadata = or_metadata.apply(get_hf_metadata)
    creation_date_hf = pd.to_datetime(hf_metadata.str["creation_date"]).dt.date
    creation_date_or = pd.to_datetime(
        or_metadata.str["created_at"].str.split("T").str[0]
    ).dt.date

    models = models.assign(
        name=or_metadata.str["short_name"]
        .str.replace(" (free)", "")
        .str.replace(" (self-moderated)", ""),
        provider_name=or_metadata.str["name"].str.split(": ").str[0],
        cost=or_metadata.apply(get_cost),
        hf_id=hf_metadata.str["hf_id"],
        size=hf_metadata.str["size"],
        type=hf_metadata.str["type"],
        license=hf_metadata.str["license"],
        creation_date=creation_date_hf.combine_first(creation_date_or),
    )
    # Filter out expensive models to keep costs reasonable
    models = models[models["cost"] <= 20.0].reset_index(drop=True)
    models["tasks"] = [
        ["translation_from", "translation_to", "classification", "mmlu", "arc", "truthfulqa", "mgsm"]
    ] * len(models)
    models = pd.concat([models, get_translation_models()])
    return models


models = load_models(date.today())