use serde_json::{json, Value};
use super::anthropic::tool_input;
use super::chat::{Block, Event, Message, Reply, Request, Role, Stop, Usage};
use super::http::{self, AiError, Body, Sse};
use crate::jobs::CancelToken;
fn headers(key: Option<&str>) -> Vec<(&'static str, String)> {
match key {
Some(k) => vec![("authorization", format!("Bearer {k}"))],
None => Vec::new(),
}
}
pub fn body(req: &Request, extras: bool) -> Value {
let mut msgs = Vec::new();
if !req.system.is_empty() {
msgs.push(json!({"role": "system", "content": req.system}));
}
msgs.extend(messages(req.messages));
let mut b = json!({
"model": req.model,
"messages": msgs,
"stream": true,
});
if !req.tools.is_empty() {
b["tools"] = req
.tools
.iter()
.map(|t| {
json!({"type": "function", "function": {
"name": t.name, "description": t.description, "parameters": t.schema}})
})
.collect();
}
if extras {
b["stream_options"] = json!({"include_usage": true});
if req.json.is_some() {
b["response_format"] = json!({"type": "json_object"});
}
}
b
}
fn messages(ms: &[Message]) -> Vec<Value> {
let mut out = Vec::new();
for m in ms {
match m.role {
Role::User => {
for b in &m.blocks {
if let Block::ToolResult {
id,
content,
is_error,
} = b
{
let content = if *is_error {
format!("Error: {content}")
} else {
content.clone()
};
out.push(json!({"role": "tool", "tool_call_id": id, "content": content}));
}
}
let text = m.text();
if !text.is_empty() {
out.push(json!({"role": "user", "content": text}));
}
}
Role::Assistant => {
let calls: Vec<Value> = m
.tool_uses()
.into_iter()
.map(|(id, name, input)| {
json!({"id": id, "type": "function", "function": {
"name": name, "arguments": match input {
Value::String(s) => s.clone(),
v => v.to_string(),
}}})
})
.collect();
let text = m.text();
let mut a = json!({"role": "assistant", "content": if text.is_empty() && !calls.is_empty() { Value::Null } else { json!(text) }});
if !calls.is_empty() {
a["tool_calls"] = Value::Array(calls);
}
out.push(a);
}
}
}
out
}
fn about_extras(message: &str) -> bool {
let m = message.to_ascii_lowercase();
[
"stream_options",
"response_format",
"json_object",
"include_usage",
"unrecognized",
"unknown field",
"extra inputs",
]
.iter()
.any(|w| m.contains(w))
}
const ANSWER_MAX: usize = 256 * 1024;
pub fn send(
base: &str,
key: Option<&str>,
req: &Request,
cancel: &CancelToken,
on_event: &mut dyn FnMut(Event),
) -> Result<Reply, AiError> {
let url = format!("{base}/chat/completions");
let h = headers(key);
let mut extras = true;
loop {
let b = serde_json::to_vec(&body(req, extras)).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 | 422,
message,
..
}) if extras && about_extras(&message) => extras = false,
Err(e) => return Err(e),
}
}
}
#[derive(Default)]
struct Call {
id: String,
name: String,
args: String,
}
fn usage_of(u: &Value, into: &mut Usage) {
if !u.is_object() {
return;
}
let n = |v: &Value| v.as_u64().unwrap_or(0);
let cached = n(&u["prompt_tokens_details"]["cached_tokens"]);
into.input = n(&u["prompt_tokens"]).saturating_sub(cached);
into.cache_read = cached;
into.output = n(&u["completion_tokens"]);
}
fn stop_of(s: &str, calls: bool) -> Stop {
match s {
_ if calls => Stop::ToolUse,
"stop" => Stop::EndTurn,
"tool_calls" | "function_call" => Stop::ToolUse,
"length" => Stop::MaxTokens,
"content_filter" => Stop::Refusal,
o => Stop::Other(o.to_string()),
}
}
fn finish(
text: String,
calls: Vec<Call>,
stop: Option<String>,
usage: Usage,
model: String,
) -> Reply {
let mut blocks = Vec::new();
if !text.is_empty() {
blocks.push(Block::Text(text));
}
let any = !calls.is_empty();
for (i, c) in calls.into_iter().enumerate() {
blocks.push(Block::ToolUse {
id: if c.id.is_empty() {
format!("call_{i}")
} else {
c.id
},
name: c.name,
input: tool_input(&c.args),
});
}
Reply {
blocks,
stop: stop_of(stop.as_deref().unwrap_or("stop"), any),
usage,
model,
}
}
fn error_in(v: &Value) -> Option<AiError> {
let e = v.get("error")?;
let code = e
.get("code")
.and_then(|c| c.as_u64().or_else(|| c.as_str()?.parse().ok()))
.filter(|c| (400..600).contains(c))
.unwrap_or(500) as u16;
Some(AiError::Status {
code,
message: e
.get("message")
.and_then(|m| m.as_str())
.or_else(|| e.as_str())
.unwrap_or_default()
.to_string(),
retry_after: None,
})
}
fn parse_stream<R: std::io::BufRead>(
mut sse: Sse<R>,
cancel: &CancelToken,
on_event: &mut dyn FnMut(Event),
) -> Result<Reply, AiError> {
let mut text = String::new();
let mut calls: Vec<Call> = Vec::new();
let mut stop = None;
let mut usage = Usage::default();
let mut model = String::new();
let mut any = 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 };
let data = data.trim();
if data.is_empty() {
continue;
}
if data == "[DONE]" {
any = true;
break;
}
let v: Value = serde_json::from_str(data)
.map_err(|e| AiError::Protocol(format!("an event is not JSON: {e}")))?;
if let Some(e) = error_in(&v) {
return Err(e);
}
any = true;
if let Some(m) = v["model"].as_str() {
model = m.to_string();
}
usage_of(&v["usage"], &mut usage);
let Some(choice) = v["choices"].get(0) else {
continue;
};
let d = &choice["delta"];
if let Some(t) = d["content"].as_str() {
if !t.is_empty() {
text.push_str(t);
on_event(Event::Text(t));
}
}
if d["reasoning_content"].is_string() || d["reasoning"].is_string() {
on_event(Event::Thinking);
}
if let Some(tcs) = d["tool_calls"].as_array() {
for tc in tcs {
let i = match tc["index"].as_u64() {
Some(i) => (i as usize).min(64),
None if calls.is_empty()
|| tc["id"].is_string()
|| tc["function"]["name"].is_string() =>
{
calls.len()
}
None => calls.len() - 1,
};
while calls.len() <= i {
calls.push(Call::default());
}
let c = &mut calls[i];
if let Some(id) = tc["id"].as_str() {
c.id = id.to_string();
}
let f = &tc["function"];
if let Some(n) = f["name"].as_str() {
if c.name.is_empty() {
on_event(Event::Tool(n));
}
c.name.push_str(n);
}
match &f["arguments"] {
Value::String(a) => c.args.push_str(a),
v @ Value::Object(_) => c.args = v.to_string(),
_ => {}
}
}
}
if let Some(r) = choice["finish_reason"].as_str() {
stop = Some(r.to_string());
}
if text.len() > ANSWER_MAX {
stop = Some("length".into());
break;
}
}
if !any {
return Err(AiError::Network("the answer stopped early".into()));
}
Ok(finish(text, calls, stop, 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 let Some(e) = error_in(&v) {
return Err(e);
}
let Some(choice) = v["choices"].get(0) else {
return Err(AiError::Protocol("the answer has no choices".into()));
};
let m = &choice["message"];
let calls = m["tool_calls"]
.as_array()
.map(|a| {
a.iter()
.map(|tc| Call {
id: tc["id"].as_str().unwrap_or_default().to_string(),
name: tc["function"]["name"]
.as_str()
.unwrap_or_default()
.to_string(),
args: match &tc["function"]["arguments"] {
Value::String(s) => s.clone(),
v => v.to_string(),
},
})
.collect()
})
.unwrap_or_default();
let mut usage = Usage::default();
usage_of(&v["usage"], &mut usage);
Ok(finish(
m["content"].as_str().unwrap_or_default().to_string(),
calls,
choice["finish_reason"].as_str().map(str::to_string),
usage,
v["model"].as_str().unwrap_or_default().to_string(),
))
}
pub(crate) fn model_ids(text: &str) -> Result<Vec<String>, AiError> {
let v: Value = serde_json::from_str(text)
.map_err(|e| AiError::Protocol(format!("the model list is not JSON: {e}")))?;
let list = v["data"]
.as_array()
.or_else(|| v["models"].as_array())
.ok_or_else(|| AiError::Protocol("the answer has no model list".into()))?;
let mut ids: Vec<String> = list
.iter()
.filter_map(|m| {
m["id"]
.as_str()
.or_else(|| m["name"].as_str())
.map(|s| s.trim_start_matches("models/").to_string())
})
.filter(|s| !s.is_empty())
.collect();
ids.sort();
ids.dedup();
Ok(ids)
}
pub fn models(base: &str, key: Option<&str>) -> Result<Vec<String>, AiError> {
model_ids(&http::get(&format!("{base}/models"), &headers(key), key)?)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ai::chat::ToolSpec;
use crate::ai::fake::{FakeReply, FakeServer};
#[test]
fn request_body_with_tool_results() {
let msgs = vec![
Message::user("find errors"),
Message {
role: Role::Assistant,
blocks: vec![Block::ToolUse {
id: "c1".into(),
name: "find_all".into(),
input: json!({"pattern": "ERROR"}),
}],
},
Message {
role: Role::User,
blocks: vec![
Block::ToolResult {
id: "c1".into(),
content: "{\"count\":2}".into(),
is_error: false,
},
Block::Text("and now?".into()),
],
},
];
let tools = [ToolSpec {
name: "find_all".into(),
description: "d".into(),
schema: json!({"type": "object"}),
}];
let schema = json!({"type": "object"});
let req = Request {
model: "llama3",
system: "sys",
messages: &msgs,
tools: &tools,
max_tokens: 100,
json: Some(&schema),
effort: None,
};
let b = body(&req, true);
let m = b["messages"].as_array().unwrap();
assert_eq!(m[0]["role"], "system");
assert_eq!(
m[2]["tool_calls"][0]["function"]["arguments"],
"{\"pattern\":\"ERROR\"}"
);
assert!(m[2]["content"].is_null());
assert_eq!(m[3]["role"], "tool");
assert_eq!(m[3]["tool_call_id"], "c1");
assert_eq!(m[4]["content"], "and now?");
assert_eq!(b["response_format"]["type"], "json_object");
assert_eq!(b["tools"][0]["function"]["name"], "find_all");
assert!(b.get("max_tokens").is_none());
assert!(body(&req, false).get("response_format").is_none());
}
#[test]
fn streamed_text_and_tool_calls() {
let server = FakeServer::start(vec![
FakeReply::openai_text("Hello there"),
FakeReply::openai_tool("count", r#"{"pattern":"timeout"}"#),
])
.unwrap();
let msgs = [Message::user("hi")];
let req = Request {
model: "m",
system: "",
messages: &msgs,
tools: &[],
max_tokens: 100,
json: None,
effort: None,
};
let mut text = String::new();
let r = send(&server.url, None, &req, &CancelToken::new(), &mut |e| {
if let Event::Text(t) = e {
text.push_str(t)
}
})
.unwrap();
assert_eq!(r.text(), "Hello there");
assert_eq!(text, "Hello there");
assert_eq!(r.stop, Stop::EndTurn);
assert_eq!(r.usage.output, 3);
let r = send(
&server.url,
Some("sk-x"),
&req,
&CancelToken::new(),
&mut |_| {},
)
.unwrap();
assert_eq!(r.stop, Stop::ToolUse);
let m = r.message();
assert_eq!(m.tool_uses()[0].2["pattern"], "timeout");
let reqs = server.requests();
assert_eq!(reqs[0].path, "/chat/completions");
assert_eq!(reqs[0].header("authorization"), None);
assert_eq!(reqs[1].header("authorization"), Some("Bearer sk-x"));
}
#[test]
fn unknown_fields_are_dropped_after_a_400() {
let server = FakeServer::start(vec![
FakeReply::error(
400,
r#"{"error":{"message":"Unrecognized request argument supplied: stream_options"}}"#,
),
FakeReply::openai_text("ok"),
])
.unwrap();
let msgs = [Message::user("hi")];
let req = Request {
model: "m",
system: "",
messages: &msgs,
tools: &[],
max_tokens: 100,
json: None,
effort: None,
};
let r = send(&server.url, None, &req, &CancelToken::new(), &mut |_| {}).unwrap();
assert_eq!(r.text(), "ok");
assert!(!server.requests()[1].body.contains("stream_options"));
}
#[test]
fn whole_answers_and_model_lists() {
let r = parse_whole(r#"{"model":"m","choices":[{"message":{"content":null,"tool_calls":[{"function":{"name":"count","arguments":{"pattern":"x"}}}]},"finish_reason":"stop"}]}"#).unwrap();
assert_eq!(r.stop, Stop::ToolUse);
assert!(
matches!(&r.blocks[0], Block::ToolUse { id, input, .. } if id == "call_0" && input["pattern"] == "x")
);
assert_eq!(
model_ids(r#"{"data":[{"id":"b"},{"id":"models/a"},{"id":"b"}]}"#).unwrap(),
vec!["a", "b"]
);
assert!(model_ids("{}").is_err());
}
#[test]
fn bad_arguments_stay_raw_for_the_checks() {
assert_eq!(tool_input("{\"a\": 1"), Value::String("{\"a\": 1".into()));
assert_eq!(tool_input(""), json!({}));
}
}