跳转到内容

构建 Agent

当你需要把 agent spec、tools、provider 和持久化组装成一个可运行的 AgentRuntime 时,使用本页。

  • 已在 Cargo.toml 中加入 awaken
  • 已有一个 LlmExecutor 实现
  • 了解 AgentSpecAgentRuntimeBuilder
  1. 定义 agent spec:
use awaken::engine::GenaiExecutor;
use awaken::registry_spec::ModelSpec;
use awaken::{AgentSpec, AgentRuntimeBuilder};
let spec = AgentSpec::new("assistant")
.with_model_id("claude-sonnet")
.with_system_prompt("You are a helpful assistant.")
.with_max_rounds(10);
  1. 注册 tools:
use std::sync::Arc;
let builder = AgentRuntimeBuilder::new()
.with_agent_spec(spec)
.with_tool("search", Arc::new(SearchTool))
.with_tool("calculator", Arc::new(CalculatorTool));
  1. 注册 provider 和 model:
let builder = builder
.with_provider("anthropic", Arc::new(GenaiExecutor::new()))
.with_model(ModelSpec::new("claude-sonnet", "anthropic", "claude-sonnet-4-20250514"));
  1. 挂接持久化:
use awaken::contract::commit_coordinator::CommitCoordinator;
use awaken::stores::{InMemoryStore, MemoryCommitCoordinator};
let store = Arc::new(InMemoryStore::new());
let coordinator = MemoryCommitCoordinator::wrap(store) as Arc<dyn CommitCoordinator>;
let builder = builder.with_commit_coordinator(coordinator);
  1. 构建并校验:
let runtime = builder.build()?;

build() 会在启动时就解析并校验所有注册项,提前发现缺失的 model、provider 或 plugin。

  1. 通过配置调优 agent 行为:

AgentSpec 就是 agent 的运行时配置对象。下面这些字段和 section 与 /v1/config/agents、admin console 页面编辑的是同一份数据:

use serde_json::json;
let mut spec = AgentSpec::new("assistant")
.with_model_id("claude-sonnet")
.with_system_prompt("You are a careful coding assistant.")
.with_hook_filter("reminder")
.with_section("reminder", json!({
"rules": [{
"tool": "*",
"output": "any",
"message": {
"target": "suffix_system",
"content": "Prefer verifying code changes before final answers.",
"cooldown_turns": 3
}
}]
}));
spec.plugin_ids.push("reminder".into());

基础 prompt 使用 system_prompt;需要页面可配置、可校验、可运行时生效的行为, 放到 remindergenerative-uipermissiondeferred_tools 等插件 section 中。后续 prompt 语义 hook 也应沿用同样的类型化 section 模式。

  1. 执行一次 run:
use awaken::RunActivation;
let request = RunActivation::new("thread-1", vec![user_message])
.with_agent_id("assistant");
// 当调用方需要流式事件时,使用 runtime.run(..., sink)。
let result = runtime.run_to_completion(request).await?;

如果启用了 server,可访问 /health;否则直接检查 AgentRunResult 是否成功完成。

错误原因修复
BuildError::ValidationFailedspec 引用了未注册的 model/providerbuild() 前补齐注册
BuildError::State多个插件重复注册同一状态键保证状态键只注册一次
运行期 RuntimeErrorprovider 推理失败检查凭据和模型 ID

examples/src/research/

  • crates/awaken-runtime/src/builder.rs
  • crates/awaken-runtime-contract/src/registry_spec.rs
  • crates/awaken-runtime/src/runtime/agent_runtime/mod.rs