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
//! GraphLoader - loads graph definitions from YAML
//!
//! Supports provider injection for LLM nodes through `GraphLoaderContext`.
use super::node::LlmNode;
use super::schema::{GraphDefinition, NodeDefinition};
use super::{EdgeTarget, NodeState, StateGraph};
use crate::providers::ModelProvider;
use crate::routing::{resolve_model_precedence, DEFAULT_MODEL_ROUTER_ID};
use anyhow::{anyhow, Context, Result};
use std::sync::Arc;
/// Context for loading graphs with runtime dependencies
///
/// Provides optional access to model providers for creating functional LLM nodes.
/// When no provider is set, LLM nodes will be created as placeholders that
/// log their invocation but don't make actual LLM calls.
#[derive(Default, Clone)]
pub struct GraphLoaderContext {
/// Model provider for LLM nodes
pub provider: Option<Arc<dyn ModelProvider>>,
/// Agent-level default model pin used in precedence resolution.
pub default_model: Option<String>,
}
impl GraphLoaderContext {
/// Create a new empty context
pub fn new() -> Self {
Self::default()
}
/// Create a context with a model provider
pub fn with_provider(provider: Arc<dyn ModelProvider>) -> Self {
Self {
provider: Some(provider),
default_model: None,
}
}
/// Create a context with provider and agent-level default model.
pub fn with_provider_and_model(
provider: Arc<dyn ModelProvider>,
default_model: impl Into<String>,
) -> Self {
Self {
provider: Some(provider),
default_model: Some(default_model.into()),
}
}
}
pub struct GraphLoader;
impl GraphLoader {
/// Load a graph from YAML string
///
/// LLM nodes will be created as placeholders that log but don't execute.
/// Use `load_from_str_with_context` to provide a model provider for
/// functional LLM nodes.
pub fn load_from_str(yaml: &str) -> Result<StateGraph> {
Self::load_from_str_with_context(yaml, &GraphLoaderContext::default())
}
/// Load a graph from YAML string with runtime context
///
/// If the context contains a model provider, LLM nodes will be created
/// as functional nodes that execute actual LLM calls.
pub fn load_from_str_with_context(yaml: &str, ctx: &GraphLoaderContext) -> Result<StateGraph> {
let def: GraphDefinition =
serde_yaml::from_str(yaml).context("Failed to parse graph definition YAML")?;
let mut graph = StateGraph::new();
// 1. Add all nodes
for (name, node_def) in &def.nodes {
match node_def {
NodeDefinition::Llm {
model,
system_prompt,
..
} => {
let (resolved_model, selection_source) = resolve_model_precedence(
model.as_deref(),
def.model.as_deref(),
ctx.default_model.as_deref(),
);
if let Some(provider) = &ctx.provider {
// Create functional LLM node with real provider
tracing::debug!(
node = %name,
selected_model = %resolved_model,
source = ?selection_source,
"Resolved LLM node model using precedence"
);
let llm_node = LlmNode::with_model(
name.clone(),
system_prompt.clone(),
resolved_model,
provider.clone(),
);
graph = graph.add_node_impl(llm_node);
} else {
let name_clone = name.clone();
let model = if resolved_model.is_empty() {
DEFAULT_MODEL_ROUTER_ID.to_string()
} else {
resolved_model
};
let prompt = system_prompt.clone();
graph = graph.add_node(name, move |_state: NodeState| {
let n = name_clone.clone();
let m = model.clone();
let p = prompt.clone();
async move {
tracing::error!(
node = %n,
model = %m,
prompt = %p,
"LLM node requires a model provider but none was configured"
);
Err(anyhow::anyhow!(
"LLM node '{}' requires a model provider. \
Use GraphLoaderContext::with_provider() when loading the graph.",
n
))
}
});
}
}
NodeDefinition::Function { action, .. } => {
let name_clone = name.clone();
let action = action.clone();
graph = graph.add_node(name, move |state: NodeState| {
let n = name_clone.clone();
let a = action.clone();
async move {
println!("⚙️ [Function Node: {}] Action: {}", n, a);
// In a real implementation, this would execute the action command
// For now, allow simple "echo" for testing
if a.starts_with("echo ") {
let output = a.trim_start_matches("echo ").to_string();
return Ok(NodeState::from_string(&output));
}
Ok(state)
}
});
}
NodeDefinition::Condition { expr, .. } => {
let name_clone = name.clone();
let expr = expr.clone();
// Condition node evaluates expression and returns the result key
// (which matches an edge key)
graph = graph.add_node(name, move |state: NodeState| {
let n = name_clone.clone();
let e = expr.clone();
async move {
println!("❓ [Condition Node: {}] Expr: {}", n, e);
// Simple mock evaluation
// If input contains "error", return "error", else "ok"
let input = state.as_str().unwrap_or("");
if e.contains("contains('error')") {
if input.contains("error") {
return Ok(NodeState::from_string("error"));
} else {
return Ok(NodeState::from_string("ok"));
}
}
Ok(NodeState::from_string("default"))
}
});
}
_ => {
return Err(anyhow!("Unsupported node type in yaml"));
}
}
}
// 2. Add edges
for (name, node_def) in &def.nodes {
let edges = node_def.edges();
// Check if this is a conditional node (router)
// If it has multiple edges with keys other than "_default",
// valid keys are the outputs of the previous node.
// For Llm/Function nodes, usually they have a single "_default" edge
// or specific keys if they return structured data?
// The schema implies simple string matching on output.
let is_conditional = matches!(node_def, NodeDefinition::Condition { .. });
if is_conditional {
// Conditional edges based on node output
let edges_clone = edges.clone();
let router = move |output: &str| -> EdgeTarget {
if let Some(target) = edges_clone.get(output) {
if target == "END" {
EdgeTarget::End
} else {
EdgeTarget::Node(target.clone())
}
} else if let Some(default) = edges_clone.get("_default") {
if default == "END" {
EdgeTarget::End
} else {
EdgeTarget::Node(default.clone())
}
} else {
EdgeTarget::End
}
};
graph = graph.add_conditional_edge(name, router);
} else {
// Standard edges
// TODO: Support branching from non-condition nodes?
// For now, assume "_default" is the main edge
if let Some(target) = edges.get("_default") {
if target == "END" {
graph = graph.add_edge_to_end(name);
} else {
graph = graph.add_edge(name, target);
}
}
}
}
// 3. Set entry point
// Ideally schema allows defining it, or we use first node?
// Current StateGraph defaults to first node if not set.
// We could look for "start" or "input" node?
// The implementation_plan example didn't specify entry point explicitly.
// Let's assume the first defined node in YAML (but HashMap is unordered).
// Use "start" or "input" if present, else random?
// Better: require `triggers` or look for a node named "start".
if def.nodes.contains_key("start") {
graph = graph.set_entry_point("start");
} else if def.nodes.contains_key("input") {
graph = graph.set_entry_point("input");
}
Ok(graph)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::providers::{ChatChoice, ChatMessage, ChatRequest, ChatResponse};
use async_trait::async_trait;
/// Mock provider for testing LLM node creation
struct MockProvider {
response: String,
}
impl MockProvider {
fn new(response: impl Into<String>) -> Self {
Self {
response: response.into(),
}
}
}
#[async_trait]
impl ModelProvider for MockProvider {
fn name(&self) -> &str {
"mock"
}
async fn chat(&self, _request: ChatRequest) -> anyhow::Result<ChatResponse> {
Ok(ChatResponse {
id: "mock-id".to_string(),
choices: vec![ChatChoice {
index: 0,
message: ChatMessage::assistant(&self.response),
finish_reason: Some("stop".to_string()),
}],
usage: None,
})
}
}
const SIMPLE_GRAPH_YAML: &str = r#"
name: test-graph
version: "1.0"
nodes:
start:
type: llm
system_prompt: "You are a helpful assistant"
edges:
_default: END
"#;
#[test]
fn test_load_without_context_creates_placeholder() {
let graph = GraphLoader::load_from_str(SIMPLE_GRAPH_YAML).unwrap();
assert!(graph.nodes.contains_key("start"));
}
#[test]
fn test_load_with_context_creates_functional_node() {
let provider = Arc::new(MockProvider::new("Hello!"));
let ctx = GraphLoaderContext::with_provider(provider);
let graph = GraphLoader::load_from_str_with_context(SIMPLE_GRAPH_YAML, &ctx).unwrap();
assert!(graph.nodes.contains_key("start"));
}
#[tokio::test]
async fn test_functional_llm_node_executes() {
let provider = Arc::new(MockProvider::new("LLM Response"));
let ctx = GraphLoaderContext::with_provider(provider);
let graph = GraphLoader::load_from_str_with_context(SIMPLE_GRAPH_YAML, &ctx).unwrap();
let compiled = graph.compile().unwrap();
// Execute the graph
let result = compiled.run("User input").await.unwrap();
assert_eq!(result.as_str(), Some("LLM Response"));
}
#[test]
fn test_context_builder() {
let ctx = GraphLoaderContext::new();
assert!(ctx.provider.is_none());
assert!(ctx.default_model.is_none());
let provider = Arc::new(MockProvider::new("test"));
let ctx = GraphLoaderContext::with_provider(provider);
assert!(ctx.provider.is_some());
assert!(ctx.default_model.is_none());
}
#[test]
fn test_context_builder_with_default_model() {
let provider = Arc::new(MockProvider::new("test"));
let ctx = GraphLoaderContext::with_provider_and_model(provider, "agent/default-model");
assert!(ctx.provider.is_some());
assert_eq!(ctx.default_model.as_deref(), Some("agent/default-model"));
}
const MULTI_NODE_YAML: &str = r#"
name: multi-node-graph
version: "1.0"
nodes:
start:
type: llm
model: gpt-4
system_prompt: "Process the input"
edges:
_default: check
check:
type: condition
expr: "input.contains('error')"
edges:
error: handle_error
ok: END
handle_error:
type: function
action: "echo error handled"
edges:
_default: END
"#;
#[test]
fn test_multi_node_graph_loading() {
let provider = Arc::new(MockProvider::new("processed"));
let ctx = GraphLoaderContext::with_provider(provider);
let graph = GraphLoader::load_from_str_with_context(MULTI_NODE_YAML, &ctx).unwrap();
assert!(graph.nodes.contains_key("start"));
assert!(graph.nodes.contains_key("check"));
assert!(graph.nodes.contains_key("handle_error"));
}
}