Files
mammouth-models-dashboard/update_models.py

151 lines
5.2 KiB
Python

import os
import requests
import json
import time
from dotenv import load_dotenv
# Charger .env.global depuis le répertoire parent
load_dotenv("../.env.global")
AIANALASYS_APIKEY = os.getenv("AIANALASYS_APIKEY")
def get_mammouth_models():
# Utilisation de l'endpoint public LiteLLM de Mammouth
url = "https://mammouth.ai/public/models"
try:
response = requests.get(url)
response.raise_for_status()
# Le format retourné est {'data': [ {id, model_info: {input_cost_per_token, ...}} ]}
return response.json().get('data', [])
except Exception as e:
print(f"Error fetching Mammouth public models: {e}")
return []
def get_aa_data():
url = "https://artificialanalysis.ai/api/v2/data/llms/models"
headers = {"x-api-key": AIANALASYS_APIKEY}
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.json().get('data', [])
except Exception as e:
print(f"Error fetching Artificial Analysis data: {e}")
return []
def generate_markdown(models_data):
categories = {}
for m in models_data:
cat = m.get('category', 'General')
if cat not in categories:
categories[cat] = []
categories[cat].append(m)
md = "# Table des Modèles Mammouth.ai\n\n"
md += "*Mise à jour automatique via Artificial Analysis & Mammouth Public API*\n\n"
md += "Dernière mise à jour : " + time.strftime("%Y-%m-%d %H:%M:%S") + "\n\n"
order = ['Coding', 'Agents', 'General']
sorted_cats = sorted(categories.keys(), key=lambda x: order.index(x) if x in order else 99)
for cat in sorted_cats:
models = categories[cat]
md += f"## {cat}\n\n"
md += "| Modèle | Prix (In / Out / 1M) | Performance (AA Index) | Vitesse (TPS) |\n"
md += "| :--- | :--- | :--- | :--- |\n"
# On trie d'abord par score décroissant, puis par prix croissant
models.sort(key=lambda x: (x.get('score') or 0, -(x.get('price_in') or 0)), reverse=True)
for m in models:
p_in = f"${m['price_in']:.2f}"
p_out = f"${m['price_out']:.2f}"
score = f"**{m['score']:.1f}**" if m['score'] else "N/A"
speed = f"{m['speed']:.1f}" if m['speed'] else "N/A"
md += f"| {m['name']} | {p_in} / {p_out} | {score} | {speed} |\n"
md += "\n"
return md
def main():
print("Fetching Mammouth public models...")
mammouth_models = get_mammouth_models()
if not mammouth_models:
print("No models found from Mammouth.")
return
print("Fetching Artificial Analysis data...")
aa_raw = get_aa_data()
# Construction du mapping AA (index par nom et par ID technique)
aa_map = {}
for aa_m in aa_raw:
name = aa_m.get('model_name', '').lower()
model_id = aa_m.get('model_id', '').lower()
if name: aa_map[name] = aa_m
if model_id: aa_map[model_id] = aa_m
enriched_models = []
for m in mammouth_models:
m_id = m.get('id', '')
info = m.get('model_info', {})
# On ignore les modèles sans ID
if not m_id: continue
# Normalisation du nom pour le mapping
m_id_low = m_id.lower()
short_name = m_id_low.split('/')[-1]
# Recherche de correspondance dans AA (Précis puis Approché)
aa_info = aa_map.get(m_id_low) or aa_map.get(short_name)
if not aa_info:
# Recherche par sous-chaîne pour les modèles comme "mistral-large-2407"
for key in aa_map:
if key in m_id_low or m_id_low in key:
aa_info = aa_map[key]
break
# Extraction des prix (LiteLLM: prix par 1 token)
try:
price_in = float(info.get('input_cost_per_token', 0)) * 1000000
price_out = float(info.get('output_cost_per_token', 0)) * 1000000
except (ValueError, TypeError):
price_in, price_out = 0, 0
score = None
speed = None
if aa_info:
evals = aa_info.get('evaluations', {})
score = evals.get('artificial_analysis_intelligence_index')
speed = aa_info.get('median_output_tokens_per_second')
# Catégorisation simplifiée
category = "General"
if any(x in m_id_low for x in ['coding', 'code', 'starcoder', 'coder']):
category = "Coding"
elif any(x in m_id_low for x in ['agent', 'hermes', 'tool', 'function']):
category = "Agents"
enriched_models.append({
'name': m_id,
'price_in': price_in,
'price_out': price_out,
'score': score,
'speed': speed,
'category': category
})
# Filtrer les modèles : prix > 0 (ceux qui sont configurés)
final_list = [m for m in enriched_models if m['price_in'] > 0 or m['price_out'] > 0]
if not final_list:
print("No valid models found after filtering.")
return
markdown = generate_markdown(final_list)
with open("README.md", "w", encoding="utf-8") as f:
f.write(markdown)
print(f"README.md updated with {len(final_list)} models!")
if __name__ == "__main__":
main()