agent_example/
agent_example.rs

1// Agent使用示例
2use rust_agent::{ExampleTool, SimpleAgent, SimpleAgentRunner, AgentOutput, Runnable};
3use std::collections::HashMap;
4
5#[tokio::main]
6async fn main() -> Result<(), Box<dyn std::error::Error>> {
7    println!("=== Rust Agent v0.0.1 - Agent使用示例 ===");
8    
9    // 创建一个简单的Agent
10    let mut agent = SimpleAgent::new();
11    
12    // 添加一些示例工具
13    let weather_tool = Box::new(ExampleTool::new(
14        "get_weather".to_string(),
15        "获取指定城市的天气信息".to_string(),
16    ));
17    
18    agent.add_tool(weather_tool);
19    
20    // 创建Agent运行器
21    let agent_runner = SimpleAgentRunner::new(agent);
22    
23    // 测试调用工具
24    println!("\n1. 测试调用工具:");
25    test_tool_invocation(&agent_runner).await?;
26    
27    // 测试直接完成
28    println!("\n2. 测试直接完成:");
29    test_direct_completion(&agent_runner).await?;
30    
31    println!("\n示例完成!");
32    Ok(())
33}
34
35/// 测试工具调用功能
36async fn test_tool_invocation(agent_runner: &SimpleAgentRunner) -> Result<(), Box<dyn std::error::Error>> {
37    let mut tool_inputs = HashMap::new();
38    tool_inputs.insert("tool".to_string(), "get_weather".to_string());
39    tool_inputs.insert("input".to_string(), "北京".to_string());
40    
41    match agent_runner.invoke(tool_inputs).await {
42        Ok(output) => match output {
43            AgentOutput::Action(action) => {
44                println!("思考过程: {}", action.thought.unwrap_or("无".to_string()));
45                println!("工具: {}", action.tool);
46                println!("输入: {}", action.tool_input);
47                println!("日志: {}", action.log);
48            },
49            AgentOutput::Finish(finish) => {
50                println!("完成结果: {:?}", finish.return_values);
51            }
52        },
53        Err(e) => println!("错误: {}", e),
54    }
55    
56    Ok(())
57}
58
59/// 测试直接完成功能
60async fn test_direct_completion(agent_runner: &SimpleAgentRunner) -> Result<(), Box<dyn std::error::Error>> {
61    let mut finish_inputs = HashMap::new();
62    finish_inputs.insert("input".to_string(), "北京的天气如何".to_string());
63    
64    match agent_runner.invoke(finish_inputs).await {
65        Ok(output) => match output {
66            AgentOutput::Action(action) => {
67                println!("思考过程: {}", action.thought.unwrap_or("无".to_string()));
68                println!("工具: {}", action.tool);
69                println!("输入: {}", action.tool_input);
70                println!("日志: {}", action.log);
71            },
72            AgentOutput::Finish(finish) => {
73                println!("完成结果: {:?}", finish.return_values);
74            }
75        },
76        Err(e) => println!("错误: {}", e),
77    }
78    
79    Ok(())
80}