use std::sync::Mutex;
use std::sync::mpsc::Sender;
use std::time::Duration;
use serde_json::{Value, json};
use super::{FenceMachine, PairState, TurnEnd, apply_fence_event};
const MAX_TOKENS: u64 = 8192;
pub(crate) fn auth_for(base_url: &str, token: Option<&str>) -> (String, Option<String>) {
match token {
Some(t) if credential_allowed(base_url) => (t.to_string(), Some(format!("Bearer {t}"))),
_ => (String::from("croft"), None),
}
}
pub(crate) fn credential_allowed(base_url: &str) -> bool {
let Ok(u) = url::Url::parse(base_url) else {
return false;
};
match u.scheme() {
"https" => true,
"http" => match u.host() {
Some(url::Host::Domain(d)) => d == "localhost",
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
None => false,
},
_ => false,
}
}
pub(crate) fn stream_turn(
base_url: &str,
model: &str,
system: &str,
messages: &mut Vec<Value>,
state: &Mutex<PairState>,
turn_tx: &Sender<TurnEnd>,
) {
stream_turn_until(
base_url,
model,
system,
messages,
state,
turn_tx,
std::time::Instant::now() + TURN_DEADLINE,
);
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn stream_turn_until(
base_url: &str,
model: &str,
system: &str,
messages: &mut Vec<Value>,
state: &Mutex<PairState>,
turn_tx: &Sender<TurnEnd>,
deadline: std::time::Instant,
) {
let req = json!({
"model": model,
"max_tokens": MAX_TOKENS,
"stream": true,
"system": system,
"messages": messages,
});
let agent = ureq3::Agent::config_builder()
.timeout_connect(Some(Duration::from_secs(5)))
.max_redirects(0)
.http_status_as_error(false)
.build()
.new_agent();
let token = std::env::var("ANTHROPIC_AUTH_TOKEN").ok();
let (api_key, bearer) = auth_for(base_url, token.as_deref());
let mut post = agent
.post(format!("{base_url}/v1/messages"))
.config()
.timeout_global(Some(
deadline.saturating_duration_since(std::time::Instant::now()),
))
.build()
.header("content-type", "application/json")
.header("anthropic-version", "2023-06-01")
.header("x-api-key", &api_key);
if let Some(bearer) = &bearer {
post = post.header("authorization", bearer);
}
let resp = match post.send(req.to_string()) {
Ok(r) => r,
Err(e) => {
messages.pop();
end_turn(
state,
turn_tx,
true,
format!("local endpoint {base_url}: {}", error_detail(&e)),
);
return;
}
};
let status = resp.status().as_u16();
if (300..400).contains(&status) {
messages.pop();
end_turn(
state,
turn_tx,
true,
format!("local endpoint {base_url}: redirect refused (status {status})"),
);
return;
}
if status >= 400 {
let body = resp.into_body().read_to_string().unwrap_or_default();
messages.pop();
end_turn(
state,
turn_tx,
true,
format!(
"local endpoint {base_url}: {}",
status_detail(status, &body)
),
);
return;
}
let mut fence = FenceMachine::new();
let mut assistant = String::new();
let mut clean_end = false;
let mut truncated = false;
let mut stream_error: Option<String> = None;
let mut reader = resp.into_body().into_reader();
let mut pending: Vec<u8> = Vec::new();
let mut chunk = [0u8; 4096];
'stream: loop {
if std::time::Instant::now() > deadline {
stream_error = Some(ceiling_msg());
break;
}
if pending.len() > 1 << 20 {
stream_error = Some(String::from("endpoint sent an over-long SSE line"));
break;
}
let n = match std::io::Read::read(&mut reader, &mut chunk) {
Ok(0) => break, Ok(n) => n,
Err(e) if is_timeout(&e) => {
stream_error = Some(ceiling_msg());
break;
}
Err(_) => break, };
pending.extend_from_slice(&chunk[..n]);
while let Some(pos) = pending.iter().position(|&b| b == b'\n') {
let raw: Vec<u8> = pending.drain(..=pos).collect();
let line = String::from_utf8_lossy(&raw[..raw.len() - 1]);
let line = line.trim_end_matches('\r');
let Some(data) = line.strip_prefix("data: ") else {
continue;
};
if data.trim() == "[DONE]" {
clean_end = true;
break 'stream;
}
let Ok(v) = serde_json::from_str::<Value>(data) else {
stream_error = Some(String::from("endpoint sent malformed SSE data"));
break 'stream;
};
match v["type"].as_str().unwrap_or("") {
"content_block_delta" => {
if v["delta"]["type"] == "text_delta"
&& let Some(text) = v["delta"]["text"].as_str()
{
assistant.push_str(text);
for event in fence.push(text) {
apply_fence_event(state, event);
}
}
}
"message_delta" if v["delta"]["stop_reason"] == "max_tokens" => {
truncated = true;
}
"message_stop" => {
clean_end = true;
break 'stream;
}
"error" => {
let msg = v["error"]["message"].as_str().unwrap_or("stream error");
stream_error = Some(msg.to_string());
break 'stream;
}
_ => {}
}
}
}
for event in fence.finish() {
apply_fence_event(state, event);
}
let failure = if let Some(err) = stream_error {
Some(err)
} else if truncated {
Some(format!("reply truncated at the {MAX_TOKENS}-token limit"))
} else if !clean_end {
Some(String::from("stream ended before message_stop"))
} else if assistant.is_empty() {
Some(String::from("endpoint streamed no text"))
} else {
None
};
match failure {
Some(reason) => {
messages.pop(); end_turn(
state,
turn_tx,
true,
format!("local endpoint {base_url}: {reason}"),
);
}
None => {
messages.push(json!({ "role": "assistant", "content": assistant }));
end_turn(state, turn_tx, false, assistant);
}
}
}
const TURN_DEADLINE: Duration = Duration::from_secs(600);
fn ceiling_msg() -> String {
format!(
"turn exceeded the {} minute ceiling",
TURN_DEADLINE.as_secs() / 60
)
}
fn error_detail(e: &ureq3::Error) -> String {
match e {
ureq3::Error::Timeout(ureq3::Timeout::Global | ureq3::Timeout::PerCall) => ceiling_msg(),
other => other.to_string(),
}
}
fn status_detail(status: u16, body: &str) -> String {
let body = body.trim();
if body.is_empty() {
format!("status {status}")
} else {
let short: String = body.chars().take(200).collect();
format!("status {status}: {short}")
}
}
fn is_timeout(e: &std::io::Error) -> bool {
matches!(
e.kind(),
std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock
) || e
.get_ref()
.and_then(|inner| inner.downcast_ref::<ureq3::Error>())
.is_some_and(|u| {
matches!(
u,
ureq3::Error::Timeout(ureq3::Timeout::Global | ureq3::Timeout::PerCall)
)
})
}
fn end_turn(state: &Mutex<PairState>, turn_tx: &Sender<TurnEnd>, is_error: bool, text: String) {
let mut st = state.lock().unwrap();
let cancelled = st.cancelled;
st.turn_active = false;
st.cancelled = false;
st.discarding = false;
st.comment_only = false;
drop(st);
let _ = turn_tx.send(TurnEnd {
is_error,
cancelled,
text,
});
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_connect_timeout_is_not_reported_as_the_turn_ceiling() {
let connect = error_detail(&ureq3::Error::Timeout(ureq3::Timeout::Connect));
assert!(
!connect.contains("ceiling"),
"a connect timeout is not the turn ceiling: {connect}"
);
let global = error_detail(&ureq3::Error::Timeout(ureq3::Timeout::Global));
assert!(
global.contains("ceiling"),
"the global timeout IS the ceiling: {global}"
);
assert!(
global.contains("10 minute"),
"the ceiling text names the enforced duration: {global}"
);
}
}