feat: OpenAI-kompatibler Modell-Client für strata

Backend in config.toml wählbar (ollama oder openai), Standard-URL für
strata im LAN (192.168.12.4:8082). Nachrichten werden ins OpenAI-Format
umgeschrieben, Tool-Antworten bekommen die passende tool_call_id. Test
für die Umwandlung grün (42 Unit-Tests). Verbindung zu strata noch nicht
möglich: alle drei Adressen lehnen ab.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-06 21:06:29 +01:00
parent 49e543360b
commit f35b68ae1f
4 changed files with 232 additions and 5 deletions

View File

@ -553,6 +553,174 @@ impl ModelClient for OllamaClient {
} }
} }
/// Modell über einen OpenAI-kompatiblen Endpunkt (`/v1/chat/completions`), z. B. strata.
/// Die internen Nachrichten werden ins OpenAI-Format umgeschrieben: Argumente als Text,
/// jeder Tool-Call mit ID, Tool-Antworten mit passender `tool_call_id`.
pub struct OpenAiClient {
pub url: String,
pub model: String,
http: reqwest::blocking::Client,
}
#[derive(Deserialize)]
struct OpenAiResponse {
choices: Vec<OpenAiChoice>,
#[serde(default)]
usage: Option<OpenAiUsage>,
}
#[derive(Deserialize)]
struct OpenAiChoice {
message: OpenAiMessage,
}
#[derive(Deserialize)]
struct OpenAiMessage {
#[serde(default)]
content: Option<String>,
#[serde(default)]
tool_calls: Vec<OpenAiToolCall>,
}
#[derive(Deserialize)]
struct OpenAiToolCall {
function: OpenAiFunction,
}
#[derive(Deserialize)]
struct OpenAiFunction {
name: String,
#[serde(default)]
arguments: String,
}
#[derive(Deserialize)]
struct OpenAiUsage {
#[serde(default)]
prompt_tokens: u32,
#[serde(default)]
completion_tokens: u32,
}
/// Wandelt den Verlauf ins OpenAI-Format um. Jeder Tool-Call bekommt eine ID; eine
/// Tool-Antwort erhält die ID des nächsten offenen Calls mit gleichem Namen.
pub fn to_openai_messages(messages: &[Message]) -> Vec<Value> {
let mut out = Vec::new();
// Offene Calls: (id, name)
let mut open: Vec<(String, String)> = Vec::new();
let mut counter = 0usize;
for m in messages {
match m.role.as_str() {
"assistant" if !m.tool_calls.is_empty() => {
let mut calls = Vec::new();
for c in &m.tool_calls {
counter += 1;
let id = format!("call_{counter}");
let args = match &c.function.arguments {
Value::String(s) => s.clone(),
other => other.to_string(),
};
calls.push(json!({
"id": id,
"type": "function",
"function": { "name": c.function.name, "arguments": args }
}));
open.push((id, c.function.name.clone()));
}
out.push(json!({ "role": "assistant", "content": m.content, "tool_calls": calls }));
}
"tool" => {
let name = m.tool_name.clone().unwrap_or_default();
let id = match open.iter().position(|(_, n)| *n == name) {
Some(i) => open.remove(i).0,
None => format!("call_orphan_{counter}"),
};
out.push(json!({ "role": "tool", "tool_call_id": id, "content": m.content }));
}
role => out.push(json!({ "role": role, "content": m.content })),
}
}
out
}
impl OpenAiClient {
pub fn new(url: &str, model: &str) -> 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(),
model: model.into(),
http,
})
}
}
impl ModelClient for OpenAiClient {
fn chat(&self, messages: &[Message], tools: &Value, timeout: Duration)
-> Result<ChatResponse, ModelError>
{
let body = json!({
"model": self.model,
"messages": to_openai_messages(messages),
"tools": tools,
"stream": false,
"temperature": 0,
});
let resp = self
.http
.post(&self.url)
.timeout(timeout)
.json(&body)
.send()
.map_err(|e| {
if e.is_timeout() {
ModelError::Timeout
} else {
ModelError::Endpoint(e.to_string())
}
})?;
if !resp.status().is_success() {
let status = resp.status();
let text = resp.text().unwrap_or_default();
return Err(ModelError::Endpoint(format!("HTTP {status}: {text}")));
}
let parsed: OpenAiResponse = resp
.json()
.map_err(|e| ModelError::Endpoint(format!("Antwort nicht lesbar: {e}")))?;
let choice = parsed
.choices
.into_iter()
.next()
.ok_or_else(|| ModelError::Endpoint("Antwort ohne choices".into()))?;
let tool_calls = choice
.message
.tool_calls
.into_iter()
.map(|c| {
// Argumente kommen als JSON-Text. Ungültiges JSON bleibt als Text,
// der Agent meldet es dann als invalid_tool_json.
let arguments = serde_json::from_str::<Value>(&c.function.arguments)
.unwrap_or(Value::String(c.function.arguments.clone()));
ToolCall {
function: FunctionCall { name: c.function.name, arguments },
}
})
.collect();
let usage = parsed.usage.unwrap_or(OpenAiUsage { prompt_tokens: 0, completion_tokens: 0 });
Ok(ChatResponse {
message: Message {
role: "assistant".into(),
content: choice.message.content.unwrap_or_default(),
tool_calls,
tool_name: None,
},
prompt_tokens: usage.prompt_tokens,
completion_tokens: usage.completion_tokens,
})
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -816,6 +984,35 @@ Rufe danach das Werkzeug done auf.";
assert_eq!(content.trim(), "hallo", "out.txt: {content:?}"); assert_eq!(content.trim(), "hallo", "out.txt: {content:?}");
} }
#[test]
fn openai_format_ordnet_tool_antworten_zu() {
let msgs = vec![
Message::new("system", "s"),
Message::new("user", "u"),
Message {
role: "assistant".into(),
content: String::new(),
tool_calls: vec![ToolCall {
function: FunctionCall { name: "read_file".into(), arguments: json!({"path": "a"}) },
}],
tool_name: None,
},
Message {
role: "tool".into(),
content: "inhalt".into(),
tool_calls: vec![],
tool_name: Some("read_file".into()),
},
];
let out = to_openai_messages(&msgs);
assert_eq!(out.len(), 4);
let call = &out[2]["tool_calls"][0];
assert_eq!(call["type"], "function");
assert_eq!(call["function"]["arguments"], "{\"path\":\"a\"}");
assert_eq!(out[3]["role"], "tool");
assert_eq!(out[3]["tool_call_id"], call["id"]);
}
#[test] #[test]
fn sh_quote_maskiert_apostrophe() { fn sh_quote_maskiert_apostrophe() {
assert_eq!(sh_quote("a'b"), "'a'\\''b'"); assert_eq!(sh_quote("a'b"), "'a'\\''b'");

View File

@ -21,8 +21,12 @@ pub struct Config {
pub tasks_dir: Option<PathBuf>, pub tasks_dir: Option<PathBuf>,
/// Container-Programm für die Sandbox (Podman-CLI). /// Container-Programm für die Sandbox (Podman-CLI).
pub container_runtime: String, pub container_runtime: String,
/// Modell-Backend: `ollama` oder `openai` (OpenAI-kompatibel, z. B. strata).
pub backend: String,
/// Ollama-Endpunkt für alle Modelle (Phase 1). /// Ollama-Endpunkt für alle Modelle (Phase 1).
pub ollama_url: String, pub ollama_url: String,
/// OpenAI-kompatibler Endpunkt, vollständige URL inkl. `/v1/chat/completions`.
pub openai_url: String,
/// Speicherlimit pro Lauf, Podman-Schreibweise. /// Speicherlimit pro Lauf, Podman-Schreibweise.
pub sandbox_memory: String, pub sandbox_memory: String,
/// CPU-Anteil pro Lauf. /// CPU-Anteil pro Lauf.
@ -36,7 +40,9 @@ impl Default for Config {
data_dir: None, data_dir: None,
tasks_dir: None, tasks_dir: None,
container_runtime: "podman".into(), container_runtime: "podman".into(),
backend: "ollama".into(),
ollama_url: "http://127.0.0.1:11434".into(), ollama_url: "http://127.0.0.1:11434".into(),
openai_url: "http://192.168.12.4:8082/v1/chat/completions".into(),
sandbox_memory: limits.memory, sandbox_memory: limits.memory,
sandbox_cpus: limits.cpus, sandbox_cpus: limits.cpus,
} }
@ -57,6 +63,15 @@ impl Config {
toml::from_str(text).map_err(|e| format!("config.toml ist ungültig: {e}")) 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. /// Ressourcenlimits der Sandbox aus der Konfiguration.
pub fn sandbox_limits(&self) -> Limits { pub fn sandbox_limits(&self) -> Limits {
Limits { Limits {

View File

@ -73,7 +73,8 @@ async fn start_batch(
let jobs = runner::plan(&models, &selected, repeats); let jobs = runner::plan(&models, &selected, repeats);
let run_cfg = RunConfig { let run_cfg = RunConfig {
runtime: cfg.container_runtime.clone(), runtime: cfg.container_runtime.clone(),
endpoint_url: cfg.ollama_url.clone(), backend: cfg.backend.clone(),
endpoint_url: cfg.endpoint_url(),
data_dir: paths.0.data_dir.clone(), data_dir: paths.0.data_dir.clone(),
limits: cfg.sandbox_limits(), limits: cfg.sandbox_limits(),
}; };

View File

@ -7,7 +7,7 @@
use crate::agent::{ use crate::agent::{
run_agent_cancellable, AgentLimits, ErrorClass, Message, ModelClient, ModelError, run_agent_cancellable, AgentLimits, ErrorClass, Message, ModelClient, ModelError,
OllamaClient, SandboxWorkspace, OllamaClient, OpenAiClient, SandboxWorkspace,
}; };
use crate::sandbox::{container_name, remove_by_name, Limits, Sandbox}; use crate::sandbox::{container_name, remove_by_name, Limits, Sandbox};
use crate::store::{RunRecord, Store}; use crate::store::{RunRecord, Store};
@ -33,6 +33,8 @@ pub struct Job {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RunConfig { pub struct RunConfig {
pub runtime: String, pub runtime: String,
/// `ollama` oder `openai`.
pub backend: String,
pub endpoint_url: String, pub endpoint_url: String,
pub data_dir: PathBuf, pub data_dir: PathBuf,
pub limits: Limits, pub limits: Limits,
@ -119,6 +121,7 @@ pub fn run_batch(
) -> Result<BatchSummary, String> { ) -> Result<BatchSummary, String> {
let config_json = json!({ let config_json = json!({
"runtime": cfg.runtime, "runtime": cfg.runtime,
"backend": cfg.backend,
"endpoint": cfg.endpoint_url, "endpoint": cfg.endpoint_url,
"limits": { "memory": cfg.limits.memory, "cpus": cfg.limits.cpus }, "limits": { "memory": cfg.limits.memory, "cpus": cfg.limits.cpus },
"system_prompt": crate::agent::SYSTEM_PROMPT, "system_prompt": crate::agent::SYSTEM_PROMPT,
@ -150,7 +153,7 @@ pub fn run_batch(
} }
'models: for model in &models { 'models: for model in &models {
let client = OllamaClient::new(&cfg.endpoint_url, model)?; let client = make_client(cfg, model)?;
let warm = client.chat( let warm = client.chat(
&[Message::new("user", "ping")], &[Message::new("user", "ping")],
&json!([]), &json!([]),
@ -211,7 +214,7 @@ pub fn run_batch(
}, },
transcript: vec![], transcript: vec![],
}, },
None => match execute_job(cfg, batch_id, i, job, &client, cancel)? { None => match execute_job(cfg, batch_id, i, job, &*client, cancel)? {
JobResult::Cancelled => { JobResult::Cancelled => {
summary.cancelled = true; summary.cancelled = true;
break 'models; break 'models;
@ -250,12 +253,21 @@ enum JobResult {
Cancelled, 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)?)),
other => Err(format!("Unbekanntes Backend: {other} (erlaubt: ollama, openai)")),
}
}
fn execute_job( fn execute_job(
cfg: &RunConfig, cfg: &RunConfig,
batch_id: i64, batch_id: i64,
seq: usize, seq: usize,
job: &Job, job: &Job,
client: &OllamaClient, client: &dyn ModelClient,
cancel: &AtomicBool, cancel: &AtomicBool,
) -> Result<JobResult, String> { ) -> Result<JobResult, String> {
let meta = &job.task.meta; let meta = &job.task.meta;
@ -442,6 +454,7 @@ mod tests {
let jobs = plan(&[model.clone()], &tasks, 2); let jobs = plan(&[model.clone()], &tasks, 2);
let cfg = RunConfig { let cfg = RunConfig {
runtime: "podman".into(), runtime: "podman".into(),
backend: "ollama".into(),
endpoint_url: url, endpoint_url: url,
data_dir: base.join("data"), data_dir: base.join("data"),
limits: Limits::default(), limits: Limits::default(),
@ -484,6 +497,7 @@ mod tests {
let jobs = plan(&[model.clone()], &tasks, 1); let jobs = plan(&[model.clone()], &tasks, 1);
let cfg = RunConfig { let cfg = RunConfig {
runtime: "podman".into(), runtime: "podman".into(),
backend: "ollama".into(),
endpoint_url: url, endpoint_url: url,
data_dir: data.clone(), data_dir: data.clone(),
limits: Limits::default(), limits: Limits::default(),