feat: Oberfläche neu, Modell-Adapter wählbar, Bewertung je Bereich
Die erste Fassung der Oberfläche war inhaltlich und optisch schwach. Neu: drei Reiter (Benchmark, Ergebnisse, Einstellungen). Modelle werden in den Einstellungen mit Adapter (Ollama oder OpenAI-kompatibel), URL, Modell-ID und Schlüssel-Variable angelegt, mit Verbindungstest. config.toml speichert die Liste. Bewertung absolut in Prozent: ein Wert je Bereich A bis D und eine Gesamtnote, gewichtet nach weight. Batch-Verlauf, Schritt-Ansicht, Erklärung der Bewertung. 55 Unit-Tests grün, svelte-check ohne Fehler. Im Browser mit Beispieldaten geprüft, nicht in der echten App. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -644,13 +644,24 @@ pub fn to_openai_messages(messages: &[Message]) -> Vec<Value> {
|
||||
out
|
||||
}
|
||||
|
||||
/// Macht aus einer Basis-URL die Adresse des Chat-Endpunkts.
|
||||
pub fn openai_chat_url(url: &str) -> String {
|
||||
let t = url.trim().trim_end_matches('/');
|
||||
if t.ends_with("/chat/completions") {
|
||||
t.to_string()
|
||||
} else {
|
||||
format!("{t}/chat/completions")
|
||||
}
|
||||
}
|
||||
|
||||
impl OpenAiClient {
|
||||
/// `url` darf die Basis (`…/v1`) oder die volle Adresse (`…/v1/chat/completions`) sein.
|
||||
pub fn new(url: &str, model: &str, api_key: Option<String>) -> Result<OpenAiClient, String> {
|
||||
let http = reqwest::blocking::Client::builder()
|
||||
.build()
|
||||
.map_err(|e| format!("HTTP-Client nicht baubar: {e}"))?;
|
||||
Ok(OpenAiClient {
|
||||
url: url.trim_end_matches('/').into(),
|
||||
url: openai_chat_url(url),
|
||||
model: model.into(),
|
||||
api_key,
|
||||
http,
|
||||
@ -662,13 +673,16 @@ impl ModelClient for OpenAiClient {
|
||||
fn chat(&self, messages: &[Message], tools: &Value, timeout: Duration)
|
||||
-> Result<ChatResponse, ModelError>
|
||||
{
|
||||
let body = json!({
|
||||
let mut body = json!({
|
||||
"model": self.model,
|
||||
"messages": to_openai_messages(messages),
|
||||
"tools": tools,
|
||||
"stream": false,
|
||||
"temperature": 0,
|
||||
});
|
||||
// Ein leeres tools-Feld lehnen manche Server ab.
|
||||
if tools.as_array().map_or(false, |a| !a.is_empty()) {
|
||||
body["tools"] = tools.clone();
|
||||
}
|
||||
let mut req = self.http.post(&self.url).timeout(timeout).json(&body);
|
||||
if let Some(key) = &self.api_key {
|
||||
req = req.bearer_auth(key);
|
||||
@ -1015,6 +1029,16 @@ Rufe danach das Werkzeug done auf.";
|
||||
assert_eq!(out[3]["tool_call_id"], call["id"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn openai_url_wird_ergaenzt() {
|
||||
assert_eq!(openai_chat_url("http://h:8082/v1"), "http://h:8082/v1/chat/completions");
|
||||
assert_eq!(openai_chat_url("http://h:8082/v1/"), "http://h:8082/v1/chat/completions");
|
||||
assert_eq!(
|
||||
openai_chat_url("http://h:8082/v1/chat/completions"),
|
||||
"http://h:8082/v1/chat/completions"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sh_quote_maskiert_apostrophe() {
|
||||
assert_eq!(sh_quote("a'b"), "'a'\\''b'");
|
||||
|
||||
@ -13,6 +13,59 @@ pub const CONFIG_FILE_NAME: &str = "config.toml";
|
||||
/// Aufgaben, die ein Paket installiert. Gilt, wenn weder die Konfiguration noch der Datenordner Aufgaben angeben.
|
||||
pub const SYSTEM_TASKS_DIR: &str = "/usr/share/coding-bench/tasks";
|
||||
|
||||
/// Ein angebundenes Modell: Anzeigename, Adapter und Endpunkt.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct ModelEntry {
|
||||
/// Anzeigename, eindeutig. Erscheint in Ranglisten.
|
||||
pub name: String,
|
||||
/// `ollama` oder `openai` (OpenAI-kompatibel, z. B. strata).
|
||||
pub adapter: String,
|
||||
/// Basis-URL des Servers, z. B. `http://host:11434` oder `http://host:8082/v1`.
|
||||
pub url: String,
|
||||
/// Modell-ID, die an den Server gesendet wird. Leer = Anzeigename.
|
||||
pub model: String,
|
||||
/// Name der Umgebungsvariable mit dem API-Schlüssel. Leer = kein Schlüssel.
|
||||
pub api_key_env: String,
|
||||
}
|
||||
|
||||
impl Default for ModelEntry {
|
||||
fn default() -> Self {
|
||||
ModelEntry {
|
||||
name: String::new(),
|
||||
adapter: "ollama".into(),
|
||||
url: String::new(),
|
||||
model: String::new(),
|
||||
api_key_env: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub const ADAPTERS: [&str; 2] = ["ollama", "openai"];
|
||||
|
||||
/// Prüft eine Modell-Liste: Namen nicht leer und eindeutig, Adapter bekannt, URL gesetzt.
|
||||
pub fn validate_models(models: &[ModelEntry]) -> Result<(), String> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for m in models {
|
||||
if m.name.trim().is_empty() {
|
||||
return Err("Ein Modell hat keinen Namen.".into());
|
||||
}
|
||||
if !seen.insert(m.name.trim().to_string()) {
|
||||
return Err(format!("Der Name {:?} kommt doppelt vor.", m.name));
|
||||
}
|
||||
if !ADAPTERS.contains(&m.adapter.as_str()) {
|
||||
return Err(format!(
|
||||
"{}: Adapter {:?} unbekannt (erlaubt: ollama, openai).",
|
||||
m.name, m.adapter
|
||||
));
|
||||
}
|
||||
if m.url.trim().is_empty() {
|
||||
return Err(format!("{}: URL fehlt.", m.name));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rohe Konfiguration, so wie sie in der Datei steht.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
@ -23,13 +76,15 @@ pub struct Config {
|
||||
pub tasks_dir: Option<PathBuf>,
|
||||
/// Container-Programm für die Sandbox (Podman-CLI).
|
||||
pub container_runtime: String,
|
||||
/// Modell-Backend: `ollama` oder `openai` (OpenAI-kompatibel, z. B. strata).
|
||||
/// Angebundene Modelle. Wird in der Oberfläche gepflegt.
|
||||
pub models: Vec<ModelEntry>,
|
||||
/// Veraltet, wird ignoriert. Bleibt nur, damit alte Dateien weiter laden.
|
||||
pub backend: String,
|
||||
/// Ollama-Endpunkt für alle Modelle (Phase 1).
|
||||
/// Veraltet, wird ignoriert.
|
||||
pub ollama_url: String,
|
||||
/// OpenAI-kompatibler Endpunkt, vollständige URL inkl. `/v1/chat/completions`.
|
||||
/// Veraltet, wird ignoriert.
|
||||
pub openai_url: String,
|
||||
/// Name der Umgebungsvariable mit dem API-Schlüssel. Der Schlüssel selbst steht nicht in der Datei.
|
||||
/// Veraltet, wird ignoriert.
|
||||
pub openai_api_key_env: String,
|
||||
/// Speicherlimit pro Lauf, Podman-Schreibweise.
|
||||
pub sandbox_memory: String,
|
||||
@ -44,10 +99,11 @@ impl Default for Config {
|
||||
data_dir: None,
|
||||
tasks_dir: None,
|
||||
container_runtime: "podman".into(),
|
||||
backend: "ollama".into(),
|
||||
ollama_url: "http://127.0.0.1:11434".into(),
|
||||
openai_url: "http://192.168.12.4:8082/v1/chat/completions".into(),
|
||||
openai_api_key_env: "STRATA_API_KEY".into(),
|
||||
models: Vec::new(),
|
||||
backend: String::new(),
|
||||
ollama_url: String::new(),
|
||||
openai_url: String::new(),
|
||||
openai_api_key_env: String::new(),
|
||||
sandbox_memory: limits.memory,
|
||||
sandbox_cpus: limits.cpus,
|
||||
}
|
||||
@ -68,15 +124,6 @@ impl Config {
|
||||
toml::from_str(text).map_err(|e| format!("config.toml ist ungültig: {e}"))
|
||||
}
|
||||
|
||||
/// Endpunkt des gewählten Backends.
|
||||
pub fn endpoint_url(&self) -> String {
|
||||
if self.backend == "openai" {
|
||||
self.openai_url.clone()
|
||||
} else {
|
||||
self.ollama_url.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// Ressourcenlimits der Sandbox aus der Konfiguration.
|
||||
pub fn sandbox_limits(&self) -> Limits {
|
||||
Limits {
|
||||
@ -103,6 +150,14 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
/// Schreibt die Konfiguration zurück. Kommentare der alten Datei gehen dabei verloren.
|
||||
pub fn save(config_file: &Path, config: &Config) -> Result<(), String> {
|
||||
let text = toml::to_string_pretty(config)
|
||||
.map_err(|e| format!("Konfiguration nicht serialisierbar: {e}"))?;
|
||||
fs::write(config_file, format!("# coding-bench Konfiguration\n{text}"))
|
||||
.map_err(|e| format!("{} nicht schreibbar: {e}", config_file.display()))
|
||||
}
|
||||
|
||||
/// Lädt die Konfiguration aus `config_dir/config.toml`, legt die Datei bei Bedarf
|
||||
/// mit Standardwerten an und stellt sicher, dass der Datenordner existiert.
|
||||
pub fn load_or_create(config_dir: &Path, default_data_dir: &Path) -> Result<(Paths, Config), String> {
|
||||
@ -157,10 +212,34 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_url_hat_standard_und_ist_ueberschreibbar() {
|
||||
assert_eq!(Config::default().ollama_url, "http://127.0.0.1:11434");
|
||||
let c = Config::parse("ollama_url = \"http://srv04:11434\"\n").unwrap();
|
||||
assert_eq!(c.ollama_url, "http://srv04:11434");
|
||||
fn modelle_werden_gelesen_und_geprueft() {
|
||||
let c = Config::parse(
|
||||
"[[models]]\nname = \"lokal\"\nadapter = \"ollama\"\nurl = \"http://h:11434\"\nmodel = \"qwen3:0.6b\"\n\n[[models]]\nname = \"strata\"\nadapter = \"openai\"\nurl = \"http://h:8082/v1\"\n",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(c.models.len(), 2);
|
||||
assert_eq!(c.models[1].adapter, "openai");
|
||||
assert!(validate_models(&c.models).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modell_pruefung_findet_fehler() {
|
||||
let m = |name: &str, adapter: &str, url: &str| ModelEntry {
|
||||
name: name.into(),
|
||||
adapter: adapter.into(),
|
||||
url: url.into(),
|
||||
..ModelEntry::default()
|
||||
};
|
||||
assert!(validate_models(&[m("", "ollama", "http://x")]).is_err());
|
||||
assert!(validate_models(&[m("a", "ollama", "http://x"), m("a", "ollama", "http://y")]).is_err());
|
||||
assert!(validate_models(&[m("a", "gpt", "http://x")]).is_err());
|
||||
assert!(validate_models(&[m("a", "ollama", " ")]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alte_config_mit_veralteten_feldern_laedt_weiter() {
|
||||
let c = Config::parse("ollama_url = \"http://srv04:11434\"\nbackend = \"openai\"\n").unwrap();
|
||||
assert!(c.models.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@ -6,11 +6,15 @@ mod sandbox;
|
||||
mod store;
|
||||
mod tasks;
|
||||
|
||||
use config::{Config, Paths};
|
||||
use runner::{BatchSummary, Event, RunConfig};
|
||||
use config::{Config, ModelEntry, Paths};
|
||||
use runner::{BatchSummary, Event, ModelConn, RunConfig};
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
use store::{RunRecord, Store};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use store::{BatchInfo, RunRecord, Store};
|
||||
use tauri::{Emitter, Manager, State};
|
||||
|
||||
pub const DB_FILE: &str = "coding-bench.sqlite";
|
||||
@ -19,6 +23,12 @@ pub const EVENT_NAME: &str = "batch-event";
|
||||
/// Aufgelöste Pfade, einmal beim Start ermittelt.
|
||||
pub struct AppPaths(pub Paths);
|
||||
|
||||
/// Die laufende Konfiguration. Die Oberfläche ändert die Modell-Liste, die Datei wird mitgeschrieben.
|
||||
pub struct ConfigState {
|
||||
pub config: Mutex<Config>,
|
||||
pub file: PathBuf,
|
||||
}
|
||||
|
||||
/// Steuerung für den laufenden Batch. Es läuft immer nur einer.
|
||||
pub struct RunState {
|
||||
/// Gesetzt, wenn der laufende Batch abbrechen soll.
|
||||
@ -27,6 +37,36 @@ pub struct RunState {
|
||||
pub running: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
/// Ein Modell für die Oberfläche, mit Hinweis, ob die Schlüssel-Variable gesetzt ist.
|
||||
#[derive(Serialize)]
|
||||
pub struct ModelInfo {
|
||||
#[serde(flatten)]
|
||||
pub entry: ModelEntry,
|
||||
pub api_key_set: bool,
|
||||
}
|
||||
|
||||
fn model_info(entry: &ModelEntry) -> ModelInfo {
|
||||
let api_key_set = !entry.api_key_env.is_empty()
|
||||
&& std::env::var(&entry.api_key_env).map_or(false, |v| !v.is_empty());
|
||||
ModelInfo { entry: entry.clone(), api_key_set }
|
||||
}
|
||||
|
||||
/// Löst einen Eintrag in eine Verbindung auf: Modell-ID und Schlüssel aus der Umgebung.
|
||||
fn conn_of(entry: &ModelEntry) -> ModelConn {
|
||||
let api_key = if entry.api_key_env.is_empty() {
|
||||
None
|
||||
} else {
|
||||
std::env::var(&entry.api_key_env).ok().filter(|k| !k.is_empty())
|
||||
};
|
||||
ModelConn {
|
||||
name: entry.name.clone(),
|
||||
adapter: entry.adapter.clone(),
|
||||
url: entry.url.clone(),
|
||||
model_id: if entry.model.trim().is_empty() { entry.name.clone() } else { entry.model.clone() },
|
||||
api_key,
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn get_paths(paths: State<'_, AppPaths>) -> Paths {
|
||||
paths.0.clone()
|
||||
@ -37,13 +77,92 @@ fn load_tasks(paths: State<'_, AppPaths>) -> tasks::LoadReport {
|
||||
tasks::load_all(&paths.0.tasks_dir)
|
||||
}
|
||||
|
||||
/// Startet einen Batch mit den angegebenen Modellen und Aufgaben-IDs.
|
||||
/// Angebundene Modelle.
|
||||
#[tauri::command]
|
||||
fn list_models(cfg: State<'_, ConfigState>) -> Result<Vec<ModelInfo>, String> {
|
||||
let c = cfg.config.lock().map_err(|e| e.to_string())?;
|
||||
Ok(c.models.iter().map(model_info).collect())
|
||||
}
|
||||
|
||||
/// Ersetzt die Modell-Liste, prüft sie und schreibt `config.toml`.
|
||||
#[tauri::command]
|
||||
fn save_models(cfg: State<'_, ConfigState>, models: Vec<ModelEntry>) -> Result<Vec<ModelInfo>, String> {
|
||||
let cleaned: Vec<ModelEntry> = models
|
||||
.into_iter()
|
||||
.map(|mut m| {
|
||||
m.name = m.name.trim().to_string();
|
||||
m.url = m.url.trim().to_string();
|
||||
m.model = m.model.trim().to_string();
|
||||
m.api_key_env = m.api_key_env.trim().to_string();
|
||||
m
|
||||
})
|
||||
.collect();
|
||||
config::validate_models(&cleaned)?;
|
||||
let mut c = cfg.config.lock().map_err(|e| e.to_string())?;
|
||||
let mut next = c.clone();
|
||||
next.models = cleaned;
|
||||
config::save(&cfg.file, &next)?;
|
||||
*c = next;
|
||||
Ok(c.models.iter().map(model_info).collect())
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct ModelTest {
|
||||
pub ok: bool,
|
||||
pub duration_ms: u128,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
/// Prüft die Verbindung zu einem Modell mit einer kurzen Anfrage.
|
||||
#[tauri::command]
|
||||
async fn test_model(cfg: State<'_, ConfigState>, name: String) -> Result<ModelTest, String> {
|
||||
let entry = {
|
||||
let c = cfg.config.lock().map_err(|e| e.to_string())?;
|
||||
c.models
|
||||
.iter()
|
||||
.find(|m| m.name == name)
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?
|
||||
};
|
||||
let conn = conn_of(&entry);
|
||||
tauri::async_runtime::spawn_blocking(move || {
|
||||
let started = Instant::now();
|
||||
let result = runner::client_for(&conn).and_then(|client| {
|
||||
client
|
||||
.chat(
|
||||
&[agent::Message::new("user", "Antworte nur mit: ok")],
|
||||
&serde_json::json!([]),
|
||||
Duration::from_secs(90),
|
||||
)
|
||||
.map_err(|e| match e {
|
||||
agent::ModelError::Timeout => "Zeitlimit überschritten (90 s)".to_string(),
|
||||
agent::ModelError::Endpoint(m) => m,
|
||||
})
|
||||
});
|
||||
let duration_ms = started.elapsed().as_millis();
|
||||
match result {
|
||||
Ok(r) => ModelTest {
|
||||
ok: true,
|
||||
duration_ms,
|
||||
message: format!(
|
||||
"Antwort erhalten ({} Prompt-, {} Completion-Tokens).",
|
||||
r.prompt_tokens, r.completion_tokens
|
||||
),
|
||||
},
|
||||
Err(message) => ModelTest { ok: false, duration_ms, message },
|
||||
}
|
||||
})
|
||||
.await
|
||||
.map_err(|e| format!("Test abgebrochen: {e}"))
|
||||
}
|
||||
|
||||
/// Startet einen Batch mit den angegebenen Modellen (Anzeigenamen) und Aufgaben-IDs.
|
||||
/// Fortschritt kommt als Ereignis `batch-event`. Das Ergebnis ist die Zusammenfassung.
|
||||
#[tauri::command]
|
||||
async fn start_batch(
|
||||
app: tauri::AppHandle,
|
||||
paths: State<'_, AppPaths>,
|
||||
cfg: State<'_, Config>,
|
||||
cfg: State<'_, ConfigState>,
|
||||
run: State<'_, RunState>,
|
||||
models: Vec<String>,
|
||||
task_ids: Vec<String>,
|
||||
@ -56,10 +175,20 @@ async fn start_batch(
|
||||
if repeats == 0 {
|
||||
return Err("Wiederholungen müssen mindestens 1 sein.".into());
|
||||
}
|
||||
if run.running.swap(true, Ordering::SeqCst) {
|
||||
return Err("Ein Batch läuft bereits.".into());
|
||||
}
|
||||
run.cancel.store(false, Ordering::SeqCst);
|
||||
|
||||
let (conns, runtime, limits) = {
|
||||
let c = cfg.config.lock().map_err(|e| e.to_string())?;
|
||||
let mut conns = Vec::new();
|
||||
for name in &models {
|
||||
let entry = c
|
||||
.models
|
||||
.iter()
|
||||
.find(|m| &m.name == name)
|
||||
.ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?;
|
||||
conns.push(conn_of(entry));
|
||||
}
|
||||
(conns, c.container_runtime.clone(), c.sandbox_limits())
|
||||
};
|
||||
|
||||
let report = tasks::load_all(&paths.0.tasks_dir);
|
||||
let selected: Vec<tasks::Task> = report
|
||||
@ -68,17 +197,20 @@ async fn start_batch(
|
||||
.filter(|t| task_ids.contains(&t.meta.id))
|
||||
.collect();
|
||||
if selected.len() != task_ids.len() {
|
||||
run.running.store(false, Ordering::SeqCst);
|
||||
return Err("Mindestens eine gewählte Aufgabe ist nicht gültig geladen.".into());
|
||||
}
|
||||
|
||||
if run.running.swap(true, Ordering::SeqCst) {
|
||||
return Err("Ein Batch läuft bereits.".into());
|
||||
}
|
||||
run.cancel.store(false, Ordering::SeqCst);
|
||||
|
||||
let jobs = runner::plan(&models, &selected, repeats);
|
||||
let run_cfg = RunConfig {
|
||||
runtime: cfg.container_runtime.clone(),
|
||||
backend: cfg.backend.clone(),
|
||||
endpoint_url: cfg.endpoint_url(),
|
||||
api_key: std::env::var(&cfg.openai_api_key_env).ok().filter(|k| !k.is_empty()),
|
||||
runtime,
|
||||
models: conns,
|
||||
data_dir: paths.0.data_dir.clone(),
|
||||
limits: cfg.sandbox_limits(),
|
||||
limits,
|
||||
};
|
||||
let db_path = paths.0.data_dir.join(DB_FILE);
|
||||
let cancel = run.cancel.clone();
|
||||
@ -114,6 +246,12 @@ fn cancel_batch(run: State<'_, RunState>) -> bool {
|
||||
running
|
||||
}
|
||||
|
||||
/// Alle bisherigen Batches, neueste zuerst.
|
||||
#[tauri::command]
|
||||
fn list_batches(paths: State<'_, AppPaths>) -> Result<Vec<BatchInfo>, String> {
|
||||
Store::open(&paths.0.data_dir.join(DB_FILE))?.list_batches()
|
||||
}
|
||||
|
||||
/// Alle gespeicherten Läufe eines Batches.
|
||||
#[tauri::command]
|
||||
fn batch_results(paths: State<'_, AppPaths>, batch_id: i64) -> Result<Vec<RunRecord>, String> {
|
||||
@ -135,7 +273,7 @@ fn run_steps(
|
||||
}
|
||||
|
||||
/// Zustand der Container-Laufzeit (Podman) für das Setup.
|
||||
#[derive(serde::Serialize)]
|
||||
#[derive(Serialize)]
|
||||
pub struct RuntimeStatus {
|
||||
pub program: String,
|
||||
pub available: bool,
|
||||
@ -143,38 +281,48 @@ pub struct RuntimeStatus {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn runtime_status(cfg: State<'_, Config>) -> RuntimeStatus {
|
||||
let program = cfg.container_runtime.clone();
|
||||
match std::process::Command::new(&program).args(["version", "--format", "{{.Client.Version}}"]).output() {
|
||||
Ok(out) if out.status.success() => RuntimeStatus {
|
||||
program,
|
||||
available: true,
|
||||
detail: format!("Version {}", String::from_utf8_lossy(&out.stdout).trim()),
|
||||
fn runtime_status(cfg: State<'_, ConfigState>) -> Result<RuntimeStatus, String> {
|
||||
let program = cfg.config.lock().map_err(|e| e.to_string())?.container_runtime.clone();
|
||||
Ok(
|
||||
match std::process::Command::new(&program)
|
||||
.args(["version", "--format", "{{.Client.Version}}"])
|
||||
.output()
|
||||
{
|
||||
Ok(out) if out.status.success() => RuntimeStatus {
|
||||
program,
|
||||
available: true,
|
||||
detail: format!("Version {}", String::from_utf8_lossy(&out.stdout).trim()),
|
||||
},
|
||||
Ok(out) => RuntimeStatus {
|
||||
program,
|
||||
available: false,
|
||||
detail: String::from_utf8_lossy(&out.stderr).trim().to_string(),
|
||||
},
|
||||
Err(e) => RuntimeStatus {
|
||||
program,
|
||||
available: false,
|
||||
detail: format!("nicht startbar: {e}"),
|
||||
},
|
||||
},
|
||||
Ok(out) => RuntimeStatus {
|
||||
program,
|
||||
available: false,
|
||||
detail: String::from_utf8_lossy(&out.stderr).trim().to_string(),
|
||||
},
|
||||
Err(e) => RuntimeStatus {
|
||||
program,
|
||||
available: false,
|
||||
detail: format!("nicht startbar: {e}"),
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
/// Rangliste und Matrix eines Batches. Gewichte kommen aus den Aufgaben.
|
||||
/// Bewertung je Modell und Bereich für einen Batch. Gruppe und Gewicht kommen aus den Aufgaben.
|
||||
#[tauri::command]
|
||||
fn batch_ranking(paths: State<'_, AppPaths>, batch_id: i64) -> Result<ranking::Ranking, String> {
|
||||
let store = Store::open(&paths.0.data_dir.join(DB_FILE))?;
|
||||
let runs = store.runs_for_batch(batch_id)?;
|
||||
let weights: std::collections::BTreeMap<String, f64> = tasks::load_all(&paths.0.tasks_dir)
|
||||
let infos: BTreeMap<String, ranking::TaskInfo> = tasks::load_all(&paths.0.tasks_dir)
|
||||
.tasks
|
||||
.into_iter()
|
||||
.map(|t| (t.meta.id, t.meta.weight))
|
||||
.map(|t| {
|
||||
(
|
||||
t.meta.id.clone(),
|
||||
ranking::TaskInfo { group: t.meta.group.clone(), weight: t.meta.weight },
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
Ok(ranking::compute(batch_id, &runs, &weights))
|
||||
Ok(ranking::compute(batch_id, &runs, &infos))
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
@ -193,8 +341,9 @@ pub fn run() {
|
||||
let (paths, cfg) = config::load_or_create(&config_dir, &default_data_dir)?;
|
||||
// Datenbank einmal anlegen, damit Fehler früh sichtbar werden.
|
||||
Store::open(&paths.data_dir.join(DB_FILE))?;
|
||||
let file = paths.config_file.clone();
|
||||
app.manage(AppPaths(paths));
|
||||
app.manage(cfg);
|
||||
app.manage(ConfigState { config: Mutex::new(cfg), file });
|
||||
app.manage(RunState {
|
||||
cancel: Arc::new(AtomicBool::new(false)),
|
||||
running: Arc::new(AtomicBool::new(false)),
|
||||
@ -204,8 +353,12 @@ pub fn run() {
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
get_paths,
|
||||
load_tasks,
|
||||
list_models,
|
||||
save_models,
|
||||
test_model,
|
||||
start_batch,
|
||||
cancel_batch,
|
||||
list_batches,
|
||||
batch_results,
|
||||
batch_ranking,
|
||||
run_steps,
|
||||
|
||||
@ -1,21 +1,45 @@
|
||||
//! Rangliste und Matrix aus den Läufen eines Batches (F-09, SPEC Abschnitt 9).
|
||||
//! Bewertung je Modell und Bereich (F-09, SPEC Abschnitt 9).
|
||||
//!
|
||||
//! Gesamtscore je Modell: gewichteter Mittelwert der Aufgaben-Scores (`weight` aus
|
||||
//! `task.toml`). Erfolgsquote je (Modell, Aufgabe): Anteil der Läufe mit Klasse `ok`.
|
||||
//! Tie-Breaker: Median der Dauer, dann mittlere Completion-Tokens. Wilson-Intervalle
|
||||
//! und Kategorie-Ranking folgen mit F-12 (Phase 2).
|
||||
//! Basis ist eine absolute Bewertung, kein Vergleich gegen ein Referenzmodell:
|
||||
//! - Wert je Bereich (Gruppe A bis D): gewichteter Mittelwert der Aufgaben im Bereich in Prozent.
|
||||
//! Je Aufgabe zählt der mittlere Score über die Wiederholungen.
|
||||
//! - Gesamtnote: gewichteter Mittelwert über alle Aufgaben des Batches in Prozent.
|
||||
//! - Gewichte kommen aus `weight` in `task.toml`.
|
||||
//! - Bereiche ohne Läufe eines Modells bleiben leer und zählen nicht mit.
|
||||
//! - Reihenfolge: Gesamtnote absteigend, dann Median der Dauer, dann mittlere Completion-Tokens.
|
||||
|
||||
use crate::agent::ErrorClass;
|
||||
use crate::store::RunRecord;
|
||||
use serde::Serialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Gruppe und Gewicht einer Aufgabe.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct TaskInfo {
|
||||
pub group: String,
|
||||
pub weight: f64,
|
||||
}
|
||||
|
||||
/// Wert eines Modells in einem Bereich.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct GroupScore {
|
||||
pub group: String,
|
||||
/// Prozent von 0 bis 100. `None`, wenn das Modell im Bereich keine Läufe hat.
|
||||
pub percent: Option<f64>,
|
||||
/// Anzahl Aufgaben, die in den Wert eingehen.
|
||||
pub tasks: usize,
|
||||
pub runs: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct ModelRank {
|
||||
pub rank: usize,
|
||||
pub model: String,
|
||||
/// Gewichteter Mittelwert der Aufgaben-Scores, 0.0 bis 1.0.
|
||||
pub total_score: f64,
|
||||
/// Gesamtnote in Prozent von 0 bis 100.
|
||||
pub total_percent: f64,
|
||||
pub groups: Vec<GroupScore>,
|
||||
/// Bereich mit dem niedrigsten Wert, nur wenn das Modell mindestens zwei Bereiche hat.
|
||||
pub weakest_group: Option<String>,
|
||||
pub runs: usize,
|
||||
pub successes: usize,
|
||||
pub median_duration_ms: u128,
|
||||
@ -28,24 +52,53 @@ pub struct MatrixCell {
|
||||
pub task_id: String,
|
||||
pub runs: usize,
|
||||
pub successes: usize,
|
||||
/// Mittlerer Score über die Wiederholungen.
|
||||
/// Mittlerer Score über die Wiederholungen, 0.0 bis 1.0.
|
||||
pub mean_score: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct TaskColumn {
|
||||
pub id: String,
|
||||
pub group: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct Ranking {
|
||||
pub batch_id: i64,
|
||||
/// Bereiche, die im Batch vorkommen, sortiert.
|
||||
pub groups: Vec<String>,
|
||||
pub models: Vec<ModelRank>,
|
||||
pub cells: Vec<MatrixCell>,
|
||||
pub tasks: Vec<String>,
|
||||
/// Aufgaben des Batches, sortiert nach Bereich und ID.
|
||||
pub tasks: Vec<TaskColumn>,
|
||||
}
|
||||
|
||||
/// Berechnet Rangliste und Matrix. `weights` ordnet jeder Aufgaben-ID ihr Gewicht zu;
|
||||
/// fehlt eine ID, zählt das Gewicht 1.0.
|
||||
pub fn compute(batch_id: i64, runs: &[RunRecord], weights: &BTreeMap<String, f64>) -> Ranking {
|
||||
let weight_of = |task: &str| weights.get(task).copied().unwrap_or(1.0);
|
||||
const UNKNOWN_GROUP: &str = "?";
|
||||
|
||||
/// Berechnet Bewertung und Matrix. Unbekannte Aufgaben zählen mit Gewicht 1.0 im Bereich `?`.
|
||||
pub fn compute(batch_id: i64, runs: &[RunRecord], tasks: &BTreeMap<String, TaskInfo>) -> Ranking {
|
||||
let info_of = |task: &str| -> TaskInfo {
|
||||
tasks.get(task).cloned().unwrap_or(TaskInfo {
|
||||
group: UNKNOWN_GROUP.into(),
|
||||
weight: 1.0,
|
||||
})
|
||||
};
|
||||
|
||||
// Aufgaben des Batches mit Bereich.
|
||||
let mut task_cols: BTreeMap<String, String> = BTreeMap::new();
|
||||
for r in runs {
|
||||
task_cols
|
||||
.entry(r.task_id.clone())
|
||||
.or_insert_with(|| info_of(&r.task_id).group);
|
||||
}
|
||||
let mut task_list: Vec<TaskColumn> = task_cols
|
||||
.iter()
|
||||
.map(|(id, group)| TaskColumn { id: id.clone(), group: group.clone() })
|
||||
.collect();
|
||||
task_list.sort_by(|a, b| a.group.cmp(&b.group).then(a.id.cmp(&b.id)));
|
||||
let mut groups: Vec<String> = task_list.iter().map(|t| t.group.clone()).collect();
|
||||
groups.dedup();
|
||||
|
||||
// Pro Modell: Liste der Läufe.
|
||||
let mut by_model: BTreeMap<&str, Vec<&RunRecord>> = BTreeMap::new();
|
||||
for r in runs {
|
||||
by_model.entry(r.model.as_str()).or_default().push(r);
|
||||
@ -54,44 +107,81 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], weights: &BTreeMap<String, f64
|
||||
let mut models: Vec<ModelRank> = by_model
|
||||
.iter()
|
||||
.map(|(model, rs)| {
|
||||
// Mittelwert je Aufgabe, dann gewichtet über die Aufgaben.
|
||||
// Mittel je Aufgabe über die Wiederholungen.
|
||||
let mut per_task: BTreeMap<&str, (f64, usize)> = BTreeMap::new();
|
||||
for r in rs {
|
||||
let e = per_task.entry(r.task_id.as_str()).or_insert((0.0, 0));
|
||||
e.0 += r.score;
|
||||
e.1 += 1;
|
||||
}
|
||||
let (mut wsum, mut wtotal) = (0.0, 0.0);
|
||||
// Je Bereich: gewichtete Summe, Gewicht, Aufgaben, Läufe.
|
||||
let mut per_group: BTreeMap<String, (f64, f64, usize, usize)> = BTreeMap::new();
|
||||
let (mut total_sum, mut total_w) = (0.0, 0.0);
|
||||
for (task, (sum, n)) in &per_task {
|
||||
let w = weight_of(task);
|
||||
wsum += w * (sum / *n as f64);
|
||||
wtotal += w;
|
||||
let info = info_of(task);
|
||||
let mean = sum / *n as f64;
|
||||
let g = per_group.entry(info.group.clone()).or_insert((0.0, 0.0, 0, 0));
|
||||
g.0 += info.weight * mean;
|
||||
g.1 += info.weight;
|
||||
g.2 += 1;
|
||||
g.3 += *n;
|
||||
total_sum += info.weight * mean;
|
||||
total_w += info.weight;
|
||||
}
|
||||
let total_score = if wtotal > 0.0 { wsum / wtotal } else { 0.0 };
|
||||
let total_percent = if total_w > 0.0 { 100.0 * total_sum / total_w } else { 0.0 };
|
||||
|
||||
let group_scores: Vec<GroupScore> = groups
|
||||
.iter()
|
||||
.map(|g| match per_group.get(g) {
|
||||
Some((sum, w, tasks_n, runs_n)) if *w > 0.0 => GroupScore {
|
||||
group: g.clone(),
|
||||
percent: Some(100.0 * sum / w),
|
||||
tasks: *tasks_n,
|
||||
runs: *runs_n,
|
||||
},
|
||||
_ => GroupScore { group: g.clone(), percent: None, tasks: 0, runs: 0 },
|
||||
})
|
||||
.collect();
|
||||
|
||||
let weakest_group = {
|
||||
let filled: Vec<&GroupScore> =
|
||||
group_scores.iter().filter(|g| g.percent.is_some()).collect();
|
||||
if filled.len() >= 2 {
|
||||
filled
|
||||
.iter()
|
||||
.min_by(|a, b| {
|
||||
a.percent
|
||||
.partial_cmp(&b.percent)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
})
|
||||
.map(|g| g.group.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let mut durations: Vec<u128> = rs.iter().map(|r| r.duration_ms).collect();
|
||||
durations.sort_unstable();
|
||||
let median = median_u128(&durations);
|
||||
|
||||
let mean_tokens = rs.iter().map(|r| r.completion_tokens as f64).sum::<f64>() / rs.len() as f64;
|
||||
let successes = rs.iter().filter(|r| r.error_class == ErrorClass::Ok).count();
|
||||
let mean_tokens =
|
||||
rs.iter().map(|r| r.completion_tokens as f64).sum::<f64>() / rs.len() as f64;
|
||||
|
||||
ModelRank {
|
||||
rank: 0,
|
||||
model: model.to_string(),
|
||||
total_score,
|
||||
total_percent,
|
||||
groups: group_scores,
|
||||
weakest_group,
|
||||
runs: rs.len(),
|
||||
successes,
|
||||
median_duration_ms: median,
|
||||
successes: rs.iter().filter(|r| r.error_class == ErrorClass::Ok).count(),
|
||||
median_duration_ms: median_u128(&durations),
|
||||
mean_completion_tokens: mean_tokens,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Absteigend nach Score, dann Median-Dauer, dann mittlere Completion-Tokens.
|
||||
models.sort_by(|a, b| {
|
||||
b.total_score
|
||||
.partial_cmp(&a.total_score)
|
||||
b.total_percent
|
||||
.partial_cmp(&a.total_percent)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
.then(a.median_duration_ms.cmp(&b.median_duration_ms))
|
||||
.then(
|
||||
@ -104,15 +194,12 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], weights: &BTreeMap<String, f64
|
||||
m.rank = i + 1;
|
||||
}
|
||||
|
||||
// Matrix Modell × Aufgabe.
|
||||
let mut cell_map: BTreeMap<(&str, &str), Vec<&RunRecord>> = BTreeMap::new();
|
||||
let mut task_set: BTreeMap<&str, ()> = BTreeMap::new();
|
||||
for r in runs {
|
||||
cell_map
|
||||
.entry((r.model.as_str(), r.task_id.as_str()))
|
||||
.or_default()
|
||||
.push(r);
|
||||
task_set.insert(r.task_id.as_str(), ());
|
||||
}
|
||||
let cells = cell_map
|
||||
.iter()
|
||||
@ -125,12 +212,7 @@ pub fn compute(batch_id: i64, runs: &[RunRecord], weights: &BTreeMap<String, f64
|
||||
})
|
||||
.collect();
|
||||
|
||||
Ranking {
|
||||
batch_id,
|
||||
models,
|
||||
cells,
|
||||
tasks: task_set.keys().map(|t| t.to_string()).collect(),
|
||||
}
|
||||
Ranking { batch_id, groups, models, cells, tasks: task_list }
|
||||
}
|
||||
|
||||
fn median_u128(sorted: &[u128]) -> u128 {
|
||||
@ -165,48 +247,101 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gewichteter_score_und_rang() {
|
||||
let runs = vec![
|
||||
run("A", "t1", 1.0, ErrorClass::Ok, 1000, 10),
|
||||
run("A", "t2", 0.0, ErrorClass::CheckFailed, 1000, 10),
|
||||
run("B", "t1", 1.0, ErrorClass::Ok, 1000, 10),
|
||||
run("B", "t2", 1.0, ErrorClass::Ok, 1000, 10),
|
||||
];
|
||||
let mut w = BTreeMap::new();
|
||||
w.insert("t1".to_string(), 1.0);
|
||||
w.insert("t2".to_string(), 3.0);
|
||||
let r = compute(1, &runs, &w);
|
||||
assert_eq!(r.models[0].model, "B");
|
||||
assert_eq!(r.models[0].rank, 1);
|
||||
assert!((r.models[0].total_score - 1.0).abs() < 1e-9);
|
||||
// A: (1*1 + 3*0) / 4 = 0.25
|
||||
assert!((r.models[1].total_score - 0.25).abs() < 1e-9);
|
||||
fn infos(list: &[(&str, &str, f64)]) -> BTreeMap<String, TaskInfo> {
|
||||
list.iter()
|
||||
.map(|(id, g, w)| (id.to_string(), TaskInfo { group: g.to_string(), weight: *w }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gleichstand_nach_median_dauer() {
|
||||
fn prozent_je_bereich_und_gesamt() {
|
||||
// A: a1 (Gewicht 1), B: b1 (Gewicht 3).
|
||||
let tasks = infos(&[("a1", "A", 1.0), ("b1", "B", 3.0)]);
|
||||
let runs = vec![
|
||||
run("slow", "t1", 1.0, ErrorClass::Ok, 9000, 10),
|
||||
run("fast", "t1", 1.0, ErrorClass::Ok, 2000, 10),
|
||||
run("m", "a1", 1.0, ErrorClass::Ok, 1000, 10),
|
||||
run("m", "b1", 0.0, ErrorClass::CheckFailed, 1000, 10),
|
||||
];
|
||||
let r = compute(1, &runs, &BTreeMap::new());
|
||||
assert_eq!(r.models[0].model, "fast");
|
||||
let r = compute(1, &runs, &tasks);
|
||||
let m = &r.models[0];
|
||||
assert_eq!(r.groups, vec!["A".to_string(), "B".to_string()]);
|
||||
assert_eq!(m.groups[0].percent, Some(100.0));
|
||||
assert_eq!(m.groups[1].percent, Some(0.0));
|
||||
// Gesamt: (1*1 + 3*0) / 4 = 25 %
|
||||
assert!((m.total_percent - 25.0).abs() < 1e-9);
|
||||
assert_eq!(m.weakest_group.as_deref(), Some("B"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix_zaehlt_erfolge_und_mittelwert() {
|
||||
fn wiederholungen_werden_je_aufgabe_gemittelt() {
|
||||
let tasks = infos(&[("a1", "A", 1.0), ("a2", "A", 1.0)]);
|
||||
let runs = vec![
|
||||
run("A", "t1", 1.0, ErrorClass::Ok, 1, 1),
|
||||
run("A", "t1", 0.5, ErrorClass::CheckFailed, 1, 1),
|
||||
run("A", "t1", 0.0, ErrorClass::MaxSteps, 1, 1),
|
||||
run("m", "a1", 1.0, ErrorClass::Ok, 1, 1),
|
||||
run("m", "a1", 0.0, ErrorClass::CheckFailed, 1, 1),
|
||||
run("m", "a2", 1.0, ErrorClass::Ok, 1, 1),
|
||||
];
|
||||
let r = compute(1, &runs, &BTreeMap::new());
|
||||
assert_eq!(r.cells.len(), 1);
|
||||
assert_eq!(r.cells[0].runs, 3);
|
||||
assert_eq!(r.cells[0].successes, 1);
|
||||
assert!((r.cells[0].mean_score - 0.5).abs() < 1e-9);
|
||||
assert_eq!(r.tasks, vec!["t1".to_string()]);
|
||||
let r = compute(1, &runs, &tasks);
|
||||
// a1: 50 %, a2: 100 % -> Bereich A 75 %. Jede Aufgabe zählt gleich viel, egal wie oft sie lief.
|
||||
assert!((r.models[0].groups[0].percent.unwrap() - 75.0).abs() < 1e-9);
|
||||
assert_eq!(r.models[0].groups[0].tasks, 2);
|
||||
assert_eq!(r.models[0].groups[0].runs, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fehlender_bereich_bleibt_leer_und_zaehlt_nicht() {
|
||||
let tasks = infos(&[("a1", "A", 1.0), ("b1", "B", 1.0)]);
|
||||
let runs = vec![
|
||||
run("x", "a1", 1.0, ErrorClass::Ok, 1, 1),
|
||||
run("y", "a1", 1.0, ErrorClass::Ok, 1, 1),
|
||||
run("y", "b1", 1.0, ErrorClass::Ok, 1, 1),
|
||||
];
|
||||
let r = compute(1, &runs, &tasks);
|
||||
let x = r.models.iter().find(|m| m.model == "x").unwrap();
|
||||
assert_eq!(x.groups[1].percent, None);
|
||||
assert_eq!(x.weakest_group, None);
|
||||
assert!((x.total_percent - 100.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rang_nach_gesamt_dann_dauer() {
|
||||
let tasks = infos(&[("a1", "A", 1.0)]);
|
||||
let runs = vec![
|
||||
run("slow", "a1", 1.0, ErrorClass::Ok, 9000, 10),
|
||||
run("fast", "a1", 1.0, ErrorClass::Ok, 2000, 10),
|
||||
run("schlecht", "a1", 0.0, ErrorClass::CheckFailed, 100, 10),
|
||||
];
|
||||
let r = compute(1, &runs, &tasks);
|
||||
let order: Vec<&str> = r.models.iter().map(|m| m.model.as_str()).collect();
|
||||
assert_eq!(order, vec!["fast", "slow", "schlecht"]);
|
||||
assert_eq!(r.models[2].rank, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn matrix_und_aufgabenliste_nach_bereich_sortiert() {
|
||||
let tasks = infos(&[("b1", "B", 1.0), ("a1", "A", 1.0)]);
|
||||
let runs = vec![
|
||||
run("m", "b1", 1.0, ErrorClass::Ok, 1, 1),
|
||||
run("m", "a1", 0.5, ErrorClass::CheckFailed, 1, 1),
|
||||
];
|
||||
let r = compute(1, &runs, &tasks);
|
||||
let ids: Vec<&str> = r.tasks.iter().map(|t| t.id.as_str()).collect();
|
||||
assert_eq!(ids, vec!["a1", "b1"]);
|
||||
assert_eq!(r.cells.len(), 2);
|
||||
let a1 = r.cells.iter().find(|c| c.task_id == "a1").unwrap();
|
||||
assert!((a1.mean_score - 0.5).abs() < 1e-9);
|
||||
assert_eq!(a1.successes, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbekannte_aufgabe_landet_im_bereich_fragezeichen() {
|
||||
let r = compute(1, &[run("m", "alt", 1.0, ErrorClass::Ok, 1, 1)], &BTreeMap::new());
|
||||
assert_eq!(r.groups, vec!["?".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leerer_batch() {
|
||||
let r = compute(7, &[], &BTreeMap::new());
|
||||
assert!(r.models.is_empty() && r.cells.is_empty() && r.tasks.is_empty() && r.groups.is_empty());
|
||||
assert_eq!(r.batch_id, 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -215,11 +350,4 @@ mod tests {
|
||||
assert_eq!(median_u128(&[1, 2, 3, 4]), 2);
|
||||
assert_eq!(median_u128(&[]), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn leerer_batch_ergibt_leere_rangliste() {
|
||||
let r = compute(7, &[], &BTreeMap::new());
|
||||
assert!(r.models.is_empty() && r.cells.is_empty() && r.tasks.is_empty());
|
||||
assert_eq!(r.batch_id, 7);
|
||||
}
|
||||
}
|
||||
|
||||
@ -29,15 +29,25 @@ pub struct Job {
|
||||
pub repeat_idx: u32,
|
||||
}
|
||||
|
||||
/// Verbindung zu einem Modell, aufgelöst aus der Konfiguration.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ModelConn {
|
||||
/// Anzeigename, wie er in Läufen und Ranglisten steht.
|
||||
pub name: String,
|
||||
/// `ollama` oder `openai`.
|
||||
pub adapter: String,
|
||||
pub url: String,
|
||||
/// Modell-ID, die der Server erwartet.
|
||||
pub model_id: String,
|
||||
/// Schlüssel, wird nicht gespeichert.
|
||||
pub api_key: Option<String>,
|
||||
}
|
||||
|
||||
/// Einstellungen für einen Batch.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunConfig {
|
||||
pub runtime: String,
|
||||
/// `ollama` oder `openai`.
|
||||
pub backend: String,
|
||||
pub endpoint_url: String,
|
||||
/// Schlüssel für den OpenAI-Endpunkt, wird nicht gespeichert.
|
||||
pub api_key: Option<String>,
|
||||
pub models: Vec<ModelConn>,
|
||||
pub data_dir: PathBuf,
|
||||
pub limits: Limits,
|
||||
}
|
||||
@ -123,8 +133,9 @@ pub fn run_batch(
|
||||
) -> Result<BatchSummary, String> {
|
||||
let config_json = json!({
|
||||
"runtime": cfg.runtime,
|
||||
"backend": cfg.backend,
|
||||
"endpoint": cfg.endpoint_url,
|
||||
"models": cfg.models.iter().map(|m| json!({
|
||||
"name": m.name, "adapter": m.adapter, "url": m.url, "model_id": m.model_id
|
||||
})).collect::<Vec<_>>(),
|
||||
"limits": { "memory": cfg.limits.memory, "cpus": cfg.limits.cpus },
|
||||
"system_prompt": crate::agent::SYSTEM_PROMPT,
|
||||
"tool_output_chars": crate::agent::MAX_TOOL_OUTPUT_CHARS,
|
||||
@ -255,12 +266,22 @@ enum JobResult {
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// Baut den Modell-Client für das gewählte Backend.
|
||||
pub fn make_client(cfg: &RunConfig, model: &str) -> Result<Box<dyn ModelClient>, String> {
|
||||
match cfg.backend.as_str() {
|
||||
"ollama" => Ok(Box::new(OllamaClient::new(&cfg.endpoint_url, model)?)),
|
||||
"openai" => Ok(Box::new(OpenAiClient::new(&cfg.endpoint_url, model, cfg.api_key.clone())?)),
|
||||
other => Err(format!("Unbekanntes Backend: {other} (erlaubt: ollama, openai)")),
|
||||
/// Baut den Modell-Client für den Adapter des Modells.
|
||||
pub fn make_client(cfg: &RunConfig, name: &str) -> Result<Box<dyn ModelClient>, String> {
|
||||
let conn = cfg
|
||||
.models
|
||||
.iter()
|
||||
.find(|m| m.name == name)
|
||||
.ok_or_else(|| format!("Modell {name:?} ist nicht angebunden."))?;
|
||||
client_for(conn)
|
||||
}
|
||||
|
||||
/// Baut den Client für eine Verbindung, je nach Adapter.
|
||||
pub fn client_for(conn: &ModelConn) -> Result<Box<dyn ModelClient>, String> {
|
||||
match conn.adapter.as_str() {
|
||||
"ollama" => Ok(Box::new(OllamaClient::new(&conn.url, &conn.model_id)?)),
|
||||
"openai" => Ok(Box::new(OpenAiClient::new(&conn.url, &conn.model_id, conn.api_key.clone())?)),
|
||||
other => Err(format!("Unbekannter Adapter: {other} (erlaubt: ollama, openai)")),
|
||||
}
|
||||
}
|
||||
|
||||
@ -456,9 +477,13 @@ mod tests {
|
||||
let jobs = plan(&[model.clone()], &tasks, 2);
|
||||
let cfg = RunConfig {
|
||||
runtime: "podman".into(),
|
||||
backend: "ollama".into(),
|
||||
endpoint_url: url,
|
||||
api_key: None,
|
||||
models: vec![ModelConn {
|
||||
name: model.clone(),
|
||||
adapter: "ollama".into(),
|
||||
url,
|
||||
model_id: model.clone(),
|
||||
api_key: None,
|
||||
}],
|
||||
data_dir: base.join("data"),
|
||||
limits: Limits::default(),
|
||||
};
|
||||
@ -507,9 +532,13 @@ mod tests {
|
||||
let jobs = plan(&[model.clone()], &tasks, 1);
|
||||
let cfg = RunConfig {
|
||||
runtime: "podman".into(),
|
||||
backend,
|
||||
endpoint_url: url,
|
||||
api_key,
|
||||
models: vec![ModelConn {
|
||||
name: model.clone(),
|
||||
adapter: backend,
|
||||
url,
|
||||
model_id: model.clone(),
|
||||
api_key,
|
||||
}],
|
||||
data_dir: data.clone(),
|
||||
limits: Limits::default(),
|
||||
};
|
||||
|
||||
@ -50,6 +50,18 @@ CREATE TABLE IF NOT EXISTS step (
|
||||
";
|
||||
|
||||
/// Ein abgeschlossener Lauf, so wie er gespeichert wird.
|
||||
/// Ein Batch in der Übersicht.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct BatchInfo {
|
||||
pub id: i64,
|
||||
pub created_at: String,
|
||||
pub note: String,
|
||||
pub repeats: u32,
|
||||
pub runs: i64,
|
||||
/// Modellnamen, durch Komma getrennt.
|
||||
pub models: String,
|
||||
}
|
||||
|
||||
/// Ein Schritt eines Laufs, für die Anzeige.
|
||||
#[derive(Debug, Clone, PartialEq, Serialize)]
|
||||
pub struct StepRow {
|
||||
@ -260,6 +272,32 @@ impl Store {
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Alle Batches, neueste zuerst.
|
||||
pub fn list_batches(&self) -> Result<Vec<BatchInfo>, String> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare(
|
||||
"SELECT b.id, b.created_at, b.note, b.repeats, COUNT(r.id),
|
||||
COALESCE(group_concat(DISTINCT r.model), '')
|
||||
FROM batch b LEFT JOIN run r ON r.batch_id = b.id
|
||||
GROUP BY b.id ORDER BY b.id DESC",
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let rows = stmt
|
||||
.query_map([], |r| {
|
||||
Ok(BatchInfo {
|
||||
id: r.get(0)?,
|
||||
created_at: r.get(1)?,
|
||||
note: r.get(2)?,
|
||||
repeats: r.get(3)?,
|
||||
runs: r.get(4)?,
|
||||
models: r.get(5)?,
|
||||
})
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
rows.collect::<Result<Vec<_>, _>>().map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
pub fn run_count(&self, batch_id: i64) -> Result<i64, String> {
|
||||
self.conn
|
||||
.query_row("SELECT COUNT(*) FROM run WHERE batch_id = ?1", params![batch_id], |r| r.get(0))
|
||||
@ -357,6 +395,21 @@ mod tests {
|
||||
assert!(s.steps_for_run(b, "m1", "a-01", 2).unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batches_werden_mit_laeufen_und_modellen_aufgelistet() {
|
||||
let mut s = Store::open_in_memory().unwrap();
|
||||
let b1 = s.create_batch("erster", 1, "{}").unwrap();
|
||||
let b2 = s.create_batch("zweiter", 2, "{}").unwrap();
|
||||
s.insert_run(&rec(b1, "m1", "a-01", 1), &[]).unwrap();
|
||||
s.insert_run(&rec(b1, "m2", "a-01", 1), &[]).unwrap();
|
||||
let list = s.list_batches().unwrap();
|
||||
assert_eq!(list.len(), 2);
|
||||
assert_eq!(list[0].id, b2, "neuester zuerst");
|
||||
assert_eq!(list[0].runs, 0);
|
||||
assert_eq!(list[1].runs, 2);
|
||||
assert!(list[1].models.contains("m1") && list[1].models.contains("m2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbekannter_batch_existiert_nicht() {
|
||||
let s = Store::open_in_memory().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user