use std::collections::HashMap;
use std::time::Duration;
use async_trait::async_trait;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use supercode_interchange::{ChatMessage, FunctionCall, Role, ToolCall};
use crate::{CachePlan, ChatRequest, Result, RuntimeError as Error, ToolSchema, Usage};
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
const READ_IDLE_TIMEOUT: Duration = Duration::from_secs(120);
const MAX_RETRIES: u32 = 2;
const RETRY_BACKOFF_BASE: Duration = Duration::from_millis(500);
#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct HttpOptions {
pub(crate) connect_timeout: Duration,
pub(crate) read_idle_timeout: Duration,
pub(crate) max_retries: u32,
pub(crate) retry_backoff_base: Duration,
}
impl Default for HttpOptions {
fn default() -> Self {
HttpOptions {
connect_timeout: CONNECT_TIMEOUT,
read_idle_timeout: READ_IDLE_TIMEOUT,
max_retries: MAX_RETRIES,
retry_backoff_base: RETRY_BACKOFF_BASE,
}
}
}
impl HttpOptions {
#[doc(hidden)]
pub fn from_retry_config(
enabled: bool,
max_retries: Option<u32>,
base_delay_ms: Option<u64>,
) -> HttpOptions {
let base = HttpOptions::default();
HttpOptions {
max_retries: if enabled {
max_retries.unwrap_or(base.max_retries)
} else {
0
},
retry_backoff_base: base_delay_ms
.map(Duration::from_millis)
.unwrap_or(base.retry_backoff_base),
..base
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RetryNotice {
pub attempt: u32,
pub delay_ms: u64,
pub reason: String,
}
#[derive(Debug, Default)]
pub struct RetryLog {
notices: std::sync::Mutex<Vec<RetryNotice>>,
}
impl RetryLog {
pub fn record(&self, notice: RetryNotice) {
self.notices
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.push(notice);
}
pub fn drain(&self) -> Vec<RetryNotice> {
std::mem::take(
&mut *self
.notices
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner),
)
}
}
pub(crate) fn build_request_body(req: &ChatRequest, stream: bool) -> serde_json::Value {
use serde_json::json;
let mut body = json!({
"model": req.model,
"messages": req.messages,
"stream": stream,
});
let obj = body.as_object_mut().unwrap();
if !req.tools.is_empty() {
obj.insert(
"tools".into(),
serde_json::to_value(req.tools.iter().map(WireTool::from).collect::<Vec<_>>()).unwrap(),
);
}
if let Some(t) = req.temperature {
obj.insert("temperature".into(), json!(t));
}
if let Some(m) = req.max_tokens {
obj.insert("max_tokens".into(), json!(m));
}
if let Some(e) = &req.effort {
obj.insert("reasoning_effort".into(), json!(e));
}
if let Some(rf) = &req.response_format {
obj.insert("response_format".into(), rf.clone());
}
if let Some(tier) = &req.service_tier {
obj.insert("service_tier".into(), json!(tier));
}
if let Some(budget) = req.thinking_budget {
let entry = obj
.entry("reasoning".to_string())
.or_insert_with(|| json!({}));
if let Some(o) = entry.as_object_mut() {
o.insert("max_tokens".into(), json!(budget));
}
}
if stream {
obj.insert("stream_options".into(), json!({"include_usage": true}));
}
for (k, v) in &req.extra_body {
obj.insert(k.clone(), v.clone());
}
body
}
#[doc(hidden)]
pub fn apply_cache_plan(
messages: &[ChatMessage],
plan: CachePlan,
imported_prefix_len: Option<usize>,
) -> Vec<ChatMessage> {
let mut out = messages.to_vec();
if !matches!(plan, CachePlan::ImportedPrefix) {
return out;
}
let Some(len) = imported_prefix_len.filter(|&n| n > 0) else {
return out;
};
let last = len - 1;
let mut targets = vec![0usize];
if last != 0 {
targets.push(last);
}
for idx in targets {
if let Some(msg) = out.get_mut(idx) {
annotate_cache_breakpoint(msg);
}
}
out
}
fn annotate_cache_breakpoint(msg: &mut ChatMessage) {
let cache_control = serde_json::json!({"type": "ephemeral"});
if let Some(parts) = msg.content_parts.as_mut() {
if let Some(text_part) = parts
.iter_mut()
.rev()
.find(|p| p.get("type").and_then(serde_json::Value::as_str) == Some("text"))
{
if let Some(obj) = text_part.as_object_mut() {
obj.insert("cache_control".to_string(), cache_control);
}
}
return;
}
let text = msg.content.take().unwrap_or_default();
msg.content_parts = Some(vec![serde_json::json!({
"type": "text",
"text": text,
"cache_control": cache_control,
})]);
}
#[doc(hidden)]
pub fn tier_change_is_cache_bust(previous: Option<u64>, current: u64) -> bool {
previous.is_some_and(|p| p != current)
}
pub(crate) const CACHE_TTL_SECS: i64 = 300;
pub(crate) const CACHE_MISS_RATIO_THRESHOLD: f64 = 0.10;
pub(crate) const CACHE_STALE_DISPROVE_RATIO_THRESHOLD: f64 = 1.0 - CACHE_MISS_RATIO_THRESHOLD;
#[doc(hidden)]
pub fn is_anthropic_family_model(model: &str) -> bool {
model.starts_with("anthropic/") || model.starts_with("claude-") || model.starts_with("claude/")
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[doc(hidden)]
pub enum CacheColdReason {
Stale {
idle_secs: i64,
},
Miss {
cached_tokens: u64,
prompt_tokens: u64,
},
}
impl CacheColdReason {
#[doc(hidden)]
pub fn message(&self) -> String {
match self {
CacheColdReason::Stale { idle_secs } => format!(
"cache likely cold — this turn was sent {}m{:02}s after the cache was last \
refreshed (Anthropic's ephemeral prompt cache expires after 5m idle) — this \
turn likely paid full input cost for the cached prefix",
idle_secs / 60,
idle_secs % 60,
),
CacheColdReason::Miss {
cached_tokens,
prompt_tokens,
} => format!(
"unexpected cache miss — only {cached_tokens}/{prompt_tokens} prompt tokens \
were served from cache this turn even though reuse was expected — this turn \
likely paid full input cost for the cached prefix",
),
}
}
}
#[doc(hidden)]
pub fn cache_cold_reason(
will_annotate: bool,
cache_established: bool,
idle_secs: Option<i64>,
usage: &Usage,
) -> Option<CacheColdReason> {
if !will_annotate {
return None;
}
if let Some(idle_secs) = idle_secs {
if idle_secs >= CACHE_TTL_SECS {
let disproven_by_usage = usage
.prompt_tokens_details
.filter(|_| usage.prompt_tokens > 0)
.is_some_and(|details| {
details.cached_tokens as f64 / usage.prompt_tokens as f64
>= CACHE_STALE_DISPROVE_RATIO_THRESHOLD
});
if !disproven_by_usage {
return Some(CacheColdReason::Stale { idle_secs });
}
}
}
if !cache_established {
return None;
}
let details = usage.prompt_tokens_details?;
if usage.prompt_tokens == 0 {
return None;
}
let ratio = details.cached_tokens as f64 / usage.prompt_tokens as f64;
if ratio < CACHE_MISS_RATIO_THRESHOLD {
return Some(CacheColdReason::Miss {
cached_tokens: details.cached_tokens,
prompt_tokens: usage.prompt_tokens,
});
}
None
}
#[async_trait]
pub trait Provider: Send + Sync {
async fn complete(
&self,
req: &ChatRequest,
on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
) -> Result<(ChatMessage, Usage)>;
}
pub struct OpenAiProvider {
client: reqwest::Client,
base_url: String,
api_key: String,
extra_headers: HashMap<String, String>,
http_options: HttpOptions,
retry_log: Option<std::sync::Arc<RetryLog>>,
}
impl OpenAiProvider {
pub fn new(
base_url: impl Into<String>,
api_key: impl Into<String>,
extra_headers: HashMap<String, String>,
) -> Self {
Self::new_with_options(base_url, api_key, extra_headers, HttpOptions::default())
}
#[doc(hidden)]
pub fn new_with_options(
base_url: impl Into<String>,
api_key: impl Into<String>,
extra_headers: HashMap<String, String>,
http_options: HttpOptions,
) -> Self {
OpenAiProvider {
client: reqwest::Client::builder()
.connect_timeout(http_options.connect_timeout)
.read_timeout(http_options.read_idle_timeout)
.build()
.expect("static reqwest client config cannot fail"),
base_url: base_url.into(),
api_key: api_key.into(),
extra_headers,
http_options,
retry_log: None,
}
}
pub fn with_retry_log(mut self, log: std::sync::Arc<RetryLog>) -> Self {
self.retry_log = Some(log);
self
}
fn endpoint(&self) -> String {
format!("{}/chat/completions", self.base_url.trim_end_matches('/'))
}
async fn send_with_retry(&self, wire: &serde_json::Value) -> Result<reqwest::Response> {
let mut attempt = 0u32;
loop {
let mut builder = self
.client
.post(self.endpoint())
.bearer_auth(&self.api_key)
.header("Content-Type", "application/json");
for (k, v) in &self.extra_headers {
builder = builder.header(k, v);
}
let sent = builder.json(wire).send().await;
let (retryable, result): (bool, Result<reqwest::Response>) = match sent {
Err(e) => (true, Err(Error::from(e))),
Ok(resp) => {
let status = resp.status();
if status.is_success() {
(false, Ok(resp))
} else if status.is_server_error() {
let body = resp.text().await.unwrap_or_default();
(
true,
Err(Error::Provider {
status: status.as_u16(),
body: truncate(&body, 2000),
}),
)
} else {
let body = resp.text().await.unwrap_or_default();
(
false,
Err(Error::Provider {
status: status.as_u16(),
body: truncate(&body, 2000),
}),
)
}
}
};
if !retryable || attempt >= self.http_options.max_retries {
return result;
}
let backoff = self.http_options.retry_backoff_base * 2u32.pow(attempt);
if let Some(log) = &self.retry_log {
log.record(RetryNotice {
attempt,
delay_ms: backoff.as_millis() as u64,
reason: match &result {
Err(e) => e.to_string(),
Ok(_) => String::new(),
},
});
}
tokio::time::sleep(backoff).await;
attempt += 1;
}
}
}
#[async_trait]
impl Provider for OpenAiProvider {
async fn complete(
&self,
req: &ChatRequest,
on_delta: &(dyn for<'a> Fn(&'a str) + Send + Sync),
) -> Result<(ChatMessage, Usage)> {
let wire = build_request_body(req, true);
let resp = self.send_with_retry(&wire).await?;
let mut acc = Accumulator::default();
let mut buf: Vec<u8> = Vec::new();
let mut deltas: Vec<String> = Vec::new();
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
let bytes = chunk?;
buf.extend_from_slice(&bytes);
drain_sse_lines(&mut buf, &mut acc, &mut deltas)?;
for d in deltas.drain(..) {
on_delta(&d);
}
}
let tail = String::from_utf8_lossy(&buf);
if !tail.trim().is_empty() {
handle_sse_line(tail.trim(), &mut acc, &mut deltas)?;
for d in deltas.drain(..) {
on_delta(&d);
}
}
Ok((acc.to_message(), acc_usage(&acc)))
}
}
#[derive(Default)]
struct Accumulator {
content: String,
tool_calls: Vec<ToolCallAccum>,
usage: Usage,
served_model: Option<String>,
}
#[derive(Default)]
struct ToolCallAccum {
id: String,
name: String,
arguments: String,
}
impl Accumulator {
fn ensure(&mut self, index: usize) -> &mut ToolCallAccum {
while self.tool_calls.len() <= index {
self.tool_calls.push(ToolCallAccum::default());
}
&mut self.tool_calls[index]
}
fn to_message(&self) -> ChatMessage {
let calls: Vec<ToolCall> = self
.tool_calls
.iter()
.filter(|c| !c.id.is_empty() || !c.name.is_empty())
.map(|c| ToolCall {
id: c.id.clone(),
kind: "function".to_string(),
function: FunctionCall {
name: c.name.clone(),
arguments: c.arguments.clone(),
},
})
.collect();
ChatMessage {
role: Role::Assistant,
content: (!self.content.is_empty()).then(|| self.content.clone()),
content_parts: None,
tool_calls: (!calls.is_empty()).then_some(calls),
tool_call_id: None,
name: None,
metadata: match &self.served_model {
Some(model) => {
let mut m = std::collections::BTreeMap::new();
m.insert(SERVED_MODEL_KEY.to_string(), model.clone());
m
}
None => Default::default(),
},
}
}
}
pub const SERVED_MODEL_KEY: &str = "served_model";
fn acc_usage(acc: &Accumulator) -> Usage {
acc.usage.clone()
}
fn drain_sse_lines(
buf: &mut Vec<u8>,
acc: &mut Accumulator,
deltas: &mut Vec<String>,
) -> Result<()> {
while let Some(pos) = buf.iter().position(|&b| b == b'\n') {
let line: Vec<u8> = buf.drain(..=pos).collect();
let line = String::from_utf8_lossy(&line);
handle_sse_line(line.trim(), acc, deltas)?;
}
Ok(())
}
fn handle_sse_line(line: &str, acc: &mut Accumulator, deltas: &mut Vec<String>) -> Result<()> {
let Some(data) = line.strip_prefix("data:") else {
return Ok(());
};
let data = data.trim();
if data.is_empty() || data == "[DONE]" {
return Ok(());
}
let chunk: StreamChunk = match serde_json::from_str(data) {
Ok(c) => c,
Err(_) => return Ok(()), };
if let Some(u) = chunk.usage {
acc.usage = u;
}
if let Some(model) = chunk.model {
if !model.is_empty() {
acc.served_model = Some(model);
}
}
for choice in chunk.choices {
if let Some(text) = choice.delta.content {
if !text.is_empty() {
acc.content.push_str(&text);
deltas.push(text);
}
}
for tc in choice.delta.tool_calls.unwrap_or_default() {
let slot = acc.ensure(tc.index);
if let Some(id) = tc.id {
slot.id = id;
}
if let Some(f) = tc.function {
if let Some(name) = f.name {
slot.name.push_str(&name);
}
if let Some(args) = f.arguments {
slot.arguments.push_str(&args);
}
}
}
}
Ok(())
}
fn truncate(s: &str, max: usize) -> String {
if s.len() <= max {
s.to_string()
} else {
let mut end = max;
while end > 0 && !s.is_char_boundary(end) {
end -= 1;
}
format!("{}…", &s[..end])
}
}
#[derive(Serialize)]
struct WireTool<'a> {
#[serde(rename = "type")]
kind: &'static str,
function: WireFunction<'a>,
}
#[derive(Serialize)]
struct WireFunction<'a> {
name: &'a str,
description: &'a str,
parameters: &'a serde_json::Value,
}
impl<'a> From<&'a ToolSchema> for WireTool<'a> {
fn from(t: &'a ToolSchema) -> Self {
WireTool {
kind: "function",
function: WireFunction {
name: &t.name,
description: &t.description,
parameters: &t.parameters,
},
}
}
}
#[derive(Deserialize)]
struct StreamChunk {
#[serde(default)]
choices: Vec<StreamChoice>,
#[serde(default)]
usage: Option<Usage>,
#[serde(default)]
model: Option<String>,
}
#[derive(Deserialize)]
struct StreamChoice {
delta: Delta,
}
#[derive(Deserialize)]
struct Delta {
#[serde(default)]
content: Option<String>,
#[serde(default)]
tool_calls: Option<Vec<ToolCallDelta>>,
}
#[derive(Deserialize)]
struct ToolCallDelta {
#[serde(default)]
index: usize,
#[serde(default)]
id: Option<String>,
#[serde(default)]
function: Option<FnDelta>,
}
#[derive(Deserialize)]
struct FnDelta {
#[serde(default)]
name: Option<String>,
#[serde(default)]
arguments: Option<String>,
}