Merge pull request 'OpenAI-compatible provider' (#138) from openai-compat-provider into main

This commit was merged in pull request #138.
This commit is contained in:
hermes committed 2026-10-07 08:29:24 +00:00
commit 1952cb41c3
6 files changed
+617 -10

No files matched your search

+14 -4
View File
@@ -19,6 +19,8 @@ use tokio::sync::Mutex;
pub enum Kind { pub enum Kind {
Claude, Claude,
Codex, Codex,
/// OpenAI-compatible endpoint from config; no OAuth.
Custom,
} }
impl std::str::FromStr for Kind { impl std::str::FromStr for Kind {
@@ -27,7 +29,8 @@ impl std::str::FromStr for Kind {
match s { match s {
"claude" | "anthropic" => Ok(Kind::Claude), "claude" | "anthropic" => Ok(Kind::Claude),
"codex" | "openai" | "chatgpt" => Ok(Kind::Codex), "codex" | "openai" | "chatgpt" => Ok(Kind::Codex),
_ => Err(format!("unknown provider {s:?} (claude|codex)")), "custom" | "openai-compat" | "local" => Ok(Kind::Custom),
_ => Err(format!("unknown provider {s:?} (claude|codex|custom)")),
} }
} }
} }
@@ -76,6 +79,7 @@ fn cfg(k: Kind) -> &'static Oauth {
match k { match k {
Kind::Claude => &CLAUDE, Kind::Claude => &CLAUDE,
Kind::Codex => &CODEX, Kind::Codex => &CODEX,
Kind::Custom => unreachable!("custom provider has no OAuth"),
} }
} }
@@ -137,6 +141,7 @@ fn save_at(p: &std::path::Path, k: Kind, c: Option<&Credential>) -> Result<()> {
/// Pull an existing login from Claude Code / Codex CLI. /// Pull an existing login from Claude Code / Codex CLI.
fn import(k: Kind) -> Option<Credential> { fn import(k: Kind) -> Option<Credential> {
match k { match k {
Kind::Custom => None,
Kind::Claude => { Kind::Claude => {
let v: Value = serde_json::from_slice( let v: Value = serde_json::from_slice(
&std::fs::read(home().join(".claude/.credentials.json")).ok()?, &std::fs::read(home().join(".claude/.credentials.json")).ok()?,
@@ -211,7 +216,7 @@ async fn token_req(k: Kind, form: &[(&str, &str)]) -> Result<Credential> {
// Anthropic wants JSON, OpenAI wants form encoding. // Anthropic wants JSON, OpenAI wants form encoding.
let rb = match k { let rb = match k {
Kind::Claude => rb.json(&form.iter().cloned().collect::<BTreeMap<_, _>>()), Kind::Claude => rb.json(&form.iter().cloned().collect::<BTreeMap<_, _>>()),
Kind::Codex => rb.form(form), Kind::Codex | Kind::Custom => rb.form(form),
}; };
let r = rb.send().await.map_err(|e| Error::Http(e.to_string()))?; let r = rb.send().await.map_err(|e| Error::Http(e.to_string()))?;
let status = r.status().as_u16(); let status = r.status().as_u16();
@@ -368,7 +373,7 @@ pub fn authorize_url(k: Kind, challenge: &str, state: &str) -> String {
]; ];
match k { match k {
Kind::Claude => p.insert(0, ("code", "true")), Kind::Claude => p.insert(0, ("code", "true")),
Kind::Codex => p.extend([ Kind::Codex | Kind::Custom => p.extend([
("id_token_add_organizations", "true"), ("id_token_add_organizations", "true"),
("codex_cli_simplified_flow", "true"), ("codex_cli_simplified_flow", "true"),
("originator", "hx"), ("originator", "hx"),
@@ -383,12 +388,17 @@ pub fn authorize_url(k: Kind, challenge: &str, state: &str) -> String {
/// Interactive browser login. Prints the URL to stderr. /// Interactive browser login. Prints the URL to stderr.
pub async fn login(k: Kind) -> Result<Credential> { pub async fn login(k: Kind) -> Result<Credential> {
if k == Kind::Custom {
return Err(Error::Http(
"custom provider has no login: set [openai_compat] in config.toml".into(),
));
}
let c = cfg(k); let c = cfg(k);
let (verifier, challenge) = pkce(); let (verifier, challenge) = pkce();
// Claude uses the verifier as state (matches Claude Code); Codex uses a random state. // Claude uses the verifier as state (matches Claude Code); Codex uses a random state.
let state = match k { let state = match k {
Kind::Claude => verifier.clone(), Kind::Claude => verifier.clone(),
Kind::Codex => pkce().0, Kind::Codex | Kind::Custom => pkce().0,
}; };
eprintln!( eprintln!(
"Open this URL to log in:\n\n{}\n\nWaiting for redirect on {} (or paste the final redirect URL / code here):", "Open this URL to log in:\n\n{}\n\nWaiting for redirect on {} (or paste the final redirect URL / code here):",
+3 -1
View File
@@ -4,6 +4,7 @@ pub mod anthropic;
pub mod auth; pub mod auth;
pub mod codex; pub mod codex;
pub mod models; pub mod models;
pub mod openai_compat;
use futures::stream::BoxStream; use futures::stream::BoxStream;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -157,13 +158,14 @@ impl Effort {
match k { match k {
auth::Kind::Claude => Effort::Off, auth::Kind::Claude => Effort::Off,
auth::Kind::Codex => Effort::Medium, auth::Kind::Codex => Effort::Medium,
auth::Kind::Custom => Effort::Off,
} }
} }
/// Levels the provider supports (Codex models can't switch reasoning off). /// Levels the provider supports (Codex models can't switch reasoning off).
pub fn levels(k: auth::Kind) -> &'static [Effort] { pub fn levels(k: auth::Kind) -> &'static [Effort] {
match k { match k {
auth::Kind::Claude => &Self::ALL, auth::Kind::Claude | auth::Kind::Custom => &Self::ALL,
auth::Kind::Codex => &Self::ALL[1..], auth::Kind::Codex => &Self::ALL[1..],
} }
} }
+7 -2
View File
@@ -35,6 +35,7 @@ pub fn fallback(k: Kind) -> Vec<ModelInfo> {
m("gpt-5.6-terra", 1_050_000), m("gpt-5.6-terra", 1_050_000),
m("gpt-5.6-luna", 1_050_000), m("gpt-5.6-luna", 1_050_000),
], ],
Kind::Custom => vec![],
} }
} }
@@ -43,11 +44,12 @@ pub fn default_for(k: Kind, models: &[ModelInfo]) -> String {
let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect(); let mine: Vec<&ModelInfo> = models.iter().filter(|m| m.kind == k).collect();
let pick = match k { let pick = match k {
Kind::Claude => mine.iter().find(|m| m.id.contains("sonnet")), Kind::Claude => mine.iter().find(|m| m.id.contains("sonnet")),
Kind::Codex => None, Kind::Codex | Kind::Custom => None,
}; };
pick.or(mine.first()) pick.or(mine.first())
.map(|m| m.id.clone()) .map(|m| m.id.clone())
.unwrap_or_else(|| fallback(k)[0].id.clone()) .or_else(|| fallback(k).first().map(|m| m.id.clone()))
.unwrap_or_default()
} }
/// Cheapest known tier of a provider (Haiku / Luna), for read-only subagents. /// Cheapest known tier of a provider (Haiku / Luna), for read-only subagents.
@@ -55,6 +57,7 @@ pub fn cheap_for(k: Kind, models: &[ModelInfo]) -> Option<String> {
let tag = match k { let tag = match k {
Kind::Claude => "haiku", Kind::Claude => "haiku",
Kind::Codex => "luna", Kind::Codex => "luna",
Kind::Custom => return None,
}; };
models models
.iter() .iter()
@@ -151,6 +154,8 @@ pub async fn load_with(
refresh: bool, refresh: bool,
) -> (Vec<ModelInfo>, Source) { ) -> (Vec<ModelInfo>, Source) {
let cached = read_cache(k); let cached = read_cache(k);
// custom endpoints are cheap to ask and their config changes by hand: never serve the cache first
let refresh = refresh || k == Kind::Custom;
if let Some(c) = cached if let Some(c) = cached
.as_ref() .as_ref()
.filter(|c| !refresh && now().saturating_sub(c.fetched) < CACHE_SECS) .filter(|c| !refresh && now().saturating_sub(c.fetched) < CACHE_SECS)
+553
View File
@@ -0,0 +1,553 @@
//! 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`.
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 {
pub fn new(cfg: Config) -> Result<Self> {
if cfg.base_url.is_empty() {
return Err(Error::Http("[openai_compat] needs base_url".into()));
}
let key = match &cfg.api_key_env {
Some(n) => Some(
std::env::var(n)
.map_err(|_| Error::Http(format!("env var {n} (api_key_env) is not set")))?,
),
None => None,
};
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()
})
.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 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]);
}
}
+37 -2
View File
@@ -91,6 +91,8 @@ struct Config {
provider: Option<Kind>, provider: Option<Kind>,
model: Option<String>, model: Option<String>,
claude_model: Option<String>, claude_model: Option<String>,
/// OpenAI-compatible endpoint (Ollama, vLLM, LM Studio, OpenRouter, ...), provider "custom".
openai_compat: Option<hx_ai::openai_compat::Config>,
codex_model: Option<String>, codex_model: Option<String>,
/// Auto-compact threshold in estimated tokens. /// Auto-compact threshold in estimated tokens.
compact_at: Option<usize>, compact_at: Option<usize>,
@@ -143,6 +145,7 @@ impl Config {
provider: o.provider.or(c.provider), provider: o.provider.or(c.provider),
model: o.model.or(c.model), model: o.model.or(c.model),
claude_model: o.claude_model.or(c.claude_model), claude_model: o.claude_model.or(c.claude_model),
openai_compat: o.openai_compat.or(c.openai_compat),
codex_model: o.codex_model.or(c.codex_model), codex_model: o.codex_model.or(c.codex_model),
compact_at: o.compact_at.or(c.compact_at), compact_at: o.compact_at.or(c.compact_at),
max_tokens: o.max_tokens.or(c.max_tokens), max_tokens: o.max_tokens.or(c.max_tokens),
@@ -201,9 +204,12 @@ fn command_specs(
/// Providers with stored or importable credentials. /// Providers with stored or importable credentials.
fn logged_in() -> Vec<Kind> { fn logged_in() -> Vec<Kind> {
[Kind::Claude, Kind::Codex] [Kind::Claude, Kind::Codex, Kind::Custom]
.into_iter() .into_iter()
.filter(|k| hx_ai::auth::Auth::load(*k).is_ok()) .filter(|k| match k {
Kind::Custom => COMPAT.get().is_some(),
k => hx_ai::auth::Auth::load(*k).is_ok(),
})
.collect() .collect()
} }
@@ -267,6 +273,9 @@ fn pricing(model: &str) -> Option<hx_ai::Pricing> {
}) })
} }
/// `[openai_compat]` from config, set once at startup.
static COMPAT: std::sync::OnceLock<hx_ai::openai_compat::Config> = std::sync::OnceLock::new();
fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> { fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
Ok(match k { Ok(match k {
Kind::Claude => { Kind::Claude => {
@@ -276,6 +285,17 @@ fn provider(k: Kind) -> hx_ai::Result<Arc<dyn Provider>> {
Err(_) => a, Err(_) => a,
}) })
} }
Kind::Custom => {
let cfg = COMPAT
.get()
.cloned()
.ok_or_else(|| hx_ai::Error::Http("no [openai_compat] in config.toml".into()))?;
let c = hx_ai::openai_compat::OpenAiCompat::new(cfg)?;
Arc::new(match std::env::var("HX_BASE_URL") {
Ok(u) => c.with_base_url(u),
Err(_) => c,
})
}
Kind::Codex => { Kind::Codex => {
let c = Codex::login_default()?; let c = Codex::login_default()?;
Arc::new(match std::env::var("HX_BASE_URL") { Arc::new(match std::env::var("HX_BASE_URL") {
@@ -344,6 +364,11 @@ async fn main() -> Result<()> {
return Ok(()); return Ok(());
} }
Some(Cmd::Models { refresh }) => { Some(Cmd::Models { refresh }) => {
if let Ok(cfg) = Config::load(&std::env::current_dir()?)
&& let Some(oc) = cfg.openai_compat
{
let _ = COMPAT.set(oc);
}
print_models(refresh).await; print_models(refresh).await;
return Ok(()); return Ok(());
} }
@@ -482,6 +507,9 @@ async fn main() -> Result<()> {
} }
let cwd = std::env::current_dir()?; let cwd = std::env::current_dir()?;
let cfg = Config::load(&cwd)?; let cfg = Config::load(&cwd)?;
if let Some(oc) = cfg.openai_compat.clone() {
let _ = COMPAT.set(oc);
}
let kinds = logged_in(); let kinds = logged_in();
let last_path = context::hx_home().join("last.json"); let last_path = context::hx_home().join("last.json");
let remember = cfg.remember_model != Some(false); let remember = cfg.remember_model != Some(false);
@@ -511,6 +539,7 @@ async fn main() -> Result<()> {
match kind { match kind {
Kind::Claude => cfg.claude_model.clone(), Kind::Claude => cfg.claude_model.clone(),
Kind::Codex => cfg.codex_model.clone(), Kind::Codex => cfg.codex_model.clone(),
Kind::Custom => None,
} }
.unwrap_or_else(|| hx_ai::models::default_for(kind, &models)) .unwrap_or_else(|| hx_ai::models::default_for(kind, &models))
}); });
@@ -847,6 +876,12 @@ mod tests {
assert_eq!(c.provider, Some(Kind::Codex)); assert_eq!(c.provider, Some(Kind::Codex));
assert_eq!(c.codex_model.as_deref(), Some("gpt-5")); assert_eq!(c.codex_model.as_deref(), Some("gpt-5"));
assert!(toml::from_str::<Config>("typo = 1").is_err()); assert!(toml::from_str::<Config>("typo = 1").is_err());
let c: Config = toml::from_str(
"provider = \"custom\"\n[openai_compat]\nbase_url = \"http://x/v1\"\nmodels = [\"q\"]",
)
.unwrap();
assert_eq!(c.provider, Some(Kind::Custom));
assert_eq!(c.openai_compat.unwrap().models, ["q"]);
assert!(pricing("claude-sonnet-4-5").is_some() && pricing("mystery").is_none()); assert!(pricing("claude-sonnet-4-5").is_some() && pricing("mystery").is_none());
assert_eq!(pricing("claude-sonnet-5-5").unwrap().input, 2.0); assert_eq!(pricing("claude-sonnet-5-5").unwrap().input, 2.0);
assert_eq!(pricing("gpt-5.6-terra").unwrap().input, 2.5); assert_eq!(pricing("gpt-5.6-terra").unwrap().input, 2.5);
+3 -1
View File
@@ -236,7 +236,9 @@ mod tests {
} }
} }
let l = lines(&v, None, 0, 60); let l = lines(&v, None, 0, 60);
assert!(text(&l[0]).starts_with(" ⠋ 1 explore ") && text(&l[0]).ends_with(" 1m12s 8c 41k")); assert!(
text(&l[0]).starts_with(" ⠋ 1 explore ") && text(&l[0]).ends_with(" 1m12s 8c 41k")
);
assert!(text(&l[1]).starts_with(" ✓ 2 explore "), "{}", text(&l[1])); assert!(text(&l[1]).starts_with(" ✓ 2 explore "), "{}", text(&l[1]));
assert!(text(&l[0]).contains('…')); assert!(text(&l[0]).contains('…'));
} }