Files
hx/crates/hx-ai/src/openai_compat.rs
T

582 lines
21 KiB
Rust

//! OpenAI-compatible Chat Completions (Ollama, vLLM, LM Studio, llama.cpp, OpenRouter, ...).
//!
//! No OAuth: the endpoint comes from `[openai_compat]` in config.toml, an optional bearer key
//! from the env var named by `api_key_env`, else the key saved by `hx login custom`.
use crate::auth::Kind;
use crate::models::ModelInfo;
use crate::{
ContentBlock, Effort, Error, Message, Provider, Request, Result, Role, StopReason, StreamEvent,
Usage,
};
use eventsource_stream::Eventsource;
use futures::{StreamExt, stream::BoxStream};
use serde::Deserialize;
use serde_json::{Value, json};
const DEFAULT_WINDOW: u64 = 128_000;
#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
/// e.g. `http://localhost:11434/v1`
pub base_url: String,
/// Name of the env var holding the API key (the key itself never goes in the config).
pub api_key_env: Option<String>,
/// Fixed model list; empty = ask `GET {base_url}/models`.
pub models: Vec<String>,
/// Context window for models that don't report one (default 128k).
pub context_window: Option<u64>,
}
pub struct OpenAiCompat {
cfg: Config,
key: Option<String>,
http: reqwest::Client,
}
impl OpenAiCompat {
/// Key: the `api_key_env` variable if set, else `stored` (from `hx login custom`), else none.
pub fn new(cfg: Config, stored: Option<String>) -> Result<Self> {
if cfg.base_url.is_empty() {
return Err(Error::Http("[openai_compat] needs base_url".into()));
}
let env = cfg.api_key_env.as_ref().and_then(|n| std::env::var(n).ok());
if let (None, None, Some(n)) = (&env, &stored, &cfg.api_key_env) {
return Err(Error::Http(format!(
"env var {n} (api_key_env) is not set; or run `hx login custom`"
)));
}
let key = env.or(stored);
Ok(Self {
cfg,
key,
http: reqwest::Client::new(),
})
}
pub fn with_base_url(mut self, u: impl Into<String>) -> Self {
self.cfg.base_url = u.into();
self
}
fn url(&self, path: &str) -> String {
format!("{}/{path}", self.cfg.base_url.trim_end_matches('/'))
}
fn req(&self, rb: reqwest::RequestBuilder) -> reqwest::RequestBuilder {
match &self.key {
Some(k) => rb.bearer_auth(k),
None => rb,
}
}
}
pub fn body(req: &Request, reasoning: bool) -> Value {
let mut messages = vec![];
if !req.system.is_empty() {
messages.push(json!({"role": "system", "content": req.system}));
}
for m in &req.messages {
match m.role {
Role::User => {
// tool results first: they must directly follow the assistant's tool_calls
for b in &m.content {
if let ContentBlock::ToolResult {
tool_use_id,
content,
..
} = b
{
messages.push(
json!({"role": "tool", "tool_call_id": tool_use_id, "content": content}),
);
}
}
let parts: Vec<Value> = m
.content
.iter()
.filter_map(|b| match b {
ContentBlock::Text { text } => Some(json!({"type": "text", "text": text})),
ContentBlock::Image { media_type, data } => Some(json!({
"type": "image_url",
"image_url": {"url": format!("data:{media_type};base64,{data}")}
})),
_ => None,
})
.collect();
if parts.iter().all(|p| p["type"] == "text") && !parts.is_empty() {
// plain string: widest server support
let t: String = parts.iter().filter_map(|p| p["text"].as_str()).collect();
messages.push(json!({"role": "user", "content": t}));
} else if !parts.is_empty() {
messages.push(json!({"role": "user", "content": parts}));
}
}
Role::Assistant => {
let calls: Vec<Value> = m
.content
.iter()
.filter_map(|b| match b {
ContentBlock::ToolUse { id, name, input } => Some(json!({
"id": id, "type": "function",
"function": {"name": name, "arguments": input.to_string()}
})),
_ => None,
})
.collect();
let mut a = json!({"role": "assistant", "content": m.text()});
if !calls.is_empty() {
a["tool_calls"] = calls.into();
}
messages.push(a);
}
}
}
let mut b = json!({
"model": req.model,
"messages": messages,
"stream": true,
"stream_options": {"include_usage": true},
"max_tokens": req.max_tokens,
});
if !req.tools.is_empty() {
b["tools"] = req
.tools
.iter()
.map(|t| {
json!({"type": "function", "function": {
"name": t.name, "description": t.description, "parameters": t.input_schema}})
})
.collect::<Vec<_>>()
.into();
}
if reasoning && req.effort != Effort::Off {
b["reasoning_effort"] = req.effort.name().into();
}
b
}
/// Folds Chat Completions SSE chunks into `StreamEvent`s.
#[derive(Default)]
pub struct Assembler {
text: String,
/// (id, name, raw arguments, start emitted) per tool call index
calls: Vec<(String, String, String, bool)>,
usage: Usage,
finish: Option<String>,
done: bool,
/// a stream error happened: no `Done` for a partial message
pub dead: bool,
}
impl Assembler {
pub fn feed(&mut self, data: &str) -> Result<Vec<StreamEvent>> {
if self.done || self.dead {
return Ok(vec![]);
}
if data.trim() == "[DONE]" {
return Ok(vec![self.finish()]);
}
let d: Value =
serde_json::from_str(data).map_err(|e| Error::Decode(format!("{e}: {data}")))?;
if let Some(e) = d.get("error").filter(|e| !e.is_null()) {
return Err(Error::Api {
status: 0,
body: e.to_string(),
});
}
let mut out = vec![];
let u = &d["usage"];
if u.is_object() {
let n = |v: &Value| v.as_u64().unwrap_or(0);
let cached = n(&u["prompt_tokens_details"]["cached_tokens"]);
self.usage.input_tokens = n(&u["prompt_tokens"]).saturating_sub(cached);
self.usage.cache_read_tokens = cached;
self.usage.output_tokens = n(&u["completion_tokens"]);
}
let c = &d["choices"][0];
let dl = &c["delta"];
if let Some(t) = dl["content"].as_str().filter(|t| !t.is_empty()) {
self.text.push_str(t);
out.push(StreamEvent::TextDelta { text: t.into() });
}
// DeepSeek/vLLM: reasoning_content; OpenRouter/others: reasoning
if let Some(t) = dl["reasoning_content"]
.as_str()
.or_else(|| dl["reasoning"].as_str())
.filter(|t| !t.is_empty())
{
out.push(StreamEvent::ThinkingDelta { text: t.into() });
}
for (i, tc) in dl["tool_calls"]
.as_array()
.into_iter()
.flatten()
.enumerate()
{
let idx = tc["index"].as_u64().unwrap_or(i as u64) as usize;
while self.calls.len() <= idx {
let n = self.calls.len();
self.calls
.push((format!("call_{n}"), String::new(), String::new(), false));
}
let call = &mut self.calls[idx];
if let Some(id) = tc["id"].as_str().filter(|s| !s.is_empty()) {
call.0 = id.into();
}
if let Some(n) = tc["function"]["name"].as_str() {
call.1.push_str(n);
}
if let Some(a) = tc["function"]["arguments"].as_str() {
call.2.push_str(a);
}
if !call.3 && !call.1.is_empty() {
call.3 = true;
out.push(StreamEvent::ToolUseStart {
id: call.0.clone(),
name: call.1.clone(),
});
}
}
if let Some(f) = c["finish_reason"].as_str() {
self.finish = Some(f.into());
}
Ok(out)
}
fn finish(&mut self) -> StreamEvent {
self.done = true;
let mut content = vec![];
if !self.text.is_empty() {
content.push(ContentBlock::Text {
text: std::mem::take(&mut self.text),
});
}
for (id, name, args, _) in std::mem::take(&mut self.calls) {
// ponytail: unparseable arguments are passed on as {"_invalid_arguments": raw} so the
// tool rejects them and the model sees the error and retries; no repair attempted
let input = if args.trim().is_empty() {
json!({})
} else {
serde_json::from_str(&args).unwrap_or_else(|_| json!({"_invalid_arguments": args}))
};
content.push(ContentBlock::ToolUse { id, name, input });
}
let tools = content
.iter()
.any(|b| matches!(b, ContentBlock::ToolUse { .. }));
let stop = match self.finish.as_deref() {
_ if tools => StopReason::ToolUse,
Some("stop") | None => StopReason::EndTurn,
Some("length") => StopReason::MaxTokens,
_ => StopReason::Other,
};
StreamEvent::Done {
message: Message {
role: Role::Assistant,
content,
},
stop,
usage: std::mem::take(&mut self.usage),
}
}
}
/// `/models` body to catalog entries; the window comes from whatever field the server offers.
pub fn parse_models(v: &Value, default_window: u64) -> Vec<ModelInfo> {
v["data"]
.as_array()
.into_iter()
.flatten()
.filter_map(|m| {
Some(ModelInfo {
id: m["id"].as_str()?.into(),
kind: Kind::Custom,
context_window: ["context_length", "max_model_len", "context_window"]
.iter()
.find_map(|k| m[*k].as_u64().filter(|n| *n > 0))
.unwrap_or(default_window),
})
})
.collect()
}
#[async_trait::async_trait]
impl Provider for OpenAiCompat {
async fn models(&self) -> Result<Vec<ModelInfo>> {
let w = self.cfg.context_window.unwrap_or(DEFAULT_WINDOW);
if !self.cfg.models.is_empty() {
return Ok(self
.cfg
.models
.iter()
.map(|id| ModelInfo {
id: id.clone(),
kind: Kind::Custom,
context_window: w,
})
.collect());
}
let v: Value = self
.req(self.http.get(self.url("models")))
.send()
.await
.map_err(|e| Error::Http(e.to_string()))?
.error_for_status()
.map_err(|e| Error::Http(e.to_string()))?
.json()
.await
.map_err(|e| Error::Decode(e.to_string()))?;
Ok(parse_models(&v, w))
}
async fn stream(&self, req: Request) -> Result<BoxStream<'static, Result<StreamEvent>>> {
let mut reasoning = true;
let r = loop {
let r = self
.req(self.http.post(self.url("chat/completions")))
.json(&body(&req, reasoning))
.send()
.await
.map_err(|e| Error::Http(e.to_string()))?;
let status = r.status().as_u16();
if (200..300).contains(&status) {
break r;
}
let text = r.text().await.unwrap_or_default();
// not every server knows reasoning_effort: retry once without it
if status == 400 && reasoning && req.effort != Effort::Off && text.contains("reasoning")
{
reasoning = false;
continue;
}
return Err(Error::Api { status, body: text });
};
let s = r
.bytes_stream()
.eventsource()
.map(|ev| ev.map(|e| e.data).map_err(|e| Error::Http(e.to_string())))
// servers that close without [DONE] still get their Done
.chain(futures::stream::once(futures::future::ready(Ok(
"[DONE]".to_string()
))))
.scan(Assembler::default(), |a, ev| {
let out = match ev.and_then(|d| a.feed(&d)) {
Ok(v) => v.into_iter().map(Ok).collect(),
Err(e) => {
a.dead = true;
vec![Err(e)]
}
};
futures::future::ready(Some(futures::stream::iter(out)))
})
.flatten();
Ok(s.boxed())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ToolSpec;
fn req() -> Request {
Request {
model: "m".into(),
system: "sys".into(),
messages: vec![
Message::user("hi"),
Message {
role: Role::Assistant,
content: vec![
ContentBlock::Thinking {
thinking: "hmm".into(),
signature: None,
},
ContentBlock::Text { text: "ok".into() },
ContentBlock::ToolUse {
id: "t1".into(),
name: "read".into(),
input: json!({"path": "a"}),
},
],
},
Message {
role: Role::User,
content: vec![
ContentBlock::ToolResult {
tool_use_id: "t1".into(),
content: "file".into(),
is_error: false,
},
ContentBlock::Image {
media_type: "image/png".into(),
data: "QQ==".into(),
},
],
},
],
tools: vec![ToolSpec {
name: "read".into(),
description: "d".into(),
input_schema: json!({"type": "object"}),
}],
max_tokens: 100,
effort: Effort::High,
}
}
#[test]
fn maps_request() {
let b = body(&req(), true);
let m = b["messages"].as_array().unwrap();
let roles: Vec<_> = m.iter().map(|x| x["role"].as_str().unwrap()).collect();
assert_eq!(roles, ["system", "user", "assistant", "tool", "user"]);
assert_eq!(m[1]["content"], "hi");
assert_eq!(m[2]["content"], "ok", "thinking dropped");
assert_eq!(
m[2]["tool_calls"][0]["function"]["arguments"],
"{\"path\":\"a\"}"
);
assert_eq!(m[3]["tool_call_id"], "t1");
assert_eq!(
m[4]["content"][0]["image_url"]["url"],
"data:image/png;base64,QQ=="
);
assert_eq!(b["tools"][0]["function"]["name"], "read");
assert_eq!(b["reasoning_effort"], "high");
assert!(body(&req(), false).get("reasoning_effort").is_none());
}
#[test]
fn assembles_stream() {
let chunks = [
r#"{"choices":[{"delta":{"reasoning_content":"th"}}]}"#,
r#"{"choices":[{"delta":{"content":"He"}}]}"#,
r#"{"choices":[{"delta":{"content":"llo"}}]}"#,
r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"id":"a","function":{"name":"read","arguments":"{\"pa"}}]}}]}"#,
r#"{"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"th\":\"x\"}"}},{"index":1,"id":"b","function":{"name":"bad","arguments":"{oops"}}]}}]}"#,
r#"{"choices":[{"delta":{},"finish_reason":"tool_calls"}]}"#,
r#"{"choices":[],"usage":{"prompt_tokens":10,"completion_tokens":5,"prompt_tokens_details":{"cached_tokens":4}}}"#,
"[DONE]",
"[DONE]",
];
let mut a = Assembler::default();
let ev: Vec<_> = chunks.iter().flat_map(|c| a.feed(c).unwrap()).collect();
let starts = ev
.iter()
.filter(|e| matches!(e, StreamEvent::ToolUseStart { .. }))
.count();
assert_eq!(starts, 2);
let dones: Vec<_> = ev
.iter()
.filter_map(|e| match e {
StreamEvent::Done {
message,
stop,
usage,
} => Some((message, stop, usage)),
_ => None,
})
.collect();
assert_eq!(dones.len(), 1, "one Done despite repeated [DONE]");
let (m, stop, u) = dones[0];
assert_eq!(*stop, StopReason::ToolUse);
assert_eq!(
(u.input_tokens, u.cache_read_tokens, u.output_tokens),
(6, 4, 5)
);
assert_eq!(m.text(), "Hello");
assert_eq!(
m.content[1],
ContentBlock::ToolUse {
id: "a".into(),
name: "read".into(),
input: json!({"path": "x"})
}
);
assert!(matches!(&m.content[2], ContentBlock::ToolUse { input, .. }
if input["_invalid_arguments"] == "{oops"));
}
/// Real HTTP round trip against a one-shot local server.
#[tokio::test]
async fn streams_over_http() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = l.local_addr().unwrap().port();
tokio::spawn(async move {
for _ in 0..2 {
let (mut s, _) = l.accept().await.unwrap();
let mut buf = vec![0; 65536];
let n = s.read(&mut buf).await.unwrap();
let head = String::from_utf8_lossy(&buf[..n]).to_string();
let (ct, body) = if head.starts_with("GET /v1/models") {
(
"application/json",
r#"{"data":[{"id":"m1","context_length":4096}]}"#.to_string(),
)
} else {
assert!(head.starts_with("POST /v1/chat/completions"));
("text/event-stream", "data: {\"choices\":[{\"delta\":{\"content\":\"yo\"},\"finish_reason\":\"stop\"}]}\n\n".to_string())
};
let r = format!(
"HTTP/1.1 200 OK\r\ncontent-type: {ct}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
s.write_all(r.as_bytes()).await.unwrap();
}
});
let p = OpenAiCompat::new(
Config {
base_url: format!("http://127.0.0.1:{port}/v1/"),
..Default::default()
},
None,
)
.unwrap();
let ms = p.models().await.unwrap();
assert_eq!((ms[0].id.as_str(), ms[0].context_window), ("m1", 4096));
let ev: Vec<_> = p.stream(req()).await.unwrap().collect().await;
let last = ev.last().unwrap().as_ref().unwrap();
assert!(
matches!(last, StreamEvent::Done { message, stop: StopReason::EndTurn, .. } if message.text() == "yo")
);
}
#[test]
fn key_precedence() {
let cfg = |env: Option<&str>| Config {
base_url: "http://x".into(),
api_key_env: env.map(Into::into),
..Default::default()
};
let key = |c, s: Option<&str>| OpenAiCompat::new(c, s.map(Into::into)).map(|p| p.key);
assert_eq!(key(cfg(None), None).unwrap(), None);
assert_eq!(key(cfg(None), Some("s")).unwrap().as_deref(), Some("s"));
assert_eq!(
key(cfg(Some("PATH")), Some("s")).unwrap().as_deref(),
Some(std::env::var("PATH").unwrap().as_str()),
"env wins"
);
assert_eq!(
key(cfg(Some("HX_NOPE_UNSET")), Some("s"))
.unwrap()
.as_deref(),
Some("s")
);
assert!(key(cfg(Some("HX_NOPE_UNSET")), None).is_err());
}
#[test]
fn parses_models() {
let v = json!({"data": [
{"id": "a", "context_length": 32000},
{"id": "b", "max_model_len": 8192},
{"id": "c"}]});
let w: Vec<_> = parse_models(&v, 128_000)
.iter()
.map(|m| m.context_window)
.collect();
assert_eq!(w, [32_000, 8_192, 128_000]);
}
}