多智能体企业可持续性分析系统

基于Amazon Bedrock和Strands Agents框架构建的生产级多智能体系统,用于企业可持续性报告的实时问答和综合分析。

  • by jesamkim
  • Python
  • 本地部署
  • 4 星标
  • 更新于
在 GitHub 查看 jesamkim/agentic-multi-agent

使用说明

Agent AI多Agent演示

AWS解决方案架构师演示:由Strands agent、A2A通信和模型上下文协议(MCP)支持的生产就绪多代理系统

主要成就:

  • 使用Claude Sonnet 4.5 OCR将PDF转换为Markdown
  • 具有A2A通信的生产就绪多代理编排
  • 具有防超时功能的智能报告生成
  • 复杂查询的响应时间低于30秒

概述

高级 agent多agent系统 用于企业可持续性分析。作为AWS解决方案架构师DEMO构建,结合了Amazon Bedrock、Strands Agents框架和模型上下文协议,用于智能可持续性报告分析。

用例: 企业可持续发展报告的实时问答和全面的HTML/PDF报告(公开文件)。

技术亮点:

  • 7名专业代理 具有智能编排功能
  • 计划执行器模式 用于复杂的多步推理
  • 智能报表代理 具有自适应数据收集功能
  • 3台MCP服务器 (基岩知识库、DuckDuckGo、HTML2PDF)
  • 任何阶段的智能澄清循环
  • 三阶段报告生成(防止超时)

演示:系统在行动

欢迎屏幕:

查询与响应:

实时可持续性分析,智能报告生成。截图显示:

  • 具有格式化面板和markdown渲染的丰富CLI界面
  • 多代理架构:主管→ 知识代理→ 基岩知识库
  • 带有markdown格式的结构化响应,以提高可读性
  • 快速响应时间(简单查询不到5秒)

系统架构

A2A和MCP的高层架构

flowchart TD
    User[User Interface<br/>CLI with Rich Formatting] --> Supervisor[Supervisor Agent V2<br/>Claude Sonnet 4.5<br/>Orchestrator + Clarification]

    Supervisor -->|Simple Query| A2A_Knowledge[call_knowledge_agent<br/>A2A Communication]
    Supervisor -->|External Query| A2A_Research[call_research_agent<br/>A2A Communication]
    Supervisor -->|Complex Query| A2A_Plan[create_and_execute_plan<br/>A2A Communication]
    Supervisor -->|Report Request| A2A_Report[create_detailed_report<br/>A2A Communication]

    A2A_Knowledge --> KnowledgeAgent[Knowledge Agent<br/>Claude Sonnet 4.5<br/>Internal Specialist]
    A2A_Research --> ResearchAgent[Research Agent<br/>Claude Sonnet 4.5<br/>Web Search Specialist]

    A2A_Plan --> Planner[Planner Agent<br/>Claude Sonnet 4.5<br/>JSON Plan Creator]
    Planner -->|ExecutionPlan JSON| Executor[Executor<br/>Sequential + Early Termination]

    Executor -->|Step: kb_query| KnowledgeAgent
    Executor -->|Step: web_search| ResearchAgent
    Executor -->|Step: aggregate| Aggregator[Aggregator Agent<br/>Claude Sonnet 4.5<br/>Data Synthesizer]
    Executor -->|Step: compare| Aggregator

    A2A_Report --> ReportAgent[Report Agent<br/>Claude Haiku 4.5<br/>Intelligent Report Generator]
    ReportAgent -->|If data insufficient| ReportA2A_Knowledge[get_additional_knowledge_data<br/>A2A to Knowledge Agent]
    ReportAgent -->|If data insufficient| ReportA2A_Research[get_additional_research_data<br/>A2A to Research Agent]
    ReportA2A_Knowledge --> KnowledgeAgent
    ReportA2A_Research --> ResearchAgent

    KnowledgeAgent -->|MCP Tool| MCP_KB[Bedrock KB Tool<br/>get_knowledge<br/>Hybrid Search]
    ResearchAgent -->|MCP Tools| MCP_Search[DuckDuckGo Tools<br/>web_search<br/>news_search]
    ReportAgent -->|3-Stage Generation| MCP_PDF[HTML2PDF Tool<br/>Puppeteer<br/>scale 80%]

    MCP_KB -->|boto3| BedrockKB[Amazon Bedrock<br/>Knowledge Base]
    MCP_Search -->|API| DuckDuckGo[DuckDuckGo<br/>Web + News Search]
    MCP_PDF -->|subprocess| PDFEngine[Node.js Puppeteer<br/>HTML → PDF]

    BedrockKB --> BedrockRuntime[Amazon Bedrock Runtime<br/>Claude Sonnet 4.5<br/>Inference Profile]

    Supervisor -.->|Clarification| User
    ReportAgent -.->|Clarification if needed| User

    style Supervisor fill:#FF6B6B,stroke:#C92A2A,stroke-width:3px,color:#fff
    style Planner fill:#4ECDC4,stroke:#087F5B,stroke-width:2px,color:#fff
    style Executor fill:#4ECDC4,stroke:#087F5B,stroke-width:2px,color:#fff
    style KnowledgeAgent fill:#95E1D3,stroke:#0CA678,stroke-width:2px
    style ResearchAgent fill:#95E1D3,stroke:#0CA678,stroke-width:2px
    style Aggregator fill:#95E1D3,stroke:#0CA678,stroke-width:2px
    style ReportAgent fill:#95E1D3,stroke:#0CA678,stroke-width:2px
    style MCP_KB fill:#FFE66D,stroke:#F59F00,stroke-width:2px
    style MCP_Search fill:#FFE66D,stroke:#F59F00,stroke-width:2px
    style MCP_PDF fill:#FFE66D,stroke:#F59F00,stroke-width:2px
    style BedrockKB fill:#A8DADC,stroke:#1864AB,stroke-width:2px
    style BedrockRuntime fill:#A8DADC,stroke:#1864AB,stroke-width:2px
    style A2A_Knowledge fill:#FFB4A2,stroke:#E03131,stroke-width:2px
    style A2A_Research fill:#FFB4A2,stroke:#E03131,stroke-width:2px
    style A2A_Plan fill:#FFB4A2,stroke:#E03131,stroke-width:2px
    style A2A_Report fill:#FFB4A2,stroke:#E03131,stroke-width:2px
    style ReportA2A_Knowledge fill:#FFB4A2,stroke:#E03131,stroke-width:2px
    style ReportA2A_Research fill:#FFB4A2,stroke:#E03131,stroke-width:2px

传说:

  • 红:编排员(主管)
  • 鲑鱼:A2A通信层
  • 凫蓝:规划与执行
  • 绿色:专业代理
  • 黄色:MCP工具层
  • 蓝色:亚马逊基岩服务
  • 点状的:澄清循环

关键架构原则

  1. LLM驱动路由 -没有硬编码,主管根据上下文决定
  2. A2A通信 -代理通过@tool-wrappers调用代理
  3. MCP集成 -外部服务的标准化工具接口
  4. 任何阶段的澄清 -客服可以要求用户提供缺失的信息
  5. 效率 -重复使用以前的答案,避免冗余的数据收集
  6. 韧性 -三级生成可防止超时和回退机制

代理商规格

1.主管代理V2(编排器)

模型: global.anthropic.claude-sonnet-4-5-20250929-v1:0

角色:具有路由、澄清和委派功能的智能编排器。

能力:

  • 问题分类(问候语/简单/复杂/报告)
  • 澄清循环(最多3轮,宽松假设)
  • 通过3个A2A工具进行代理路由
  • 对话历史意识
  • 直接回答问候

A2A工具(3):

1. call_knowledge_agent(query) → Knowledge Agent → Bedrock KB
2. call_research_agent(query) → Research Agent → DuckDuckGo
3. create_and_execute_plan(query) → Planner + Executor
4. create_detailed_report(topic, previous_analysis) → Report Agent

路由逻辑(LLM决定):

  • 问候/闲聊→ 直接响应
  • 内部知识→ 呼叫_知识_代理
  • 外部信息→ 呼叫搜索代理
  • 多公司比较→ 创建和执行计划
  • "보고서" (报告)关键字→ create_detailed_report

实施: src/agents/supervisor_agent_v2.py

2.知识代理人(专家)

模型: global.anthropic.claude-sonnet-4-5-20250929-v1:0

角色:内部知识专家

数据源:

  • AWS基岩知识库(YOUR_KB_ID)
  • 企业可持续发展报告

MCP工具: get_knowledge(query, num_results=10)

答案风格(自适应):

  • 聊天模式:3-5句(简洁)
  • 报告模式:综合(当查询包含“상Ǯ하게”或“综合”时)

效率:

  • 每次查询调用知识库工具一次
  • 混合搜索(关键字+语义)

实施: src/agents/esg_agent.py

3.研究代理人(专家)

模型: global.anthropic.claude-sonnet-4-5-20250929-v1:0

角色:外部信息和竞争研究

MCP工具:

  • web_search(query, max_results=10) -一般网络搜索
  • news_search(query, max_results=10) -新闻文章

效率指南:

  • 每家公司最多搜索1-2次
  • 合并搜索词
  • 避免冗余查询

特殊功能:

def research_multiple_companies(
    companies: List[str],
    topic: str
) -> Dict[str, Any]:
    """Dynamic N-company research"""

实施: src/agents/research_agent.py

4.规划师代理

模型: global.anthropic.claude-sonnet-4-5-20250929-v1:0

角色:为复杂问题制定结构化的执行计划

输出:带Pydantic验证的JSON执行计划

自适应步长限制:

  • 简单:最多5步
  • 中等:最多10步
  • 复杂:最多15步

步骤类型:

class StepType(str, Enum):
    REASONING = "reasoning"
    WEB_SEARCH = "web_search"
    NEWS_SEARCH = "news_search"
    KB_QUERY = "kb_query"
    AGGREGATE = "aggregate"
    COMPARE = "compare"

实施: src/agents/planner_agent.py

5.执行人

类型:Python编排器(不是LLM代理)

角色:逐步执行计划

能力:

  • 具有依赖关系管理的顺序执行
  • 基于step_type的代理路由
  • 提前终止检测(聚合/比较后>800个字符)
  • 结果聚合

代理路由:

REASONING → Research Agent
WEB_SEARCH → Research Agent
NEWS_SEARCH → Research Agent
KB_QUERY → ESG Agent
AGGREGATE → Aggregator Agent
COMPARE → Aggregator Agent

实施: src/agents/executor_agent.py

6.聚合剂

模型: global.anthropic.claude-sonnet-4-5-20250929-v1:0

角色:数据综合和比较分析

能力:

  • 多源数据收集
  • 度量标准化
  • 比较分析
  • 简明摘要(4-6句)

工具:无(纯数据处理)

实施: src/agents/aggregator_agent.py

7.报告代理(智能)

模型: global.anthropic.claude-haiku-4-5-20251001-v1:0 (俳句代表速度)

角色:智能报告生成专家

主要特点:

  • 评估现有数据 -检查先前的分析是否充分
  • 收集额外数据 -如有需要,请致电ESG/研究代理
  • 要求澄清 -如果数据不可用,请用户输入
  • 三级发电 -防止超时

工具(3):

1. generate_detailed_report - HTML/PDF creation
2. get_additional_knowledge_data - Internal KB queries (A2A)
3. get_additional_research_data - External web search (A2A)

三阶段发电:

Stage 1: Executive Summary (200-300 tokens)
Stage 2: Detailed Analysis (1000-1500 tokens)
Stage 3: Conclusions (300-500 tokens)

# Each stage = separate API call = no timeout

决策逻辑:

IF previous_analysis sufficient:
    → Generate report (3 stages)

IF previous_analysis insufficient:
    → get_additional_knowledge_data / get_additional_research_data
    → Generate report

IF data unavailable from KB/Web:
    → Return "CLARIFICATION_NEEDED: [questions]"
    → User answers
    → Generate report

实施: src/agents/report_agent.py


代理到代理(A2A)通信

A2A图案

Strands代理商使用 代理作为工具 图案:

from strands import Agent, tool

# Specialized agents
knowledge_agent = Agent(
    model="claude-sonnet-4.5",
    tools=[get_knowledge],
    system_prompt="Internal knowledge specialist..."
)

# Wrap as tool for A2A
@tool
def call_knowledge_agent(query: str) -> str:
    """Call knowledge specialist."""
    response = knowledge_agent(query)  # ← A2A communication
    return str(response)

# Supervisor uses A2A tools
supervisor = Agent(
    model="claude-sonnet-4.5",
    tools=[call_knowledge_agent, call_research_agent, ...],
    system_prompt="Route questions..."
)

A2A通信流程

流程1:简单问题

User: "탄소배출량은?"
  ↓
Supervisor (LLM decides)
  ↓
call_knowledge_agent (A2A)
  ↓
Knowledge Agent
  ↓
MCP: get_knowledge (KB search)
  ↓
User: "543만 톤CO2e, 2030년까지 30% 감축 목표입니다."

(3-5 seconds, 2 tool calls)

流程2:复杂比较

User: "회사 A와 회사 B의 LTIR 비교"
  ↓
Supervisor (LLM decides)
  ↓
create_and_execute_plan (A2A)
  ↓
Planner → JSON Plan (8 steps)
  ↓
Executor:
  Step 1-2: call_research_agent (A2A) → Company B LTIR
  Step 3: call_knowledge_agent (A2A) → Company A LTIR
  Step 4: Aggregator (A2A) → 비교 분석
  ↓ (Early termination: >800 chars)
User: "Company A 0.15, Company B 0.18. Company A가 우수합니다."

(15-20 seconds, 8-10 tool calls, early termination)

流程3:报告生成

1. User: "지속가능성 공시 의무는?"
   → Supervisor → call_knowledge_agent → 답변

2. User: "보고서 만들어줘"
   → Supervisor (conversation history 전달)
   ↓
   create_detailed_report(
       topic="지속가능성 공시 의무",
       previous_analysis="이전 답변 전체"
   )
   ↓
   Report Agent (Haiku 4.5):
     • Evaluate: 이전 답변 충분한가?
     • Yes → generate_detailed_report (3 stages)
     • No → get_additional_knowledge_data → generate (3 stages)
   ↓
   Stage 1: Executive Summary (5s)
   Stage 2: Detailed Analysis (8s)
   Stage 3: Conclusions (5s)
   ↓
   HTML + PDF 생성
   ↓
   User: reports/report_지속가능성_공시_의무_20251122_140530.html/pdf

(15-20 seconds total, no timeout)

模型上下文协议(MCP)集成

MCP服务器1:基岩知识库

位置: src/tools/bedrock_kb_tool.py

工具: get_knowledge(query: str, num_results: int = 10)

配置:

  • KB ID: YOUR_KB_ID
  • 搜索类型:混合(关键字+语义)
  • 地区:美国西部-2
  • 配置文件:默认(或您的自定义AWS配置文件)

数据源:使用Claude Sonnet 4.5 OCR的PDF到Markdown转换器将企业可持续发展报告转换为Markdown

用途:

from src.tools import get_knowledge

result = get_knowledge(
    query="carbon emissions 2024",
    num_results=10
)

MCP服务器2:DuckDuckGo搜索

位置: src/tools/search_tools.py

工具:

  • web_search(query: str, max_results: int = 10)
  • news_search(query: str, max_results: int = 10)

配置:

  • 地区:kr-kr(韩国)
  • 自由层(无API密钥)
  • 速率限制:内置

用途:

from src.tools import web_search, news_search

web_result = web_search("sustainability report 2024")
news_result = news_search("sustainability regulations")

MCP服务器3:HTML2PDF

位置: mcp/html2pdf/ (Node.js TypeScript)

后端:木偶(无头铬合金)

整合:Python子进程→ Node.js脚本(.mjs)

配置:

  • 比例:80%
  • 格式:A4
  • 边距:15mm
  • 背景:印刷

由呼叫:报告生成流程(自动)


智能报表生成

报表代理功能

1.自适应数据收集

场景A:足够的数据

Previous answer has comprehensive data
  ↓
Report Agent: Evaluate → Sufficient
  ↓
Generate report immediately (3 stages)

场景B:数据不足

Previous answer is brief or incomplete
  ↓
Report Agent: Evaluate → Insufficient
  ↓
Identify missing data:
  - Internal data? → get_additional_knowledge_data
  - External information? → get_additional_research_data
  ↓
Generate report with complete data (3 stages)

场景C:需要澄清

Critical info cannot be obtained from KB or Web
  ↓
Report Agent: Return "CLARIFICATION_NEEDED:\n1. [question]"
  ↓
CLI: Ask user
  ↓
User answers → Report Agent re-called
  ↓
Generate report (3 stages)

2.三阶段生成(防止超时)

问题:长HTML的单个API调用(8000个令牌)→ 读超时

解决方案:分为3个单独的通话

# Stage 1: Executive Summary
prompt_1 = "Generate ONLY Executive Summary (2-3 paragraphs)"
section_1 = report_agent(prompt_1)  # ~300 tokens, 5s

# Stage 2: Detailed Analysis
prompt_2 = "Generate ONLY Detailed Analysis (with tables)"
section_2 = report_agent(prompt_2)  # ~1500 tokens, 8s

# Stage 3: Conclusions
prompt_3 = "Generate ONLY Conclusions and Recommendations"
section_3 = report_agent(prompt_3)  # ~500 tokens, 5s

# Combine
html_content = section_1 + section_2 + section_3

优点:

  • 无超时(每次通话<10s)
  • 更稳定(输出更小)
  • 结构更好(明确的部分)

3.Markdown回退

安全机构 如果报表代理输出Markdown而不是HTML:

def _is_markdown(content: str) -> bool:
    """Detect Markdown syntax (##, **, -, etc.)"""

if _is_markdown(content):
    html_content = markdown.markdown(
        content,
        extensions=['tables', 'fenced_code', 'nl2br']
    )

计划执行器模式

使用时

  • 复杂问题 需要多步骤推理
  • 多公司比较
  • 行业标杆
  • 无法通过单一客服电话回答的问题

执行流程

Complex Question
    ↓
Planner Agent (Sonnet 4.5)
    ↓ JSON ExecutionPlan
{
  "complexity": "medium",
  "steps": [
    {"step_id": 1, "step_type": "kb_query", "action": "..."},
    {"step_id": 2, "step_type": "web_search", "action": "..."},
    {"step_id": 3, "step_type": "aggregate", "dependencies": [1,2]}
  ]
}
    ↓
Executor (Sequential)
    ├─ Step 1: ESG Agent (A2A) → KB query
    ├─ Step 2: Research Agent (A2A) → Web search
    └─ Step 3: Aggregator Agent (A2A) → Compare
         ↓ Check early termination
         ✓ Output >800 chars, remaining are searches
         → STOP (save time & cost)
    ↓
Final Answer (Concise, 4-6 sentences)

Pydantic模型

from pydantic import BaseModel, Field
from typing import List
from enum import Enum

class StepType(str, Enum):
    REASONING = "reasoning"
    WEB_SEARCH = "web_search"
    NEWS_SEARCH = "news_search"
    KB_QUERY = "kb_query"
    AGGREGATE = "aggregate"
    COMPARE = "compare"

class ExecutionStep(BaseModel):
    step_id: int
    step_type: StepType
    description: str
    action: str
    dependencies: List[int] = []
    expected_output: str

class ExecutionPlan(BaseModel):
    question: str
    analysis: str
    steps: List[ExecutionStep] = Field(max_length=15)
    complexity: str  # "simple", "medium", "complex"
    expected_final_output: str

澄清循环

多层次澄清

可用网址:

  1. 主管级别 -Unclear questions(“主要建筑公司”=which companys?)
  2. 报告代理级别 -缺少报告的关键数据
  3. 任何代理人 -可以返回CLARIFICATION_NEEED

实施

代理商退货:

"CLARIFICATION_NEEDED:
1. 어떤 건설사들을 비교하고 싶으신가요?
2. 어떤 연도 데이터를 원하시나요?"

CLI句柄:

if response.startswith("CLARIFICATION_NEEDED:"):
    questions = parse_questions(response)
    for q in questions:
        answer = ask_user(q)
    enhanced_query = enhance_with_answers(original, answers)
    response = agent(enhanced_query)  # Retry with clarification

项目结构

agentic-multi-agent/
├── src/
│   ├── agents/                    # Strands Agents
│   │   ├── supervisor_agent_v2.py # Orchestrator (Sonnet 4.5)
│   │   ├── planner_agent.py       # Plan creator (Sonnet 4.5)
│   │   ├── executor_agent.py      # Plan executor
│   │   ├── esg_agent.py           # Knowledge specialist (Sonnet 4.5)
│   │   ├── research_agent.py      # Web search specialist (Sonnet 4.5)
│   │   ├── aggregator_agent.py    # Data synthesizer (Sonnet 4.5)
│   │   ├── report_agent.py        # Report generator (Haiku 4.5)
│   │   └── plan_models.py         # Pydantic schemas
│   │
│   ├── tools/                     # MCP Tools
│   │   ├── bedrock_kb_tool.py     # KB retrieval
│   │   ├── search_tools.py        # DuckDuckGo search
│   │   └── report_tools.py        # HTML/PDF generation
│   │
│   ├── config.py                  # AWS configuration
│   ├── bedrock_client.py          # Bedrock API wrapper
│   ├── pdf_to_markdown.py         # PDF → Markdown converter
│   ├── image_extractor.py         # PDF image extraction
│   └── chatbot_cli.py             # CLI interface
│
├── mcp/                           # MCP Servers
│   └── html2pdf/                  # Node.js Puppeteer
│       ├── src/
│       ├── dist/
│       └── package.json
│
├── tests/                         # Unit tests
│   ├── test_report_generation.py
│   └── test_supervisor_agent.py
│
├── reports/                       # Generated reports
├── output/                        # Markdown output
├── pdf/                           # Source PDFs
│
├── requirements.txt               # Python dependencies
└── README.md                      # This file

技术栈

核心框架

  • Strands代理SDK 1.18.0-使用A2A进行多代理编排
  • 亚马逊基石 -克劳德·十四行诗4.5与俳句4.5推理
  • 派丹蒂克 2.12.4-结构化数据验证
  • 富有的 14.2.0-增强的CLI界面

AWS服务

  • 基岩运行时间 -LLM推理(克劳德模型)
  • 基岩药剂运行时间 -知识库检索
  • 知识库 YOUR_KB_ID-企业可持续发展文件

MCP集成

  • 基岩KB -Python@工具装饰器
  • 鸭鸭搜 -带有duckduckgo搜索库的Python@工具装饰器
  • HTML2PDF -Node.js Puppeteer通过子进程

模型使用

代理 型号 原因
主管 Sonnet 4.5 复杂的路由决策
Planner Sonnet 4.5 JSON计划生成
知识代理 Sonnet 4.5 精确的KB解释
研究代理 Sonnet 4.5 Web数据合成
聚合器 Sonnet 4.5 比较分析
报告代理 俳句4.5 快速生成HTML,无超时

安装和设置

先决条件

  • Python 3.10+ (绞合线代理要求,推荐3.12)
  • Node.js 20+ (用于PDF转换)
  • AWS-CLI 配置了配置文件
  • 基岩通道 克劳德·十四行诗4.5和俳句4.5
  • 知识库 在亚马逊基岩中创建(更新配置中的YOUR_KB_ID)

安装步骤

# 1. Clone repository
git clone https://github.com/jesamkim/agentic-multi-agent.git
cd agentic-multi-agent

# 2. Create virtual environment
python3.12 -m venv venv
source venv/bin/activate

# 3. Install Python dependencies
pip install -r requirements.txt

# 4. Build HTML2PDF MCP server
cd mcp/html2pdf
npm install
npm run build
cd ../..

# 5. Configure AWS credentials
# For default profile:
aws configure
# Enter your AWS Access Key ID, Secret Access Key, and region

# For custom profile (optional):
aws configure --profile your-profile-name
# Then update AWS_PROFILE in src/config.py to match your profile name

# 6. Update configuration
# Edit src/config.py:
# - Set AWS_PROFILE (default or your custom profile)
# - Set AWS_REGION (must match your KB region)
# - Set KB_ID (your Bedrock Knowledge Base ID)

配置

src/config.py:

# AWS Configuration
AWS_PROFILE = "default"  # Change to your AWS CLI profile name if using custom profile
AWS_REGION = "us-west-2"  # Change to your KB region

# Bedrock Models
SUPERVISOR_MODEL = "global.anthropic.claude-sonnet-4-5-20250929-v1:0"
REPORT_MODEL = "global.anthropic.claude-haiku-4-5-20251001-v1:0"

# Knowledge Base
KB_ID = "YOUR_KB_ID"  # Replace with your Bedrock Knowledge Base ID

# Bedrock Configuration
MAX_TOKENS = 8192
TEMPERATURE = 0

运行聊天机器人

source venv/bin/activate
python src/chatbot_cli.py

CLI命令

  • 你的问题 -询问可持续发展主题
  • help -显示可用命令
  • history -查看对话历史记录
  • clear -清除对话历史记录
  • quit 或 exit -结束会话

主要特征说明

1.对话历史

CLI维护历史记录并传递给代理:

# Last 2 exchanges included as context
context = f"""
Previous Q: {q1}
Previous A: {a1}

Previous Q: {q2}
Previous A: {a2}

Current question: {q3}
"""

优点:

  • 报告生成重用以前的答案
  • 后续问题有背景
  • 无冗余数据收集

2.提前终止

当收集到足够的数据时,执行器停止:

if step.step_type in [StepType.AGGREGATE, StepType.COMPARE]:
    if len(output) > 800 and remaining_steps_are_searches:
        logger.info("Early termination: sufficient data")
        return result

储蓄:某些查询的时间减少30-50%

3.自适应复杂性

Planner根据复杂性调整步长限制:

复杂性 最大步数 示例
简单 5 单一公司,单一指标
中等 10 2-3家公司,多个指标
复杂 15 多公司,深入分析

4.效率优化

ESG代理人:

  • 调用知识库工具一次
  • 仅提取相关数据
  • 默认简洁(3-5句)

研究代理:

  • 每家公司最多搜索1-2次
  • 合并搜索词
  • 找到关键信息时停止

报告代理:

  • 重复使用以前的答案(首选)
  • 三阶段生成(防止超时)
  • 俳句4.5(比十四行诗快3倍)

测试

单元测试

# Run all tests
pytest tests/ -v

# Specific test suites
pytest tests/test_report_generation.py -v
pytest tests/test_supervisor_agent.py -v

测试覆盖范围:

  • Markdown检测和转换(5个测试)
  • HTML报告生成(2个测试)
  • 报告代理集成(3个测试)
  • 主管路由逻辑(6个测试)

当前状态:16/16项测试通过✓


技术细节

文档处理管道

PDF到Markdown的转换:

Enterprise PDF
    ↓
pdf2image (450 DPI PNG)
    ↓
Claude Sonnet 4.5 OCR (Vision API)
    ↓
Markdown with images
    ↓
Image Extraction (PyMuPDF)
    ↓
Bedrock Knowledge Base ingestion
    ↓
Hybrid Search (keyword + semantic)

知识库配置

{
  "knowledgeBaseId": "YOUR_KB_ID",
  "retrievalConfiguration": {
    "vectorSearchConfiguration": {
      "numberOfResults": 10,
      "overrideSearchType": "HYBRID"
    }
  }
}

代理配置

from strands import Agent

agent = Agent(
    model="global.anthropic.claude-sonnet-4-5-20250929-v1:0",
    tools=[tool1, tool2],
    system_prompt="Your role...",
    max_tokens=8192,
    temperature=0
)

故障排除

常见问题

1.报告生成超时

  • 已修复3级发电
  • 每个阶段<10s
  • Haiku 4.5防止超时

2.HTML报表中的Markdown语法

  • 自动检测和转换
  • 带表扩展的markdown库

3.PDF转换失败

  • ES模块兼容性(.mjs)
  • 检查Node.js版本(20+)
  • 在mcp/html2pdf中安装npm/

4.KB不返回任何结果

  • 检查AWS凭据
  • 验证您的知识库ID是否在src/config.py中正确设置
  • 检查区域是否与您的知识库位置匹配(默认值:us-west-2)

许可证

MIT许可证


作者

由AWS解决方案架构师作为演示构建,用于演示:

  • 代理多代理模式
  • 代理到代理(A2A)通信
  • 模型上下文协议(MCP)集成
  • Strands代理框架
  • AWS基岩克劳德模型
  • 生产就绪的人工智能系统

数据源:企业可持续发展报告(公开)


致谢

  • Strands代理SDK -多代理编排框架
  • 亚马逊基石 -克劳德十四行诗4.5和俳句4.5
  • Anthropic -克劳德模型
  • 模型上下文协议 -标准化工具界面
  • 供参考数据的公共可持续性报告