This repository was archived by the owner on Apr 14, 2026. It is now read-only.
forked from Abraxas-365/langchain-rust
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtool_runtime.rs
More file actions
273 lines (232 loc) · 7 KB
/
tool_runtime.rs
File metadata and controls
273 lines (232 loc) · 7 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
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
use std::sync::Arc;
use async_trait::async_trait;
use langchain_ai_rust::{
agent::{create_agent_with_runtime, Command},
chain::Chain,
error::ToolError,
prompt_args,
tools::{InMemoryStore, SimpleContext, Tool, ToolResult, ToolRuntime},
};
use serde_json::{json, Value};
/// Example tool that accesses runtime state
struct StateAwareTool;
#[async_trait]
impl Tool for StateAwareTool {
fn name(&self) -> String {
"get_conversation_summary".to_string()
}
fn description(&self) -> String {
"Get a summary of the current conversation".to_string()
}
fn requires_runtime(&self) -> bool {
true
}
async fn run(&self, _input: Value) -> Result<String, ToolError> {
Ok("This tool requires runtime".to_string())
}
async fn run_with_runtime(
&self,
_input: Value,
runtime: &ToolRuntime,
) -> Result<ToolResult, Box<dyn std::error::Error>> {
let state = runtime.state().await;
let messages = &state.messages;
let human_count = messages
.iter()
.filter(|m| {
matches!(
m.message_type,
langchain_ai_rust::schemas::MessageType::HumanMessage
)
})
.count();
let ai_count = messages
.iter()
.filter(|m| {
matches!(
m.message_type,
langchain_ai_rust::schemas::MessageType::AIMessage
)
})
.count();
let summary = format!(
"Conversation has {} user messages and {} AI responses",
human_count, ai_count
);
Ok(ToolResult::text(summary))
}
}
/// Example tool that uses context
struct ContextAwareTool;
#[async_trait]
impl Tool for ContextAwareTool {
fn name(&self) -> String {
"get_user_info".to_string()
}
fn description(&self) -> String {
"Get information about the current user".to_string()
}
fn requires_runtime(&self) -> bool {
true
}
async fn run(&self, _input: Value) -> Result<String, ToolError> {
Ok("This tool requires runtime".to_string())
}
async fn run_with_runtime(
&self,
_input: Value,
runtime: &ToolRuntime,
) -> Result<ToolResult, Box<dyn std::error::Error>> {
let context = runtime.context();
let user_id = context.user_id().unwrap_or("unknown");
let session_id = context.session_id().unwrap_or("none");
Ok(ToolResult::text(format!(
"User ID: {}, Session ID: {}",
user_id, session_id
)))
}
}
/// Example tool that uses store
struct StoreAwareTool;
#[async_trait]
impl Tool for StoreAwareTool {
fn name(&self) -> String {
"save_preference".to_string()
}
fn description(&self) -> String {
"Save a user preference to persistent storage".to_string()
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "Preference key"
},
"value": {
"type": "string",
"description": "Preference value"
}
},
"required": ["key", "value"]
})
}
fn requires_runtime(&self) -> bool {
true
}
async fn run(&self, _input: Value) -> Result<String, ToolError> {
Ok("This tool requires runtime".to_string())
}
async fn run_with_runtime(
&self,
input: Value,
runtime: &ToolRuntime,
) -> Result<ToolResult, Box<dyn std::error::Error>> {
let key = input["key"]
.as_str()
.ok_or_else(|| ToolError::MissingInput("key".to_string()))?
.to_string();
let value = input["value"]
.as_str()
.ok_or_else(|| ToolError::MissingInput("value".to_string()))?
.to_string();
runtime
.store()
.put(&["preferences"], &key, json!(value))
.await;
Ok(ToolResult::text(format!(
"Saved preference: {} = {}",
key, value
)))
}
}
/// Example tool that updates state
struct StateUpdateTool;
#[async_trait]
impl Tool for StateUpdateTool {
fn name(&self) -> String {
"set_custom_field".to_string()
}
fn description(&self) -> String {
"Set a custom field in the agent state".to_string()
}
fn parameters(&self) -> Value {
json!({
"type": "object",
"properties": {
"field": {
"type": "string",
"description": "Field name"
},
"value": {
"type": "string",
"description": "Field value"
}
},
"required": ["field", "value"]
})
}
fn requires_runtime(&self) -> bool {
true
}
async fn run(&self, _input: Value) -> Result<String, ToolError> {
Ok("This tool requires runtime".to_string())
}
async fn run_with_runtime(
&self,
input: Value,
runtime: &ToolRuntime,
) -> Result<ToolResult, Box<dyn std::error::Error>> {
let field = input["field"]
.as_str()
.ok_or_else(|| ToolError::MissingInput("field".to_string()))?
.to_string();
let value = input["value"].clone();
let mut state = runtime.state().await;
state.set_field(field.clone(), value.clone());
let command = Command::UpdateState {
fields: {
let mut fields = std::collections::HashMap::new();
fields.insert(field, value);
fields
},
};
Ok(ToolResult::with_command(
format!("Field set successfully"),
command,
))
}
}
#[tokio::main]
async fn main() {
// Create context with user information
let context = Arc::new(SimpleContext::new().with_user_id("user123".to_string()));
// Create store for persistent data
let store = Arc::new(InMemoryStore::new());
// Create agent with runtime support
let agent = create_agent_with_runtime(
"gpt-4o-mini",
&[
Arc::new(StateAwareTool),
Arc::new(ContextAwareTool),
Arc::new(StoreAwareTool),
Arc::new(StateUpdateTool),
],
Some("You are a helpful assistant with access to runtime information"),
Some(context),
Some(store),
None, // response_format
None, // middleware
None, // file_backend
)
.expect("Failed to create agent");
// Use the agent
let result = agent
.invoke(prompt_args! {
"input" => "What's my user ID and save a preference with key 'theme' and value 'dark'"
})
.await
.expect("Failed to invoke agent");
println!("Result: {}", result);
}