Ollama Cloud: Schlüssel als Bearer im Ollama-Adapter, Modellauswahl aus der Server-Liste mit Filter, Vorlagen für Ollama Cloud und OpenRouter
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@ -65,7 +65,7 @@ Zeichen: ✓ fertig · ◐ teilweise · ✗ offen · ? nicht geprüft.
|
||||
- [#1030] **OpenAI-kompatibler Endpunkt.** Adapter und Auswahl je Modell sind gebaut (vorgezogen nach 0.1.0, siehe #1041). Offen: Anthropic-kompatibler Adapter, GPU Dispatcher prüfen. → #1013
|
||||
- [#1048] **Echte Tempo-Messung.** Antworten streamen, Zeit bis zum ersten Token und reine Erzeugungsgeschwindigkeit messen. Heute ist Tok/s Tokens geteilt durch die ganze Laufzeit inklusive Tool- und Prüfzeit. → #1006
|
||||
- [#1049] **Batches vergleichen.** Zwei Batches nebeneinander (gleiches Modell vor und nach Wechsel, Aufgabenmenge und Wiederholungen sichtbar). → #1009
|
||||
- [#1050] **Ollama-Modelle direkt anlegen.** Aus der Modell-Liste des Servers per Klick Modelle als Einträge übernehmen, statt die ID zu wählen. → #1008
|
||||
- [#1050] **Ollama-Modelle direkt anlegen.** Teilweise erledigt am 09.11.2026: In den Einstellungen wählt man das Modell aus der Liste des Servers (Filter, auch für OpenRouter mit rund 460 Modellen), und es gibt Vorlagen für Ollama lokal, Ollama Cloud, OpenRouter. Der Ollama-Adapter schickt jetzt den Schlüssel als Bearer-Token (vorher nur der OpenAI-Adapter). Offen: mehrere Modelle auf einmal aus der Liste als Einträge übernehmen. Klicktests fehlen noch. → #1008
|
||||
- [#1055] **Harness-Adapter (Pi, OpenCode).** Das Harness wird eine Auswahl neben dem eigenen von coding-bench: Jedes Ergebnis gehört zu einem Harness, verglichen wird nur innerhalb eines Harness. Die App startet Pi oder OpenCode headless in einem Arbeitsordner und prüft danach wie beim Import (#1053). Vorab ein kleiner Versuch: dieselben zwei Aufgaben mit einem lokalen Modell im eigenen Harness und in Pi, um den Harness-Effekt zu sehen. Offen zu klären: Netz für das Modell im Container, welche Messdaten das Harness liefert, Nutzungsbedingungen für Abo-Zugänge. Blocker: #1053 (Import) muss geprüft sein. → #1052
|
||||
- [#1031] **Export.** JSON und eigenständiger HTML-Report. → #1014
|
||||
|
||||
|
||||
@ -498,6 +498,8 @@ fn first_line(stderr: &str, code: Option<i32>) -> String {
|
||||
pub struct OllamaClient {
|
||||
pub base_url: String,
|
||||
pub model: String,
|
||||
/// Schlüssel für Ollama Cloud (`https://ollama.com`), als Bearer-Token. Lokale Server brauchen keinen.
|
||||
api_key: Option<String>,
|
||||
http: reqwest::blocking::Client,
|
||||
}
|
||||
|
||||
@ -511,13 +513,14 @@ struct OllamaResponse {
|
||||
}
|
||||
|
||||
impl OllamaClient {
|
||||
pub fn new(base_url: &str, model: &str) -> Result<OllamaClient, String> {
|
||||
pub fn new(base_url: &str, model: &str, api_key: Option<String>) -> Result<OllamaClient, String> {
|
||||
let http = reqwest::blocking::Client::builder()
|
||||
.build()
|
||||
.map_err(|e| format!("HTTP-Client nicht baubar: {e}"))?;
|
||||
Ok(OllamaClient {
|
||||
base_url: base_url.trim_end_matches('/').into(),
|
||||
model: model.into(),
|
||||
api_key,
|
||||
http,
|
||||
})
|
||||
}
|
||||
@ -534,11 +537,11 @@ impl ModelClient for OllamaClient {
|
||||
"stream": false,
|
||||
"options": { "temperature": 0 },
|
||||
});
|
||||
let resp = self
|
||||
.http
|
||||
.post(format!("{}/api/chat", self.base_url))
|
||||
.timeout(timeout)
|
||||
.json(&body)
|
||||
let mut req = self.http.post(format!("{}/api/chat", self.base_url)).timeout(timeout).json(&body);
|
||||
if let Some(key) = &self.api_key {
|
||||
req = req.bearer_auth(key);
|
||||
}
|
||||
let resp = req
|
||||
.send()
|
||||
.map_err(|e| {
|
||||
if e.is_timeout() {
|
||||
@ -993,7 +996,7 @@ mod tests {
|
||||
let name = container_name(&format!("ollama-{}", std::process::id()));
|
||||
let sb = Sandbox::start("podman", &name, &image, &Limits::default(), None).expect("Start");
|
||||
let ws = SandboxWorkspace { sandbox: &sb };
|
||||
let client = OllamaClient::new(&url, &model).unwrap();
|
||||
let client = OllamaClient::new(&url, &model, None).unwrap();
|
||||
let lim = AgentLimits { max_steps: 10, timeout: Duration::from_secs(600) };
|
||||
|
||||
let prompt = "Erstelle die Datei out.txt mit dem Inhalt hallo (ohne Zeilenumbruch). \
|
||||
@ -1053,4 +1056,64 @@ Rufe danach das Werkzeug done auf.";
|
||||
fn sh_quote_maskiert_apostrophe() {
|
||||
assert_eq!(sh_quote("a'b"), "'a'\\''b'");
|
||||
}
|
||||
|
||||
/// Mini-Server, der genau eine Anfrage entgegennimmt, die Kopfzeilen merkt und eine Ollama-Antwort schickt.
|
||||
fn one_shot_server() -> (String, std::sync::mpsc::Receiver<String>) {
|
||||
use std::io::{Read, Write};
|
||||
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
||||
let url = format!("http://{}", listener.local_addr().unwrap());
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
let (mut conn, _) = listener.accept().unwrap();
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 1024];
|
||||
// Kopfzeilen und Body lesen (Content-Length ist klein).
|
||||
loop {
|
||||
let n = conn.read(&mut chunk).unwrap();
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
let text = String::from_utf8_lossy(&buf).to_string();
|
||||
if let Some(pos) = text.find("\r\n\r\n") {
|
||||
let len = text[..pos]
|
||||
.lines()
|
||||
.find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap_or(0)))
|
||||
.unwrap_or(0);
|
||||
if buf.len() >= pos + 4 + len {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let _ = tx.send(String::from_utf8_lossy(&buf).to_string());
|
||||
let body = r#"{"message":{"role":"assistant","content":"ok"},"prompt_eval_count":1,"eval_count":1}"#;
|
||||
let _ = write!(
|
||||
conn,
|
||||
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
|
||||
body.len(),
|
||||
body
|
||||
);
|
||||
});
|
||||
(url, rx)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_cloud_schluessel_wird_als_bearer_gesendet() {
|
||||
let (url, rx) = one_shot_server();
|
||||
let client = OllamaClient::new(&url, "gpt-oss:120b", Some("geheim-123".into())).unwrap();
|
||||
let r = client.chat(&[Message::new("user", "hi")], &json!([]), Duration::from_secs(10)).unwrap();
|
||||
assert_eq!(r.message.content, "ok");
|
||||
let req = rx.recv().unwrap().to_ascii_lowercase();
|
||||
assert!(req.contains("authorization: bearer geheim-123"), "{req}");
|
||||
assert!(req.starts_with("post /api/chat"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ollama_lokal_sendet_keinen_schluessel() {
|
||||
let (url, rx) = one_shot_server();
|
||||
let client = OllamaClient::new(&url, "qwen3:0.6b", None).unwrap();
|
||||
client.chat(&[Message::new("user", "hi")], &json!([]), Duration::from_secs(10)).unwrap();
|
||||
let req = rx.recv().unwrap().to_ascii_lowercase();
|
||||
assert!(!req.contains("authorization:"), "{req}");
|
||||
}
|
||||
}
|
||||
|
||||
@ -295,7 +295,7 @@ pub fn make_client(cfg: &RunConfig, name: &str) -> Result<Box<dyn ModelClient>,
|
||||
/// 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)?)),
|
||||
"ollama" => Ok(Box::new(OllamaClient::new(&conn.url, &conn.model_id, conn.api_key.clone())?)),
|
||||
"openai" => Ok(Box::new(OpenAiClient::new(&conn.url, &conn.model_id, conn.api_key.clone())?)),
|
||||
other => Err(format!("Unbekannter Adapter: {other} (erlaubt: ollama, openai)")),
|
||||
}
|
||||
|
||||
@ -24,8 +24,8 @@
|
||||
} = $props();
|
||||
|
||||
const ADAPTERS = [
|
||||
{ id: "ollama", label: "Ollama", hint: "http://host:11434" },
|
||||
{ id: "openai", label: "OpenAI-kompatibel", hint: "http://host:8082/v1" },
|
||||
{ id: "ollama", label: "Ollama", hint: "http://host:11434 oder https://ollama.com" },
|
||||
{ id: "openai", label: "OpenAI-kompatibel", hint: "http://host:8082/v1 oder https://openrouter.ai/api/v1" },
|
||||
];
|
||||
|
||||
function toEntry(m: ModelInfo): ModelEntry {
|
||||
@ -45,10 +45,44 @@
|
||||
saveError = "";
|
||||
}
|
||||
|
||||
function addModel() {
|
||||
draft.push({ name: "", adapter: "ollama", url: "", model: "", api_key_env: "" });
|
||||
open = [...open, draft.length - 1];
|
||||
// Vorlagen für häufige Anbieter. Der Schlüssel bleibt eine Umgebungsvariable.
|
||||
const PRESETS: Record<string, ModelEntry> = {
|
||||
ollama: { name: "Ollama lokal", adapter: "ollama", url: "http://127.0.0.1:11434", model: "", api_key_env: "" },
|
||||
ollamacloud: { name: "Ollama Cloud", adapter: "ollama", url: "https://ollama.com", model: "", api_key_env: "OLLAMA_API_KEY" },
|
||||
openrouter: { name: "OpenRouter", adapter: "openai", url: "https://openrouter.ai/api/v1", model: "", api_key_env: "OPENROUTER_API_KEY" },
|
||||
openai: { name: "OpenAI-kompatibel", adapter: "openai", url: "", model: "", api_key_env: "" },
|
||||
};
|
||||
|
||||
function addModel(preset = "ollama") {
|
||||
draft.push({ ...PRESETS[preset] });
|
||||
const i = draft.length - 1;
|
||||
open = [...open, i];
|
||||
markDirty();
|
||||
if (draft[i].url) check(i);
|
||||
}
|
||||
|
||||
// Modellauswahl aus der Liste des Servers.
|
||||
let picking = $state<number | null>(null);
|
||||
let filter = $state("");
|
||||
const SHOW_MAX = 60;
|
||||
|
||||
function pickList(i: number): string[] {
|
||||
const all = reach[i]?.models ?? [];
|
||||
const f = filter.trim().toLowerCase();
|
||||
return f ? all.filter((n) => n.toLowerCase().includes(f)) : all;
|
||||
}
|
||||
|
||||
function choose(i: number, name: string) {
|
||||
draft[i].model = name;
|
||||
picking = null;
|
||||
filter = "";
|
||||
markDirty();
|
||||
}
|
||||
|
||||
async function startPick(i: number) {
|
||||
picking = picking === i ? null : i;
|
||||
filter = "";
|
||||
if (picking === i && !reach[i]?.models.length) await check(i);
|
||||
}
|
||||
|
||||
function removeModel(i: number) {
|
||||
@ -248,24 +282,45 @@
|
||||
</label>
|
||||
<label>
|
||||
Modell-ID beim Server
|
||||
<input
|
||||
bind:value={m.model}
|
||||
oninput={markDirty}
|
||||
list={`models-${i}`}
|
||||
placeholder={r?.models.length ? "aus der Liste wählen oder leer = Name" : "leer = Name"}
|
||||
/>
|
||||
<datalist id={`models-${i}`}>
|
||||
{#each r?.models ?? [] as name (name)}<option value={name}></option>{/each}
|
||||
</datalist>
|
||||
<span class="idrow">
|
||||
<input bind:value={m.model} oninput={markDirty} placeholder="leer = Name" />
|
||||
<button type="button" onclick={() => startPick(i)}>{picking === i ? "Liste schließen" : "Aus Liste wählen"}</button>
|
||||
</span>
|
||||
</label>
|
||||
<label>
|
||||
Schlüssel-Variable
|
||||
<input bind:value={m.api_key_env} oninput={markDirty} placeholder="leer = kein Schlüssel" />
|
||||
</label>
|
||||
</div>
|
||||
{#if r?.state === "fehler"}<p class="error small">{r.message}</p>{/if}
|
||||
{#if r?.state === "ok" && r.models.length > 0}
|
||||
<p class="muted small">Beim Server verfügbar: {r.models.slice(0, 8).join(", ")}{r.models.length > 8 ? " …" : ""}</p>
|
||||
{#if picking === i}
|
||||
<div class="picker">
|
||||
{#if r?.state === "prüft"}
|
||||
<p class="muted small">Frage den Server …</p>
|
||||
{:else if r?.state === "fehler"}
|
||||
<p class="error small">{r.message}</p>
|
||||
{:else}
|
||||
<input bind:value={filter} placeholder="Filtern, z. B. qwen oder gpt-oss ({r?.models.length ?? 0} Modelle)" />
|
||||
{@const list = pickList(i)}
|
||||
<ul>
|
||||
{#each list.slice(0, SHOW_MAX) as name (name)}
|
||||
<li><button type="button" class:sel={name === m.model} onclick={() => choose(i, name)}>{name}</button></li>
|
||||
{/each}
|
||||
</ul>
|
||||
{#if list.length > SHOW_MAX}
|
||||
<p class="muted small">{list.length - SHOW_MAX} weitere. Filter eingrenzen.</p>
|
||||
{:else if list.length === 0}
|
||||
<p class="muted small">Kein Treffer.</p>
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
{:else if r?.state === "fehler"}
|
||||
<p class="error small">{r.message}</p>
|
||||
{/if}
|
||||
{#if m.api_key_env && savedInfo(m.name) && !savedInfo(m.name)?.api_key_set}
|
||||
<p class="muted small">
|
||||
Die App sieht nur Umgebungsvariablen, die beim Start gesetzt waren. Starte sie aus einem Terminal, in dem
|
||||
<code>{m.api_key_env}</code> gesetzt ist, oder trage sie in <code>~/.config/environment.d/</code> ein und melde dich neu an.
|
||||
</p>
|
||||
{/if}
|
||||
<div class="row">
|
||||
{#if m.api_key_env && savedInfo(m.name)}
|
||||
@ -300,7 +355,11 @@
|
||||
{/each}
|
||||
|
||||
<div class="row">
|
||||
<button onclick={addModel}>Modell hinzufügen</button>
|
||||
<span class="muted small">Hinzufügen:</span>
|
||||
<button onclick={() => addModel("ollama")}>Ollama lokal</button>
|
||||
<button onclick={() => addModel("ollamacloud")}>Ollama Cloud</button>
|
||||
<button onclick={() => addModel("openrouter")}>OpenRouter</button>
|
||||
<button onclick={() => addModel("openai")}>Anderer OpenAI-Server</button>
|
||||
<span class="spacer"></span>
|
||||
{#if saveError}<span class="error">{saveError}</span>{/if}
|
||||
{#if dirty}<span class="muted">Ungespeicherte Änderungen</span>{/if}
|
||||
@ -392,6 +451,46 @@
|
||||
.mhead:hover:not(:disabled) {
|
||||
border-color: transparent;
|
||||
}
|
||||
.idrow {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.idrow input {
|
||||
flex: 1;
|
||||
}
|
||||
.picker {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
background: var(--bg);
|
||||
padding: 0.6rem;
|
||||
margin-top: 0.6rem;
|
||||
}
|
||||
.picker ul {
|
||||
list-style: none;
|
||||
margin: 0.5rem 0 0;
|
||||
padding: 0;
|
||||
max-height: 14rem;
|
||||
overflow-y: auto;
|
||||
display: grid;
|
||||
gap: 0.15rem;
|
||||
}
|
||||
.picker li button {
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
border: none;
|
||||
background: none;
|
||||
padding: 0.3rem 0.5rem;
|
||||
font-family: ui-monospace, Menlo, monospace;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.picker li button:hover,
|
||||
.picker li button.sel {
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
.picker > input {
|
||||
width: 100%;
|
||||
color: var(--text);
|
||||
}
|
||||
.chev {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user