集成修改报告

KB Agent × Deep Research
Instruction 整合方案

分析 KB_WORKFLOW_INSTRUCTIONS_RESEARCH 与 deep_research 各层 Prompt 的职责边界, 给出最小侵入性的修改建议与完整集成代码,含逐行 diff 对比。

报告日期:2026-04-20 框架:deepagents (LangGraph) 主模型:claude-sonnet-4-6
目录
  1. 集成决策:为何不合并 RESEARCH_WORKFLOW_INSTRUCTIONS
  2. Prompt 职责映射表
  3. Section F 修改内容(主 agent 唯一改动)
  4. 新增:RESEARCH_AGENT_INSTRUCTIONS(subagent prompt)
  5. 原始 vs 改写 RESEARCHER_INSTRUCTIONS 对比
  6. 完整运行时架构
  7. 完整集成代码
  8. 关键设计决策说明
1
集成决策:为何不合并 RESEARCH_WORKFLOW_INSTRUCTIONS

deep_research 示例中,主 agent 的 system_prompt 由两段组成:

# deep_research 原始主 agent prompt 构成
INSTRUCTIONS = (
    RESEARCH_WORKFLOW_INSTRUCTIONS       # ① 研究流程编排规范
    + SUBAGENT_DELEGATION_INSTRUCTIONS   # ② 并发调度规范
)

如果直接将这两段追加到 KB_WORKFLOW_INSTRUCTIONS_RESEARCH 末尾,会产生以下冲突:

❌ 若直接合并的问题
  • 双重编排逻辑冲突:KB 指令已有 Sections A-F 的路由规则,RESEARCH_WORKFLOW_INSTRUCTIONS 又定义了一套六步研究流程,模型会在两套规则间不确定性选择
  • Todo 规则重复:KB Section 3 与 deep_research 的规划步骤均含 write_todos() 指令,触发条件不一致
  • 并发控制错位SUBAGENT_DELEGATION_INSTRUCTIONS 专为多路 web 搜索设计,KB 场景无并发 research 需求
  • 身份混淆:KB agent 是"知识库问答专家",合并后变成"研究编排者",主要身份被稀释
✅ 正确的集成策略
  • 主 agent prompt 最小修改:只补充 Section F 的委派接口细节,其余不变
  • subagent prompt 完整重写:将 RESEARCHER_INSTRUCTIONS 适配为 KB 工具版本
  • 保留身份优先级:KB agent 职责描述永远在 prompt 最前
  • 职责边界清晰:主 agent 合成报告,subagent 只返回证据包
核心原则
KB_WORKFLOW_INSTRUCTIONS_RESEARCH 本身已经是完整的 orchestration 规范。 集成 deep_research 能力 = 定义一个高质量的 research-agent subagent,而不是向主 agent 追加编排规则。
2
Prompt 职责映射表
Prompt 组件来源集成归属处理方式原因
KB_WORKFLOW_INSTRUCTIONS_RESEARCH 原有 主 agent system_prompt 保留,仅 Section F 小幅增补 已是完整编排规范,无需合并外部规则
RESEARCH_WORKFLOW_INSTRUCTIONS deep_research 不使用 Web 研究编排规范,与 KB 路由规则冲突
SUBAGENT_DELEGATION_INSTRUCTIONS deep_research 不使用 并发 web 搜索调度规范,KB 场景不适用
RESEARCHER_INSTRUCTIONS deep_research research-agent subagent 改写为 KB 工具版本 保留方法论,替换工具集,修改输出格式
RESEARCH_AGENT_INSTRUCTIONS 新增 research-agent subagent 新建 KB 工具版研究员 prompt,替代原 RESEARCHER_INSTRUCTIONS
3
Section F 修改内容(主 agent 唯一改动)

原始 Section F 已正确指向 task(subagent_type="research-agent"),但缺少:

Section F — Report Writing and Structured Analysis +6 行  -1 行
82 ### F. Report Writing and Structured Analysis
83 - **Trigger**: user asks to write, draft, complete, or polish structured reports.
84 - **Execution**:
85- 1. **Delegate first (required)**: call `task(subagent_type="research-agent")` to produce
86- report-ready content, including key findings, evidence grounding, and sectioned structure.
87- 2. **Context and evidence**: ensure report claims are grounded in available business context
88- and knowledge retrieval outputs; include `[citation:x]` for factual statements when sources exist.
89- 3. **Output quality**: return a clear report format with sections aligned to user intent.
90- 4. **Fallback**: if delegation fails or evidence is insufficient, explain the limitation.
85+ 1. **Pre-collect context (required before delegation)**:
86+ - Call `retrieve_from_kb(query)` if not already done to gather seed evidence.
87+ - Call `list_business_contexts()` if not already done to confirm active task and entities.
88+ 2. **Delegate with packed context**: call `task(subagent_type="research-agent")` and include:
89+ - Report topic and required sections (background, risks, financials, conclusion).
90+ - Pre-retrieved KB snippets and their citation indexes.
91+ - Active business context summary (borrower name, task ID, key entities).
92+ 3. **Receive structured findings**: research-agent returns an evidence package with
93+ `[citation:x]` tags; do NOT ask it to produce the final user-facing report.
94+ 4. **Synthesize final report**: combine research-agent findings with direct evidence you hold;
95+ write the final report yourself with proper sections and citations.
96+ 5. **Output quality**: sections must align to user intent; all facts must carry `[citation:x]`.
97+ 6. **Fallback**: if delegation fails, explain limitation and provide draft outline + missing inputs.
⚠️ 原版问题
原版步骤 1 直接说 "delegate first",但 subagent 的上下文窗口是隔离的—— 如果主 agent 不把已有的 KB 证据和业务上下文打包进 task() 的 prompt, subagent 就会从零开始重复检索,造成 token 浪费和结果不一致。
✅ 修改后的改进
新版明确了"委派前预收集"步骤,subagent 收到的 prompt 包含: 主题 + 所需章节 + 已有 KB 证据片段 + 业务上下文摘要, 避免重复检索,保证引用连贯。
4
新增:RESEARCH_AGENT_INSTRUCTIONS(subagent prompt)

这是本次集成的核心新增内容。基于 RESEARCHER_INSTRUCTIONS 的方法论,完整改写为适配 KB 工具集的版本。

完整 RESEARCH_AGENT_INSTRUCTIONS
RESEARCH_AGENT_INSTRUCTIONS = f"""You are a research analyst specializing in
business due-diligence and knowledge-base evidence gathering.
Today's date is {current_date}.

## Role
Your job is to gather comprehensive, citation-backed evidence from the knowledge
base and business context, then return a structured evidence package.
The orchestrator (main agent) will synthesize your output into the final
user-facing report — your role is evidence gathering and structuring,
not final report writing.

## Available Tools
- `retrieve_from_kb(query)`      — semantic search (primary tool)
- `list_business_contexts()`     — active tasks, borrowers, entity metadata
- `get_doc_context_by_id(id)`    — read specific document content
- `think_tool`                   — structured reasoning & planning

## Research Process (follow in order)

### Step 1 — Think first
Use `think_tool` to:
- Decompose the report topic into 3-5 specific evidence sub-questions
- Identify which entities, metrics, or facts are required
- Plan query sequence (broad → specific)

### Step 2 — Retrieve from KB
- Start with broad queries covering the core topic
- After each call, pause: "Do I have sufficient evidence? What's still missing?"
- Refine queries to fill specific gaps
- Hard limit: max 5 calls; max 3 for simple topics
- Stop early when 3+ relevant sources found or last two queries overlap

### Step 3 — Validate with business context
- Call `list_business_contexts()` once to confirm active task, borrower, key entities
- Cross-reference retrieved facts against the business context

### Step 4 — Read key files (only if retrieval is insufficient)
- Identify candidate file IDs from business context or retrieval metadata
- Call `get_doc_context_by_id(file_id)` for at most 3 files
- Prioritize files most directly relevant to evidence gaps

### Step 5 — Synthesize evidence package
Compile all gathered evidence into the output format below.

## Hard Limits
| Tool                      | Max calls | Stop condition                        |
|---------------------------|-----------|---------------------------------------|
| retrieve_from_kb          | 5         | sufficient evidence or repeating      |
| list_business_contexts    | 1         | always call at most once              |
| get_doc_context_by_id     | 3         | only when retrieval is insufficient   |
| think_tool                | unlimited | use freely                            |

## Output Format (required — evidence package, NOT user-facing report)
## Evidence Package

### Key Findings
- [Finding 1] [citation:1]
- [Finding 2] [citation:2]

### Evidence by Section
**[Background / Financials / Risk Factors / ...]**
- [evidence point] [citation:x]

### Evidence Gaps
- [What could not be found and why]

### Sources
[1] [document title or KB chunk identifier]
[2] ...

## Constraints
- Never fabricate facts, entities, or figures
- Only cite what was actually returned by tools
- If evidence is insufficient, list gaps explicitly
"""
5
原始 vs 改写 RESEARCHER_INSTRUCTIONS 对比
维度原始(deep_research)改写(KB 集成)
身份 通用研究助手,处理任意 web 研究主题 业务尽调研究分析师,专注 KB 证据采集
主要工具 tavily_search(互联网) retrieve_from_kb(知识库语义检索)
辅助工具 think_tool list_business_contexts + get_doc_context_by_id + think_tool
调用上限 simple: 2-3 次;complex: 5 次搜索 KB 检索 5 次;文件读取 3 次;业务上下文 1 次
停止条件 3+ 相关来源 / 最近两次结果重叠 同上 + 证据充分性评估
输出格式 含 URL 列表的最终研究报告(直接面向用户) Evidence Package(证据包,供主 agent 合成)
引用格式 [1][2][3] + URL Sources 列表 [citation:x](与 KB agent 引用规范一致)
核心方法论 保留:先宽后窄 · 适时停止 · think_tool 规划 · 硬性调用上限
最关键的输出格式变化
原版 RESEARCHER_INSTRUCTIONS 要求 subagent 直接写出最终报告(含标题、段落、URL 来源)。 改写后,subagent 只返回证据包(Evidence Package):结构化的发现列表 + 证据缺口 + 来源索引。 最终报告由主 agent 合成,保证语言一致性、引用格式统一、报告结构符合用户意图。
6
完整运行时架构
┌─────────────────────────────────────────────────────────────────┐ │ KB Agent(主 agent) │ │ │ │ system_prompt: KB_WORKFLOW_INSTRUCTIONS_RESEARCH │ │ (Section F 补充了委派接口契约,其余原文不变) │ │ │ │ tools: retrieve_from_kb · list_business_contexts │ │ get_doc_context_by_id · think_tool │ │ built-in: write_todos · task() · ls · read_file · ... │ └──────┬──────────────┬────────────────┬───────────────────────────┘ │ │ │ task("research-agent") task("file_catalog") task("mermaid-expert") │ │ │ ┌──────▼──────┐ ┌───────▼──────┐ ┌───▼─────────────┐ │research- │ │file_catalog │ │mermaid-expert │ │agent │ │SubAgent │ │SubAgent │ │ │ │ │ │ │ │RESEARCH_ │ │(已有, │ │(已有,图表 │ │AGENT_ │ │ 无需修改) │ │ 生成,无需修改)│ │INSTRUCTIONS │ │ │ │ │ │tools: │ └──────────────┘ └─────────────────┘ │ retrieve_ │ │ from_kb │ │ list_biz_ │ │ contexts │ │ get_doc_ │ │ context │ │ think_tool │ │↩ 返回: │ │ Evidence │ │ Package │ └─────────────┘
Section F 调用序列(用户请求"写尽调报告"时)
1
主 agent 预收集调用 retrieve_from_kb("尽调主题") 获取种子证据;调用 list_business_contexts() 确认借款方和任务 ID
2
主 agent 委派调用 task(subagent_type="research-agent", prompt="..."),prompt 中打包:报告主题、所需章节、已有 KB 证据片段、业务上下文摘要
3
research-agent 执行按 RESEARCH_AGENT_INSTRUCTIONS:think → retrieve_from_kb(最多5次)→ list_business_contexts(1次)→ get_doc_context_by_id(最多3次)→ 返回 Evidence Package
4
主 agent 合成报告将 Evidence Package 与自身持有的证据合并,按用户意图写出最终报告,添加 [citation:x] 标注
7
完整集成代码
kb_agent_integrated.py
from datetime import datetime
from langchain.chat_models import init_chat_model
from deepagents import create_deep_agent

# ── 1. 主 agent 系统提示(Section F 已补充委派接口细节)──
KB_WORKFLOW_INSTRUCTIONS_RESEARCH = """You are a knowledge-base Q&A expert...
[原文保留,仅 Section F 按 diff 修改]
"""

# ── 2. research-agent subagent 提示词 ──
current_date = datetime.now().strftime("%Y-%m-%d")

RESEARCH_AGENT_INSTRUCTIONS = f"""You are a research analyst specializing in
business due-diligence and knowledge-base evidence gathering.
Today's date is {current_date}.

## Role
Your job is to gather evidence from the KB and return a structured
evidence package. The orchestrator synthesizes the final report.

## Available Tools
- retrieve_from_kb(query)   — KB semantic search (primary)
- list_business_contexts()  — active tasks & entity metadata
- get_doc_context_by_id(id) — document content
- think_tool                — planning & reasoning

## Research Process
Step 1 — think_tool: decompose topic into 3-5 sub-questions
Step 2 — retrieve_from_kb: broad → specific (max 5 calls)
Step 3 — list_business_contexts: validate entities (once)
Step 4 — get_doc_context_by_id: fill gaps (max 3 files)
Step 5 — return Evidence Package (see format below)

## Hard Limits
| Tool                   | Max | Stop condition               |
|------------------------|-----|------------------------------|
| retrieve_from_kb       | 5   | sufficient / repeating       |
| list_business_contexts | 1   | once per task                |
| get_doc_context_by_id  | 3   | only if retrieval insufficient|
| think_tool             | ∞   | use freely                   |

## Output Format
## Evidence Package
### Key Findings
- [finding] [citation:x]
### Evidence by Section
**[Background / Financials / Risks]**
- [evidence] [citation:x]
### Evidence Gaps
- [gap description]
### Sources
[x] [document title or KB chunk ID]

## Constraints
- No fabrication; only cite tool-returned facts
- List gaps explicitly when evidence is insufficient
"""

# ── 3. SubAgent 定义 ──
research_sub_agent = {
    "name": "research-agent",
    "description": (
        "Gathers evidence from the knowledge base, business context, and documents "
        "to produce structured citation-backed findings for report writing. "
        "Pass: report topic, required sections, seed KB context, "
        "and business context summary."
    ),
    "system_prompt": RESEARCH_AGENT_INSTRUCTIONS,
    "tools": [
        retrieve_from_kb,
        list_business_contexts,
        get_doc_context_by_id,
        think_tool,
    ],
    # 可选:用 Haiku 降低证据采集成本
    # "model": "anthropic:claude-haiku-4-5-20251001",
}

# ── 4. 创建集成 agent ──
agent = create_deep_agent(
    model=init_chat_model("anthropic:claude-sonnet-4-6", temperature=0.0),
    tools=[
        retrieve_from_kb,        # 主 agent 持有,subagent 可继承
        list_business_contexts,
        get_doc_context_by_id,
        think_tool,
    ],
    system_prompt=KB_WORKFLOW_INSTRUCTIONS_RESEARCH,
    subagents=[
        research_sub_agent,
        mermaid_expert_subagent,   # 已有,不变
        file_catalog_subagent,     # 已有,不变
    ],
)
8
关键设计决策说明
🔀 主 agent 合成 vs subagent 直接输出报告

选择"主 agent 合成"而非"subagent 直接写报告"的原因:

  • 主 agent 掌握完整对话历史和用户原始意图
  • 语言一致性(中/英切换)由主 agent 统一控制
  • 引用格式 [citation:x] 全局连续编号
  • 防止 subagent 超出"证据采集"职责,保持关注点分离
📦 为何委派前要打包上下文

deepagents 框架中 subagent 运行在隔离的上下文窗口(过滤掉主 agent 的 messages、todos、memory)。

若不打包:

  • subagent 会从零开始重复 retrieve_from_kb,浪费 token
  • 主 agent 已有的引用编号和 subagent 新产出的不连续
  • 业务实体(借款方、任务 ID)在 subagent 侧不可见
💰 成本优化:Haiku for research-agent

证据采集是高频、低推理任务(检索 + 整理),可使用 claude-haiku-4-5-20251001 替代 Sonnet:

research_sub_agent = {
  ...
  "model": "anthropic:claude-haiku-4-5-20251001",
}

主 agent(最终合成)保留 Sonnet 保证报告质量。

🛡️ 防循环设计一致性

KB 主 agent 的"Anti-loop rule"与 research-agent 的"Hard Limits"形成两层防护:

  • 主 agent:每个问题最多一次 Section F 委派
  • subagent:retrieve_from_kb 最多 5 次,文件读取最多 3 次
  • 两层限制相互独立,共同防止无限递归和 token 爆炸
📋 修改清单(总览)
文件/组件修改类型具体变更
KB_WORKFLOW_INSTRUCTIONS_RESEARCH 小幅修改 Section F:步骤 1-2 改为"预收集 → 打包委派",步骤 3-4 明确证据包接口和主 agent 合成职责
RESEARCH_AGENT_INSTRUCTIONS 新增 完整 KB 工具版研究员 prompt,替代 RESEARCHER_INSTRUCTIONS
research_sub_agent 定义 新增 name + description + system_prompt + KB tools 四字段
create_deep_agent() 调用 更新 subagents 列表中加入 research_sub_agent
RESEARCH_WORKFLOW_INSTRUCTIONS 不使用 Web 编排规范,与 KB 路由规则冲突,弃用
SUBAGENT_DELEGATION_INSTRUCTIONS 不使用 并发 web 搜索调度,KB 场景不适用,弃用
基于 langchain-ai/deepagents 源码分析 · 报告生成时间:2026-04-20