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:
2026-11-09 11:40:07 +01:00
parent a4eac68c58
commit 36f29e7848
4 changed files with 189 additions and 27 deletions

View File

@ -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}");
}
}

View File

@ -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)")),
}