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

566 lines
20 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Anthropic Messages API over Claude subscription OAuth.
use crate::auth::{Auth, Kind};
use crate::{
ContentBlock, Error, Message, Provider, Request, Result, Role, StopReason, StreamEvent, Usage,
};
use eventsource_stream::Eventsource;
use futures::{StreamExt, stream::BoxStream};
use serde_json::{Value, json};
const CC_VERSION: &str = "2.1.280";
const CC_IDENTITY: &str = "You are Claude Code, Anthropic's official CLI for Claude.";
/// OAuth tokens are only accepted with Claude Code tool-name casing.
const CC_TOOLS: &[&str] = &[
"Read",
"Write",
"Edit",
"Bash",
"Grep",
"Glob",
"WebFetch",
"WebSearch",
"Task",
"TodoWrite",
];
fn to_cc(name: &str) -> String {
CC_TOOLS
.iter()
.find(|t| t.eq_ignore_ascii_case(name))
.map_or_else(|| name.to_string(), |t| t.to_string())
}
fn from_cc(name: &str, req: &Request) -> String {
req.tools
.iter()
.find(|t| t.name.eq_ignore_ascii_case(name))
.map_or_else(|| name.to_string(), |t| t.name.clone())
}
pub struct Anthropic {
auth: Auth,
base_url: String,
http: reqwest::Client,
}
impl Anthropic {
pub fn new(auth: Auth) -> Self {
Self {
auth,
base_url: "https://api.anthropic.com".into(),
http: reqwest::Client::new(),
}
}
pub fn login_default() -> Result<Self> {
Ok(Self::new(Auth::load(Kind::Claude)?))
}
pub fn with_base_url(mut self, u: impl Into<String>) -> Self {
self.base_url = u.into();
self
}
}
fn block_json(b: &ContentBlock) -> Value {
match b {
ContentBlock::Image { media_type, data } => json!({
"type": "image",
"source": {"type": "base64", "media_type": media_type, "data": data}
}),
ContentBlock::ToolUse { id, name, input } => {
json!({"type": "tool_use", "id": id, "name": to_cc(name), "input": input})
}
other => serde_json::to_value(other).unwrap_or(Value::Null),
}
}
pub fn body(req: &Request) -> Value {
let mut system = vec![json!({"type": "text", "text": CC_IDENTITY})];
if !req.system.is_empty() {
system.push(json!({"type": "text", "text": req.system}));
}
// cache the stable prefix
if let Some(last) = system.last_mut() {
last["cache_control"] = json!({"type": "ephemeral"});
}
let mut messages: Vec<Value> = req
.messages
.iter()
.map(|m| json!({"role": m.role, "content": m.content.iter().map(block_json).collect::<Vec<_>>()}))
.collect();
// Rolling breakpoints (tools+system are covered by the system one): the last message, and the
// user message before it, which is where the previous request's breakpoint sat -> cache read.
let n = messages.len();
let prev_user = (0..n.saturating_sub(1))
.rev()
.find(|&i| req.messages[i].role == Role::User);
for i in [n.checked_sub(1), prev_user].into_iter().flatten() {
if req.messages[i].role != Role::User {
continue;
}
if let Some(last) = messages[i]["content"]
.as_array_mut()
.and_then(|c| c.last_mut())
{
last["cache_control"] = json!({"type": "ephemeral"});
}
}
let tools: Vec<Value> = req
.tools
.iter()
.map(|t| json!({"name": to_cc(&t.name), "description": t.description, "input_schema": t.input_schema}))
.collect();
let mut b = json!({
"model": req.model,
"max_tokens": req.max_tokens,
"stream": true,
"system": system,
"messages": messages,
});
if !tools.is_empty() {
b["tools"] = tools.into();
}
// ponytail: fixed token budgets; newer models may prefer adaptive thinking, add when needed
let budget = match req.effort {
crate::Effort::Off => 0,
crate::Effort::Low => 4_000,
crate::Effort::Medium => 10_000,
crate::Effort::High => 24_000,
};
if budget > 0 {
b["thinking"] = json!({"type": "enabled", "budget_tokens": budget});
// the budget counts against max_tokens, which must leave room for the reply
b["max_tokens"] = req.max_tokens.max(budget + 4_096).into();
}
b
}
/// Folds Anthropic SSE events into `StreamEvent`s.
#[derive(Default)]
pub struct Assembler {
blocks: Vec<ContentBlock>,
/// partial JSON for tool_use input, per block index
partial: Vec<String>,
usage: Usage,
stop: Option<StopReason>,
}
impl Assembler {
pub fn feed(&mut self, event: &str, data: &str, req: &Request) -> Result<Vec<StreamEvent>> {
let d: Value = match event {
"ping" | "" => return Ok(vec![]),
_ => serde_json::from_str(data).map_err(|e| Error::Decode(format!("{e}: {data}")))?,
};
let u = |v: &Value| v.as_u64().unwrap_or(0);
let mut out = vec![];
match event {
"message_start" => {
let us = &d["message"]["usage"];
self.usage.input_tokens = u(&us["input_tokens"]);
self.usage.cache_read_tokens = u(&us["cache_read_input_tokens"]);
self.usage.cache_write_tokens = u(&us["cache_creation_input_tokens"]);
self.usage.output_tokens = u(&us["output_tokens"]);
}
"content_block_start" => {
let cb = &d["content_block"];
let s = |k: &str| cb[k].as_str().unwrap_or_default().to_string();
let b = match cb["type"].as_str() {
Some("text") => ContentBlock::Text { text: s("text") },
Some("thinking") => ContentBlock::Thinking {
thinking: s("thinking"),
signature: None,
},
Some("tool_use") => {
let name = from_cc(&s("name"), req);
out.push(StreamEvent::ToolUseStart {
id: s("id"),
name: name.clone(),
});
ContentBlock::ToolUse {
id: s("id"),
name,
input: json!({}),
}
}
// redacted_thinking etc: keep as empty text so indices stay aligned
_ => ContentBlock::Text {
text: String::new(),
},
};
self.blocks.push(b);
self.partial.push(String::new());
}
"content_block_delta" => {
let i = u(&d["index"]) as usize;
let dl = &d["delta"];
let s = |k: &str| dl[k].as_str().unwrap_or_default();
let (Some(b), Some(p)) = (self.blocks.get_mut(i), self.partial.get_mut(i)) else {
return Err(Error::Decode(format!("delta for unknown block {i}")));
};
match (dl["type"].as_str(), b) {
(Some("text_delta"), ContentBlock::Text { text }) => {
text.push_str(s("text"));
out.push(StreamEvent::TextDelta {
text: s("text").into(),
});
}
(Some("thinking_delta"), ContentBlock::Thinking { thinking, .. }) => {
thinking.push_str(s("thinking"));
out.push(StreamEvent::ThinkingDelta {
text: s("thinking").into(),
});
}
(Some("signature_delta"), ContentBlock::Thinking { signature, .. }) => {
*signature = Some(s("signature").into());
}
(Some("input_json_delta"), ContentBlock::ToolUse { .. }) => {
p.push_str(s("partial_json"))
}
_ => {}
}
}
"content_block_stop" => {
let i = u(&d["index"]) as usize;
if let (Some(ContentBlock::ToolUse { input, .. }), Some(p)) =
(self.blocks.get_mut(i), self.partial.get(i))
&& !p.is_empty()
{
*input = serde_json::from_str(p)
.map_err(|e| Error::Decode(format!("tool input: {e}: {p}")))?;
}
}
"message_delta" => {
self.usage.output_tokens =
u(&d["usage"]["output_tokens"]).max(self.usage.output_tokens);
self.stop = Some(match d["delta"]["stop_reason"].as_str() {
Some("end_turn" | "stop_sequence") => StopReason::EndTurn,
Some("tool_use") => StopReason::ToolUse,
Some("max_tokens") => StopReason::MaxTokens,
_ => StopReason::Other,
});
}
"message_stop" => {
let content = std::mem::take(&mut self.blocks)
.into_iter()
.filter(|b| !matches!(b, ContentBlock::Text { text } if text.is_empty()))
.collect();
out.push(StreamEvent::Done {
message: Message {
role: Role::Assistant,
content,
},
stop: self.stop.unwrap_or(StopReason::EndTurn),
usage: std::mem::take(&mut self.usage),
});
}
"error" => {
return Err(Error::Api {
status: 0,
body: d["error"].to_string(),
});
}
_ => {}
}
Ok(out)
}
}
/// Claude subscription limits from `anthropic-ratelimit-unified-*` headers (5h and 7d windows,
/// utilization as a 0–1 fraction, reset as unix seconds) plus extra-usage (overage) state.
pub fn quota(h: &reqwest::header::HeaderMap) -> Option<crate::Quota> {
use crate::hdr;
let mut q = crate::Quota::default();
for (abbr, label) in [("5h", "5h"), ("7d", "week")] {
let util = hdr(
h,
&format!("anthropic-ratelimit-unified-{abbr}-utilization"),
)
.and_then(|v| v.parse::<f64>().ok());
if let Some(u) = util {
q.windows.push(crate::QuotaWindow {
label: label.into(),
used_pct: (u * 100.0).clamp(0.0, 100.0),
resets_at: hdr(h, &format!("anthropic-ratelimit-unified-{abbr}-reset"))
.and_then(|v| v.parse().ok()),
});
}
}
q.credits = match hdr(h, "anthropic-ratelimit-unified-overage-status") {
Some(s @ ("allowed" | "allowed_warning"))
if hdr(h, "anthropic-ratelimit-unified-status") == Some("rejected") =>
{
Some(format!("using extra usage ({s})"))
}
Some("rejected") => hdr(h, "anthropic-ratelimit-unified-overage-disabled-reason")
.map(|r| format!("extra usage off: {r}")),
_ => None,
};
(!q.windows.is_empty() || q.credits.is_some()).then_some(q)
}
#[async_trait::async_trait]
impl Provider for Anthropic {
/// `GET /v1/models` — ids, newest first, with `max_input_tokens` as the window.
async fn models(&self) -> Result<Vec<crate::models::ModelInfo>> {
let (token, _) = self.auth.token().await?;
let v: Value = self
.http
.get(format!("{}/v1/models?limit=100", self.base_url))
.bearer_auth(token)
.header("anthropic-version", "2023-06-01")
.header("anthropic-beta", "oauth-2025-04-20")
.header("user-agent", format!("claude-cli/{CC_VERSION}"))
.send()
.await
.map_err(|e| Error::Http(e.to_string()))?
.error_for_status()
.map_err(|e| Error::Http(e.to_string()))?
.json()
.await
.map_err(|e| Error::Decode(e.to_string()))?;
Ok(parse_models(&v))
}
async fn stream(&self, req: Request) -> Result<BoxStream<'static, Result<StreamEvent>>> {
let (token, _) = self.auth.token().await?;
let r = self
.http
.post(format!("{}/v1/messages", self.base_url))
.bearer_auth(token)
.header("anthropic-version", "2023-06-01")
.header(
"anthropic-beta",
"claude-code-20250219,oauth-2025-04-20,interleaved-thinking-2025-05-14",
)
.header("user-agent", format!("claude-cli/{CC_VERSION}"))
.header("x-app", "cli")
.json(&body(&req))
.send()
.await
.map_err(|e| Error::Http(e.to_string()))?;
let status = r.status().as_u16();
if !(200..300).contains(&status) {
let body = r.text().await.unwrap_or_default();
return Err(Error::Api { status, body });
}
let q = quota(r.headers());
let s = r
.bytes_stream()
.eventsource()
.scan(Assembler::default(), move |a, ev| {
let out = match ev {
Ok(ev) => match a.feed(&ev.event, &ev.data, &req) {
Ok(v) => v.into_iter().map(Ok).collect(),
Err(e) => vec![Err(e)],
},
Err(e) => vec![Err(Error::Http(e.to_string()))],
};
futures::future::ready(Some(futures::stream::iter(out)))
})
.flatten();
Ok(crate::with_quota(q, s.boxed()))
}
}
/// `/v1/models` body to catalog entries (aliases only when the API lists them; else ids as-is).
pub fn parse_models(v: &Value) -> Vec<crate::models::ModelInfo> {
v["data"]
.as_array()
.into_iter()
.flatten()
.filter_map(|m| {
let id = m["id"].as_str()?;
Some(crate::models::ModelInfo {
id: id.into(),
kind: Kind::Claude,
context_window: m["max_input_tokens"]
.as_u64()
.filter(|n| *n > 0)
.unwrap_or_else(|| {
crate::models::window(&crate::models::fallback(Kind::Claude), id)
}),
})
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ToolSpec;
#[test]
fn effort_sets_thinking_budget() {
let mut r = req();
assert!(body(&r).get("thinking").is_none());
r.effort = crate::Effort::High;
let b = body(&r);
assert_eq!(b["thinking"]["budget_tokens"], 24_000);
assert!(b["max_tokens"].as_u64().unwrap() > 24_000);
}
#[test]
fn quota_and_models() {
let mut h = reqwest::header::HeaderMap::new();
for (k, v) in [
("anthropic-ratelimit-unified-5h-utilization", "0.42"),
("anthropic-ratelimit-unified-5h-reset", "1790850000"),
("anthropic-ratelimit-unified-7d-utilization", "0.13"),
("anthropic-ratelimit-unified-status", "rejected"),
("anthropic-ratelimit-unified-overage-status", "allowed"),
] {
h.insert(k, v.parse().unwrap());
}
let q = quota(&h).unwrap();
assert_eq!(q.windows[0].label, "5h");
assert!((q.windows[0].used_pct - 42.0).abs() < 1e-9);
assert_eq!(q.windows[0].resets_at, Some(1_790_850_000));
assert_eq!(
(q.windows[1].label.as_str(), q.windows[1].resets_at),
("week", None)
);
assert_eq!(q.credits.as_deref(), Some("using extra usage (allowed)"));
assert!(quota(&reqwest::header::HeaderMap::new()).is_none());
let m = parse_models(&json!({"data": [
{"id": "claude-opus-5-5", "max_input_tokens": 1000000},
{"id": "claude-haiku-4-5-20251001", "max_input_tokens": null},
{"type": "model"}
]}));
assert_eq!(m.len(), 2);
assert_eq!(
(m[0].id.as_str(), m[0].context_window),
("claude-opus-5-5", 1_000_000)
);
assert_eq!(
m[1].context_window, 200_000,
"missing window: catalog guess"
);
}
fn req() -> Request {
Request {
model: "claude-sonnet-4-5".into(),
system: "be terse".into(),
messages: vec![Message::user("read a")],
tools: vec![ToolSpec {
name: "read".into(),
description: "read file".into(),
input_schema: json!({"type": "object"}),
}],
max_tokens: 1024,
effort: crate::Effort::Off,
}
}
#[test]
fn request_body() {
let b = body(&req());
assert_eq!(b["system"][0]["text"], CC_IDENTITY);
assert_eq!(b["system"][1]["text"], "be terse");
assert_eq!(b["tools"][0]["name"], "Read");
assert_eq!(b["messages"][0]["content"][0]["type"], "text");
assert_eq!(b["stream"], true);
// message tail is a cache breakpoint (single user message here)
assert_eq!(
b["messages"][0]["content"][0]["cache_control"]["type"],
"ephemeral"
);
}
#[test]
fn rolling_breakpoints() {
let mut r = req();
r.messages = vec![
Message::user("a"),
Message {
role: Role::Assistant,
content: vec![ContentBlock::Text { text: "b".into() }],
},
Message::user("c"),
];
let b = body(&r);
let has = |i: usize| {
b["messages"][i]["content"][0]
.get("cache_control")
.is_some()
};
assert!(has(0) && !has(1) && has(2));
}
#[test]
fn assemble_tool_use() {
let fixture = r#"message_start|{"type":"message_start","message":{"usage":{"input_tokens":10,"cache_read_input_tokens":3,"output_tokens":1}}}
ping|{}
content_block_start|{"index":0,"content_block":{"type":"thinking","thinking":""}}
content_block_delta|{"index":0,"delta":{"type":"thinking_delta","thinking":"hmm"}}
content_block_delta|{"index":0,"delta":{"type":"signature_delta","signature":"sig"}}
content_block_stop|{"index":0}
content_block_start|{"index":1,"content_block":{"type":"text","text":""}}
content_block_delta|{"index":1,"delta":{"type":"text_delta","text":"Read"}}
content_block_delta|{"index":1,"delta":{"type":"text_delta","text":"ing."}}
content_block_stop|{"index":1}
content_block_start|{"index":2,"content_block":{"type":"tool_use","id":"tu_1","name":"Read","input":{}}}
content_block_delta|{"index":2,"delta":{"type":"input_json_delta","partial_json":"{\"path\":"}}
content_block_delta|{"index":2,"delta":{"type":"input_json_delta","partial_json":"\"a\"}"}}
content_block_stop|{"index":2}
message_delta|{"delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":42}}
message_stop|{}"#;
let r = req();
let mut a = Assembler::default();
let mut evs = vec![];
for l in fixture.lines() {
let (e, d) = l.split_once('|').unwrap();
evs.extend(a.feed(e, d, &r).unwrap());
}
assert_eq!(evs[0], StreamEvent::ThinkingDelta { text: "hmm".into() });
assert_eq!(
evs[3],
StreamEvent::ToolUseStart {
id: "tu_1".into(),
name: "read".into()
}
);
let StreamEvent::Done {
message,
stop,
usage,
} = evs.last().unwrap()
else {
panic!()
};
assert_eq!(*stop, StopReason::ToolUse);
assert_eq!(
(
usage.input_tokens,
usage.output_tokens,
usage.cache_read_tokens
),
(10, 42, 3)
);
assert_eq!(message.text(), "Reading.");
assert_eq!(
message.content[0],
ContentBlock::Thinking {
thinking: "hmm".into(),
signature: Some("sig".into())
}
);
assert_eq!(
message.content[2],
ContentBlock::ToolUse {
id: "tu_1".into(),
name: "read".into(),
input: json!({"path": "a"})
}
);
}
#[test]
fn error_event() {
let e =
Assembler::default().feed("error", r#"{"error":{"type":"overloaded_error"}}"#, &req());
assert!(matches!(e, Err(Error::Api { .. })));
}
}