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)]
mod tests {
use super::*;
@ -816,6 +984,35 @@ Rufe danach das Werkzeug done auf.";
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]
fn sh_quote_maskiert_apostrophe() {
assert_eq!(sh_quote("a'b"), "'a'\\''b'");