graphrt-llm 0.8.0

Model providers (OpenAI-compatible, Anthropic, Gemini, AWS Bedrock, TypeSafe Jev) and LLM, classifier, extractor and agent nodes for the graphrt workflow runtime.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
//! `model.fallbacks` against fake provider servers: real OpenAI, Azure OpenAI and
//! Anthropic adapters, nodes running in the engine.
//!
//! - 5xx, connection failures and a stream cut before its first token move on to the
//!   next model; 401 and 400 do not. A 429 moves on after the node's retries.
//! - Tool calls and structured output work on the fallback, and the call is charged
//!   at the price of the model that answered.
//! - A stream cut after its first token is the node's error: nothing is answered twice.
//! - The circuit breaker stops calling a provider that keeps failing.
//! - No key is ever in an event.

#![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";

/// A reply of the fake server: status, content type, body, and whether to
/// close the connection before the body is complete (a cut stream).
#[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 }
}

/// Serves the scripted replies in order (the last one repeats). Returns the
/// base URL and the request bodies seen.
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)
}

/// An OpenAI-style stream: `text`, or a tool call when `tool` is set.
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(), &registry).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.");
    // Both turns went to the primary first (its breaker has not opened after two failures).
    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() {
    // Nothing listens on the primary's port: the connection is refused.
    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}}),
    );
    // 100 in and 100 out at Claude's price is 1 000 + 3 000 micro units (at GPT's, 200):
    // a 5 000 budget affords the call, a 3 000 one is passed by it.
    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() {
    // Headers and the stream's start, then the connection closes.
    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"));
}