Skip to content

Goose 核心概念

本章概览

本章将深入解析 Goose 的核心概念,帮助你理解:

  • Agent:智能体的核心抽象
  • Provider:LLM 提供者接口
  • Extension:能力扩展机制
  • Tool:工具调用系统
  • Session:会话管理
  • Message:消息和对话流

1. Agent(智能体)

1.1 什么是 Agent?

通俗解释

Agent 就像一个"超级大脑",它能够:

  • 理解你说的话
  • 决定需要做什么
  • 调用各种工具完成任务
  • 根据结果继续思考和行动

技术定义: Agent 是 Goose 的核心组件,负责协调 LLM 和工具之间的交互,实现自主任务执行。

1.2 Agent 结构

rust
// 位于 crates/goose/src/agents/agent.rs

pub struct Agent {
    // LLM Provider(必需)
    pub provider: SharedProvider,

    // 扩展管理器
    pub extension_manager: Arc<ExtensionManager>,

    // 子配方(Recipe)
    sub_recipes: Mutex<HashMap<String, SubRecipe>>,

    // 前端工具
    frontend_tools: Mutex<HashMap<String, FrontendTool>>,

    // 提示管理器
    prompt_manager: Mutex<PromptManager>,

    // 权限确认通道
    confirmation_tx: mpsc::Sender<(String, PermissionConfirmation)>,
    confirmation_rx: Mutex<mpsc::Receiver<(String, PermissionConfirmation)>>,

    // 工具检查管理器
    tool_inspection_manager: ToolInspectionManager,

    // 重试管理器
    retry_manager: RetryManager,
}

1.3 Agent 事件

Agent 在执行过程中会产生各种事件:

rust
pub enum AgentEvent {
    Message(Message),                              // 新消息
    McpNotification((String, ServerNotification)), // MCP 通知
    ModelChange { model: String, mode: String },   // 模型变更
    HistoryReplaced(Conversation),                 // 历史替换
}

1.4 Agent 生命周期

┌─────────────────────────────────────────────────────────────┐
│                     Agent 生命周期                           │
├─────────────────────────────────────────────────────────────┤
│  1. 创建 Agent                                              │
│     └── Agent::new()                                        │
│         ├── 初始化 ExtensionManager                         │
│         ├── 创建 ToolInspectionManager                      │
│         └── 设置默认配置                                    │
│                                                             │
│  2. 配置 Provider                                           │
│     └── agent.set_provider(provider)                        │
│                                                             │
│  3. 加载扩展                                                 │
│     └── extension_manager.register(config)                  │
│         ├── 连接 MCP Server                                 │
│         └── 获取工具列表                                    │
│                                                             │
│  4. 开始会话                                                 │
│     └── agent.reply(conversation)                           │
│         ├── 交互循环开始                                    │
│         ├── 调用 LLM                                        │
│         ├── 执行工具                                        │
│         └── 返回结果                                        │
│                                                             │
│  5. 结束会话                                                 │
│     └── 保存对话历史                                        │
└─────────────────────────────────────────────────────────────┘

2. Provider(提供者)

2.1 什么是 Provider?

通俗解释

Provider 就像一个"翻译官",帮助 Goose 与不同的 LLM(如 GPT-4、Claude)交流。 每个 LLM 都有自己的 API 格式,Provider 负责处理这些差异。

技术定义: Provider 是一个抽象层,定义了与 LLM 交互的统一接口。

2.2 Provider Trait

rust
// 位于 crates/goose/src/providers/base.rs

#[async_trait]
pub trait Provider: Send + Sync {
    /// 获取 Provider 名称
    fn name(&self) -> &str;

    /// 获取模型信息
    fn model_info(&self) -> &ModelInfo;

    /// 获取元数据
    fn metadata(&self) -> &ProviderMetadata;

    /// 发送聊天请求
    async fn chat(
        &self,
        messages: &[Message],
        tools: &[Tool],
    ) -> Result<Message, ProviderError>;

    /// 流式聊天
    async fn chat_stream(
        &self,
        messages: &[Message],
        tools: &[Tool],
    ) -> Result<BoxStream<StreamEvent>, ProviderError>;
}

2.3 ModelInfo

每个模型都有相关信息:

rust
pub struct ModelInfo {
    /// 模型名称
    pub name: String,

    /// 最大上下文长度
    pub context_limit: usize,

    /// 输入 token 成本(可选)
    pub input_token_cost: Option<f64>,

    /// 输出 token 成本(可选)
    pub output_token_cost: Option<f64>,

    /// 是否支持缓存控制
    pub supports_cache_control: Option<bool>,
}

2.4 Provider 类型

rust
pub enum ProviderType {
    Preferred,     // 推荐的 Provider
    Builtin,       // 内置 Provider
    Declarative,   // 声明式 Provider
    Custom,        // 自定义 Provider
}

2.5 支持的 Provider

Provider支持的模型特点
openaiGPT-4, GPT-4o, GPT-4o-mini最常用
anthropicClaude 3.5, Claude 3强大的推理能力
ollamaLlama, Mistral, Qwen本地运行
azureAzure OpenAI企业级
bedrockAWS Bedrock 模型AWS 集成
gcpvertexaiGoogle Vertex AIGCP 集成
openrouter多种模型模型代理
litellm多种模型统一接口

3. Extension(扩展)

3.1 什么是 Extension?

通俗解释

Extension 就像 Goose 的"技能包"。每个扩展提供一组特定能力:

  • Developer 扩展:让 Goose 能操作文件、运行命令
  • Computer Controller 扩展:让 Goose 能控制浏览器
  • Memory 扩展:让 Goose 能记住之前的对话

技术定义: Extension 是通过 MCP 协议与 Goose 交互的外部组件,提供工具供 Agent 调用。

3.2 Extension Trait

rust
// 位于 crates/goose/src/agents/extension.rs

#[async_trait]
pub trait Extension: Send + Sync {
    /// 扩展名称
    fn name(&self) -> &str;

    /// 扩展描述(给人看的)
    fn description(&self) -> &str;

    /// 使用说明(会加入系统提示)
    fn instructions(&self) -> &str;

    /// 暴露的工具列表
    fn tools(&self) -> &[Tool];

    /// 获取扩展状态
    async fn status(&self) -> Result<HashMap<String, Value>>;

    /// 调用工具
    async fn call_tool(
        &self,
        tool_name: &str,
        parameters: HashMap<String, Value>,
    ) -> ToolResult<Value>;
}

3.3 ExtensionConfig

扩展配置:

rust
pub struct ExtensionConfig {
    /// 扩展类型
    pub extension_type: ExtensionType,

    /// 扩展名称
    pub name: String,

    /// 环境变量
    pub env: HashMap<String, String>,

    /// 超时设置
    pub timeout: Option<Duration>,

    /// 是否启用
    pub enabled: bool,
}

pub enum ExtensionType {
    Builtin(String),           // 内置扩展
    Sse(String),               // SSE 连接
    Stdio(PathBuf, Vec<String>), // stdio 进程
}

3.4 内置扩展

扩展名功能工具示例
developer开发工具read_file, write_file, shell
computercontroller浏览器控制screenshot, open_url, click
memory跨会话记忆remember, recall, forget
jetbrainsIDE 集成open_file, run_action

3.5 MCP 通信

Extension 通过 MCP 协议与 Goose 通信:

┌────────────┐         JSON-RPC          ┌────────────┐
│   Goose    │ ◄─────────────────────► │    MCP     │
│   Agent    │   over stdio / SSE       │   Server   │
└────────────┘                          └────────────┘

请求示例:
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "read_file",
    "arguments": {"path": "/path/to/file"}
  },
  "id": 1
}

响应示例:
{
  "jsonrpc": "2.0",
  "result": {
    "content": [{"type": "text", "text": "file content..."}]
  },
  "id": 1
}

4. Tool(工具)

4.1 什么是 Tool?

通俗解释

Tool 就是 Goose 可以使用的"技能"。比如:

  • read_file:读取文件
  • shell:运行命令
  • screenshot:截图

技术定义: Tool 是一个可调用的函数,有名称、描述、参数定义和执行逻辑。

4.2 Tool 结构

rust
// 来自 rmcp crate

pub struct Tool {
    /// 工具名称
    pub name: String,

    /// 工具描述
    pub description: String,

    /// 输入参数的 JSON Schema
    pub input_schema: Value,
}

4.3 ToolCall 和 ToolResult

rust
// 工具调用请求
pub struct ToolCall {
    /// 调用 ID
    pub id: String,

    /// 工具名称
    pub name: String,

    /// 参数
    pub arguments: Value,
}

// 工具调用结果
pub struct CallToolResult {
    /// 结果内容
    pub content: Vec<Content>,

    /// 是否出错
    pub is_error: Option<bool>,
}

4.4 工具调用流程

1. LLM 决定调用工具
   ┌────────────────────────────────────────────┐
   │ AIMessage:                                  │
   │   tool_calls: [                             │
   │     {                                       │
   │       id: "call_123",                       │
   │       name: "read_file",                    │
   │       arguments: {"path": "/etc/hosts"}     │
   │     }                                       │
   │   ]                                         │
   └────────────────────────────────────────────┘


2. Agent 执行工具
   ┌────────────────────────────────────────────┐
   │ extension_manager.call_tool(                │
   │     "read_file",                            │
   │     {"path": "/etc/hosts"}                  │
   │ )                                           │
   └────────────────────────────────────────────┘


3. 返回工具结果
   ┌────────────────────────────────────────────┐
   │ ToolMessage:                                │
   │   tool_call_id: "call_123",                 │
   │   content: "127.0.0.1 localhost..."         │
   └────────────────────────────────────────────┘


4. LLM 继续处理
   ┌────────────────────────────────────────────┐
   │ AIMessage:                                  │
   │   content: "文件内容显示..."                │
   └────────────────────────────────────────────┘

5. Session(会话)

5.1 什么是 Session?

通俗解释

Session 就是你和 Goose 的一次"对话"。包含:

  • 对话历史
  • 使用的扩展
  • 各种设置

5.2 Session 结构

rust
// 位于 crates/goose/src/session/mod.rs

pub struct Session {
    /// 会话 ID
    pub id: String,

    /// 会话类型
    pub session_type: SessionType,

    /// 对话内容
    pub conversation: Conversation,

    /// 元数据
    pub metadata: SessionMetadata,

    /// 扩展数据
    pub extension_data: ExtensionData,
}

pub enum SessionType {
    Interactive,    // 交互式会话
    Scheduled,      // 定时任务
    Subagent,       // 子 Agent
}

5.3 SessionConfig

rust
pub struct SessionConfig {
    /// Provider 名称
    pub provider: String,

    /// 模型名称
    pub model: String,

    /// 安全模式
    pub goose_mode: GooseMode,

    /// 最大轮数
    pub max_turns: Option<u32>,

    /// 系统提示
    pub system_prompt: Option<String>,
}

5.4 会话恢复

Goose 支持恢复之前的会话:

bash
# CLI 恢复最近会话
goose session -r

# 或指定会话 ID
goose session --resume-id abc123

6. Message(消息)

6.1 消息类型

Goose 使用多种消息类型:

rust
// 位于 crates/goose/src/conversation/message.rs

pub struct Message {
    /// 消息角色
    pub role: Role,

    /// 消息内容
    pub content: Vec<MessageContent>,

    /// 工具调用(仅 Assistant)
    pub tool_calls: Option<Vec<ToolCall>>,

    /// 工具调用 ID(仅 Tool)
    pub tool_call_id: Option<String>,

    /// 元数据
    pub metadata: Option<MessageMetadata>,
}

pub enum Role {
    User,       // 用户消息
    Assistant,  // AI 回复
    System,     // 系统提示
    Tool,       // 工具结果
}

6.2 MessageContent

rust
pub enum MessageContent {
    Text(String),           // 文本
    Image { url: String },  // 图片
    ToolUse(ToolCall),      // 工具调用
    ToolResult {            // 工具结果
        tool_call_id: String,
        content: String,
    },
}

6.3 Conversation

rust
pub struct Conversation {
    /// 消息列表
    messages: Vec<Message>,

    /// 系统提示
    system_prompt: Option<String>,
}

impl Conversation {
    /// 添加用户消息
    pub fn add_user_message(&mut self, content: &str);

    /// 添加 AI 消息
    pub fn add_assistant_message(&mut self, message: Message);

    /// 添加工具结果
    pub fn add_tool_result(&mut self, tool_call_id: &str, result: Value);

    /// 获取所有消息
    pub fn messages(&self) -> &[Message];
}

7. Recipe(配方)

7.1 什么是 Recipe?

通俗解释

Recipe 是预定义的任务模板,可以快速启动特定类型的工作。 比如 "code review" recipe 会自动设置代码审查相关的提示和工具。

7.2 Recipe 结构

rust
pub struct Recipe {
    /// 配方名称
    pub name: String,

    /// 描述
    pub description: String,

    /// 作者
    pub author: Author,

    /// 设置
    pub settings: Settings,

    /// 子配方
    pub sub_recipes: Vec<SubRecipe>,
}

pub struct Settings {
    /// 系统提示模板
    pub system_prompt_template: Option<String>,

    /// 需要的扩展
    pub required_extensions: Vec<String>,

    /// 环境变量
    pub env: HashMap<String, String>,
}

7.3 使用 Recipe

bash
# 通过 URL 加载
goose session --recipe https://example.com/recipe.yaml

# 通过本地文件
goose session --recipe ./my-recipe.yaml

8. 错误处理

8.1 错误类型

Goose 使用分层的错误处理:

rust
// Provider 错误
pub enum ProviderError {
    RateLimited { retry_after: Option<Duration> },
    InvalidRequest(String),
    AuthenticationError(String),
    ServerError(String),
    NetworkError(String),
    Unknown(String),
}

// Agent 错误
pub struct ErrorData {
    pub code: ErrorCode,
    pub message: String,
    pub data: Option<Value>,
}

8.2 错误恢复

Agent 错误会被发送回 LLM,让其尝试恢复:

1. 工具调用失败
   ToolResult { is_error: true, content: "文件不存在" }

2. LLM 收到错误
   "工具调用失败:文件不存在。我来尝试其他方法..."

3. LLM 尝试恢复
   调用其他工具或修改参数重试

8.3 重试机制

rust
pub struct RetryManager {
    max_attempts: u32,
    current_attempts: AtomicU32,
}

impl RetryManager {
    /// 检查是否可以重试
    pub fn can_retry(&self) -> bool;

    /// 增加重试次数
    pub fn increment(&self) -> u32;

    /// 重置计数器
    pub fn reset(&self);
}

9. 概念关系图

┌─────────────────────────────────────────────────────────────────────┐
│                          Goose 核心概念关系                          │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│  ┌─────────┐     管理      ┌─────────────┐                         │
│  │ Session │ ─────────── │ Conversation │                         │
│  └────┬────┘              └──────┬──────┘                         │
│       │                          │                                  │
│       │ 包含                     │ 包含                             │
│       ▼                          ▼                                  │
│  ┌─────────┐              ┌───────────┐                            │
│  │  Agent  │              │  Message  │ ◄─── Role: User/Assistant  │
│  └────┬────┘              └───────────┘      /System/Tool          │
│       │                                                             │
│       ├── 使用 ──► ┌──────────┐                                    │
│       │            │ Provider │ ◄─── OpenAI/Anthropic/Ollama...   │
│       │            └──────────┘                                    │
│       │                                                             │
│       └── 管理 ──► ┌──────────────────┐                            │
│                    │ ExtensionManager │                            │
│                    └────────┬─────────┘                            │
│                             │                                       │
│                             │ 包含                                  │
│                             ▼                                       │
│                    ┌─────────────┐        ┌────────┐               │
│                    │  Extension  │ ─暴露─►│  Tool  │               │
│                    └─────────────┘        └────────┘               │
│                                                                     │
│  ┌─────────┐                                                       │
│  │ Recipe  │ ─── 预配置 ──► Agent + Extensions + Prompts           │
│  └─────────┘                                                       │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

10. 术语表

术语英文解释
智能体Agent协调 LLM 和工具的核心组件
提供者ProviderLLM API 的抽象接口
扩展Extension通过 MCP 提供能力的组件
工具Tool扩展暴露的可调用函数
会话Session一次完整的对话过程
对话Conversation消息的有序集合
消息Message对话中的单条内容
配方Recipe预定义的任务模板
交互循环Interactive LoopAgent 的核心执行逻辑

上一章:架构设计下一章:实现细节

基于 MIT 许可证发布。内容版权归作者所有。