agent 0.0.1

A flexible AI Agent SDK for building intelligent agents
Documentation
use agent::{Agent, AgentExecutor, Message, Result, Tool, ToolRegistry};
use async_trait::async_trait;
use serde_json::{json, Value};
use std::sync::Arc;

// 简单的模拟执行器
struct MockExecutor;

#[async_trait]
impl AgentExecutor for MockExecutor {
    async fn execute(&self, messages: Vec<Message>) -> Result<String> {
        let last_message = messages.last()
            .map(|m| m.content.as_str())
            .unwrap_or("");
        
        Ok(format!("收到消息: {}. 这是一个模拟响应。[DONE]", last_message))
    }
}

// 示例工具:计算器
struct CalculatorTool;

#[async_trait]
impl Tool for CalculatorTool {
    fn name(&self) -> &str {
        "calculator"
    }

    fn description(&self) -> &str {
        "执行基本的数学计算"
    }

    async fn execute(&self, params: Value) -> Result<Value> {
        let a = params["a"].as_f64().unwrap_or(0.0);
        let b = params["b"].as_f64().unwrap_or(0.0);
        let op = params["op"].as_str().unwrap_or("add");

        let result = match op {
            "add" => a + b,
            "subtract" => a - b,
            "multiply" => a * b,
            "divide" => if b != 0.0 { a / b } else { 0.0 },
            _ => 0.0,
        };

        Ok(json!({ "result": result }))
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    println!("=== AI Agent SDK 示例 ===\n");

    // 创建工具注册表
    let tools = ToolRegistry::new()
        .register(Arc::new(CalculatorTool));

    // 构建 Agent
    let mut agent = Agent::builder()
        .name("助手")
        .description("一个有用的 AI 助手")
        .system_prompt("你是一个友好的 AI 助手,可以帮助用户解决问题。")
        .max_iterations(5)
        .temperature(0.7)
        .tools(tools)
        .executor(Arc::new(MockExecutor))
        .build();

    // 运行对话
    println!("用户: 你好!");
    let response = agent.run("你好!").await?;
    println!("Agent: {}\n", response);

    // 测试工具
    println!("测试计算器工具:");
    let calc_result = agent.tools().execute(
        "calculator",
        json!({ "a": 10, "b": 5, "op": "add" })
    ).await?;
    println!("10 + 5 = {}\n", calc_result["result"]);

    // 查看历史
    println!("对话历史:");
    let history = agent.get_history().await?;
    for (i, msg) in history.iter().enumerate() {
        println!("{}. {:?}: {}", i + 1, msg.role, msg.content);
    }

    Ok(())
}