agent-base 0.1.1

A lightweight Agent Runtime Kernel for building AI agents in Rust
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
404
405
use std::io::{self, Write};
use std::sync::Arc;

use agent_base::{
    AgentBuilder, AgentError, AgentEvent, AgentResult, ApprovalDecision, ApprovalHandler,
    ApprovalRequest, OpenAiClient, RiskLevel, Tool, ToolContext, ToolControlFlow, ToolOutput,
    ToolPolicy,
};
use async_trait::async_trait;
use dotenvy::dotenv;
use serde_json::{json, Value};

// ---------------------------------------------------------------------------
// Arithmetic tools
// ---------------------------------------------------------------------------

struct AddTool;

#[async_trait]
impl Tool for AddTool {
    fn name(&self) -> &'static str {
        "add"
    }

    fn definition(&self) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": "add",
                "description": "Calculate the sum of two integers",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "a": { "type": "integer", "description": "First addend" },
                        "b": { "type": "integer", "description": "Second addend" }
                    },
                    "required": ["a", "b"]
                }
            }
        })
    }

    async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<ToolOutput> {
        let a = args["a"].as_i64().unwrap_or(0);
        let b = args["b"].as_i64().unwrap_or(0);
        let result = a + b;
        Ok(ToolOutput {
            summary: format!("{} + {} = {}", a, b, result),
            raw: Some(json!({ "result": result })),
            control_flow: ToolControlFlow::Break,
            truncation: None,
        })
    }
}

struct SubtractTool;

#[async_trait]
impl Tool for SubtractTool {
    fn name(&self) -> &'static str {
        "subtract"
    }

    fn definition(&self) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": "subtract",
                "description": "Calculate the difference of two integers(a - b)",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "a": { "type": "integer", "description": "Minuend" },
                        "b": { "type": "integer", "description": "Subtrahend" }
                    },
                    "required": ["a", "b"]
                }
            }
        })
    }

    async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<ToolOutput> {
        let a = args["a"].as_i64().unwrap_or(0);
        let b = args["b"].as_i64().unwrap_or(0);
        let result = a - b;
        Ok(ToolOutput {
            summary: format!("{} - {} = {}", a, b, result),
            raw: Some(json!({ "result": result })),
            control_flow: ToolControlFlow::Break,
            truncation: None,
        })
    }
}

struct MultiplyTool;

#[async_trait]
impl Tool for MultiplyTool {
    fn name(&self) -> &'static str {
        "multiply"
    }

    fn definition(&self) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": "multiply",
                "description": "Calculate the product of two integers",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "a": { "type": "integer", "description": "Multiplier" },
                        "b": { "type": "integer", "description": "Multiplier" }
                    },
                    "required": ["a", "b"]
                }
            }
        })
    }

    async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<ToolOutput> {
        let a = args["a"].as_i64().unwrap_or(0);
        let b = args["b"].as_i64().unwrap_or(0);
        let result = a * b;
        Ok(ToolOutput {
            summary: format!("{} × {} = {}", a, b, result),
            raw: Some(json!({ "result": result })),
            control_flow: ToolControlFlow::Break,
            truncation: None,
        })
    }
}

struct DivideTool;

#[async_trait]
impl Tool for DivideTool {
    fn name(&self) -> &'static str {
        "divide"
    }

    fn definition(&self) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": "divide",
                "description": "Calculate the quotient of two integers(a ÷ b),Returns quotient and remainder",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "a": { "type": "integer", "description": "Dividend" },
                        "b": { "type": "integer", "description": "Divisor" }
                    },
                    "required": ["a", "b"]
                }
            }
        })
    }

    async fn call(&self, args: &Value, _ctx: &ToolContext) -> AgentResult<ToolOutput> {
        let a = args["a"].as_i64().unwrap_or(0);
        let b = args["b"].as_i64().unwrap_or(0);
        if b == 0 {
            return Ok(ToolOutput {
                summary: "Error:Divisor cannot be zero".to_string(),
                raw: Some(json!({ "error": "division by zero" })),
                control_flow: ToolControlFlow::Break,
                truncation: None,
            });
        }
        let quotient = a / b;
        let remainder = a % b;
        Ok(ToolOutput {
            summary: format!("{} ÷ {} = {}(remainder {}", a, b, quotient, remainder),
            raw: Some(json!({ "quotient": quotient, "remainder": remainder })),
            control_flow: ToolControlFlow::Break,
            truncation: None,
        })
    }
}

// ---------------------------------------------------------------------------
// CLI Approval handler
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Default)]
struct CliApprovalHandler;

#[async_trait]
impl ApprovalHandler for CliApprovalHandler {
    async fn approve(&self, request: ApprovalRequest) -> AgentResult<ApprovalDecision> {
        println!();
        println!("[Approval request] {}", request.title);
        println!("  Risk level: {:?}", request.risk_level);
        println!("  Content: {}", request.message);

        loop {
            print!("  Choice [y=Allow / a=AlwaysAllow / n=Deny]: ");
            io::stdout().flush().unwrap();

            let mut input = String::new();
            io::stdin()
                .read_line(&mut input)
                .map_err(|e| AgentError::internal(format!("Failed to read input: {e}")))?;
            match input.trim().to_ascii_lowercase().as_str() {
                "y" | "yes" => return Ok(ApprovalDecision::AllowOnce),
                "a" | "always" => return Ok(ApprovalDecision::AllowAlways),
                "n" | "no" => return Ok(ApprovalDecision::Deny),
                _ => println!("  Invalid input,Please enter y / a / n"),
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Event printer
// ---------------------------------------------------------------------------

struct EventPrinter;

impl EventPrinter {
    fn handle(event: AgentEvent) -> AgentResult<()> {
        match event {
            AgentEvent::TextDelta { text, .. } => {
                print!("{}", text);
                io::stdout().flush().unwrap();
            }
            AgentEvent::ThoughtDelta { text, .. } => {
                print!("[Thinking]:\x1b[90m{} \x1b[0m", text);
                println!();
                io::stdout().flush().unwrap();
            }
            AgentEvent::ToolCallStarted {
                tool_name, args_json, ..
            } => {
                println!();
                println!("[Tool call] {} (with args: {})", tool_name, args_json);
            }
            AgentEvent::ToolCallFinished {
                tool_name, summary, ..
            } => {
                println!("[Tool finished] {} -> {}", tool_name, summary);
            }
            AgentEvent::AwaitingApproval { request, .. } => {
                println!(
                    "[Waiting for approval] {} (Risk: {:?})",
                    request.title, request.risk_level
                );
            }
            AgentEvent::RunFinished { .. } => {
                println!();
                println!("[Run finished]");
            }
            AgentEvent::Custom { payload, .. } => {
                println!("[Custom event] {}", payload);
            }
            AgentEvent::Checkpoint { .. } => {}
            AgentEvent::PlanGenerated { plan, .. } => {
                println!("[Plan generated] id={}, objective={}", plan.id, plan.objective);
            }
            AgentEvent::PlanStepStarted { step_id, step_description, .. } => {
                println!("[Plan step started] {} - {}", step_id, step_description);
            }
            AgentEvent::PlanStepCompleted { step_id, success, .. } => {
                println!("[Plan step completed] {} success={}", step_id, success);
            }
            AgentEvent::PlanCompleted { plan_id, success, .. } => {
                println!("[Plan completed] {} success={}", plan_id, success);
            }
            AgentEvent::PlanGenerating { .. } | AgentEvent::PlanStepParsed { .. } | AgentEvent::PlanFailed { .. } => {}
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Tool approval policy
// ---------------------------------------------------------------------------

struct ArithmeticToolPolicy;

impl ToolPolicy for ArithmeticToolPolicy {
    fn evaluate_approval(
        &self,
        tool_name: &str,
        _args: &Value,
    ) -> Option<ApprovalRequest> {
        if tool_name == "divide" {
            return Some(ApprovalRequest {
                title: "Division operation".to_string(),
                message: "Allow division execution?".to_string(),
                action_key: Some("divide".to_string()),
                risk_level: RiskLevel::Safe,
                raw: None,
            });
        }
        None
    }

    fn before_call(&self, _tool_name: &str, _args: &Value, _ctx: &ToolContext) -> AgentResult<()> {
        Ok(())
    }

    fn after_call(
        &self,
        _tool_name: &str,
        _args: &Value,
        _result: &ToolOutput,
        _ctx: &ToolContext,
    ) -> AgentResult<()> {
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Main - REPL Entry
// ---------------------------------------------------------------------------

const SYSTEM_PROMPT: &str = r#"You are an arithmetic assistant,You can help users perform various arithmetic operations。

The tools available to you include:
- add: Calculate the sum of two integers
- subtract: Calculate the difference of two integers
- multiply: Calculate the product of two integers
- divide: Calculate the quotient of two integers

Please select the appropriate tool based on the user's request. If the request involves multiple steps,
you may call tools step by step。After each calculation,explain the result to the user。"#;

#[tokio::main]
async fn main() -> AgentResult<()> {
    dotenv().ok();

    let api_key = std::env::var("OPENAI_API_KEY")
        .or_else(|_| std::env::var("DASHSCOPE_API_KEY"))
        .map_err(|_| AgentError::internal("Please set OPENAI_API_KEY or DASHSCOPE_API_KEY environment variable"))?;

    let model = std::env::var("OPENAI_MODEL")
        .or_else(|_| std::env::var("DASHSCOPE_MODEL"))
        .unwrap_or_else(|_| "gpt-4o-mini".to_string());

    let base_url = std::env::var("OPENAI_BASE_URL")
        .or_else(|_| std::env::var("DASHSCOPE_BASE_URL"))
        .unwrap_or_else(|_| "https://api.openai.com/v1".to_string());

    let llm_client = Arc::new(OpenAiClient::new(api_key, model.clone(), Some(base_url)));

    let runtime = AgentBuilder::new(llm_client)
        .system_prompt(SYSTEM_PROMPT)
        .enable_thought(false)
        .enable_thinking(false)
        .register_tool(AddTool)
        .register_tool(SubtractTool)
        .register_tool(MultiplyTool)
        .register_tool(DivideTool)
        .tool_policy(Arc::new(ArithmeticToolPolicy))
        .approval_handler(Arc::new(CliApprovalHandler))
        .build().unwrap();

    let mut session_id = runtime.create_session().await;

    println!("=== agent-base REPL (arithmetic Demo) ===");
    println!("model: {}", model);
    println!("Input 'exit' quit, 'reset' recreate session");
    println!();

    loop {
        print!("> ");
        io::stdout().flush().unwrap();

        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .map_err(|e| AgentError::internal(format!("Failed to read input: {e}")))?;
        let input = input.trim().to_string();

        if input.is_empty() {
            continue;
        }
        if matches!(input.as_str(), "exit" | "quit") {
            break;
        }
        if input == "reset" {
            session_id = runtime.create_session().await;
            println!("Created new session");
            continue;
        }

        match runtime
            .run_turn_with_handler(session_id.clone(), &input, |event| EventPrinter::handle(event))
            .await
        {
            Ok(_outcome) => {}
            Err(e) => {
                if e.is_cancelled() {
                    println!("Cancelled");
                } else {
                    println!("Error: {}", e);
                }
            }
        }
    }

    Ok(())
}