use crate::config::ProviderConfig;
use crate::error::{Error, HttpFailure, ProviderFailure, Result};
use crate::hooks::ToolChoice;
use crate::message::{Message, Role};
use crate::stream::{DeltaFn, SseParser, StreamAccumulator};
use crate::tools::ToolSpec;
use crate::usage::TurnUsage;
use async_trait::async_trait;
use serde_json::{json, Value};
use std::fmt;
use std::time::Duration;
#[async_trait]
pub trait ChatProvider: Send + Sync {
async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message>;
async fn chat_stream(
&self,
messages: &[Message],
tools: &[ToolSpec],
on_delta: DeltaFn<'_>,
) -> Result<Message> {
let _ = on_delta;
self.chat(messages, tools).await
}
async fn chat_stream_patched(
&self,
messages: &[Message],
tools: &[ToolSpec],
on_delta: DeltaFn<'_>,
patch: &crate::hooks::RequestPatch,
) -> Result<Message> {
if !patch.is_empty() {
return Err(Error::provider(format!(
"this provider cannot apply a request patch ({} set); use an \
OpenAI-compatible provider, or a hook that only observes",
patch.describe()
)));
}
self.chat_stream(messages, tools, on_delta).await
}
fn take_usage(&self) -> Option<TurnUsage> {
None
}
fn can_see(&self) -> bool {
false
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RequestOptions {
pub top_p: Option<f64>,
pub seed: Option<i64>,
pub stop: Option<Vec<String>>,
pub parallel_tool_calls: Option<bool>,
pub tool_choice: Option<ToolChoice>,
pub extra_body: Value,
}
impl RequestOptions {
fn applied_keys(&self) -> Vec<&'static str> {
let mut keys = Vec::new();
if self.top_p.is_some() {
keys.push("top_p");
}
if self.seed.is_some() {
keys.push("seed");
}
if self.stop.is_some() {
keys.push("stop");
}
if self.parallel_tool_calls.is_some() {
keys.push("parallel_tool_calls");
}
if self.tool_choice.is_some() {
keys.push("tool_choice");
}
keys
}
}
pub struct OpenAiProvider {
client: reqwest::Client,
url: String,
api_key: Option<String>,
model: String,
temperature: Option<f64>,
max_tokens: Option<u32>,
options: RequestOptions,
profile: ProviderProfile,
can_see: bool,
reasoning: Reasoning,
dial: crate::reasoning::Shared,
stream: bool,
max_retries: u32,
retry_after_send: bool,
retry_base_delay: Duration,
idle: Duration,
last_usage: std::sync::Mutex<Option<TurnUsage>>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct ProviderProfile {
pub name: String,
pub tool_choice: bool,
pub stream_usage: bool,
pub max_tokens_field: Option<String>,
pub supports_tools: bool,
pub send_reasoning: bool,
pub body: serde_json::Value,
pub reasoning: Option<crate::reasoning::Policy>,
pub models: std::collections::BTreeMap<String, ModelReasoning>,
pub request: RequestPolicy,
pub vision: Option<bool>,
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RequestPolicy {
pub num_ctx: Option<u32>,
pub num_ctx_field: Option<String>,
pub max_output: Option<u32>,
pub temperature: Option<Temperature>,
pub reject_response_formats: Vec<String>,
pub aux_model: Option<String>,
pub models: std::collections::BTreeMap<String, ModelLimits>,
}
impl RequestPolicy {
pub fn limits_for(&self, model: &str) -> ModelLimits {
let own = self.models.get(model);
ModelLimits {
num_ctx: own.and_then(|m| m.num_ctx).or(self.num_ctx),
max_output: own.and_then(|m| m.max_output).or(self.max_output),
}
}
pub fn rejects_format(&self, kind: &str) -> bool {
self.reject_response_formats
.iter()
.any(|rejected| rejected == kind)
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ModelLimits {
pub num_ctx: Option<u32>,
pub max_output: Option<u32>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Temperature {
#[allow(dead_code)]
Default,
Omit,
Fixed(f32),
}
#[derive(Debug, Clone, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum ModelReasoning {
Toggle(bool),
Policy(crate::reasoning::Policy),
}
impl Default for ProviderProfile {
fn default() -> Self {
Self::builtin("openai").expect("openai is a built-in profile")
}
}
impl ProviderProfile {
fn make(name: &str, tool_choice: bool, stream_usage: bool, body: serde_json::Value) -> Self {
Self {
name: name.into(),
tool_choice,
stream_usage,
max_tokens_field: Some("max_tokens".into()),
supports_tools: true,
send_reasoning: false,
body,
reasoning: None,
models: std::collections::BTreeMap::new(),
request: RequestPolicy::default(),
vision: None,
}
}
pub fn builtin(name: &str) -> Option<Self> {
match name {
"openai" | "" => {
let mut p = Self::make("openai", true, true, json!({}));
p.send_reasoning = true;
p.reasoning = Some(crate::reasoning::Policy::openai());
Some(p)
}
"llamacpp" => {
let mut p = Self::make("llamacpp", false, false, json!({}));
p.reasoning = Some(crate::reasoning::Policy::llamacpp());
Some(p)
}
_ => None,
}
}
pub fn resolve(name: &str, from_plugins: &[ProviderProfile]) -> crate::Result<Self> {
if let Some(p) = from_plugins.iter().find(|p| p.name == name) {
return Ok(p.clone());
}
Self::builtin(name).ok_or_else(|| {
crate::Error::Config(format!(
"unknown provider profile {name:?}; built in: openai, llamacpp, or one a \
plugin declares"
))
})
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Reasoning {
Policy(crate::reasoning::Policy),
Off,
Undeclared,
}
impl Reasoning {
pub fn declared_default(&self) -> Option<&str> {
match self {
Reasoning::Policy(policy) if policy.has_dial() => policy.default_effort(),
Reasoning::Policy(_) | Reasoning::Off | Reasoning::Undeclared => None,
}
}
}
impl ProviderProfile {
pub fn reasoning_for(&self, model: &str) -> Reasoning {
match self.models.get(model) {
Some(ModelReasoning::Toggle(false)) => Reasoning::Off,
Some(ModelReasoning::Toggle(true)) => match &self.reasoning {
Some(policy) => Reasoning::Policy(policy.clone()),
None => Reasoning::Undeclared,
},
Some(ModelReasoning::Policy(policy)) => Reasoning::Policy(policy.clone()),
None => match &self.reasoning {
Some(policy) => Reasoning::Policy(policy.clone()),
None => Reasoning::Undeclared,
},
}
}
}
const MAX_RETRY_AFTER: Duration = Duration::from_secs(30);
fn backoff_delay(base: Duration, retry: u32) -> Duration {
base.saturating_mul(1u32 << (retry - 1).min(16))
}
fn request_id(headers: &reqwest::header::HeaderMap) -> Option<String> {
["x-request-id", "request-id", "x-amzn-requestid", "cf-ray"]
.iter()
.find_map(|name| {
let value = headers.get(*name)?.to_str().ok()?.trim();
(!value.is_empty()).then(|| value.to_string())
})
}
fn mentions_field(haystack: &str, field: &str) -> bool {
let bytes = haystack.as_bytes();
haystack.match_indices(field).any(|(i, _)| {
let before_ok = i == 0 || !is_word_byte(bytes[i - 1]);
let after = i + field.len();
let after_ok = after >= bytes.len() || !is_word_byte(bytes[after]);
before_ok && after_ok
})
}
fn is_word_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
fn describe_transport(e: &reqwest::Error) -> String {
let detail = deepest_cause(e);
if e.is_timeout() {
return format!("the request timed out: {detail}");
}
if e.is_connect() {
return format!("the connection could not be established: {detail} — is the server up?");
}
if e.is_body() || e.is_decode() {
return format!("the connection broke while sending or decoding: {detail}");
}
detail
}
fn deepest_cause(e: &dyn std::error::Error) -> String {
let mut source = e.source();
let mut text = e.to_string();
while let Some(inner) = source {
text = inner.to_string();
source = inner.source();
}
text
}
fn with_attempts(failure: ProviderFailure, attempts: u32) -> ProviderFailure {
if attempts <= 1 {
return failure;
}
let note = format!("{attempts} attempts, with backoff");
match failure {
ProviderFailure::Transport { url, message, sent } => ProviderFailure::Transport {
url,
message: format!("{message} ({note})"),
sent,
},
ProviderFailure::Unauthorized(mut h) => {
h.hint = Some(join_hint(h.hint.take(), ¬e));
ProviderFailure::Unauthorized(h)
}
ProviderFailure::InvalidRequest(mut h) => {
h.hint = Some(join_hint(h.hint.take(), ¬e));
ProviderFailure::InvalidRequest(h)
}
ProviderFailure::Http(mut h) => {
h.hint = Some(join_hint(h.hint.take(), ¬e));
ProviderFailure::Http(h)
}
other => other,
}
}
fn join_hint(hint: Option<String>, note: &str) -> String {
match hint {
Some(h) => format!("{h}; {note}"),
None => note.to_string(),
}
}
fn retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
headers
.get(reqwest::header::RETRY_AFTER)?
.to_str()
.ok()?
.trim()
.parse::<u64>()
.ok()
.map(Duration::from_secs)
}
impl fmt::Debug for OpenAiProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("OpenAiProvider")
.field("url", &self.url)
.field("model", &self.model)
.finish_non_exhaustive()
}
}
impl OpenAiProvider {
pub fn new(cfg: &ProviderConfig) -> Result<Self> {
Self::with_dial(cfg, &[], None)
}
pub fn with_dial(
cfg: &ProviderConfig,
from_plugins: &[ProviderProfile],
dial: Option<crate::reasoning::Shared>,
) -> Result<Self> {
Self::build(cfg, from_plugins, dial)
}
pub fn with_profiles(cfg: &ProviderConfig, from_plugins: &[ProviderProfile]) -> Result<Self> {
Self::build(cfg, from_plugins, None)
}
fn build(
cfg: &ProviderConfig,
from_plugins: &[ProviderProfile],
dial: Option<crate::reasoning::Shared>,
) -> Result<Self> {
let base = cfg.base_url.trim().trim_end_matches('/');
if base.is_empty() {
return Err(Error::Config("provider.base_url is not set".into()));
}
let idle = Duration::from_secs(cfg.timeout_secs.max(1));
let client = reqwest::Client::builder()
.connect_timeout(idle)
.build()
.map_err(|e| Error::provider(format!("could not build an HTTP client: {e}")))?;
let profile =
ProviderProfile::resolve(cfg.profile.as_deref().unwrap_or("openai"), from_plugins)?;
let can_see = cfg.vision.unwrap_or(profile.vision == Some(true));
let options = RequestOptions {
top_p: cfg.top_p,
seed: cfg.seed,
stop: cfg
.stop
.as_ref()
.map(|s| {
s.iter()
.filter(|one| !one.is_empty())
.cloned()
.collect::<Vec<_>>()
})
.filter(|s: &Vec<String>| !s.is_empty()),
parallel_tool_calls: cfg.parallel_tool_calls,
tool_choice: cfg.tool_choice.clone(),
extra_body: cfg.extra_body.clone().unwrap_or(serde_json::Value::Null),
};
if let Some(top_p) = options.top_p {
if !(0.0..=1.0).contains(&top_p) {
return Err(Error::Config(format!(
"provider.top_p must be between 0 and 1, got {top_p}"
)));
}
}
Ok(Self {
client,
url: format!("{base}/chat/completions"),
api_key: cfg.api_key.clone().filter(|k| !k.is_empty()),
model: cfg.model.clone(),
temperature: cfg.temperature,
max_tokens: cfg.max_tokens,
options,
reasoning: profile.reasoning_for(&cfg.model),
dial: dial.unwrap_or_else(|| {
std::sync::Arc::new(crate::reasoning::Dial::new(cfg.reasoning_effort.clone()))
}),
profile,
can_see,
stream: cfg.stream,
max_retries: cfg.max_retries,
retry_after_send: cfg.retry_after_send,
retry_base_delay: Duration::from_millis(cfg.retry_base_delay_ms),
idle,
last_usage: std::sync::Mutex::new(None),
})
}
pub fn profile_name(&self) -> &str {
&self.profile.name
}
pub fn reasoning_effort(&self) -> Option<String> {
self.dial.effort()
}
pub fn reasoning(&self) -> &Reasoning {
&self.reasoning
}
pub fn request_body(&self, messages: &[Message], tools: &[ToolSpec]) -> Value {
self.request_body_with(messages, tools, &crate::hooks::RequestPatch::default())
}
pub fn request_body_with(
&self,
messages: &[Message],
tools: &[ToolSpec],
patch: &crate::hooks::RequestPatch,
) -> Value {
let live_from = messages
.iter()
.rposition(|m| m.role == Role::User)
.unwrap_or(0);
let wire_messages: Vec<Value> = messages
.iter()
.enumerate()
.map(|(i, m)| {
let mut v = serde_json::to_value(m).expect("a message serializes");
if let Some(obj) = v.as_object_mut() {
if !m.images.is_empty() {
obj.remove("images");
match m.wire_content() {
Some(content) => {
obj.insert("content".to_string(), content);
}
None => {
obj.remove("content");
}
}
}
if !self.profile.send_reasoning || i < live_from {
obj.remove("reasoning_content");
}
}
v
})
.collect();
let mut body = json!({"model": self.model, "messages": wire_messages});
if self.profile.supports_tools && !tools.is_empty() {
body["tools"] = json!(tools);
match &self.options.tool_choice {
Some(choice) => body["tool_choice"] = choice.to_json(),
None if self.profile.tool_choice => body["tool_choice"] = json!("auto"),
None => {}
}
}
if let Some(t) = self.temperature {
body["temperature"] = json!(t);
}
if let (Some(max), Some(field)) = (self.max_tokens, &self.profile.max_tokens_field) {
body[field] = json!(max);
}
if let Some(p) = self.options.top_p {
body["top_p"] = json!(p);
}
if let Some(seed) = self.options.seed {
body["seed"] = json!(seed);
}
if let Some(stop) = &self.options.stop {
body["stop"] = json!(stop);
}
let asked = self.reasoning_effort();
match &self.reasoning {
Reasoning::Off => {}
Reasoning::Policy(policy) => {
let wire = policy.resolve_at(asked.as_deref(), Some(&self.url));
if !matches!(wire, crate::reasoning::Wire::Omit(_)) {
merge_json(&mut body, wire.body(policy));
}
}
Reasoning::Undeclared => {
if let Some(level) = asked.as_deref() {
if !crate::reasoning::is_omit(level) {
body["reasoning_effort"] = json!(level);
}
}
}
}
if let Some(parallel) = self.options.parallel_tool_calls {
body["parallel_tool_calls"] = json!(parallel);
}
merge_json(&mut body, self.profile.body.clone());
if !self.options.extra_body.is_null() {
merge_json(&mut body, self.options.extra_body.clone());
}
if let Some(t) = patch.temperature {
body["temperature"] = json!(t);
}
if let (Some(max), Some(field)) = (patch.max_tokens, &self.profile.max_tokens_field) {
body[field] = json!(max);
}
if let Some(choice) = &patch.tool_choice {
if body.get("tools").is_none() {
body["tools"] = json!([]);
}
body["tool_choice"] = choice.to_json();
}
for (key, value) in &patch.extra_params {
body[key.as_str()] = value.clone();
}
self.apply_request_policy(&mut body);
body
}
fn apply_request_policy(&self, body: &mut Value) {
let limits = self.profile.request.limits_for(&self.model);
if let Some(ctx) = limits.num_ctx {
let field = self
.profile
.request
.num_ctx_field
.as_deref()
.unwrap_or("options.num_ctx");
merge_json(body, crate::reasoning::field_path(field, json!(ctx)));
}
if let Some(cap) = limits.max_output {
let field = self
.profile
.max_tokens_field
.clone()
.unwrap_or_else(|| "max_tokens".to_string());
let asked = body.get(&field).and_then(|v| v.as_u64());
let send = match asked {
Some(n) => n.min(u64::from(cap)),
None => u64::from(cap),
};
body[field.as_str()] = json!(send);
}
match self.profile.request.temperature {
Some(Temperature::Omit) => {
if let Some(obj) = body.as_object_mut() {
obj.remove("temperature");
}
}
Some(Temperature::Fixed(value)) => body["temperature"] = json!(value),
Some(Temperature::Default) | None => {}
}
if let Some(kind) = body
.get("response_format")
.and_then(|f| f.get("type"))
.and_then(|t| t.as_str())
.map(str::to_string)
{
if self.profile.request.rejects_format(&kind) {
if let Some(obj) = body.as_object_mut() {
obj.remove("response_format");
}
}
}
}
}
fn merge_json(base: &mut Value, over: Value) {
match (base, over) {
(_, Value::Null) => {}
(Value::Object(base), Value::Object(over)) => {
for (key, value) in over {
match base.get_mut(&key) {
Some(slot) => merge_json(slot, value),
None => {
base.insert(key, value);
}
}
}
}
(slot, over) => *slot = over,
}
}
pub fn parse_response(body: &Value) -> Result<Message> {
let msg = body.pointer("/choices/0/message").ok_or_else(|| {
Error::Provider(ProviderFailure::Response {
message: "the reply has no choices".into(),
body: Some(clip(body)),
})
})?;
let mut m: Message = serde_json::from_value(msg.clone()).map_err(|e| {
Error::Provider(ProviderFailure::Response {
message: format!("the message is not one we can read: {e}"),
body: Some(clip(msg)),
})
})?;
m.role = Role::Assistant;
m.finish_reason = body
.pointer("/choices/0/finish_reason")
.and_then(Value::as_str)
.map(str::to_string);
for (i, call) in m.tool_calls.iter_mut().enumerate() {
if call.id.is_empty() {
call.id = format!("call_{i}");
}
}
Ok(m)
}
fn clip(v: &Value) -> String {
let s = v.to_string();
match s.char_indices().nth(300) {
Some((i, _)) => format!("{}…", &s[..i]),
None => s,
}
}
impl OpenAiProvider {
async fn send(&self, body: &Value) -> Result<reqwest::Response> {
let mut retries = 0u32;
loop {
let mut req = self.client.post(&self.url).json(body);
if let Some(k) = &self.api_key {
req = req.bearer_auth(k);
}
let sent = match tokio::time::timeout(self.idle, req.send()).await {
Ok(sent) => sent,
Err(_) => {
return Err(Error::Provider(ProviderFailure::Transport {
url: self.url.clone(),
message: format!("the endpoint said nothing for {} s", self.idle.as_secs()),
sent: true,
}));
}
};
let failure = match sent {
Ok(resp) if resp.status().is_success() => return Ok(resp),
Ok(resp) => self.classify_http(resp, body).await,
Err(e) => ProviderFailure::Transport {
url: self.url.clone(),
message: describe_transport(&e),
sent: !e.is_connect(),
},
};
match self.wait_before_retry(retries, &failure) {
Some(delay) => {
retries += 1;
tokio::time::sleep(delay).await;
}
None => return Err(Error::Provider(with_attempts(failure, retries + 1))),
}
}
}
fn wait_before_retry(&self, retries: u32, failure: &ProviderFailure) -> Option<Duration> {
let may_repeat = if failure.after_send() {
self.retry_after_send
} else {
failure.is_retryable()
};
if !may_repeat || self.max_retries == 0 || retries >= self.max_retries {
return None;
}
match failure.retry_after_secs().map(Duration::from_secs) {
Some(asked) if asked > MAX_RETRY_AFTER => None,
Some(asked) => Some(asked),
None => Some(backoff_delay(self.retry_base_delay, retries + 1)),
}
}
async fn classify_http(&self, resp: reqwest::Response, sent: &Value) -> ProviderFailure {
let status = resp.status().as_u16();
let request_id = request_id(resp.headers());
let retry_after_secs = retry_after(resp.headers()).map(|d| d.as_secs());
let text = match tokio::time::timeout(self.idle, resp.text()).await {
Ok(Ok(text)) => text,
Ok(Err(_)) | Err(_) => String::new(),
};
let mut failure = HttpFailure {
status,
body: text.chars().take(600).collect(),
request_id,
retry_after_secs,
hint: None,
};
failure.hint = self.explain(status, &failure.body, sent);
match status {
401 | 403 => ProviderFailure::Unauthorized(failure),
400 | 404 | 405 | 422 => ProviderFailure::InvalidRequest(failure),
_ => ProviderFailure::Http(failure),
}
}
fn explain(&self, status: u16, body: &str, sent: &Value) -> Option<String> {
if status == 404 {
return Some(format!(
"check provider.base_url and provider.model: `{}` may not be served at this URL",
self.model
));
}
if !matches!(status, 400 | 422) {
return None;
}
let lower = body.to_ascii_lowercase();
let mut candidates: Vec<String> = self
.options
.applied_keys()
.into_iter()
.map(str::to_string)
.collect();
if let Some(field) = &self.profile.max_tokens_field {
if sent.get(field.as_str()).is_some() {
candidates.push(field.clone());
}
}
candidates.sort_by_key(|k| std::cmp::Reverse(k.len()));
let named = candidates
.iter()
.find(|key| mentions_field(&lower, key))
.cloned()?;
Some(format!(
"`{named}` was sent for model `{}` and this server refused it — remove provider.{named} \
from the config, or send it under `[provider] extra_body` if this backend spells it \
another way",
self.model
))
}
async fn read_json_reply_timed(
mut resp: reqwest::Response,
started_ms: u64,
idle: Duration,
) -> Result<(Message, TurnUsage)> {
let mut raw = Vec::new();
loop {
match tokio::time::timeout(idle, resp.chunk()).await {
Ok(Ok(Some(chunk))) => raw.extend_from_slice(&chunk),
Ok(Ok(None)) => break,
Ok(Err(e)) => {
return Err(Error::Provider(ProviderFailure::Transport {
url: "the reply body".into(),
message: format!("the connection dropped while reading it: {e}"),
sent: true,
}))
}
Err(_) => {
return Err(Error::Provider(ProviderFailure::Transport {
url: "the reply body".into(),
message: format!("the endpoint sent nothing for {} s", idle.as_secs()),
sent: true,
}))
}
}
}
let text = String::from_utf8_lossy(&raw).into_owned();
let body: Value = serde_json::from_str(&text).map_err(|e| {
Error::Provider(ProviderFailure::Response {
message: format!("the reply is not JSON: {e}"),
body: Some(text.chars().take(600).collect()),
})
})?;
let msg = parse_response(&body)?;
Ok((msg, TurnUsage::from_body(&body, started_ms)))
}
fn record_usage(&self, usage: TurnUsage) {
if let Ok(mut slot) = self.last_usage.lock() {
*slot = Some(usage);
}
}
}
#[async_trait]
impl ChatProvider for OpenAiProvider {
fn can_see(&self) -> bool {
self.can_see
}
async fn chat(&self, messages: &[Message], tools: &[ToolSpec]) -> Result<Message> {
let started = std::time::Instant::now();
let resp = self.send(&self.request_body(messages, tools)).await?;
let (msg, usage) =
Self::read_json_reply_timed(resp, started.elapsed().as_millis() as u64, self.idle)
.await?;
self.record_usage(usage);
Ok(msg)
}
fn take_usage(&self) -> Option<TurnUsage> {
self.last_usage.lock().ok().and_then(|mut slot| slot.take())
}
async fn chat_stream_patched(
&self,
messages: &[Message],
tools: &[ToolSpec],
on_delta: DeltaFn<'_>,
patch: &crate::hooks::RequestPatch,
) -> Result<Message> {
if !self.stream {
let started = std::time::Instant::now();
let resp = self
.send(&self.request_body_with(messages, tools, patch))
.await?;
let (msg, usage) =
Self::read_json_reply_timed(resp, started.elapsed().as_millis() as u64, self.idle)
.await?;
self.record_usage(usage);
return Ok(msg);
}
self.stream_with(messages, tools, on_delta, patch).await
}
async fn chat_stream(
&self,
messages: &[Message],
tools: &[ToolSpec],
on_delta: DeltaFn<'_>,
) -> Result<Message> {
if !self.stream {
return self.chat(messages, tools).await;
}
self.stream_with(
messages,
tools,
on_delta,
&crate::hooks::RequestPatch::default(),
)
.await
}
}
impl OpenAiProvider {
async fn stream_with(
&self,
messages: &[Message],
tools: &[ToolSpec],
on_delta: DeltaFn<'_>,
patch: &crate::hooks::RequestPatch,
) -> Result<Message> {
let mut body = self.request_body_with(messages, tools, patch);
body["stream"] = json!(true);
if self.profile.stream_usage {
body["stream_options"] = json!({"include_usage": true});
}
let shown = std::sync::atomic::AtomicUsize::new(0);
let counting = |d: crate::stream::Delta| {
shown.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
on_delta(d);
};
let mut attempts = 0u32;
loop {
match self.stream_once(&body, &counting).await {
Ok((msg, usage)) => {
self.note_usage(usage);
return Ok(msg);
}
Err(e) => {
let retry = attempts == 0
&& self.max_retries > 0
&& shown.load(std::sync::atomic::Ordering::Relaxed) == 0
&& e.provider_failure().is_some_and(|f| f.is_retryable());
if !retry {
return Err(e);
}
attempts += 1;
}
}
}
}
async fn stream_once(
&self,
body: &Value,
on_delta: DeltaFn<'_>,
) -> Result<(Message, TurnUsage)> {
let mut resp = self.send(body).await?;
let is_sse = resp
.headers()
.get(reqwest::header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.to_ascii_lowercase().contains("text/event-stream"));
let started = std::time::Instant::now();
if !is_sse {
return Self::read_json_reply_timed(
resp,
started.elapsed().as_millis() as u64,
self.idle,
)
.await;
}
let mut parser = SseParser::default();
let mut acc = StreamAccumulator::default();
let mut received = 0usize;
loop {
let chunk = match tokio::time::timeout(self.idle, resp.chunk()).await {
Ok(Ok(Some(chunk))) => chunk,
Ok(Ok(None)) => break,
Err(_) => {
return Err(Error::Provider(ProviderFailure::Truncated {
message: format!(
"the endpoint sent nothing for {} s mid-reply",
self.idle.as_secs()
),
streamed_chars: received,
}));
}
Ok(Err(e)) => {
let message = if received == 0 {
format!("the connection dropped before the reply arrived: {e}")
} else {
format!("the connection dropped mid-reply: {e}")
};
return Err(Error::Provider(ProviderFailure::Truncated {
message,
streamed_chars: received,
}));
}
};
received += chunk.len();
for event in parser.push(&chunk) {
acc.push_event(&event, on_delta)?;
}
}
for event in parser.finish() {
acc.push_event(&event, on_delta)?;
}
let usage_body = acc.usage_body();
let msg = acc.finish()?;
Ok((
msg,
TurnUsage::from_body(&usage_body, started.elapsed().as_millis() as u64),
))
}
fn note_usage(&self, usage: TurnUsage) {
if usage.is_empty() {
self.record_usage(TurnUsage {
latency_ms: usage.latency_ms,
..Default::default()
});
} else {
self.record_usage(usage);
}
}
}
pub async fn list_models(
base_url: &str,
api_key: Option<&str>,
timeout: std::time::Duration,
) -> Result<Vec<String>> {
let url = format!("{}/models", base_url.trim_end_matches('/'));
let client = reqwest::Client::builder()
.timeout(timeout)
.build()
.map_err(|e| Error::provider(format!("could not build an HTTP client: {e}")))?;
let mut req = client.get(&url);
if let Some(key) = api_key {
req = req.bearer_auth(key);
}
let resp = req.send().await.map_err(|e| {
Error::Provider(ProviderFailure::Transport {
url: url.clone(),
message: describe_transport(&e),
sent: !e.is_connect(),
})
})?;
let status = resp.status();
let request_id = request_id(resp.headers());
let text = resp.text().await.unwrap_or_default();
if !status.is_success() {
let failure = HttpFailure {
status: status.as_u16(),
body: text.chars().take(300).collect(),
request_id,
retry_after_secs: None,
hint: None,
};
return Err(Error::Provider(
if status.as_u16() == 401 || status.as_u16() == 403 {
ProviderFailure::Unauthorized(failure)
} else {
ProviderFailure::Http(failure)
},
));
}
let body: serde_json::Value = serde_json::from_str(&text).map_err(|e| {
Error::Provider(ProviderFailure::Response {
message: format!("{url} did not answer with JSON: {e}"),
body: Some(text.chars().take(300).collect()),
})
})?;
let mut out: Vec<String> = body
.get("data")
.and_then(serde_json::Value::as_array)
.map(|rows| {
rows.iter()
.filter_map(|r| r.get("id").and_then(serde_json::Value::as_str))
.map(str::to_string)
.collect()
})
.unwrap_or_default();
out.dedup();
Ok(out)
}
pub async fn advertised_context_window(
base_url: &str,
api_key: Option<&str>,
model: &str,
timeout: std::time::Duration,
) -> Option<usize> {
let base = base_url.trim_end_matches('/');
let root = base.strip_suffix("/v1").unwrap_or(base);
let client = reqwest::Client::builder().timeout(timeout).build().ok()?;
for url in [
format!("{root}/props"),
format!("{root}/props?model={}", encode_query(model)),
] {
let mut req = client.get(url);
if let Some(key) = api_key {
req = req.bearer_auth(key);
}
let Ok(resp) = req.send().await else { continue };
if !resp.status().is_success() {
continue;
}
let Ok(body) = resp.json::<serde_json::Value>().await else {
continue;
};
if let Some(n) = body
.pointer("/default_generation_settings/n_ctx")
.and_then(serde_json::Value::as_u64)
.filter(|n| *n > 0)
{
return Some(n as usize);
}
}
let mut req = client.get(format!("{base}/models"));
if let Some(key) = api_key {
req = req.bearer_auth(key);
}
let Ok(resp) = req.send().await else {
return None;
};
if !resp.status().is_success() {
return None;
}
let Ok(body) = resp.json::<serde_json::Value>().await else {
return None;
};
let rows = body
.get("data")
.and_then(serde_json::Value::as_array)?
.as_slice();
fn id_of(row: &serde_json::Value) -> &str {
row.get("id")
.and_then(serde_json::Value::as_str)
.unwrap_or_default()
}
let figure_of = |row: &serde_json::Value| -> Option<usize> {
for pointer in [
"/context_length",
"/context_window",
"/max_model_len",
"/n_ctx",
"/meta/n_ctx",
] {
if let Some(n) = row
.pointer(pointer)
.and_then(serde_json::Value::as_u64)
.filter(|n| *n > 0)
{
return Some(n as usize);
}
}
None
};
if let Some(row) = rows.iter().find(|r| id_of(r) == model) {
return figure_of(row);
}
if let Some(row) = rows.iter().find(|r| id_matches_loosely(id_of(r), model)) {
return figure_of(row);
}
match rows {
[only] => figure_of(only),
_ => None,
}
}
fn id_matches_loosely(served: &str, configured: &str) -> bool {
let tail = |s: &str| s.rsplit('/').next().unwrap_or(s).to_string();
!served.is_empty() && !configured.is_empty() && tail(served) == tail(configured)
}
fn encode_query(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
out.push(b as char)
}
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tools::{ToolSpec, ToolSpecFunction};
use std::sync::{Arc, Mutex};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::Notify;
fn cfg(base: &str) -> ProviderConfig {
ProviderConfig {
base_url: base.into(),
model: "m".into(),
api_key: Some("k".into()),
retry_base_delay_ms: 20,
..ProviderConfig::default()
}
}
#[tokio::test]
async fn a_provider_that_cannot_patch_says_so_instead_of_dropping_it() {
struct Plain;
#[async_trait]
impl ChatProvider for Plain {
async fn chat(&self, _m: &[Message], _t: &[ToolSpec]) -> Result<Message> {
Ok(Message::assistant("ok"))
}
}
let patch = crate::hooks::RequestPatch {
tool_choice: Some(crate::hooks::ToolChoice::Required),
..Default::default()
};
let err = Plain
.chat_stream_patched(&[], &[], &|_| {}, &patch)
.await
.unwrap_err()
.to_string();
assert!(err.contains("cannot apply a request patch"), "{err}");
assert!(
err.contains("tool_choice"),
"the error names what was set: {err}"
);
let ok = Plain
.chat_stream_patched(&[], &[], &|_| {}, &crate::hooks::RequestPatch::default())
.await
.unwrap();
assert_eq!(ok.content.as_deref(), Some("ok"));
}
#[test]
fn requires_base_url_and_trims_slash() {
assert!(OpenAiProvider::new(&ProviderConfig::default()).is_err());
let p = OpenAiProvider::new(&cfg("http://h/v1/")).unwrap();
assert_eq!(p.url, "http://h/v1/chat/completions");
}
#[test]
fn reasoning_is_round_tripped_only_when_the_profile_wants_it() {
let mut m = Message::assistant("done");
m.reasoning = Some("thinking".into());
let openai = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
assert_eq!(
openai.request_body(&[m.clone()], &[])["messages"][0]["reasoning_content"],
json!("thinking")
);
let mut c = cfg("http://h/v1");
c.profile = Some("llamacpp".into());
let local = OpenAiProvider::new(&c).unwrap();
let body = local.request_body(&[m], &[]);
assert!(
body["messages"][0].get("reasoning_content").is_none(),
"a backend that did not ask for it must not see it: {body}"
);
}
#[test]
fn reasoning_stops_at_the_end_of_its_turn() {
let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
let mut first = Message::assistant("worked on the old thing");
first.reasoning = Some("old thinking".into());
let mut second = Message::assistant("tool call in the live turn");
second.reasoning = Some("live thinking".into());
let history = [
Message::user("do the old thing"),
first,
Message::tool_result("c1", "ok"),
Message::user("now do the new thing"),
second,
];
let body = p.request_body(&history, &[]);
let msgs = body["messages"].as_array().unwrap();
assert!(
msgs[1].get("reasoning_content").is_none(),
"the finished turn's thinking is not sent again: {body}"
);
assert_eq!(
msgs[4]["reasoning_content"],
json!("live thinking"),
"the turn in progress still carries its own plan: {body}"
);
}
#[test]
fn request_body_shape() {
let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
let b = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(b["model"], "m");
assert_eq!(b["messages"][0]["role"], "user");
assert!(b.get("tools").is_none());
}
#[test]
fn temperature_is_sent_without_float_noise() {
let mut c = cfg("http://h/v1");
c.temperature = Some(0.7);
let p = OpenAiProvider::new(&c).unwrap();
let b = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(b["temperature"].to_string(), "0.7");
}
#[test]
fn parses_text_and_tool_call_replies() {
let m =
parse_response(&json!({"choices":[{"message":{"role":"assistant","content":"yo"}}]}))
.unwrap();
assert_eq!(m.content.as_deref(), Some("yo"));
let m = parse_response(&json!({"choices":[{"message":{"role":"assistant","content":null,
"tool_calls":[{"id":"","type":"function","function":{"name":"shell","arguments":"{}"}}]}}]}))
.unwrap();
assert_eq!(m.tool_calls[0].function.name, "shell");
assert_eq!(m.tool_calls[0].id, "call_0");
assert!(parse_response(&json!({"error":"x"})).is_err());
}
async fn read_request(s: &mut tokio::net::TcpStream) -> String {
let mut buf = Vec::new();
loop {
let mut chunk = [0u8; 4096];
let n = s.read(&mut chunk).await.unwrap();
buf.extend_from_slice(&chunk[..n]);
let text = String::from_utf8_lossy(&buf).to_string();
if let Some(idx) = text.find("\r\n\r\n") {
let len = text[..idx]
.to_lowercase()
.lines()
.find_map(|l| {
l.strip_prefix("content-length: ")
.map(|v| v.trim().parse::<usize>().unwrap())
})
.unwrap_or(0);
if buf.len() >= idx + 4 + len {
break;
}
}
if n == 0 {
break;
}
}
String::from_utf8_lossy(&buf).to_string()
}
async fn serve_once(status: &str, body: &str) -> (String, tokio::task::JoinHandle<String>) {
serve_once_typed(status, "application/json", body).await
}
async fn serve_headers_then_stall(status: &str) -> (String, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let response = format!(
"HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: 4096\r\nconnection: close\r\n\r\n"
);
let h = tokio::spawn(async move {
let Ok((mut s, _)) = listener.accept().await else {
return;
};
let _ = read_request(&mut s).await;
let _ = s.write_all(response.as_bytes()).await;
let _ = s.flush().await;
tokio::time::sleep(Duration::from_secs(60)).await;
});
(base, h)
}
async fn serve_once_typed(
status: &str,
content_type: &str,
body: &str,
) -> (String, tokio::task::JoinHandle<String>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let response = format!(
"HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
let h = tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
let req = read_request(&mut s).await;
s.write_all(response.as_bytes()).await.unwrap();
req
});
(base, h)
}
async fn serve_sse_cut_then_ok(
first: &'static str,
) -> (String, tokio::task::JoinHandle<usize>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let h = tokio::spawn(async move {
let mut seen = 0;
for attempt in 0..2 {
let Ok(Ok((mut s, _))) =
tokio::time::timeout(Duration::from_millis(700), listener.accept()).await
else {
break;
};
let _ = read_request(&mut s).await;
seen += 1;
let body = if attempt == 0 {
first.to_string()
} else {
"data: {\"choices\":[{\"delta\":{\"content\":\"whole\"},\"finish_reason\":\"stop\"}]}\n\n\
data: [DONE]\n\n"
.to_string()
};
let _ = s
.write_all(b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n")
.await;
let _ = s.write_all(body.as_bytes()).await;
let _ = s.flush().await;
drop(s);
tokio::time::sleep(Duration::from_millis(20)).await;
}
seen
});
(base, h)
}
async fn serve_sse_trickle(n: usize, gap_ms: u64) -> (String, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let h = tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
let _ = read_request(&mut s).await;
s.write_all(
b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
)
.await
.unwrap();
for i in 0..n {
let ev = format!(
"data: {{\"choices\":[{{\"delta\":{{\"content\":\"t{i} \"}} ,\"index\":0}}]}}\n\n"
);
s.write_all(ev.as_bytes()).await.unwrap();
s.flush().await.unwrap();
tokio::time::sleep(Duration::from_millis(gap_ms)).await;
}
let _ = s.write_all(b"data: [DONE]\n\n").await;
let _ = s.flush().await;
});
(base, h)
}
async fn serve_sse_then_silence(silence: Duration) -> (String, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let h = tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
let _ = read_request(&mut s).await;
s.write_all(
b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
)
.await
.unwrap();
s.write_all(
b"data: {\"choices\":[{\"delta\":{\"content\":\"half\"},\"index\":0}]}\n\n",
)
.await
.unwrap();
s.flush().await.unwrap();
tokio::time::sleep(silence).await;
});
(base, h)
}
#[tokio::test]
async fn a_reply_that_keeps_arriving_outlives_the_timeout_it_started_under() {
let (base, h) = serve_sse_trickle(20, 200).await;
let mut c = cfg(&base);
c.timeout_secs = 1;
let p = OpenAiProvider::new(&c).unwrap();
let reply = p
.chat_stream_patched(
&[Message::user("think for a while")],
&[],
&|_: crate::stream::Delta| {},
&crate::hooks::RequestPatch::default(),
)
.await
.unwrap();
let text = reply.content.unwrap_or_default();
assert!(text.contains("t19"), "the last token arrived: {text:?}");
assert_eq!(text.matches('t').count(), 20);
h.await.ok();
}
#[tokio::test]
async fn a_whole_body_that_keeps_arriving_is_read_past_the_budget_too() {
let (base, h) = serve_sse_trickle(20, 200).await;
let mut c = cfg(&base);
c.timeout_secs = 1;
let p = OpenAiProvider::new(&c).unwrap();
let err = p
.chat(&[Message::user("hi")], &[])
.await
.expect_err("trickled SSE is not JSON");
let text = err.to_string();
assert!(!text.contains("sent nothing"), "read to the end: {text}");
h.await.ok();
}
#[tokio::test]
async fn a_failed_attempt_whose_body_stalls_is_bounded_by_the_idle_budget() {
let (base, h) = serve_headers_then_stall("503 Service Unavailable").await;
let mut c = cfg(&base);
c.timeout_secs = 1;
c.max_retries = 0;
let p = OpenAiProvider::new(&c).unwrap();
let err =
tokio::time::timeout(Duration::from_secs(15), p.chat(&[Message::user("hi")], &[]))
.await
.expect("the body read is bounded: without the fix this never returns")
.expect_err("503 is a failure");
let text = err.to_string();
assert!(
text.contains("503"),
"the status survives an unreadable body: {text}"
);
h.abort();
}
#[tokio::test]
async fn a_stream_that_goes_silent_mid_reply_names_the_silence() {
let (base, h) = serve_sse_then_silence(Duration::from_secs(3)).await;
let mut c = cfg(&base);
c.timeout_secs = 1;
c.max_retries = 0;
let p = OpenAiProvider::new(&c).unwrap();
let err = p
.chat(&[Message::user("go quiet")], &[])
.await
.expect_err("silence must not be reported as a finished reply");
let text = err.to_string();
assert!(text.contains("sent nothing for 1 s"), "{text}");
h.abort();
}
async fn serve_sse(
first: &'static str,
gate: Arc<Notify>,
rest: &'static str,
) -> (String, tokio::task::JoinHandle<String>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let h = tokio::spawn(async move {
let (mut s, _) = listener.accept().await.unwrap();
let req = read_request(&mut s).await;
s.write_all(
b"HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n",
)
.await
.unwrap();
s.write_all(first.as_bytes()).await.unwrap();
s.flush().await.unwrap();
gate.notified().await;
s.write_all(rest.as_bytes()).await.unwrap();
req
});
(base, h)
}
#[tokio::test]
async fn chat_posts_to_configured_endpoint_with_bearer_key() {
let (base, h) = serve_once(
"200 OK",
r#"{"choices":[{"message":{"role":"assistant","content":"pong"}}]}"#,
)
.await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let reply = p.chat(&[Message::user("ping")], &[]).await.unwrap();
assert_eq!(reply.content.as_deref(), Some("pong"));
let req = h.await.unwrap().to_lowercase();
assert!(req.starts_with("post /v1/chat/completions"), "{req}");
assert!(req.contains("authorization: bearer k"));
assert!(req.contains("\"ping\""));
}
#[tokio::test]
async fn chat_surfaces_http_errors() {
let (base, _h) = serve_once("401 Unauthorized", r#"{"error":"bad key"}"#).await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let err = p
.chat(&[Message::user("x")], &[])
.await
.unwrap_err()
.to_string();
assert!(err.contains("401") && err.contains("bad key"), "{err}");
}
#[tokio::test]
async fn stream_delivers_deltas_before_the_reply_is_complete() {
let gate = Arc::new(Notify::new());
let (base, h) = serve_sse(
"data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n\
data: {\"choices\":[{\"delta\":{\"content\":\"lo\"}}]}\n\nda",
gate.clone(),
"ta: {\"choices\":[{\"delta\":{\"content\":\"!\"},\"finish_reason\":\"stop\"}]}\n\n\
data: [DONE]\n\n",
)
.await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let seen = Mutex::new(Vec::<String>::new());
let sink = |d: crate::stream::Delta| {
if let crate::stream::Delta::Text(t) = d {
let mut seen = seen.lock().unwrap();
seen.push(t);
if seen.len() == 2 {
gate.notify_one();
}
}
};
let reply = tokio::time::timeout(
Duration::from_secs(5),
p.chat_stream(&[Message::user("hi")], &[], &sink),
)
.await
.expect("stream was not delivered incrementally")
.unwrap();
assert_eq!(*seen.lock().unwrap(), ["Hel", "lo", "!"]);
assert_eq!(reply.content.as_deref(), Some("Hello!"));
let req = h.await.unwrap();
assert!(req.contains("\"stream\":true"), "{req}");
}
#[tokio::test]
async fn stream_assembles_tool_calls() {
let gate = Arc::new(Notify::new());
gate.notify_one();
let (base, _h) = serve_sse(
"data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"id\":\"c1\",\"function\":{\"name\":\"shell\",\"arguments\":\"{\\\"command\\\"\"}}]}}]}\n\n",
gate,
"data: {\"choices\":[{\"delta\":{\"tool_calls\":[{\"index\":0,\"function\":{\"arguments\":\":\\\"ls\\\"}\"}}]},\"finish_reason\":\"tool_calls\"}]}\n\n",
)
.await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let reply = p
.chat_stream(&[Message::user("x")], &[], &|_| {})
.await
.unwrap();
assert_eq!(reply.tool_calls[0].id, "c1");
assert_eq!(
reply.tool_calls[0].function.arguments,
r#"{"command":"ls"}"#
);
}
#[tokio::test]
async fn stream_cut_short_is_an_error_not_a_reply() {
let gate = Arc::new(Notify::new());
gate.notify_one();
let (base, _h) = serve_sse(
"data: {\"choices\":[{\"delta\":{\"content\":\"half\"}}]}\n\n",
gate,
"",
)
.await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let err = p
.chat_stream(&[Message::user("x")], &[], &|_| {})
.await
.unwrap_err()
.to_string();
assert!(err.contains("before the model finished"), "{err}");
}
#[tokio::test]
async fn stream_falls_back_to_plain_json_replies() {
let (base, h) = serve_once(
"200 OK",
r#"{"choices":[{"message":{"role":"assistant","content":"whole"}}]}"#,
)
.await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let deltas = Mutex::new(0);
let reply = p
.chat_stream(&[Message::user("x")], &[], &|_| {
*deltas.lock().unwrap() += 1
})
.await
.unwrap();
assert_eq!(reply.content.as_deref(), Some("whole"));
assert_eq!(*deltas.lock().unwrap(), 0);
assert!(h.await.unwrap().contains("\"stream\":true"));
}
#[tokio::test]
async fn streaming_can_be_disabled_and_errors_still_surface() {
let mut c = cfg("http://unused/v1");
c.stream = false;
let (base, h) = serve_once(
"200 OK",
r#"{"choices":[{"message":{"role":"assistant","content":"plain"}}]}"#,
)
.await;
c.base_url = base;
let p = OpenAiProvider::new(&c).unwrap();
let reply = p
.chat_stream(&[Message::user("x")], &[], &|_| {})
.await
.unwrap();
assert_eq!(reply.content.as_deref(), Some("plain"));
assert!(!h.await.unwrap().contains("\"stream\""));
let (base, _h) = serve_once("500 Internal Server Error", "boom").await;
let mut c = cfg(&base);
c.max_retries = 0;
let p = OpenAiProvider::new(&c).unwrap();
let err = p
.chat_stream(&[Message::user("x")], &[], &|_| {})
.await
.unwrap_err()
.to_string();
assert!(err.contains("500") && err.contains("boom"), "{err}");
}
async fn serve_script(
script: Vec<(&'static str, &'static str, &'static str)>,
) -> (String, tokio::task::JoinHandle<usize>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let h = tokio::spawn(async move {
let mut seen = 0;
for (status, headers, body) in script {
let accepted = tokio::time::timeout(Duration::from_millis(500), listener.accept());
let Ok(Ok((mut s, _))) = accepted.await else {
break;
};
read_request(&mut s).await;
seen += 1;
let resp = format!(
"HTTP/1.1 {status}\r\ncontent-type: application/json\r\n{headers}content-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
s.write_all(resp.as_bytes()).await.unwrap();
}
seen
});
(base, h)
}
const OK_BODY: &str = r#"{"choices":[{"message":{"role":"assistant","content":"ok"}}]}"#;
#[test]
fn backoff_doubles_from_the_base() {
let base = Duration::from_secs(2);
let waits: Vec<_> = (1..=3).map(|n| backoff_delay(base, n).as_secs()).collect();
assert_eq!(waits, [2, 4, 8]);
assert!(crate::error::is_retryable_status(429));
assert!(crate::error::is_retryable_status(502));
for s in [400, 401, 403, 404, 422] {
assert!(!crate::error::is_retryable_status(s));
}
assert_eq!(ProviderConfig::default().max_retries, 3);
assert_eq!(ProviderConfig::default().retry_base_delay_ms, 2000);
}
#[tokio::test]
async fn retries_429_and_5xx_then_succeeds_with_backoff() {
let (base, server) = serve_script(vec![
("429 Too Many Requests", "", "slow down"),
("503 Service Unavailable", "", "busy"),
("200 OK", "", OK_BODY),
])
.await;
let mut c = cfg(&base);
c.retry_base_delay_ms = 60;
let p = OpenAiProvider::new(&c).unwrap();
let start = std::time::Instant::now();
let reply = p.chat(&[Message::user("x")], &[]).await.unwrap();
assert_eq!(reply.content.as_deref(), Some("ok"));
assert_eq!(server.await.unwrap(), 3);
assert!(
start.elapsed() >= Duration::from_millis(60 + 120),
"waited only {:?}",
start.elapsed()
);
}
#[tokio::test]
async fn gives_up_after_max_retries_and_reports_it() {
let (base, server) = serve_script(vec![
("500 Internal Server Error", "", "e1"),
("500 Internal Server Error", "", "e2"),
("500 Internal Server Error", "", "e3"),
("502 Bad Gateway", "", "last"),
("200 OK", "", OK_BODY),
])
.await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let err = p
.chat(&[Message::user("x")], &[])
.await
.unwrap_err()
.to_string();
assert!(
err.contains("502") && err.contains("last") && err.contains("4 attempts"),
"{err}"
);
assert_eq!(server.await.unwrap(), 4, "1 try + 3 retries, no more");
}
#[tokio::test]
async fn other_4xx_are_not_retried() {
for status in ["400 Bad Request", "401 Unauthorized", "404 Not Found"] {
let (base, server) =
serve_script(vec![(status, "", "no"), ("200 OK", "", OK_BODY)]).await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let err = p
.chat(&[Message::user("x")], &[])
.await
.unwrap_err()
.to_string();
assert!(
err.contains(&status[..3]) && !err.contains("gave up"),
"{err}"
);
assert_eq!(server.await.unwrap(), 1, "{status}");
}
}
#[tokio::test]
async fn retries_can_be_disabled_and_retry_after_is_honoured() {
let (base, server) = serve_script(vec![
("503 Service Unavailable", "", "down"),
("200 OK", "", OK_BODY),
])
.await;
let mut c = cfg(&base);
c.max_retries = 0;
let err = OpenAiProvider::new(&c)
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.unwrap_err()
.to_string();
assert!(err.contains("503") && !err.contains("gave up"), "{err}");
assert_eq!(server.await.unwrap(), 1);
let (base, server) = serve_script(vec![
("429 Too Many Requests", "retry-after: 0\r\n", "wait"),
("200 OK", "", OK_BODY),
])
.await;
let mut c = cfg(&base);
c.retry_base_delay_ms = 600_000;
let reply = tokio::time::timeout(
Duration::from_secs(5),
OpenAiProvider::new(&c)
.unwrap()
.chat(&[Message::user("x")], &[]),
)
.await
.expect("Retry-After was ignored")
.unwrap();
assert_eq!(reply.content.as_deref(), Some("ok"));
assert_eq!(server.await.unwrap(), 2);
let (base, server) = serve_script(vec![(
"429 Too Many Requests",
"retry-after: 3600\r\n",
"later",
)])
.await;
let err = OpenAiProvider::new(&cfg(&base))
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.unwrap_err()
.to_string();
assert!(err.contains("429") && err.contains("later"), "{err}");
assert_eq!(server.await.unwrap(), 1, "a Retry-After of an hour is a no");
}
#[tokio::test]
async fn streaming_requests_are_retried_before_the_stream_starts() {
let (base, server) = serve_script(vec![
("503 Service Unavailable", "", "busy"),
("200 OK", "", OK_BODY),
])
.await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let reply = p
.chat_stream(&[Message::user("x")], &[], &|_| {})
.await
.unwrap();
assert_eq!(reply.content.as_deref(), Some("ok"));
assert_eq!(server.await.unwrap(), 2);
}
async fn serve_drop_then_ok() -> (String, tokio::task::JoinHandle<usize>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
let h = tokio::spawn(async move {
let mut seen = 0;
if let Ok(Ok((mut s, _))) =
tokio::time::timeout(Duration::from_millis(500), listener.accept()).await
{
read_request(&mut s).await;
seen += 1;
drop(s); tokio::time::sleep(Duration::from_millis(20)).await;
}
if let Ok(Ok((mut s, _))) =
tokio::time::timeout(Duration::from_millis(500), listener.accept()).await
{
read_request(&mut s).await;
seen += 1;
let resp = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{OK_BODY}",
OK_BODY.len()
);
let _ = s.write_all(resp.as_bytes()).await;
}
seen
});
(base, h)
}
#[tokio::test]
async fn a_drop_after_the_request_went_out_is_not_repeated_by_default() {
let (base, server) = serve_drop_then_ok().await;
let failed = OpenAiProvider::new(&cfg(&base))
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.expect_err("a drop after the send is not repeated unless the config says so");
let failure = failed.provider_failure().expect("a provider failure");
assert!(
failure.after_send(),
"the failure knows the request had gone out: {failure}"
);
assert_eq!(
server.await.unwrap(),
1,
"exactly one request reached the server"
);
}
#[tokio::test]
async fn a_drop_after_the_send_is_repeated_when_the_config_allows_it() {
let (base, server) = serve_drop_then_ok().await;
let mut c = cfg(&base);
c.retry_after_send = true;
let reply = OpenAiProvider::new(&c)
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.expect("the config allows repeating a request that was already sent");
assert_eq!(reply.content.as_deref(), Some("ok"));
assert_eq!(server.await.unwrap(), 2, "the drop was repeated as asked");
}
#[tokio::test]
async fn a_server_that_is_never_there_gives_up_and_says_how_many_attempts_it_spent() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}/v1", listener.local_addr().unwrap());
drop(listener);
let mut c = cfg(&base);
c.max_retries = 1;
c.retry_base_delay_ms = 1;
let err = OpenAiProvider::new(&c)
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.unwrap_err()
.to_string();
assert!(err.contains("could not reach"), "{err}");
assert!(err.contains("connection could not be established"), "{err}");
assert!(err.contains("2 attempts"), "it says what it spent: {err}");
}
#[tokio::test]
async fn retries_can_be_turned_off_entirely() {
let (base, server) = serve_script(vec![
("503 Service Unavailable", "", "busy"),
("200 OK", "", OK_BODY),
])
.await;
let mut c = cfg(&base);
c.max_retries = 0;
let err = OpenAiProvider::new(&c)
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.unwrap_err()
.to_string();
assert!(err.contains("503"), "{err}");
assert_eq!(server.await.unwrap(), 1, "max_retries = 0 means one try");
}
#[test]
fn the_default_profile_sends_tools_and_usage_the_openai_way() {
let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
assert_eq!(p.profile_name(), "openai");
let tools = vec![ToolSpec {
kind: "function",
function: ToolSpecFunction {
name: "t".into(),
description: "d".into(),
parameters: json!({"type": "object"}),
},
}];
let body = p.request_body(&[Message::user("hi")], &tools);
assert_eq!(body["tool_choice"], "auto");
assert!(
body.get("stream_options").is_none(),
"only sent when streaming"
);
assert!(body.get("max_tokens").is_none(), "no cap unless configured");
}
#[test]
fn the_llamacpp_profile_keeps_tools_but_drops_tool_choice() {
let mut c = cfg("http://h/v1");
c.profile = Some("llamacpp".into());
let p = OpenAiProvider::new(&c).unwrap();
let tools = vec![ToolSpec {
kind: "function",
function: ToolSpecFunction {
name: "t".into(),
description: "d".into(),
parameters: json!({"type": "object"}),
},
}];
let body = p.request_body(&[Message::user("hi")], &tools);
assert!(body.get("tools").is_some());
assert!(body.get("tool_choice").is_none());
}
fn shipped(name: &str) -> ProviderProfile {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../../plugins")
.join(name)
.join("plugin.toml");
let text = std::fs::read_to_string(&path)
.unwrap_or_else(|e| panic!("{} is not readable: {e}", path.display()));
let manifest: crate::plugins::Manifest = toml::from_str(&text)
.unwrap_or_else(|e| panic!("{} does not parse: {e}", path.display()));
let def = manifest
.provider_profiles
.first()
.unwrap_or_else(|| panic!("{} declares no profile", path.display()));
crate::plugins::profile_from_def(def)
}
fn shipped_effort(name: &str, model: &str, asked: Option<&str>) -> serde_json::Value {
let plugin = shipped(name);
let profile_name = plugin.name.clone();
let mut c = cfg("http://h/v1");
c.profile = Some(profile_name);
c.model = model.into();
let dial = std::sync::Arc::new(crate::reasoning::Dial::new(asked.map(str::to_string)));
let p = OpenAiProvider::with_dial(&c, &[plugin], Some(dial)).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
body.get("reasoning_effort").cloned().unwrap_or(json!(null))
}
#[test]
fn the_shipped_profiles_send_exactly_what_they_promise() {
assert_eq!(
shipped_effort(
"provider-profile-llamacpp",
"mmnuc/inkling-2-mini",
Some("xhigh")
),
json!("high")
);
assert_eq!(
shipped_effort(
"provider-profile-llamacpp",
"mmnuc/inkling-2-mini",
Some("minimal")
),
json!("low")
);
assert_eq!(
shipped_effort(
"provider-profile-llamacpp",
"mmnuc/inkling-2-mini",
Some("none")
),
json!("none")
);
assert_eq!(
shipped_effort("provider-profile-llamacpp", "mmnuc/inkling-2-mini", None),
json!("medium"),
"nothing asked resolves the profile's declared default (`#276`)"
);
assert_eq!(
shipped_effort(
"provider-profile-ollama-cloud",
"gpt-oss:120b",
Some("xhigh")
),
json!("max")
);
assert_eq!(
shipped_effort(
"provider-profile-ollama-cloud",
"gpt-oss:120b",
Some("minimal")
),
json!("low")
);
assert_eq!(
shipped_effort(
"provider-profile-ollama-cloud",
"gpt-oss:120b",
Some("none")
),
json!("none")
);
assert_eq!(
shipped_effort("provider-profile-ollama-cloud", "gpt-oss:120b", None),
json!("medium"),
"the cloud profile ships the same default"
);
assert_eq!(
shipped_effort(
"provider-profile-llamacpp",
"mmnuc/gemma-4-12b-it-qat",
Some("high")
),
json!(null),
"an off-only model refuses a graded level"
);
assert_eq!(
shipped_effort(
"provider-profile-llamacpp",
"mmnuc/gemma-4-12b-it-qat",
None
),
json!(null),
"and with nothing asked it still sends nothing: its entry declares no default, so \
`not sent` is the truth about this model rather than the shipped `medium` (`#276`)"
);
let gemma = {
let plugin = shipped("provider-profile-llamacpp");
let mut c = cfg("http://h/v1");
c.profile = Some(plugin.name.clone());
c.model = "mmnuc/gemma-4-12b-it-qat".into();
let dial = std::sync::Arc::new(crate::reasoning::Dial::new(Some("none".into())));
OpenAiProvider::with_dial(&c, &[plugin], Some(dial))
.unwrap()
.request_body(&[Message::user("hi")], &[])
};
assert!(
gemma.get("reasoning_effort").is_none(),
"gemma's off switch is the template kwarg, and the other field is never sent: {gemma}"
);
assert_eq!(
gemma["chat_template_kwargs"]["enable_thinking"],
json!(false),
"the fragment goes out as a nested object"
);
}
#[test]
fn the_ollama_off_switch_goes_to_ollama_and_nowhere_else() {
use crate::reasoning::looks_like_ollama;
for url in [
"http://127.0.0.1:11434/v1",
"http://192.168.1.50:11434",
"http://ollama:11434/v1",
"http://ollama/v1",
"http://my-ollama.lan:8080/v1",
"http://gpu.ollama.internal/v1",
"http://OLLAMA.LOCAL/v1",
] {
assert!(
looks_like_ollama(url),
"{url} is Ollama on somebody's network"
);
}
for url in [
"https://ollama.com/v1",
"https://api.ollama.ai/v1",
"https://ollama-cloud.example/v1",
"https://llama.mhnets.com/v1",
"http://192.168.1.120:18011/v1",
"",
] {
assert!(!looks_like_ollama(url), "{url} is not Ollama native");
}
let plugin = shipped("provider-profile-ollama-cloud");
let body_at = |url: &str| {
let mut c = cfg(url);
c.profile = Some(plugin.name.clone());
let dial = std::sync::Arc::new(crate::reasoning::Dial::new(Some("none".into())));
OpenAiProvider::with_dial(&c, std::slice::from_ref(&plugin), Some(dial))
.unwrap()
.request_body(&[Message::user("hi")], &[])
};
let cloud = body_at("https://ollama.com/v1");
assert_eq!(
cloud["reasoning_effort"],
json!("none"),
"the cloud's off switch"
);
assert!(
cloud.get("think").is_none(),
"and never the native flag: {cloud}"
);
let native = body_at("http://127.0.0.1:11434/v1");
assert_eq!(native["think"], json!(false), "the native off switch");
assert!(
native.get("reasoning_effort").is_none(),
"which is not the cloud's: {native}"
);
}
#[test]
fn a_profile_can_constrain_every_request_it_makes() {
let mut plugin = ProviderProfile::builtin("llamacpp").unwrap();
plugin.request = RequestPolicy {
num_ctx: Some(8192),
num_ctx_field: Some("n_ctx".into()),
max_output: Some(2048),
temperature: Some(Temperature::Omit),
reject_response_formats: vec!["json_object".into()],
aux_model: Some("small".into()),
models: [(
"big-model".to_string(),
ModelLimits {
max_output: Some(1024),
num_ctx: None,
},
)]
.into_iter()
.collect(),
};
let mut c = cfg("http://h/v1");
c.profile = Some("llamacpp".into());
c.model = "m".into();
c.temperature = Some(0.9);
c.max_tokens = Some(4096);
let p = OpenAiProvider::with_profiles(&c, &[plugin.clone()]).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(body["n_ctx"], json!(8192), "the manifest names the field");
assert_eq!(
body["max_tokens"],
json!(2048),
"the cap wins over the config's 4096"
);
assert!(
body.get("temperature").is_none(),
"a route that rejects it never sees it"
);
let mut patch = crate::hooks::RequestPatch::default();
patch
.extra_params
.insert("response_format".into(), json!({"type": "json_object"}));
let body = p.request_body_with(&[Message::user("hi")], &[], &patch);
assert!(body.get("response_format").is_none(), "{body}");
let mut patch = crate::hooks::RequestPatch::default();
patch.extra_params.insert(
"response_format".into(),
json!({"type": "json_schema", "json_schema": {}}),
);
let body = p.request_body_with(&[Message::user("hi")], &[], &patch);
assert_eq!(body["response_format"]["type"], json!("json_schema"));
let mut c2 = c.clone();
c2.model = "big-model".into();
let p2 = OpenAiProvider::with_profiles(&c2, &[plugin]).unwrap();
assert_eq!(
p2.request_body(&[Message::user("hi")], &[])["max_tokens"],
json!(1024)
);
}
#[test]
fn a_profile_with_no_body_does_not_replace_the_request_with_null() {
let mut plugin = ProviderProfile::builtin("llamacpp").unwrap();
plugin.name = "no-body".into();
plugin.body = serde_json::Value::Null;
let mut c = cfg("http://h/v1");
c.profile = Some("no-body".into());
let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(body["model"], json!("m"), "the model survives the merge");
assert!(body["messages"].is_array(), "{body}");
}
#[test]
fn the_effort_is_read_per_request_so_a_session_override_reaches_the_next_body() {
use crate::reasoning::Dial;
let mut c = cfg("http://h/v1");
c.reasoning_effort = Some("low".into());
let dial = std::sync::Arc::new(Dial::new(c.reasoning_effort.clone()));
let p = OpenAiProvider::with_dial(&c, &[], Some(dial.clone())).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(
body["reasoning_effort"],
json!("low"),
"the configured level"
);
dial.set_session(Some("high".into()));
let body = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(
body["reasoning_effort"],
json!("high"),
"the same provider, the next request: no restart"
);
dial.set_session(Some("none".into()));
assert!(p
.request_body(&[Message::user("hi")], &[])
.get("reasoning_effort")
.is_none());
}
#[test]
fn omit_puts_no_reasoning_field_on_the_wire_on_every_declared_profile() {
for (profile, model) in [
("provider-profile-llamacpp", "mmnuc/inkling-2-mini"),
("provider-profile-ollama-cloud", "gpt-oss:120b"),
] {
assert_eq!(
shipped_effort(profile, model, Some("omit")),
json!(null),
"{profile} was asked for no field"
);
assert_ne!(
shipped_effort(profile, model, Some("omit")),
shipped_effort(profile, model, Some("none")),
"{profile}: `omit` and `none` are two outcomes, not one"
);
}
}
#[test]
fn an_undeclared_backend_is_not_sent_the_word_omit() {
let c = cfg("http://h/v1");
let dial = std::sync::Arc::new(crate::reasoning::Dial::new(Some("omit".into())));
let p = OpenAiProvider::with_dial(&c, &[], Some(dial)).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
assert!(
body.get("reasoning_effort").is_none(),
"an undeclared backend carries no field: {body}"
);
}
#[test]
fn a_level_the_backend_lacks_is_clamped_or_omitted_never_sent_as_itself() {
use crate::reasoning::{Dial, Policy};
use std::collections::BTreeMap;
let mut c = cfg("http://h/v1");
c.profile = Some("llamacpp".into());
c.reasoning_effort = Some("xhigh".into());
let dial = std::sync::Arc::new(Dial::new(c.reasoning_effort.clone()));
let p = OpenAiProvider::with_dial(&c, &[], Some(dial.clone())).unwrap();
assert_eq!(
p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
json!("high"),
"xhigh is not a rung llama.cpp has; the nearest weaker one is"
);
let mut models = BTreeMap::new();
models.insert(
"gemma-4-12b".to_string(),
ModelReasoning::Policy(Policy {
field: "reasoning_effort".into(),
kind: crate::reasoning::Kind::Level,
off: Some("none".into()),
ollama_off: None,
levels: Vec::new(),
map: BTreeMap::new(),
default: None,
}),
);
let mut plugin = ProviderProfile::builtin("llamacpp").unwrap();
plugin.models = models;
let mut c2 = c.clone();
c2.model = "gemma-4-12b".into();
let p = OpenAiProvider::with_dial(&c2, &[plugin], Some(dial.clone())).unwrap();
assert!(
p.request_body(&[Message::user("hi")], &[])
.get("reasoning_effort")
.is_none(),
"a level this model has nowhere to put is omitted, not sent and ignored"
);
dial.set_session(Some("none".into()));
assert_eq!(
p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
json!("none")
);
}
#[test]
fn a_declared_vendor_mapping_is_what_reaches_an_ollama_cloud_body() {
use crate::reasoning::{Dial, Policy};
use std::collections::BTreeMap;
let mut map = BTreeMap::new();
map.insert("minimal".to_string(), "low".to_string());
map.insert("xhigh".to_string(), "max".to_string());
let policy = Policy {
field: "reasoning_effort".into(),
kind: crate::reasoning::Kind::Level,
off: Some("none".into()),
ollama_off: None,
levels: vec!["low".into(), "medium".into(), "high".into(), "max".into()],
map,
default: None,
};
let mut plugin = ProviderProfile::builtin("openai").unwrap();
plugin.name = "ollama-cloud".into();
plugin.reasoning = Some(policy);
let mut c = cfg("https://ollama.com/v1");
c.profile = Some("ollama-cloud".into());
let dial = std::sync::Arc::new(Dial::new(None));
let p = OpenAiProvider::with_dial(&c, &[plugin], Some(dial.clone())).unwrap();
for (asked, sent) in [("xhigh", "max"), ("minimal", "low"), ("high", "high")] {
dial.set_session(Some(asked.into()));
assert_eq!(
p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
json!(sent),
"{asked} on ollama-cloud"
);
}
dial.set_session(Some("none".into()));
assert_eq!(
p.request_body(&[Message::user("hi")], &[])["reasoning_effort"],
json!("none")
);
dial.set_session(Some("none".into()));
assert!(p
.request_body(&[Message::user("hi")], &[])
.get("think")
.is_none());
}
#[test]
fn a_plugin_profile_can_replace_a_builtin_and_add_body_fields() {
let mut c = cfg("http://h/v1");
c.profile = Some("llamacpp".into());
let plugin = ProviderProfile {
name: "llamacpp".into(),
tool_choice: true,
stream_usage: false,
max_tokens_field: Some("max_completion_tokens".into()),
supports_tools: true,
send_reasoning: false,
body: json!({"chat_template_kwargs": {"enable_thinking": false}}),
reasoning: None,
models: std::collections::BTreeMap::new(),
request: RequestPolicy::default(),
vision: None,
};
let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
let tools = vec![ToolSpec {
kind: "function",
function: ToolSpecFunction {
name: "t".into(),
description: "d".into(),
parameters: json!({"type": "object"}),
},
}];
let body = p.request_body(&[Message::user("hi")], &tools);
assert_eq!(body["tool_choice"], "auto", "the plugin profile won");
assert_eq!(
body["chat_template_kwargs"]["enable_thinking"],
json!(false),
"profile body fields reach the request"
);
}
#[test]
fn a_profile_can_disable_tools_entirely() {
let mut c = cfg("http://h/v1");
c.profile = Some("notools".into());
let plugin = ProviderProfile {
name: "notools".into(),
tool_choice: true,
stream_usage: true,
max_tokens_field: None,
supports_tools: false,
send_reasoning: false,
body: json!({}),
reasoning: None,
models: std::collections::BTreeMap::new(),
request: RequestPolicy::default(),
vision: None,
};
let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
let tools = vec![ToolSpec {
kind: "function",
function: ToolSpecFunction {
name: "t".into(),
description: "d".into(),
parameters: json!({"type": "object"}),
},
}];
let body = p.request_body(&[Message::user("hi")], &tools);
assert!(body.get("tools").is_none());
assert!(body.get("tool_choice").is_none());
}
#[test]
fn a_reply_cap_is_sent_under_the_profiles_field_name() {
let mut c = cfg("http://h/v1");
c.max_tokens = Some(64);
let p = OpenAiProvider::new(&c).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(body["max_tokens"], 64);
let mut plugin = ProviderProfile::builtin("openai").unwrap();
plugin.max_tokens_field = Some("max_completion_tokens".into());
let p = OpenAiProvider::with_profiles(&c, &[plugin]).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(body["max_completion_tokens"], 64);
assert!(body.get("max_tokens").is_none());
}
#[test]
fn an_unknown_profile_is_a_config_error_that_lists_the_options() {
let mut c = cfg("http://h/v1");
c.profile = Some("nope".into());
let err = OpenAiProvider::new(&c).unwrap_err().to_string();
assert!(err.contains("unknown provider profile"), "{err}");
assert!(err.contains("llamacpp"), "{err}");
}
const PROPS_404: (&str, &str, &str) = ("404 Not Found", "", r#"{"error":"no props"}"#);
fn props_then_models(models: &'static str) -> Vec<(&'static str, &'static str, &'static str)> {
vec![PROPS_404, PROPS_404, ("200 OK", "", models)]
}
#[tokio::test]
async fn context_window_prefers_llama_cpp_props() {
let (base, h) = serve_script(vec![(
"200 OK",
"",
r#"{"default_generation_settings":{"n_ctx":327680}}"#,
)])
.await;
let got = advertised_context_window(&base, None, "m", Duration::from_millis(400)).await;
assert_eq!(got, Some(327680));
h.await.unwrap();
}
#[tokio::test]
async fn a_multi_model_list_reports_the_configured_models_window_not_the_first_row() {
let rows = r#"{"data":[{"id":"mmnuc/gemma-4-12b-it-qat","context_length":131072},
{"id":"mmnuc/inkling-2-mini","context_length":327680},
{"id":"pc1/qwen-3.8-125b","context_length":262144}]}"#;
let (base, h) = serve_script(props_then_models(rows)).await;
let got = advertised_context_window(
&base,
None,
"mmnuc/inkling-2-mini",
Duration::from_millis(400),
)
.await;
assert_eq!(
got,
Some(327680),
"the configured model's window, not row 0's"
);
h.await.unwrap();
}
#[tokio::test]
async fn a_namespaced_id_matches_on_its_last_segment() {
let rows = r#"{"data":[{"id":"mmnuc/gemma-4-12b-it-qat","context_length":131072},
{"id":"pc1/inkling-2-mini","context_window":327680}]}"#;
let (base, h) = serve_script(props_then_models(rows)).await;
let got =
advertised_context_window(&base, None, "inkling-2-mini", Duration::from_millis(400))
.await;
assert_eq!(got, Some(327680));
h.await.unwrap();
}
#[tokio::test]
async fn a_similar_but_different_model_is_not_a_match() {
let rows = r#"{"data":[{"id":"pc1/qwen-3.8-27b","context_length":262144},
{"id":"pc1/qwen-3.8-125b-model","context_length":32768}]}"#;
let (base, h) = serve_script(props_then_models(rows)).await;
let got =
advertised_context_window(&base, None, "qwen-3.8-125b", Duration::from_millis(400))
.await;
assert_eq!(got, None, "no row is this model, so nothing is invented");
h.await.unwrap();
}
#[tokio::test]
async fn a_single_row_list_is_used_even_when_its_id_differs() {
let rows = r#"{"data":[{"id":"local-alias","max_model_len":131072}]}"#;
let (base, h) = serve_script(props_then_models(rows)).await;
let got = advertised_context_window(&base, None, "m", Duration::from_millis(400)).await;
assert_eq!(got, Some(131072));
h.await.unwrap();
}
#[tokio::test]
async fn context_window_is_none_when_nothing_answers() {
let rows = r#"{"data":[{"id":"m"}]}"#;
let (base, h) = serve_script(props_then_models(rows)).await;
let got = advertised_context_window(&base, None, "m", Duration::from_millis(400)).await;
assert_eq!(
got, None,
"no figure anywhere: no budget, never an invented one"
);
h.await.unwrap();
}
#[tokio::test]
async fn listing_models_reads_the_openai_shape_and_fails_small() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let serving = std::thread::spawn(move || {
for _ in 0..2 {
let (mut s, _) = listener.accept().unwrap();
let mut buf = [0u8; 2048];
use std::io::{Read, Write};
let n = s.read(&mut buf).unwrap();
let req = String::from_utf8_lossy(&buf[..n]).to_string();
let (code, body) = if req.contains("/wrong") {
("404 Not Found", r#"{"error":"nope"}"#)
} else if req.contains("/models") {
(
"200 OK",
r#"{"data":[{"id":"m-one"},{"id":"m-two"},{"id":"m-two"}]}"#,
)
} else {
("404 Not Found", r#"{"error":"nope"}"#)
};
let _ = write!(
s,
"HTTP/1.1 {code}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
body.len()
);
}
});
let models = list_models(&base, None, std::time::Duration::from_secs(2))
.await
.unwrap();
assert_eq!(models, vec!["m-one", "m-two"], "ids, deduplicated");
let err = list_models(
&format!("{base}/wrong"),
None,
std::time::Duration::from_secs(2),
)
.await
.expect_err("404 is not a model list");
assert!(err.to_string().contains("404"), "{err}");
serving.join().unwrap();
}
#[tokio::test]
async fn an_http_failure_keeps_the_status_the_body_and_the_request_id() {
let err_body = r#"{"error":{"message":"upstream model crashed"}}"#;
let (base, server) = serve_script(vec![
(
"500 Internal Server Error",
"x-request-id: req_abc123\r\n",
err_body,
),
(
"500 Internal Server Error",
"x-request-id: req_abc123\r\n",
err_body,
),
(
"500 Internal Server Error",
"x-request-id: req_abc123\r\n",
err_body,
),
(
"500 Internal Server Error",
"x-request-id: req_abc123\r\n",
err_body,
),
])
.await;
let err = OpenAiProvider::new(&cfg(&base))
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.unwrap_err();
let failure = err.provider_failure().expect("a provider failure");
assert_eq!(failure.kind(), crate::error::ProviderFailureKind::Http);
assert_eq!(failure.status(), Some(500));
assert!(
failure.body().unwrap().contains("upstream model crashed"),
"the server's own words survive: {:?}",
failure.body()
);
assert_eq!(failure.request_id(), Some("req_abc123"));
assert_eq!(server.await.unwrap(), 4, "1 try + 3 retries");
let rendered = err.to_string();
assert!(rendered.contains("500"), "{rendered}");
assert!(rendered.contains("upstream model crashed"), "{rendered}");
assert!(rendered.contains("req_abc123"), "{rendered}");
assert!(rendered.contains("4 attempts"), "{rendered}");
}
#[tokio::test]
async fn a_wrong_key_is_classified_as_unauthorized_and_not_retried() {
let (base, server) = serve_script(vec![
("401 Unauthorized", "", r#"{"error":"bad key"}"#),
("200 OK", "", OK_BODY),
])
.await;
let err = OpenAiProvider::new(&cfg(&base))
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.unwrap_err();
assert_eq!(
err.provider_failure().map(|f| f.kind()),
Some(crate::error::ProviderFailureKind::Unauthorized)
);
assert!(!err.provider_failure().unwrap().is_retryable());
assert!(
server.await.unwrap() <= 1,
"a bad key is not worth repeating"
);
}
#[tokio::test]
async fn an_option_the_server_refuses_names_the_option_and_the_model() {
let (base, _h) = serve_once(
"400 Bad Request",
r#"{"error":{"message":"unknown field 'top_p'","type":"invalid_request_error"}}"#,
)
.await;
let mut c = cfg(&base);
c.model = "qwen3.8-27b".into();
c.top_p = Some(0.9);
let err = OpenAiProvider::new(&c)
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.unwrap_err();
let failure = err.provider_failure().unwrap();
assert_eq!(
failure.kind(),
crate::error::ProviderFailureKind::InvalidRequest
);
assert_eq!(failure.status(), Some(400));
let hint = failure.hint().expect("a hint naming the field");
assert!(hint.contains("top_p"), "{hint}");
assert!(hint.contains("qwen3.8-27b"), "{hint}");
assert!(
hint.contains("extra_body"),
"it says what to do instead: {hint}"
);
assert!(err.to_string().contains("provider.top_p"), "{err}");
}
#[tokio::test]
async fn an_unreadable_reply_is_not_retried() {
let (base, server) = serve_script(vec![
("200 OK", "", "this is not json"),
("200 OK", "", OK_BODY),
])
.await;
let err = OpenAiProvider::new(&cfg(&base))
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.unwrap_err();
assert_eq!(
err.provider_failure().map(|f| f.kind()),
Some(crate::error::ProviderFailureKind::Response)
);
assert_eq!(server.await.unwrap(), 1, "reading it twice reads the same");
}
#[test]
fn optional_fields_are_absent_from_the_body_until_asked_for() {
let p = OpenAiProvider::new(&cfg("http://h/v1")).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
for key in ["top_p", "seed", "stop", "parallel_tool_calls"] {
assert!(
body.get(key).is_none(),
"{key} must not be sent unless configured: {body}"
);
}
assert_eq!(
body.get("reasoning_effort"),
Some(&serde_json::json!(crate::reasoning::SHIPPED_DEFAULT)),
"the route's declared default is the level an unconfigured request carries: {body}"
);
}
#[test]
fn top_p_seed_and_the_rest_reach_the_body_when_set() {
let mut c = cfg("http://h/v1");
c.top_p = Some(0.9);
c.seed = Some(7);
c.stop = Some(vec!["</s>".into(), "USER:".into()]);
c.reasoning_effort = Some("high".into());
c.parallel_tool_calls = Some(false);
let p = OpenAiProvider::new(&c).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(body["top_p"], json!(0.9));
assert_eq!(body["seed"], json!(7));
assert_eq!(body["stop"], json!(["</s>", "USER:"]));
assert_eq!(body["reasoning_effort"], json!("high"));
assert_eq!(body["parallel_tool_calls"], json!(false));
}
#[tokio::test]
async fn the_options_are_on_the_wire_not_just_in_the_body_builder() {
let (base, h) = serve_once("200 OK", OK_BODY).await;
let mut c = cfg(&base);
c.top_p = Some(0.9);
c.seed = Some(7);
OpenAiProvider::new(&c)
.unwrap()
.chat(&[Message::user("x")], &[])
.await
.unwrap();
let sent = h.await.unwrap();
assert!(sent.contains("\"top_p\":0.9"), "{sent}");
assert!(sent.contains("\"seed\":7"), "{sent}");
}
#[test]
fn an_out_of_range_top_p_is_a_config_error_rather_than_a_400() {
let mut c = cfg("http://h/v1");
c.top_p = Some(1.5);
let err = OpenAiProvider::new(&c).unwrap_err().to_string();
assert!(err.contains("provider.top_p"), "{err}");
assert!(err.contains("1.5"), "{err}");
}
#[test]
fn a_tool_choice_from_config_overrides_the_profiles_default() {
let tools = vec![ToolSpec {
kind: "function",
function: ToolSpecFunction {
name: "read_file".into(),
description: "read".into(),
parameters: json!({"type": "object"}),
},
}];
let mut c = cfg("http://h/v1");
c.profile = Some("llamacpp".into());
let plain = OpenAiProvider::new(&c).unwrap();
assert!(plain
.request_body(&[Message::user("hi")], &tools)
.get("tool_choice")
.is_none());
c.tool_choice = Some(ToolChoice::Function("read_file".into()));
let forced = OpenAiProvider::new(&c).unwrap();
let body = forced.request_body(&[Message::user("hi")], &tools);
assert_eq!(
body["tool_choice"],
json!({"type": "function", "function": {"name": "read_file"}})
);
}
#[test]
fn extra_body_is_the_escape_hatch_and_a_turn_patch_still_wins() {
let mut c = cfg("http://h/v1");
c.extra_body = Some(json!({
"chat_template_kwargs": {"enable_thinking": false},
"seed": 1
}));
let p = OpenAiProvider::new(&c).unwrap();
let body = p.request_body(&[Message::user("hi")], &[]);
assert_eq!(
body["chat_template_kwargs"]["enable_thinking"],
json!(false)
);
assert_eq!(body["seed"], json!(1));
let patch = crate::hooks::RequestPatch {
extra_params: [("seed".to_string(), json!(99))].into_iter().collect(),
..Default::default()
};
let patched = p.request_body_with(&[Message::user("hi")], &[], &patch);
assert_eq!(patched["seed"], json!(99));
assert_eq!(
patched["chat_template_kwargs"]["enable_thinking"],
json!(false)
);
}
#[tokio::test]
async fn a_stream_cut_before_any_text_is_retried_once_and_can_succeed() {
let (base, server) =
serve_sse_cut_then_ok("data: {\"choices\":[],\"usage\":{\"total_tokens\":3}}\n\n")
.await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let reply = p
.chat_stream(&[Message::user("x")], &[], &|_| {})
.await
.expect("a cut before any text is worth one more request");
assert_eq!(reply.content.as_deref(), Some("whole"));
assert_eq!(server.await.unwrap(), 2);
}
#[tokio::test]
async fn a_stream_cut_after_text_is_not_retried() {
let (base, server) =
serve_sse_cut_then_ok("data: {\"choices\":[{\"delta\":{\"content\":\"half\"}}]}\n\n")
.await;
let p = OpenAiProvider::new(&cfg(&base)).unwrap();
let seen = Mutex::new(Vec::<String>::new());
let err = p
.chat_stream(&[Message::user("x")], &[], &|d| {
if let crate::stream::Delta::Text(t) = d {
seen.lock().unwrap().push(t);
}
})
.await
.unwrap_err();
assert_eq!(*seen.lock().unwrap(), ["half"]);
assert_eq!(
err.provider_failure().map(|f| f.kind()),
Some(crate::error::ProviderFailureKind::Truncated)
);
assert_eq!(server.await.unwrap(), 1, "the reader already saw the start");
}
#[test]
fn a_field_name_is_matched_as_a_word_not_as_a_substring() {
assert!(mentions_field("unknown field 'top_p'", "top_p"));
assert!(mentions_field("top_p is not supported", "top_p"));
assert!(!mentions_field("the stop_reason was null", "stop"));
assert!(!mentions_field("unstoppable", "stop"));
assert!(mentions_field("bad value for stop", "stop"));
}
#[test]
fn per_route_vision_overrides_the_profile() {
let mut c = cfg("http://h/v1");
c.profile = Some("llamacpp".into());
assert!(!OpenAiProvider::new(&c).unwrap().can_see());
c.vision = Some(true);
assert!(OpenAiProvider::new(&c).unwrap().can_see());
let mut seeing = ProviderProfile::builtin("openai").unwrap();
seeing.name = "seeing".into();
seeing.vision = Some(true);
let profiles = [seeing];
c.profile = Some("seeing".into());
c.vision = None;
assert!(OpenAiProvider::with_profiles(&c, &profiles)
.unwrap()
.can_see());
c.vision = Some(false);
assert!(!OpenAiProvider::with_profiles(&c, &profiles)
.unwrap()
.can_see());
}
}