Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

核心智能体

基础智能体模式示例。

基础回声智能体

最简单的智能体,回显输入。

位置: examples/echo_agent/

#![allow(unused)]
fn main() {
use mofa_sdk::kernel::prelude::*;

struct EchoAgent;

#[async_trait]
impl MoFAAgent for EchoAgent {
    fn id(&self) -> &str { "echo" }
    fn name(&self) -> &str { "Echo Agent" }
    fn capabilities(&self) -> &AgentCapabilities {
        static CAPS: AgentCapabilities = AgentCapabilities::simple("echo");
        &CAPS
    }
    fn state(&self) -> AgentState { AgentState::Ready }

    async fn execute(&mut self, input: AgentInput, _ctx: &AgentContext) -> AgentResult<AgentOutput> {
        Ok(AgentOutput::text(format!("Echo: {}", input.to_text())))
    }
}
}

LLM 聊天智能体

基于 LLM 的智能体。

位置: examples/chat_stream/

use mofa_sdk::llm::{LLMClient, openai_from_env};

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

    let client = LLMClient::new(Arc::new(openai_from_env()?));

    // 流式聊天
    let mut stream = client.stream()
        .system("你是一个有帮助的助手。")
        .user("介绍一下 Rust")
        .start()
        .await?;

    while let Some(chunk) = stream.next().await {
        print!("{}", chunk?);
    }

    Ok(())
}

ReAct 智能体

推理 + 行动智能体,带有工具支持。

位置: examples/react_agent/

use mofa_sdk::react::ReActAgent;
use mofa_sdk::kernel::{Tool, ToolError};

// 定义工具
struct CalculatorTool;
struct WeatherTool;

#[async_trait]
impl Tool for CalculatorTool {
    fn name(&self) -> &str { "calculator" }
    fn description(&self) -> &str { "执行算术运算" }
    async fn execute(&self, params: Value) -> Result<Value, ToolError> {
        // 实现
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let agent = ReActAgent::builder()
        .with_llm(LLMClient::from_env()?)
        .with_tools(vec![
            Arc::new(CalculatorTool),
            Arc::new(WeatherTool::new()?),
        ])
        .with_max_iterations(5)
        .build();

    let output = agent.execute(
        AgentInput::text("东京天气如何?另外计算 25 * 4"),
        &ctx
    ).await?;

    println!("{}", output.as_text().unwrap());
    Ok(())
}

运行示例

# 基础聊天
cargo run -p chat_stream

# ReAct 智能体
cargo run -p react_agent

# 秘书智能体
cargo run -p secretary_agent

可用示例

示例描述
echo_agent简单回声智能体
chat_stream流式 LLM 聊天
react_agent推理 + 行动智能体
secretary_agent人在回路智能体
tool_routing动态工具路由
skills技能系统演示

相关链接