#![cfg(all(feature = "openai", feature = "anthropic", feature = "mock"))]
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
use std::sync::{Arc, Mutex};
use futures::StreamExt;
use graphrt_core::Workflow;
use graphrt_core::engine::{Engine, Limits, RunInput};
use graphrt_core::event::Event;
use graphrt_core::graph::Graph;
use graphrt_core::node::{Registry, Services};
use graphrt_core::tool::{ToolOutput, ToolRegistry, ToolSpec};
use graphrt_core::tool_node::NativeTools;
use graphrt_llm::ModelRegistry;
use graphrt_llm::registry::Price;
use serde_json::{Value as Json, json};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
const OPENAI_KEY: &str = "sk-openai-test-0123456789";
const AZURE_KEY: &str = "azure-test-key-0123456789";
const ANTHROPIC_KEY: &str = "sk-ant-test-0123456789";
#[derive(Clone)]
struct Reply {
status: u16,
content_type: &'static str,
body: String,
cut: bool,
}
fn reply(status: u16, body: &str) -> Reply {
Reply { status, content_type: "application/json", body: body.to_owned(), cut: false }
}
fn sse(body: String) -> Reply {
Reply { status: 200, content_type: "text/event-stream", body, cut: false }
}
async fn serve(script: Vec<Reply>) -> (String, Arc<Mutex<Vec<Json>>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let seen = Arc::new(Mutex::new(Vec::new()));
let seen2 = seen.clone();
let script = Arc::new(Mutex::new(script));
tokio::spawn(async move {
loop {
let Ok((mut socket, _)) = listener.accept().await else { break };
let seen = seen2.clone();
let script = script.clone();
tokio::spawn(async move {
let mut buf = Vec::new();
let mut tmp = [0u8; 8192];
let header_end = loop {
let n = socket.read(&mut tmp).await.unwrap_or(0);
if n == 0 {
return;
}
buf.extend_from_slice(&tmp[..n]);
if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
break pos + 4;
}
};
let head = String::from_utf8_lossy(&buf[..header_end]).to_ascii_lowercase();
let len: usize = head
.lines()
.find_map(|l| l.strip_prefix("content-length:"))
.and_then(|v| v.trim().parse().ok())
.unwrap_or(0);
while buf.len() < header_end + len {
let n = socket.read(&mut tmp).await.unwrap_or(0);
if n == 0 {
break;
}
buf.extend_from_slice(&tmp[..n]);
}
seen.lock().unwrap().push(serde_json::from_slice(&buf[header_end..]).unwrap_or(Json::Null));
let reply = {
let mut script = script.lock().unwrap();
if script.len() > 1 { script.remove(0) } else { script[0].clone() }
};
let length = if reply.cut { reply.body.len() + 100 } else { reply.body.len() };
let text = format!(
"HTTP/1.1 {} X\r\ncontent-type: {}\r\ncontent-length: {length}\r\nconnection: close\r\n\r\n{}",
reply.status, reply.content_type, reply.body
);
let _ = socket.write_all(text.as_bytes()).await;
let _ = socket.shutdown().await;
});
}
});
(format!("http://{addr}"), seen)
}
fn openai_stream(text: &str, tool: Option<(&str, &str, &str)>) -> String {
let mut out = String::new();
if let Some((id, name, args)) = tool {
let call = json!({"choices": [{"index": 0, "delta": {"tool_calls": [
{"index": 0, "id": id, "type": "function", "function": {"name": name, "arguments": args}}]}}]});
out.push_str(&format!("data: {call}\n\n"));
out.push_str("data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n");
} else {
let delta = json!({"choices": [{"index": 0, "delta": {"content": text}}]});
out.push_str(&format!("data: {delta}\n\n"));
out.push_str("data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n");
}
out.push_str(
"data: {\"choices\":[],\"usage\":{\"prompt_tokens\":100,\"completion_tokens\":100,\"total_tokens\":200}}\n\n",
);
out.push_str("data: [DONE]\n\n");
out
}
fn anthropic_text(text: &str) -> String {
let delta = json!({"type": "content_block_delta", "index": 0, "delta": {"type": "text_delta", "text": text}});
[
"event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"usage\":{\"input_tokens\":100,\"output_tokens\":1}}}\n\n".to_owned(),
"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"text\",\"text\":\"\"}}\n\n".to_owned(),
format!("event: content_block_delta\ndata: {delta}\n\n"),
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n".to_owned(),
"event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"end_turn\"},\"usage\":{\"output_tokens\":100}}\n\n".to_owned(),
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n".to_owned(),
]
.concat()
}
const UNAVAILABLE: &str = r#"{"error":{"message":"The server is overloaded"}}"#;
fn registry(openai: &str, azure: &str, anthropic: &str) -> ModelRegistry {
let vars = |pairs: &[(&str, String)]| pairs.iter().map(|(k, v)| ((*k).to_owned(), v.clone())).collect::<Vec<_>>();
ModelRegistry::from_vars(&vars(&[
("OPENAI_API_KEY", OPENAI_KEY.to_owned()),
("OPENAI_BASE_URL", format!("{openai}/v1")),
("AZURE_OPENAI_ENDPOINT", azure.to_owned()),
("AZURE_OPENAI_API_KEY", AZURE_KEY.to_owned()),
("ANTHROPIC_API_KEY", ANTHROPIC_KEY.to_owned()),
("ANTHROPIC_BASE_URL", anthropic.to_owned()),
]))
.unwrap()
}
fn model(fallbacks: Json) -> Json {
json!({"provider": "openai", "name": "gpt-4o-mini", "fallbacks": fallbacks})
}
fn graph(node: Json) -> Arc<Graph> {
let id = node["id"].as_str().unwrap().to_owned();
let doc = json!({"graph": {
"nodes": [
{"id": "start", "type": "start"},
node,
{"id": "end", "type": "end", "outputs": [
{"variable": "text", "value_selector": [id, "text"]},
{"variable": "structured", "value_selector": [id, "structured_output"]}
]}
],
"edges": [{"source": "start", "target": id}, {"source": id, "target": "end"}]
}});
let mut registry = Registry::with_builtins();
graphrt_llm::register(&mut registry);
Arc::new(Graph::build(Workflow::from_value(doc).unwrap(), ®istry).unwrap())
}
fn llm(model: Json, extra: Json) -> Json {
let mut node = json!({"id": "llm", "type": "llm", "model": model,
"prompt_template": [{"role": "user", "text": "{{#sys.query#}}"}]});
if let (Some(node), Json::Object(extra)) = (node.as_object_mut(), extra) {
node.extend(extra);
}
node
}
fn tools() -> ToolRegistry {
let spec = ToolSpec {
name: "weather".into(),
description: "Weather of a city".into(),
parameters: json!({"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}),
effects: Vec::new(),
};
let native = NativeTools::new().with(spec, |args: Json| async move {
Ok(ToolOutput::text(format!("sunny in {}", args["city"].as_str().unwrap_or("?"))))
});
let mut registry = ToolRegistry::new();
registry.add("w", Arc::new(native));
registry
}
async fn run(graph: Arc<Graph>, models: ModelRegistry, limits: Limits) -> Vec<Event> {
let engine = Engine::new(graph).with_services(Services::new().with(models).with(tools())).with_limits(limits);
engine.run(RunInput::new().sys("query", "weather in Paris?")).collect().await
}
fn outputs(events: &[Event]) -> Json {
match events.last() {
Some(Event::RunSucceeded { outputs, .. }) => {
Json::Object(outputs.iter().map(|(k, v)| (k.clone(), v.to_json())).collect())
}
other => panic!("expected success, got {other:?}"),
}
}
fn failure(events: &[Event]) -> String {
match events.last() {
Some(Event::RunFailed { error, .. }) => error.clone(),
other => panic!("expected a failure, got {other:?}"),
}
}
fn failovers(events: &[Event]) -> Vec<Json> {
events
.iter()
.filter_map(|e| match e {
Event::NodeProgress { name, data, .. } if name == "model_failover" => Some(data.to_json()),
_ => None,
})
.collect()
}
fn assert_no_keys(events: &[Event]) {
let text = format!("{events:?}");
for key in [OPENAI_KEY, AZURE_KEY, ANTHROPIC_KEY] {
assert!(!text.contains(key), "a key is in the events");
}
}
#[tokio::test(flavor = "multi_thread")]
async fn an_agent_fails_over_to_azure_and_its_tool_calls_still_work() {
let (openai, openai_seen) = serve(vec![reply(503, UNAVAILABLE)]).await;
let (azure, azure_seen) = serve(vec![
sse(openai_stream("", Some(("call_1", "weather", r#"{"city":"Paris"}"#)))),
sse(openai_stream("It is sunny in Paris.", None)),
])
.await;
let models = registry(&openai, &azure, "http://127.0.0.1:9");
let agent = json!({"id": "agent", "type": "agent", "query": "{{#sys.query#}}", "tools": ["w/weather"],
"model": model(json!([{"provider": "azure-openai", "name": "gpt-4o-mini-prod"}]))});
let events = run(graph(agent), models, Limits::default()).await;
assert_eq!(outputs(&events)["text"], "It is sunny in Paris.");
assert_eq!(openai_seen.lock().unwrap().len(), 2);
let azure_seen = azure_seen.lock().unwrap().clone();
assert_eq!(azure_seen.len(), 2);
assert_eq!(azure_seen[0]["model"], "gpt-4o-mini-prod");
let tool_result = azure_seen[1]["messages"].as_array().unwrap().iter().find(|m| m["role"] == "tool").unwrap();
assert_eq!(tool_result["content"], "sunny in Paris");
let reports = failovers(&events);
assert_eq!(reports.len(), 2);
assert_eq!(reports[0]["provider"], "azure-openai");
assert_eq!(reports[0]["model"], "gpt-4o-mini-prod");
assert_eq!(reports[0]["failed"][0]["provider"], "openai");
assert!(reports[0]["failed"][0]["reason"].as_str().unwrap().contains("503"), "{reports:?}");
assert_no_keys(&events);
}
#[tokio::test(flavor = "multi_thread")]
async fn auth_and_request_errors_are_reported_and_never_fail_over() {
for (status, body, kind) in [
(401, r#"{"error":{"message":"Incorrect API key provided"}}"#, "authentication failed"),
(400, r#"{"error":{"message":"Invalid schema for response_format"}}"#, "bad request"),
] {
let (openai, _) = serve(vec![reply(status, body)]).await;
let (azure, azure_seen) = serve(vec![sse(openai_stream("unused", None))]).await;
let models = registry(&openai, &azure, "http://127.0.0.1:9");
let node = llm(model(json!([{"provider": "azure-openai", "name": "d"}])), json!({}));
let events = run(graph(node), models, Limits::default()).await;
let error = failure(&events);
assert!(error.contains("openai/gpt-4o-mini"), "{error}");
let failed_kind = events.iter().find_map(|e| match e {
Event::NodeFailed { error, .. } => Some(error.clone()),
_ => None,
});
assert!(format!("{failed_kind:?}").contains(kind), "{failed_kind:?}");
assert!(azure_seen.lock().unwrap().is_empty(), "{status} must not fail over");
assert!(failovers(&events).is_empty());
assert_no_keys(&events);
}
}
#[tokio::test(flavor = "multi_thread")]
async fn a_rate_limit_waits_for_the_nodes_retries_then_fails_over() {
let limited = Reply {
status: 429,
content_type: "application/json",
body: r#"{"error":{"message":"Rate limit reached"}}"#.into(),
cut: false,
};
let (openai, openai_seen) = serve(vec![limited]).await;
let (azure, azure_seen) = serve(vec![sse(openai_stream("from azure", None))]).await;
let models = registry(&openai, &azure, "http://127.0.0.1:9");
let node = llm(
model(json!([{"provider": "azure-openai", "name": "d"}])),
json!({"retry": {"max_retries": 1, "interval_ms": 0}}),
);
let events = run(graph(node), models, Limits::default()).await;
assert_eq!(outputs(&events)["text"], "from azure");
assert_eq!(openai_seen.lock().unwrap().len(), 2, "first attempt, then the retry");
assert_eq!(azure_seen.lock().unwrap().len(), 1, "only the last attempt fails over");
assert!(events.iter().any(|e| matches!(e, Event::NodeRetry { .. })));
}
#[tokio::test(flavor = "multi_thread")]
async fn a_dead_provider_fails_over_to_claude_with_structured_output_charged_at_claudes_price() {
let closed = TcpListener::bind("127.0.0.1:0").await.unwrap();
let dead = format!("http://{}", closed.local_addr().unwrap());
drop(closed);
let (anthropic, anthropic_seen) = serve(vec![sse(anthropic_text(r#"{"city":"Paris","sunny":true}"#))]).await;
let mut models = registry(&dead, "http://127.0.0.1:9", &anthropic);
models.set_price("openai", "gpt-4o-mini", Price::new(1.0, 1.0).unwrap());
models.set_price("anthropic", "claude-haiku-4-5", Price::new(10.0, 30.0).unwrap());
let schema = json!({"type": "object", "properties": {"city": {"type": "string"}, "sunny": {"type": "boolean"}},
"required": ["city", "sunny"]});
let node = llm(
model(json!([{"provider": "anthropic", "name": "claude-haiku-4-5"}])),
json!({"structured_output_enabled": true, "structured_output": {"schema": schema}}),
);
let limits = Limits { max_cost_micros: Some(5_000), ..Limits::default() };
let events = run(graph(node.clone()), models.clone(), limits).await;
assert_eq!(outputs(&events)["structured"], json!({"city": "Paris", "sunny": true}));
let body = anthropic_seen.lock().unwrap()[0].clone();
assert_eq!(body["model"], "claude-haiku-4-5");
assert!(body["system"].as_str().unwrap().contains("JSON Schema"), "{body}");
assert_eq!(failovers(&events)[0]["provider"], "anthropic");
let limits = Limits { max_cost_micros: Some(3_000), ..Limits::default() };
let events = run(graph(node), models, limits).await;
let error = failure(&events);
assert!(error.contains("budget") || error.contains("limit"), "{error}");
}
#[tokio::test(flavor = "multi_thread")]
async fn a_stream_cut_before_its_first_token_fails_over_and_one_cut_after_it_does_not() {
let before = Reply { status: 200, content_type: "text/event-stream", body: String::new(), cut: true };
let (openai, _) = serve(vec![before]).await;
let (azure, azure_seen) = serve(vec![sse(openai_stream("from azure", None))]).await;
let models = registry(&openai, &azure, "http://127.0.0.1:9");
let node = llm(model(json!([{"provider": "azure-openai", "name": "d"}])), json!({}));
let events = run(graph(node), models, Limits::default()).await;
assert_eq!(outputs(&events)["text"], "from azure");
assert_eq!(azure_seen.lock().unwrap().len(), 1);
let first_token = "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hel\"}}]}\n\n".to_owned();
let after = Reply { status: 200, content_type: "text/event-stream", body: first_token, cut: true };
let (openai, _) = serve(vec![after]).await;
let (azure, azure_seen) = serve(vec![sse(openai_stream("from azure", None))]).await;
let models = registry(&openai, &azure, "http://127.0.0.1:9");
let node = llm(model(json!([{"provider": "azure-openai", "name": "d"}])), json!({}));
let events = run(graph(node), models, Limits::default()).await;
let streamed: String = events
.iter()
.filter_map(|e| match e {
Event::NodeChunk { chunk, .. } => Some(chunk.clone()),
_ => None,
})
.collect();
assert!(streamed.contains("Hel"), "the first token reached the user: {streamed:?}");
assert!(failure(&events).contains("network"), "{}", failure(&events));
assert!(azure_seen.lock().unwrap().is_empty(), "nothing is answered twice");
}
#[tokio::test(flavor = "multi_thread")]
async fn the_breaker_stops_calling_a_provider_that_keeps_failing() {
let (openai, openai_seen) = serve(vec![reply(502, UNAVAILABLE)]).await;
let (azure, azure_seen) = serve(vec![sse(openai_stream("ok", None))]).await;
let models = registry(&openai, &azure, "http://127.0.0.1:9");
let g = graph(llm(model(json!([{"provider": "azure-openai", "name": "d"}])), json!({})));
for _ in 0..5 {
let events = run(g.clone(), models.clone(), Limits::default()).await;
assert_eq!(outputs(&events)["text"], "ok");
}
assert_eq!(openai_seen.lock().unwrap().len(), graphrt_llm::failover::BREAKER_THRESHOLD as usize);
assert_eq!(azure_seen.lock().unwrap().len(), 5);
}
#[tokio::test(flavor = "multi_thread")]
async fn an_unconfigured_fallback_is_reported_and_the_primary_still_answers() {
let (openai, _) = serve(vec![sse(openai_stream("primary", None))]).await;
let models = registry(&openai, "http://127.0.0.1:9", "http://127.0.0.1:9");
let node = llm(model(json!([{"provider": "gemini", "name": "gemini-2.5-flash"}])), json!({}));
let events = run(graph(node), models, Limits::default()).await;
assert_eq!(outputs(&events)["text"], "primary");
let reports = failovers(&events);
assert_eq!(reports[0]["skipped"][0]["provider"], "gemini");
assert!(reports[0]["skipped"][0]["reason"].as_str().unwrap().contains("unknown model provider"));
}