AI_agent/test_ollama_mistral2.py
2025-03-27 14:54:06 +01:00

81 lines
3.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
import os
from datetime import datetime
import uuid #pour générer un identifiant unique
from itertools import product #pour générer toutes les combinaisons de paramètres
#=== Configuration ===
model_name = "mistral:latest"
prompt = "Explique-moi ce qu'et l'intelligence artificielle."
#Paramètres par défaut
base_params = {
"model": model_name,
"prompt": prompt,
"temperature": 0.5, # Créativité (0.1 = précis, 1.5 = créatif)
"top_p": 0.9, # Probabilité cumulée (1.0 = complet)
"top_k": 50, # Top-k tokens à considérer (0 = désactivé)
"repeat_penalty": 1.1, # Pénalise les répétitions (>1 = punit)
"num_predict": 512, # Max tokens générés
"stop": [], # Liste de tokens d'arrêt (optionnel)
"seed": None, # Pour reproduction des résultats
"stream": False
}
#Paramètres à faire varier
parameters_to_test = {
"temperature": [0.1, 0.5, 1.0],
#"top_p": [0.5, 0.9, 1.0],
#"top_k": [10, 50, 100],
#"repeat_penalty": [1.0, 1.1, 1.2],
}
#Préparation des combinaisons
varying_keys = list(parameters_to_test.keys())
combinations = list(product(*[parameters_to_test[k] for k in varying_keys]))
#Création des dossiers de logs
os.makedirs("logs", exist_ok=True)
index_path = "log_index.md"
# Boucle de test
for combo in combinations:
test_params = base_params.copy()
combo_desc = []
for i, key in enumerate(varying_keys):
test_params[key] = combo[i]
combo_desc.append(f"{key}={combo[i]}")
#Requête à ollama
response = requests.post("http://217.182.105.173:11434/api/generate", json=test_params)
result = response.json()["response"] if response.ok else f"Erreur: {response.text}"
#enregistrement des résultats
now = datetime.now()
now_str = now.strftime("%Y-%m-%d_%H-%M-%S")
uid = str(uuid.uuid4())[:8] #générer un identifiant unique
log_name = f"mistral_{now_str}_{uid}.md" #nom du fichier de log
# === Fichier principal .md (réponse) ===
log_path = os.path.join("logs", log_name)
# Sauvegarde Markdown
with open(log_path, "w", encoding="utf-8") as f:
f.write(f"# Résultat génération Mistral\n\n")
f.write(f"** Test ID :** {uid}\n")
f.write(f"** Date :** {now.strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"** Modèle :** {model_name}\n")
f.write(f"** Prompt :** {prompt}\n")
f.write(f"** Combinaison :** {', '.join(combo_desc)}\n\n")
f.write("---\n\n## Paramètres complets\n\n")
for key in test_params:
if key not in ["model", "prompt"]:
val = test_params[key]
val = " / ".join(val) if isinstance(val, list) else val or "*Aucun*"
f.write(f"- {key.replace('_', ' ').title()} : {val}\n")
f.write("\n---\n\n## Réponse du modèle\n\n")
f.write(result.strip() + "\n")
# Mise à jour de lindex
with open(index_path, "a", encoding="utf-8") as idx:
idx.write(f"- **{now.strftime('%Y-%m-%d %H:%M:%S')}** | `{uid}` | ")
idx.write(f"`{model_name}` | {' | '.join(combo_desc)} | [Voir le log](logs/{log_name})\n")