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/reflection_agent/

use mofa_sdk::react::{ReflectionAgent, ReflectionConfig};

#[tokio::main]
async fn main() -> Result<()> {
    let llm_agent = Arc::new(create_llm_agent()?);

    // 创建反思智能体
    let agent = ReflectionAgent::builder()
        .with_generator(llm_agent.clone())
        .with_config(ReflectionConfig::default().with_max_rounds(3))
        .with_verbose(true)
        .build()?;

    let task = "解释 Rust 中所有权的概念。";
    let result = agent.run(task).await?;

    println!("轮次: {}", result.rounds);
    println!("耗时: {}ms", result.duration_ms);
    println!("最终答案:\n{}", result.final_answer);

    // 查看改进过程
    for step in &result.steps {
        println!("[第 {} 轮]", step.round + 1);
        println!("初稿: {}", step.draft);
        println!("批评: {}", step.critique);
    }

    Ok(())
}

反思过程

  1. 生成:创建初始响应
  2. 批评:分析响应质量
  3. 改进:基于批评进行改进
  4. 重复:直到满意或达到最大轮次

配置

#![allow(unused)]
fn main() {
let config = ReflectionConfig::default()
    .with_max_rounds(5)              // 最大改进轮次
    .with_quality_threshold(0.8)      // 超过阈值则停止
    .with_critique_prompt("...")      // 自定义批评提示
    .with_verbose(true);              // 记录每一步
}

人在回路秘书

具有人工决策点的秘书智能体。

位置: examples/hitl_secretary/

#![allow(unused)]
fn main() {
use mofa_sdk::secretary::{
    SecretaryCore, DefaultSecretaryBuilder, DispatchStrategy,
    DefaultInput, DefaultOutput, SecretaryCommand, QueryType,
};

async fn run_secretary() -> Result<()> {
    // 创建通信通道
    let (connection, input_tx, mut output_rx) =
        ChannelConnection::<DefaultInput, DefaultOutput>::new_pair(64);

    // 构建秘书行为
    let behavior = DefaultSecretaryBuilder::new()
        .with_name("项目秘书")
        .with_llm(llm_provider)
        .with_dispatch_strategy(DispatchStrategy::CapabilityFirst)
        .with_auto_clarify(true)
        .with_auto_dispatch(false)  // 需要人工批准
        .build();

    // 启动秘书引擎
    let core = SecretaryCore::new(behavior);
    let (_handle, _join_handle) = core.start(connection).await;

    // 后台处理输出
    tokio::spawn(async move {
        while let Some(output) = output_rx.recv().await {
            match output {
                DefaultOutput::DecisionRequired { decision } => {
                    // 向人工展示决策
                    println!("需要决策: {}", decision.description);
                    for (i, opt) in decision.options.iter().enumerate() {
                        println!("  [{}] {}", i, opt.label);
                    }
                }
                DefaultOutput::TaskCompleted { todo_id, result } => {
                    println!("任务 {} 完成: {}", todo_id, result.summary);
                }
                // ... 其他输出
            }
        }
    });

    // 发送输入
    input_tx.send(DefaultInput::Idea {
        content: "构建一个 REST API".to_string(),
        priority: Some(TodoPriority::High),
        metadata: None,
    }).await?;

    Ok(())
}
}

5 阶段工作流

  1. 接收想法 → 记录为 TODO
  2. 澄清需求 → 生成项目文档
  3. 调度分配 → 分配给执行智能体
  4. 监控反馈 → 推送关键决策给人工
  5. 验收汇报 → 更新 TODO 状态

秘书命令

命令描述
idea:<内容>提交新想法
clarify:<todo_id>澄清需求
dispatch:<todo_id>开始任务执行
decide:<id>:<选项>做出待决策
status显示统计信息
report生成进度报告

插件与 Rhai 结合

结合编译时插件与运行时 Rhai 脚本。

位置: examples/agent_with_plugins_and_rhai/

#![allow(unused)]
fn main() {
use mofa_sdk::plugins::{RhaiPlugin, RustPlugin};

// 编译时 Rust 插件
let rust_plugin = LoggingPlugin::new("info");

// 运行时 Rhai 脚本
let rhai_plugin = RhaiPlugin::from_file("./scripts/transform.rhai").await?;

// 构建带两种插件的智能体
let agent = ReActAgent::builder()
    .with_llm(llm_client)
    .with_tools(vec![calculator, weather])
    .with_plugin(rust_plugin)
    .with_plugin(rhai_plugin)
    .build();

// 插件执行顺序:
// 1. Rust 插件 (before_execute)
// 2. 智能体执行
// 3. Rhai 插件 (transform output)
// 4. Rust 插件 (after_execute)
}

CLI 生产冒烟测试

生产就绪性验证。

位置: examples/cli_production_smoke/

// 运行全面检查
// - 智能体创建和执行
// - LLM 连接性
// - 插件加载
// - 持久化层
// - 消息总线操作

#[tokio::main]
async fn main() -> Result<()> {
    println!("运行生产冒烟测试...\n");

    // 测试 1:智能体生命周期
    test_agent_lifecycle().await?;

    // 测试 2:LLM 连接性
    test_llm_connection().await?;

    // 测试 3:插件系统
    test_plugin_loading().await?;

    // 测试 4:数据库持久化
    test_persistence().await?;

    // 测试 5:消息总线
    test_message_bus().await?;

    println!("\n所有冒烟测试通过!");
    Ok(())
}

配置示例

配置管理模式。

位置: examples/config/

#![allow(unused)]
fn main() {
use mofa_sdk::config::{AgentConfig, LLMConfig, PersistenceConfig};

// 从文件加载
let config = AgentConfig::from_file("agent.toml")?;

// 或编程构建
let config = AgentConfig::builder()
    .id("my-agent")
    .name("我的智能体")
    .llm(LLMConfig {
        provider: "openai".into(),
        model: "gpt-4o-mini".into(),
        temperature: 0.7,
    })
    .persistence(PersistenceConfig {
        backend: "postgres".into(),
        url: env::var("DATABASE_URL")?,
    })
    .build()?;

// 从配置创建智能体
let agent = LLMAgentBuilder::from_config(&config).build_async().await?;
}

运行示例

# 反思智能体
export OPENAI_API_KEY=sk-xxx
cargo run -p reflection_agent

# 人在回路秘书
cargo run -p hitl_secretary

# 插件组合
cargo run -p agent_with_plugins_and_rhai

# 冒烟测试
cargo run -p cli_production_smoke

# 配置
cargo run -p config

可用示例

示例描述
reflection_agent自我改进智能体模式
hitl_secretary人在回路秘书
agent_with_plugins_and_rhai插件与 Rhai 结合
cli_production_smoke生产冒烟测试
config配置管理

相关链接