use serde_json::{json, Value};
use super::chat::{Block, Event, Message, Reply, Request, Role, Stop, Usage};
use super::http::{self, AiError, Body, Sse};
use crate::jobs::CancelToken;
pub const VERSION: &str = "2026-10-21";
fn headers(key: Option<&str>, workspace: Option<&str>) -> Vec<(&'static str, String)> {
let mut h = vec![("anthropic-version", VERSION.to_string())];
if let Some(k) = key {
h.push(("x-api-key", k.to_string()));
}
if let Some(w) = workspace {
h.push(("anthropic-workspace-id", w.to_string()));
}
h
}
pub fn body(req: &Request, extras: bool, no_thinking: bool) -> Value {
let mut b = json!({
"model": req.model,
"max_tokens": req.max_tokens,
"messages": messages(req.messages, no_thinking),
"stream": true,
});
if !req.system.is_empty() {
b["system"] = json!(req.system);
}
if !req.tools.is_empty() {
b["tools"] = req
.tools
.iter()
.map(
|t| json!({"name": t.name, "description": t.description, "input_schema": t.schema}),
)
.collect();
}
if extras {
let mut oc = serde_json::Map::new();
if let Some(e) = req.effort {
oc.insert("effort".into(), json!(e.id()));
}
if let Some(schema) = req.json {
oc.insert(
"format".into(),
json!({"type": "json_schema", "schema": schema}),
);
}
if !oc.is_empty() {
b["output_config"] = Value::Object(oc);
}
b["cache_control"] = json!({"type": "ephemeral"});
}
b
}
fn is_thinking(v: &Value) -> bool {
matches!(
v.get("type").and_then(|t| t.as_str()),
Some("thinking" | "redacted_thinking")
)
}
fn messages(ms: &[Message], no_thinking: bool) -> Value {
ms.iter()
.map(|m| {
let role = match m.role {
Role::User => "user",
Role::Assistant => "assistant",
};
let mut content: Vec<Value> = m
.blocks
.iter()
.filter_map(|b| match b {
Block::Text(t) if t.trim().is_empty() => None,
Block::Text(t) => Some(json!({"type": "text", "text": t})),
Block::ToolUse { id, name, input } => {
Some(json!({"type": "tool_use", "id": id, "name": name, "input": input}))
}
Block::ToolResult {
id,
content,
is_error,
} => Some(json!({
"type": "tool_result",
"tool_use_id": id,
"content": if content.is_empty() { "(empty)" } else { content.as_str() },
"is_error": is_error,
})),
Block::Opaque(v) if no_thinking && is_thinking(v) => None,
Block::Opaque(v) => Some(v.clone()),
})
.collect();
if content.is_empty() {
content.push(json!({"type": "text", "text": "…"}));
}
json!({"role": role, "content": content})
})
.collect()
}
fn about_extras(message: &str) -> bool {
let m = message.to_ascii_lowercase();
[
"effort",
"output_config",
"cache_control",
"json_schema",
"structured",
]
.iter()
.any(|w| m.contains(w))
}
pub fn send(
base: &str,
key: Option<&str>,
workspace: Option<&str>,
req: &Request,
cancel: &CancelToken,
on_event: &mut dyn FnMut(Event),
) -> Result<Reply, AiError> {
let url = format!("{base}/messages");
let h = headers(key, workspace);
let (mut extras, mut no_thinking) = (true, false);
loop {
let b = serde_json::to_vec(&body(req, extras, no_thinking)).unwrap_or_default();
match http::post(&url, &h, &b, key, cancel) {
Ok(Body::Stream(s)) => return parse_stream(s, cancel, on_event),
Ok(Body::Whole(t)) => return parse_whole(&t),
Err(AiError::Status {
code: 400, message, ..
}) if extras && about_extras(&message) => extras = false,
Err(AiError::Status {
code: 400, message, ..
}) if !no_thinking && message.contains("signature") => no_thinking = true,
Err(e) => return Err(e),
}
}
}
fn usage_of(u: &Value, into: &mut Usage) {
let n = |k: &str| u.get(k).and_then(|v| v.as_u64());
if let Some(x) = n("input_tokens") {
into.input = x;
}
if let Some(x) = n("output_tokens") {
into.output = x;
}
if let Some(x) = n("cache_read_input_tokens") {
into.cache_read = x;
}
if let Some(x) = n("cache_creation_input_tokens") {
into.cache_write = x;
}
}
fn stop_of(s: &str) -> Stop {
match s {
"end_turn" | "stop_sequence" => Stop::EndTurn,
"tool_use" => Stop::ToolUse,
"max_tokens" => Stop::MaxTokens,
"refusal" => Stop::Refusal,
o => Stop::Other(o.to_string()),
}
}
fn stream_error(v: &Value) -> AiError {
let e = v.get("error").unwrap_or(v);
let code = match e.get("type").and_then(|t| t.as_str()) {
Some("overloaded_error") => 529,
Some("rate_limit_error") => 429,
Some("invalid_request_error") => 400,
Some("authentication_error") => 401,
Some("permission_error") => 403,
Some("not_found_error") => 404,
_ => 500,
};
AiError::Status {
code,
message: e
.get("message")
.and_then(|m| m.as_str())
.unwrap_or_default()
.to_string(),
retry_after: None,
}
}
enum Part {
Text(String),
Tool {
id: String,
name: String,
json: String,
},
Thinking {
thinking: String,
signature: String,
},
Other(Value),
}
pub(crate) fn tool_input(raw: &str) -> Value {
if raw.trim().is_empty() {
return json!({});
}
serde_json::from_str(raw).unwrap_or_else(|_| Value::String(raw.to_string()))
}
fn parse_stream<R: std::io::BufRead>(
mut sse: Sse<R>,
cancel: &CancelToken,
on_event: &mut dyn FnMut(Event),
) -> Result<Reply, AiError> {
let mut parts: Vec<Part> = Vec::new();
let mut usage = Usage::default();
let mut model = String::new();
let mut stop = None;
let mut done = false;
loop {
if cancel.is_cancelled() {
return Err(AiError::Cancelled);
}
let ev = sse
.next_event()
.map_err(|e| AiError::Network(e.to_string()))?;
let Some((_, data)) = ev else { break };
if data.trim().is_empty() {
continue;
}
let v: Value = serde_json::from_str(&data)
.map_err(|e| AiError::Protocol(format!("an event is not JSON: {e}")))?;
match v.get("type").and_then(|t| t.as_str()).unwrap_or_default() {
"message_start" => {
let m = &v["message"];
model = m["model"].as_str().unwrap_or_default().to_string();
usage_of(&m["usage"], &mut usage);
}
"content_block_start" => {
let cb = &v["content_block"];
let part = match cb["type"].as_str().unwrap_or_default() {
"text" => Part::Text(cb["text"].as_str().unwrap_or_default().to_string()),
"tool_use" => {
let name = cb["name"].as_str().unwrap_or_default().to_string();
on_event(Event::Tool(&name));
Part::Tool {
id: cb["id"].as_str().unwrap_or_default().to_string(),
name,
json: String::new(),
}
}
"thinking" => {
on_event(Event::Thinking);
Part::Thinking {
thinking: cb["thinking"].as_str().unwrap_or_default().to_string(),
signature: cb["signature"].as_str().unwrap_or_default().to_string(),
}
}
_ => Part::Other(cb.clone()),
};
let i = v["index"].as_u64().unwrap_or(parts.len() as u64) as usize;
if i < parts.len() {
parts[i] = part;
} else {
parts.push(part);
}
}
"content_block_delta" => {
let i = v["index"].as_u64().unwrap_or(0) as usize;
let d = &v["delta"];
let s = |k: &str| d[k].as_str().unwrap_or_default();
match (parts.get_mut(i), d["type"].as_str().unwrap_or_default()) {
(Some(Part::Text(t)), "text_delta") => {
t.push_str(s("text"));
on_event(Event::Text(s("text")));
}
(Some(Part::Tool { json, .. }), "input_json_delta") => {
json.push_str(s("partial_json"))
}
(Some(Part::Thinking { thinking, .. }), "thinking_delta") => {
thinking.push_str(s("thinking"));
on_event(Event::Thinking);
}
(Some(Part::Thinking { signature, .. }), "signature_delta") => {
signature.push_str(s("signature"))
}
_ => {}
}
}
"message_delta" => {
if let Some(s) = v["delta"]["stop_reason"].as_str() {
stop = Some(stop_of(s));
}
usage_of(&v["usage"], &mut usage);
}
"message_stop" => {
done = true;
break;
}
"error" => return Err(stream_error(&v)),
_ => {}
}
}
if !done && stop.is_none() {
return Err(AiError::Network("the answer stopped early".into()));
}
let blocks = parts
.into_iter()
.map(|p| match p {
Part::Text(t) => Block::Text(t),
Part::Tool { id, name, json } => Block::ToolUse {
id,
name,
input: tool_input(&json),
},
Part::Thinking {
thinking,
signature,
} => Block::Opaque(
json!({"type": "thinking", "thinking": thinking, "signature": signature}),
),
Part::Other(v) => Block::Opaque(v),
})
.collect();
Ok(Reply {
blocks,
stop: stop.unwrap_or(Stop::EndTurn),
usage,
model,
})
}
fn parse_whole(text: &str) -> Result<Reply, AiError> {
let v: Value = serde_json::from_str(text)
.map_err(|e| AiError::Protocol(format!("the answer is not JSON: {e}")))?;
if v["type"] == "error" {
return Err(stream_error(&v));
}
let Some(content) = v["content"].as_array() else {
return Err(AiError::Protocol("the answer has no content".into()));
};
let blocks = content
.iter()
.map(|b| match b["type"].as_str().unwrap_or_default() {
"text" => Block::Text(b["text"].as_str().unwrap_or_default().to_string()),
"tool_use" => Block::ToolUse {
id: b["id"].as_str().unwrap_or_default().to_string(),
name: b["name"].as_str().unwrap_or_default().to_string(),
input: b["input"].clone(),
},
_ => Block::Opaque(b.clone()),
})
.collect();
let mut usage = Usage::default();
usage_of(&v["usage"], &mut usage);
Ok(Reply {
blocks,
stop: stop_of(v["stop_reason"].as_str().unwrap_or("end_turn")),
usage,
model: v["model"].as_str().unwrap_or_default().to_string(),
})
}
pub fn models(
base: &str,
key: Option<&str>,
workspace: Option<&str>,
) -> Result<Vec<String>, AiError> {
let text = http::get(
&format!("{base}/models?limit=1000"),
&headers(key, workspace),
key,
)?;
super::openai::model_ids(&text)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ai::chat::{Effort, ToolSpec};
use crate::ai::fake::{FakeReply, FakeServer};
fn tool() -> ToolSpec {
ToolSpec {
name: "find_all".into(),
description: "Find".into(),
schema: json!({"type": "object", "properties": {"pattern": {"type": "string"}}}),
}
}
#[test]
fn request_body() {
let msgs = vec![
Message::user("find errors"),
Message {
role: Role::Assistant,
blocks: vec![
Block::Opaque(json!({"type": "thinking", "thinking": "", "signature": "s"})),
Block::ToolUse {
id: "t1".into(),
name: "find_all".into(),
input: json!({"pattern": "ERROR"}),
},
],
},
Message {
role: Role::User,
blocks: vec![Block::ToolResult {
id: "t1".into(),
content: "{\"count\": 3}".into(),
is_error: false,
}],
},
];
let tools = [tool()];
let req = Request {
model: "claude-opus-5-5",
system: "sys",
messages: &msgs,
tools: &tools,
max_tokens: 4096,
json: None,
effort: Some(Effort::Low),
};
let b = body(&req, true, false);
assert_eq!(b["system"], "sys");
assert_eq!(b["output_config"]["effort"], "low");
assert_eq!(b["cache_control"]["type"], "ephemeral");
assert_eq!(b["tools"][0]["input_schema"]["type"], "object");
assert_eq!(b["messages"][1]["content"][0]["signature"], "s");
assert_eq!(b["messages"][2]["content"][0]["tool_use_id"], "t1");
assert!(b.get("temperature").is_none());
let plain = body(&req, false, true);
assert!(plain.get("output_config").is_none());
assert!(plain.get("cache_control").is_none());
assert_eq!(plain["messages"][1]["content"][0]["type"], "tool_use");
}
#[test]
fn streamed_tool_call_and_thinking() {
let server = FakeServer::start(vec![FakeReply::anthropic_tool(
"find_all",
r#"{"pattern":"ERROR","regex":false}"#,
)])
.unwrap();
let msgs = [Message::user("find errors")];
let tools = [tool()];
let req = Request {
model: "claude-opus-5-5",
system: "",
messages: &msgs,
tools: &tools,
max_tokens: 1024,
json: None,
effort: None,
};
let mut seen = Vec::new();
let r = send(
&server.url,
Some("sk-ant-test"),
None,
&req,
&CancelToken::new(),
&mut |e| seen.push(format!("{e:?}")),
)
.unwrap();
assert_eq!(r.stop, Stop::ToolUse);
let calls = r.message();
let calls = calls.tool_uses();
assert_eq!(calls[0].1, "find_all");
assert_eq!(calls[0].2["pattern"], "ERROR");
assert!(matches!(&r.blocks[0], Block::Opaque(v) if v["signature"] == "sig"));
assert_eq!(r.usage.input, 120);
assert_eq!(r.usage.output, 30);
assert!(seen.iter().any(|s| s.contains("Tool")));
let reqs = server.requests();
assert_eq!(reqs[0].path, "/messages");
assert_eq!(reqs[0].header("x-api-key"), Some("sk-ant-test"));
assert_eq!(reqs[0].header("anthropic-version"), Some(VERSION));
assert_eq!(reqs[0].header("anthropic-workspace-id"), None);
}
#[test]
fn an_organization_key_names_its_workspace() {
let server = FakeServer::start(vec![
FakeReply::anthropic_text("ok"),
FakeReply::json(r#"{"data":[{"id":"claude-opus-5-5"}]}"#),
])
.unwrap();
let msgs = [Message::user("hi")];
let req = Request {
model: "m",
system: "",
messages: &msgs,
tools: &[],
max_tokens: 100,
json: None,
effort: None,
};
send(
&server.url,
Some("k"),
Some("wrkspc_test"),
&req,
&CancelToken::new(),
&mut |_| {},
)
.unwrap();
assert_eq!(
models(&server.url, Some("k"), Some("wrkspc_test")).unwrap(),
vec!["claude-opus-5-5"]
);
for r in server.requests() {
assert_eq!(r.header("anthropic-workspace-id"), Some("wrkspc_test"));
}
}
#[test]
fn extras_are_dropped_after_a_400_about_them() {
let server = FakeServer::start(vec![
FakeReply::error(400, r#"{"type":"error","error":{"type":"invalid_request_error","message":"output_config.effort: not supported on this model"}}"#),
FakeReply::anthropic_text("ok"),
])
.unwrap();
let msgs = [Message::user("hi")];
let req = Request {
model: "m",
system: "",
messages: &msgs,
tools: &[],
max_tokens: 100,
json: None,
effort: Some(Effort::Low),
};
let r = send(
&server.url,
Some("k"),
None,
&req,
&CancelToken::new(),
&mut |_| {},
)
.unwrap();
assert_eq!(r.text(), "ok");
let reqs = server.requests();
assert_eq!(reqs.len(), 2);
assert!(reqs[0].body.contains("effort"));
assert!(!reqs[1].body.contains("effort"));
}
#[test]
fn errors_carry_the_providers_message() {
let server = FakeServer::start(vec![FakeReply::error(
401,
r#"{"type":"error","error":{"type":"authentication_error","message":"invalid x-api-key"}}"#,
)])
.unwrap();
let msgs = [Message::user("hi")];
let req = Request {
model: "m",
system: "",
messages: &msgs,
tools: &[],
max_tokens: 100,
json: None,
effort: None,
};
let e = send(
&server.url,
Some("k"),
None,
&req,
&CancelToken::new(),
&mut |_| {},
)
.unwrap_err();
assert_eq!(
e,
AiError::Status {
code: 401,
message: "invalid x-api-key".into(),
retry_after: None
}
);
}
#[test]
fn a_whole_answer_is_read_too() {
let r = parse_whole(r#"{"model":"m","content":[{"type":"text","text":"hello"}],"stop_reason":"end_turn","usage":{"input_tokens":5,"output_tokens":1}}"#).unwrap();
assert_eq!(r.text(), "hello");
assert_eq!(r.usage.input, 5);
}
}