forked from tinyhumansai/tinyagents
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_graph.rs
More file actions
Latest commit
82 lines (76 loc) · 2.51 KB
/
Copy pathbasic_graph.rs
File metadata and controls
82 lines (76 loc) · 2.51 KB
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
//! A minimal durable graph: a whole-state agent/tool loop.
//!
//! Builds a [`GraphBuilder`] over `Update == State` with the overwrite reducer
//! (each node returns the full next state). The `agent` node appends an
//! assistant message and is wired with conditional edges: while `needs_tool` is
//! set the run routes to `tool`, otherwise it ends. The `tool` node appends a
//! tool result, clears the flag, and loops back to `agent`.
//!
//! Run with:
//!
//! ```text
//! cargo run --example basic_graph
//! ```
use tinyagents::graph::END;
use tinyagents::harness::message::Message;
use tinyagents::{GraphBuilder,NodeContext,NodeResult,Result};
#[derive(Clone,Debug)]
structAgentState{
messages:Vec<Message>,
needs_tool:bool,
}
#[tokio::main]
asyncfnmain() -> Result<()>{
let graph = GraphBuilder::<AgentState,AgentState>::overwrite()
.add_node(
"agent",
|mutstate:AgentState,_ctx:NodeContext| asyncmove{
state
.messages
.push(Message::assistant("I should check the local tool."));
Ok(NodeResult::Update(state))
},
)
.add_node(
"tool",
|mutstate:AgentState,_ctx:NodeContext| asyncmove{
state
.messages
.push(Message::tool("echo","tool result: hello from tinyagents"));
state.needs_tool = false;
// A whole-state continue: the static edge `tool -> agent` routes us.
Ok(NodeResult::Update(state))
},
)
.set_entry("agent")
.add_conditional_edges(
"agent",
|state:&AgentState| {
if state.needs_tool{
"tool".to_string()
}else{
"done".to_string()
}
},
[("tool","tool"),("done",END)],
)
.add_edge("tool","agent")
.compile()?;
let run = graph
.run(AgentState{
messages:vec![Message::user("Can you use a tool?")],
needs_tool:true,
})
.await?;
for message in&run.state.messages{
let role = match message {
Message::System(_) => "system",
Message::User(_) => "user",
Message::Assistant(_) => "assistant",
Message::Tool(_) => "tool",
};
println!("{role}: {}", message.text());
}
println!("visited: {:?}", run.visited);
Ok(())
}