使用 subagents 和 Elastic Agent Builder 将业务上下文引入代码规划

0 阅读16分钟

作者:来自 Elastic Gustavo Llermaly

了解什么是 subagents、如何确保它们拥有正确的信息,以及如何创建一个专用的 subagent,将 Claude Code 连接到你的 Elasticsearch 数据。

Agent Builder 现已正式发布。立即开始使用 Elastic Cloud Trial,并在此查看 Agent Builder 的文档。

Claude Code 中的 subagents 允许你将专门任务卸载到独立的上下文窗口中,从而保持主对话的专注。在本文中,你将了解什么是 subagents、何时使用它们,以及如何使用 Elastic Agent Builder 构建一个检索 subagent,将你的开发工作流连接到 Elasticsearch 中的业务数据。

什么是 subagents?

Subagents 是专门的助手,可以被调用来执行特定任务,并使用它们自己的上下文窗口。它们完成任务后将结果返回给主 agent,从而防止主 agent 在上下文窗口中保存与后续对话无关的信息。

它们的四个核心原则是:

  • 上下文保留:每个 subagent 使用自己的上下文窗口。
  • 专业化能力:每个 subagent 都为特定任务而设计。
  • 可复用性:你可以在不同会话和项目中重复使用同一个 subagent。
  • 灵活访问控制:你可以限制 subagent 访问特定工具。

每个 subagent 都可以访问 Claude Code 工具来操作终端,例如 glob、read、write、grep 或 bash,或者访问互联网,例如 search、fetch,或通过 Model Context Protocol (MCP) servers 调用外部工具。

一个 subagent 使用如下 schema:

`

1.  ---
2.  name: your-sub-agent-name
3.  description: Description of when this subagent should be invoked
4.  tools: tool1, tool2, tool3  # Optional - inherits all tools if omitted
5.  model: sonnet  # Optional - specify model alias or 'inherit'
6.  permissionMode: default  # Optional - permission mode for the subagent
7.  skills: skill1, skill2  # Optional - skills to auto-load
8.  ---

10.  Your subagent's system prompt goes here. This can be multiple paragraphs
11.  and should clearly define the subagent's role, capabilities, and approach
12.  to solve problems.

14.  Include specific instructions, best practices, and any constraints
15.  the subagent should follow.

`AI写代码![](https://csdnimg.cn/release/blogv2/dist/pc/img/runCode/icon-arrowwhite.png)

你可以通过描述它们要执行的任务来隐式调用 subagents,Claude 会自动调用它们。例如,你可以说:“I want to plan my new functionality.”

你也可以通过直接要求 Claude Code 使用某个 subagent 来显式调用它,并告诉它:“Use the planning subagent to plan my new functionality.”

另一个重要特性是 subagents 是有状态的,因此一旦你给它分配任务,它会生成一个 ID。这样,当你再次使用它时,可以选择从头开始,或者提供该 ID 以继承之前任务的上下文。

你可以在此阅读完整文档

什么时候使用 subagents?

当你需要委派需要特定上下文的任务,但又不想让主聊天窗口变得杂乱时,subagents 非常有用。以编码为例,最常见的子任务包括:

子任务类型描述常用工具
Exploration / research搜索并分析代码而不进行修改。Read、grep、glob
Planning运行深度分析以创建实现计划。Read、grep、glob、bash
Code review审查代码质量、安全性和最佳实践。Read、grep、glob、bash
Code modification编写和编辑代码。Read、edit、write、grep、glob
Testing / debugging运行测试并分析问题。Bash、read、grep、edit
Retrieval从外部来源(APIs、数据库)获取信息。MCP 工具、bash

Claude Code 包含三个内置 agent,用于展示这些使用场景:

  • Explore:用于在代码库中进行只读搜索的快速 agent。非常适合回答类似“Where are the client's errors handled?”这样的问题。
  • Plan:研究型 agent,在 plan 模式下激活,在提出更改前分析代码库。
  • General-purpose:功能最强大的 agent,适用于需要多步骤且可能包含修改的复杂任务。

上下文管理:确保 subagents 拥有正确的信息

在设计 subagents 时,最重要的决策之一是如何处理上下文。有三个关键考虑因素:

1)subagent 应该获得哪些上下文

你提供给 subagent 的提示必须包含完成任务所需的所有信息,因为 subagent 无法访问主聊天内容。你需要具体说明:

  • 不要说:“Review the code.”
  • 要说:“Review the changes to src/auth/index.ts, focusing on JWT token validation.”

提供精确的文件名,会决定是直接使用 read 工具读取文件,还是使用 grep 进行大范围搜索,从而浪费时间和 tokens。

还要考虑不要包含什么内容。无关的上下文可能会分散 subagent 的注意力或导致结果偏差。一次请求多个事项很诱人,但专注的任务会产生更好的结果:

  • 不要说:“Review src/auth/index.ts. Here is also the database schema and our API docs for reference, fix bugs and suggest improvements about the architecture decisions.”
  • 要说:“Fix the token refresh bug in src/auth/index.ts that's throwing AUTH_TOKEN_EXPIRED unexpectedly.”

2)提供哪些工具

将工具限制在严格必要的范围内。这可以提高安全性,使 subagent 保持专注,并减少不必要的工具调用和执行成本。

`

1.  # 仅用于分析的 agent
2.  tools: Read, Grep, Glob

4.  # 需要修改代码的 agent
5.  tools: Read, Edit, Write, Grep, Glob

`AI写代码

如果你未指定 tools 字段,subagent 将继承主 agent 的所有工具,包括 MCP 工具。

你可以在此了解所有 Claude Code 工具。

3)如何在调用之间保持上下文

subagents 可以通过它们的 agentId 进行恢复:

`

1.  # 第一次调用
2.  > Use the code-analyzer agent to review the authentication module
3.  [Agent completes the analysis and returns agentId: "abc123"]

5.  # 使用之前的上下文继续
6.  > Resume agent abc123 and now analyze the authorization module
7.  [Agent continues with the context from the previous chat]

`AI写代码

你可以向 Claude 查询 agent ID,或在 ~/.claude/projects/{project}/{sessionId}/subagents/ 中找到它。

这对于长时间研究任务或多步骤工作流尤其有用。

另一种保持上下文一致的方法是让 agent 编写一个 Markdown 清单,记录其正在执行的内容和当前进度。然后你可以执行 /clear 而不会丢失初始指令。在该请求中,你可以定义任务粒度或需要保留的细节,以符合你的使用场景。

`

1.  # Task: Review authentication module

3.  ## Progress
4.  - [x] Analyzed src/auth/index.ts
5.  - [x] Found JWT validation issue
6.  - [ ] Review authorization module
7.  - [ ] Check rate limiting

9.  ## Findings
10.  - Token refresh has race condition in line 42

`AI写代码![](https://csdnimg.cn/release/blogv2/dist/pc/img/runCode/icon-arrowwhite.png)

在你清除对话后,下一个 agent 可以从这里继续。这在你希望 agent 针对一个列表运行脚本并逐条查看输出记录时非常有用。

编排模式

将 subagents 视为一种上下文优化机制非常重要。你如何协调它们,将决定整个系统的效率。存在不同的编排模式。

顺序模式(chaining)

在这种模式下,一个 subagent 完成任务,其结果会传递给下一个 subagent,形成一系列任务,类似于传统的 Linux 管道机制。

调用示例:

首先使用 planning agent 设计该功能,
然后使用 coding agent 实现它,
最后使用 reviewer agent 检查代码

并行

在这种模式下,多个 subagents 同时运行彼此独立的任务。主 Claude Code agent 负责调用它们,因为 subagents 不能生成其他 subagents

这种方法可以减少像代码审查这样的任务的执行时间,因为它允许你从不同角度处理相同的代码,而不会影响运行时间。

中心辐射模式(Hub-and-spoke / delegation)

在这种模式下,主 agent 充当协调者,将任务委派给专门的 subagents,然后汇总结果。

这是我们在示例中要实现的模式:主 Claude Code agent 将业务信息收集任务委派给使用 Elastic Agent Builder 构建的 retrieval agent,同时 explore agent 会查看本地文件,planning agent 则制定计划。

为什么使用 agent 而不是单个查询?

在构建 retrieval subagent 之前,值得理解什么时候 agent 能带来价值,而什么时候简单的 Elasticsearch Query Language (ES|QL) 查询就足够。

如果你只需要单个聚合,比如 “What's our most visited page?”,直接运行查询即可。当你的问题需要以下情况时,agent 才有价值:

  • 多个查询依赖彼此:查询 1 的答案会影响查询 2。

  • 跨索引推理:关联来自不同来源的数据。

  • 歧义解析:agent 可以解释并跟进线索。

  • 综合分析:将定量数据与定性知识结合。

我们的示例将展示所有这些能力。

作为 subagent 的 Agent Builder

使用 AI 生成代码非常快,但问题在于如何有一个良好的规划阶段,为我们的 coding agent 设定边界。为此,Claude 创建了一个专门负责规划的 subagent,进行深度分析并为主 agent 制定待办清单。

通过这个流程,你可以基于 Claude Code 在本地文件和互联网上看到的内容进行计划。然而,Elasticsearch 中仍有一些知识是你无法通过标准工具访问的。

为了在规划阶段访问我们的内部知识,我们将通过 Agent Builder 创建一个 Claude Code subagent,制作一个 retrieval agent。

你可以使用 UI 或 API 配置 agent。在这个示例中,我们将使用后者。

前提条件

场景:技术债务冲刺规划

你是 tech lead。有两周时间和两名开发人员。你的 TECH_DEBT.md 列出了 12 个条目。你可能只能处理三到四个。哪些应该优先处理?

复杂性在于你需要同时在多个维度上优化:

  • 用户影响:有多少用户遇到这个问题?
  • 业务影响:是否影响付费客户?Enterprise tier?
  • 严重性:错误?性能?还是只是代码丑陋?
  • 努力程度:快速胜利还是深坑?
  • 依赖关系:修复 A 是否能解锁修复 B?
  • 战略对齐:是否符合 Q1 优先事项?

单个查询比如 “What's the most important tech debt item?” 无法解决,因为这需要:

  1. 阅读 TECH_DEBT.md 了解这 12 个条目是什么。
  2. 对每个条目,查询 error_logs 以获取错误频率。
  3. 跨索引参考 customer_data 查看客户层级分布。
  4. 检查 support_tickets 了解投诉量。
  5. 阅读 knowledge base 中的 engineering_standards 查看是否有条目违反核心原则。
  6. 阅读 Q1_roadmap 检查战略对齐情况。
  7. 将所有信息综合成优先级推荐。

这就是 retrieval agent 在协调跨不同索引的多个查询并综合结果时发挥作用的地方。

步骤

准备测试数据集

我们将创建四个 indices:一个包含内部文档的 knowledge base、error logs、support tickets 和 customer data。

你可以使用以下方法之一来创建 indices、索引数据并创建 agent:

  • Kibana Dev Tools:使用下面提供的 Elasticsearch requests。
  • Jupyter Notebook:使用为本文编写的完整 notebook。

创建 indices

打开 Kibana Dev Tools,并运行以下 requests,为每个 index 创建 mapping 并批量索引数据。下面是 knowledge index 的结构和要索引的数据示例:

`

1.  PUT customer_data
2.  {
3.    "mappings": {
4.      "properties": {
5.        "user_id": { "type": "keyword" },
6.        "customer_tier": { "type": "keyword" },
7.        "company_name": { "type": "text" },
8.        "mrr": { "type": "float" },
9.        "joined_at": { "type": "date" }
10.      }
11.    }
12.  }

14.  POST customer_data/_bulk
15.  {"index":{}}
16.  {"user_id":"enterprise_user_01","customer_tier":"enterprise","company_name":"Acme Corp","mrr":2500.00,"joined_at":"2023-01-15"}
17.  {"index":{}}
18.  {"user_id":"enterprise_user_02","customer_tier":"enterprise","company_name":"GlobalTech Inc","mrr":4200.00,"joined_at":"2022-08-20"}
19.  {"index":{}}
20.  {"user_id":"enterprise_user_05","customer_tier":"enterprise","company_name":"DataFlow Systems","mrr":3100.00,"joined_at":"2023-06-01"}
21.  {"index":{}}
22.  {"user_id":"user_001","customer_tier":"free","company_name":"","mrr":0,"joined_at":"2024-03-15"}
23.  {"index":{}}
24.  {"user_id":"user_002","customer_tier":"free","company_name":"","mrr":0,"joined_at":"2024-05-20"}
25.  {"index":{}}
26.  {"user_id":"user_045","customer_tier":"pro","company_name":"SmallBiz LLC","mrr":49.00,"joined_at":"2024-01-10"}
27.  {"index":{}}
28.  {"user_id":"user_089","customer_tier":"pro","company_name":"StartupXYZ","mrr":49.00,"joined_at":"2024-02-28"}

`AI写代码![](https://csdnimg.cn/release/blogv2/dist/pc/img/runCode/icon-arrowwhite.png)

所有 indices 的完整请求:

原始 JSON 文件也可用:

本地项目文件

在你的项目中创建以下 Markdown (MD) 文件。这些文件示例如下:

`

1.  # Tech Debt Items

3.  ## AUTH-001: Token refresh race condition
4.  - **Module**: src/auth/refresh.ts
5.  - **Symptom**: Users randomly logged out
6.  - **Estimate**: 3 days

8.  ## EXPORT-002: CSV export timeout on large datasets
9.  - **Module**: src/export/csv.ts
10.  - **Symptom**: Timeout after 30s for >10k rows
11.  - **Estimate**: 2 days

13.  ...

`AI写代码![](https://csdnimg.cn/release/blogv2/dist/pc/img/runCode/icon-arrowwhite.png)

完整文件:

这些文件直接对应 tech debt 条目,为 agent 在与 Elasticsearch 数据交叉参考时提供明确的优先级。

使用 Agent Builder 创建 agent

现在我们将创建一个 agent,它能够使用 ES|QL 运行分析查询,为我们提供 app 使用信息,同时还能搜索 Knowledge Base (KB) 中的非结构化文本信息。

我们使用内置工具,因为它们涵盖了对任意 index 的搜索和分析。Agent Builder 也支持自定义工具以执行更专业的操作,例如指定 index 范围或添加 ES|QL 动态参数,但这里不在讨论范围内。

你可以使用 create_agent.txt 中的 curl request 来创建 agent。

`

1.  curl -X POST "https://${KIBANA_URL}/api/agent_builder/agents" \
2.    -H "Authorization: ApiKey ${API_KEY}" \
3.    -H "kbn-xsrf: true" \
4.    -H "Content-Type: application/json" \
5.    -d '{
6.      "id": "tech-debt-advisor",
7.      "name": "Tech Debt Prioritization Agent",
8.      "description": "I help prioritize technical debt by analyzing error logs, support tickets, customer impact, and aligning with engineering standards and roadmap priorities.",
9.      "avatar_color": "#BFDBFF",
10.      "avatar_symbol": "TD",
11.      "configuration": {
12.        "instructions": "This agent helps prioritize technical debt items. Use the following indices:\n\n- knowledge: Engineering standards, policies, and roadmap priorities\n- error_logs: Production error frequency by module\n- support_tickets: Customer complaints and their urgency\n- customer_data: Customer tier information (enterprise, pro, free)\n\nWhen analyzing tech debt:\n1. Check error frequency in error_logs\n2. Cross-reference affected users with customer_data to understand tier impact\n3. Count support tickets and note urgency markers\n4. Check knowledge base for relevant policies and Q1 priorities\n5. Synthesize findings into prioritized recommendations",
13.        "tools": [
14.          {
15.            "tool_ids": [
16.              "platform.core.search",
17.              "platform.core.list_indices",
18.              "platform.core.get_index_mapping",
19.              "platform.core.get_document_by_id",
20.              "platform.core.execute_esql",
21.              "platform.core.generate_esql"
22.            ]
23.          }
24.        ]
25.      }
26.    }'

`AI写代码![](https://csdnimg.cn/release/blogv2/dist/pc/img/runCode/icon-arrowwhite.png)

如果一切正常,你会收到如下响应:

`

1.  {
2.    "id": "tech-debt-advisor",
3.    "type": "chat",
4.    "name": "Tech Debt Prioritization Agent",
5.    "description": "I help prioritize technical debt by analyzing error logs, support tickets, customer impact, and aligning with engineering standards and roadmap priorities.",
6.    ...
7.  }

`AI写代码

该 agent 将在 Kibana 中可用,所以你现在可以与它进行聊天:

将 agent 配置为 Claude Code 工具

我们刚创建的 agent 会暴露一个 MCP server。现在使用已生成的 API key 将该 MCP server 添加到 Claude Code:

`claude mcp add --transport http agentbuilder https://${KIBANA_URL}/api/agent_builder/mcp --header "Authorization: ApiKey ${API_KEY}"`AI写代码

我们可以使用 claude mcp get agentbuilder 检查连接状态。

创建使用该工具的 subagent

现在我们已经将 Agent Builder 作为一组 MCP tools 可用,就可以在 Claude Code 中创建一个 subagent,使用这些工具的全部或部分,并与 Claude Code 的工具结合使用。

Claude Code 建议在此步骤使用其 agent creator 工具:

  1. 在 Claude Code 中输入 /agents。

  2. 选择 Create new agent

  3. 选择 Project scope,使其仅在此项目中可用。(这是推荐设置,以避免 agent 溢出。)

  4. 选择 Generate with Claude(推荐)。

  5. 输入描述:"Agent that analyzes technical debt by querying Elasticsearch for error logs, support tickets, customer data, and engineering knowledge base. Use this agent when you need to prioritize tech debt items based on business impact."

  6. 在 “Select tools” 中,选择 Advanced options,并选择我们在 agent 创建时定义的工具。

    `
    
    1.  Individual Tools:
    2.  ☒ platform.core.search (agentbuilder)
    3.  ☒ platform.core.list_indices (agentbuilder)
    4.  ☒ platform.core.get_index_mapping (agentbuilder)
    5.  ☒ platform.core.get_document_by_id (agentbuilder)
    6.  ☒ platform.core.execute_esql (agentbuilder)
    7.  ☒ platform.core.generate_esq (agentbuilder)
    
    `AI写代码
    
  7. 选择 [ Continue ]。

    1. 现在选择模型。对于 planning 任务,推荐使用 Opus,因为它具有较强的推理能力。选择后继续。
    2. 最后,选择 subagent 文本的背景颜色并确认。
    3. Claude 会根据描述自动为我们的 subagent 命名(例如 tech-debt-analyzer)。

测试 agent

一旦 agent 创建完成,我们可以使用一个需要多步骤推理的复杂优先级问题来测试它:

`

1.  > Based on TECH_DEBT.md, which items should we prioritize for our 2-week sprint?
2.  > Use the tech-debt-analyzer agent to check error frequency, customer impact,
3.  > support ticket volume, and alignment with engineering standards.

`AI写代码

观察该 agent 如何协调多个查询:

并会为你提供结合本地文件与 Elasticsearch 数据的全面分析:

这展示了为什么单次 query 会失败而 agent 成功:它在不同的 indices 中协调五个或更多查询,关联数据,并综合出一个建议,这可能与简单的 “修复错误数最高项” 方法相矛盾。

通过输入 /context,我们可以看到每个 MCP tool 定义和 subagent prompt 使用了多少 context。在创建 subagents 时,需要注意这些开销。

开始规划

我们现在可以开始使用本地文件、互联网和 Elasticsearch 知识作为信息来源进行规划。

可以问类似的问题:

`

1.  "Based on our requirements defined in REQUIREMENTS.md, use the planning agent
2.  to create a detailed implementation plan, prioritizing tasks according to
3.  business impact. Use the tech-debt-analyzer agent to query about internal
4.  company knowledge and make analytical queries about error patterns and
5.  customer impact."

`AI写代码

注意:Claude 会按照 hub-and-spoke 协作模式并行运行 Elasticsearch 数据分析和本地文档读取。

分析完成后,你将得到一个基于实际业务数据而非假设的优先级计划。这个 context 会使你的 AI 编程体验更加可靠,因为你可以将该计划直接提供给 agent 并逐步执行:

你提供的细节越多,指令越集中,计划的质量就越高。如果你有现有的 codebase,它会建议代码修改。

结论

Subagents 是一个很棒的工具,用于卸载特定任务,只需将最终结果提供给主 chat(无需展示执行过程),保持 chat 流的集中性。

通过选择合适的协作模式(顺序、并行或 hub-and-spoke)并正确管理 context,我们可以构建高效且易维护的 agent 系统。

Elastic Agent Builder 及其 MCP 功能允许我们使用 retrieval subagent 访问数据,通过结合本地(files、source code)、外部(internet)和内部(Elasticsearch)资源来辅助规划和编码。关键洞察在于,agents 的价值不在于简单查询,而在于需要基于前置结果进行多步骤推理并整合多来源信息时。

资源

原文:www.elastic.co/search-labs…