Chapter 9:企业实战案例与架构沉淀
9.1 企业级 Agent 系统设计
设计原则
┌─────────────────────────────────────────────────────────────┐
│ 企业级 Agent 系统六大原则 │
├─────────────────────────────────────────────────────────────┤
│ 1. 职责单一 → 每个 Agent 只负责一个领域 │
│ 2. 清晰边界 → Agent 间通过定义好的接口通信 │
│ 3. 可观测性 → 全链路日志、追踪、监控 │
│ 4. 韧性设计 → 错误处理、降级、熔断 │
│ 5. 安全性 → 权限控制、数据隔离 │
│ 6. 可扩展性 → 易于添加新 Agent 和能力 │
└─────────────────────────────────────────────────────────────┘
分层架构
┌─────────────────────────────────────────────────────────────┐
│ 展示层 (Presentation) │
│ Web UI / API / 钉钉/企微 / 移动端 │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 网关层 (Gateway) │
│ 鉴权 / 限流 / 路由 / 协议转换 │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 编排层 (Orchestration) │
│ Sequential / Parallel / Routing / Loop │
│ Graph 工作流引擎 │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ Agent 层 (Agents) │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ Search │ │ Order │ │Refund │ │ Technical│ │
│ │ Agent │ │ Agent │ │ Agent │ │ Support │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ 工具层 (Tools) │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ 数据库 │ │ 搜索 │ │ 外部 API │ │ 文件系统 │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ LLM 层 (LLM Providers) │
│ DashScope / OpenAI / Azure / 自部署 │
└─────────────────────────────────────────────────────────────┘
9.2 案例一:智能客服系统
业务需求
┌─────────────────────────────────────────────────────────────┐
│ 智能客服系统需求 │
├─────────────────────────────────────────────────────────────┤
│ • 7x24 小时自动客服 │
│ • 支持咨询、订单、售后、技术支持 │
│ • 多轮对话,记住上下文 │
│ • 情感识别,负面情绪自动升级 │
│ • 人工接管无缝衔接 │
│ • 完整对话记录用于质检和分析 │
└─────────────────────────────────────────────────────────────┘
架构设计
java
@Configuration
public class CustomerServiceArchitecture {
@Bean
public StateGraph customerServiceGraph(ChatModel chatModel) {
return StateGraph.builder()
.defineState(new CustomerServiceState())
// 节点定义
.addNode("entry", new EntryNode())
.addNode("intent_classify", createIntentClassifier(chatModel))
.addNode("consultation", createConsultationNode(chatModel))
.addNode("order", createOrderNode(chatModel))
.addNode("refund", createRefundNode(chatModel))
.addNode("technical", createTechnicalNode(chatModel))
.addNode("sentiment", createSentimentNode(chatModel))
.addNode("escalation", createEscalationNode())
.addNode("human_handover", createHumanHandoverNode())
.addNode("summary", createSummaryNode())
// 边定义
.addEdge("entry", "intent_classify")
.addConditionalEdge("intent_classify",
state -> state.getIntent(),
Map.of(
"consultation", "consultation",
"order", "order",
"refund", "refund",
"technical", "technical"
))
// ... 更多边
.setEntryPoint("entry")
.setFinishPoint("summary")
.compile();
}
}
核心流程
java
public class CustomerServiceFlow {
public AssistantMessage handle(String userId, String message) {
// 1. 获取上下文
ChatContext context = chatMemory.getContext(userId);
// 2. 意图分类
Intent intent = classifyIntent(message);
// 3. 更新上下文
context.addUserMessage(message);
context.setCurrentIntent(intent);
// 4. 路由到对应处理
AssistantMessage response = routeAndProcess(intent, message, context);
// 5. 情感分析
double sentiment = analyzeSentiment(message);
if (sentiment < 3.0 || context.getNegativeCount() > 2) {
// 触发升级
escalateToHuman(userId, context);
}
// 6. 保存上下文
context.addAssistantMessage(response.getText());
chatMemory.save(userId, context);
return response;
}
}
9.3 案例二:数据智能分析平台
业务需求
┌─────────────────────────────────────────────────────────────┐
│ 数据智能分析平台需求 │
├─────────────────────────────────────────────────────────────┤
│ • 自然语言查询数据库 │
│ • 自动生成 SQL 并执行 │
│ • 数据可视化建议 │
│ • 多维度分析 │
│ • 异常检测与告警 │
│ • 生成分析报告 │
└─────────────────────────────────────────────────────────────┘
架构设计
java
@Configuration
public class DataAnalysisArchitecture {
@Bean
public SequentialAgent dataAnalysisPipeline(ChatModel chatModel) {
// 子图:NL2SQL
StateGraph nl2sqlGraph = createNL2SQLGraph(chatModel);
// 子图:Python 分析
StateGraph pythonGraph = createPythonAnalysisGraph(chatModel);
return SequentialAgent.builder()
.name("data_analysis_pipeline")
.agents(
// 第一步:意图理解
ReactAgent.builder()
.name("intent_understanding")
.chatModel(chatModel)
.systemPrompt("""
理解用户的数据分析需求:
1. 要查询什么数据
2. 需要什么维度的分析
3. 期望的输出形式
""")
.build(),
// 第二步:SQL 生成与执行(子图)
nl2sqlGraph.asAgent(),
// 第三步:深度分析(子图)
pythonGraph.asAgent(),
// 第四步:报告生成
ReactAgent.builder()
.name("report_generation")
.chatModel(chatModel)
.systemPrompt("""
基于分析结果,生成专业的分析报告:
1. 执行摘要
2. 关键发现
3. 数据可视化建议
4. 行动建议
""")
.build()
)
.build();
}
}
关键组件
java
@Component
public class NL2SQLNode implements Node {
private final ChatModel chatModel;
private final JdbcTemplate jdbcTemplate;
@Override
public AnalysisState process(AnalysisState state) {
String nlQuestion = state.getUserQuestion();
String schema = getDatabaseSchema();
// 1. 生成 SQL
String sql = generateSQL(nlQuestion, schema);
state.setGeneratedSQL(sql);
// 2. 验证 SQL
if (!validateSQL(sql)) {
state.setError("SQL 验证失败");
return state;
}
// 3. 执行 SQL
try {
List<Map<String, Object>> results = jdbcTemplate.queryForList(sql);
state.setQueryResults(results);
state.setRowCount(results.size());
} catch (Exception e) {
state.setError("SQL 执行失败: " + e.getMessage());
}
return state;
}
}
9.4 A2A 协议集成
A2A 概述
Agent-to-Agent (A2A) 协议定义了 Agent 之间如何通信:
┌─────────────┐ ┌─────────────┐
│ Agent A │◄───── A2A Protocol ──►│ Agent B │
│ │ │ │
│ • 发现 │ │ • 能力注册 │
│ • 通信 │ │ • 任务处理 │
│ • 协作 │ │ • 结果返回 │
└─────────────┘ └─────────────┘
A2A 服务端实现
java
@Configuration
public class A2AServerConfig {
@Bean
public A2AServerAgent weatherAgent(ChatModel chatModel) {
return A2AServerAgent.builder()
.name("weather_agent")
.description("提供天气预报服务")
.capabilities(List.of(
Capability.builder()
.name("get_weather")
.description("获取指定城市的天气")
.inputSchema("""
{
"type": "object",
"properties": {
"city": {"type": "string"},
"date": {"type": "string"}
},
"required": ["city"]
}
""")
.build()
))
.agent(ReactAgent.builder()
.name("weather_processor")
.chatModel(chatModel)
.tools(List.of(weatherApiTool()))
.build())
.build();
}
}
A2A 客户端调用
java
@Service
@Slf4j
public class A2AClientService {
private final A2AClient a2aClient;
public String getWeather(String city) {
// 1. 发现 Agent
AgentCard agent = a2aClient.discoverAgent("weather_agent");
// 2. 构造任务
Task task = Task.builder()
.id(UUID.randomUUID().toString())
.agent(agent.getName())
.action("get_weather")
.input(Map.of("city", city))
.build();
// 3. 发送任务
TaskResult result = a2aClient.sendTask(task);
// 4. 处理结果
if (result.getStatus() == TaskStatus.SUCCESS) {
return result.getOutput().get("weather").toString();
} else {
log.error("Weather agent failed: {}", result.getError());
return "获取天气失败";
}
}
}
9.5 MCP 协议集成
MCP 概述
Model Context Protocol (MCP) 提供了标准化的工具调用能力:
┌─────────────┐ ┌─────────────┐
│ Client │◄───── MCP Protocol ──►│ Server │
│ (Agent) │ │ (Tools) │
│ │ │ │
│ • 调用工具 │ │ • 暴露工具 │
│ • 获取结果 │ │ • 参数验证 │
└─────────────┘ └─────────────┘
MCP 服务端实现
java
@Configuration
public class MCPServerConfig {
@Bean
public MCPServer springAI AlibabaMCPServer(
ChatModel chatModel,
DatabaseTool databaseTool,
SearchTool searchTool) {
return MCPServer.builder()
.name("spring-ai-alibaba-tools")
.version("1.0.0")
.description("Spring AI Alibaba 工具集")
.tools(List.of(
MCP_tool.builder()
.name("database_query")
.description("执行数据库查询")
.inputSchema(databaseQuerySchema())
.handler(databaseTool::query)
.build(),
MCP_tool.builder()
.name("web_search")
.description("网络搜索")
.inputSchema(webSearchSchema())
.handler(searchTool::search)
.build()
))
.build();
}
}
MCP 客户端调用
java
@Service
public class MCPClientService {
private final MCPClient mcpClient;
public List<Document> search(String query) {
ToolResult result = mcpClient.callTool("web_search",
Map.of("query", query)
);
if (result.isSuccess()) {
return result.getDocuments();
} else {
throw new RuntimeException("Search failed: " + result.getError());
}
}
}
9.6 企业级架构设计模板
模板一:基础 Agent 服务模板
yaml
Agent Service Template:
name: {service_name}
type: single_agent
llm:
provider: dashscope
model: qwen-plus
temperature: 0.7
max_tokens: 2000
tools:
- name: search
enabled: true
config:
max_results: 10
- name: database
enabled: true
config:
max_rows: 100
memory:
type: buffered
max_messages: 20
error_handling:
timeout_seconds: 30
max_retries: 3
fallback_response: "抱歉,暂时无法处理您的请求"
observability:
logging: true
tracing: true
metrics: true
模板二:多 Agent 协作模板
yaml
Multi-Agent Template:
name: {workflow_name}
type: multi_agent
orchestration:
type: {sequential|parallel|routing|loop|graph}
agents:
- name: agent_1
type: react
tools: [...]
prompt: ...
- name: agent_2
type: react
tools: [...]
prompt: ...
routing:
classifier:
type: llm
prompt: ...
rules:
- intent: {intent_name}
agent: agent_1
keywords: [...]
state:
persistence: true
store_type: redis
ttl_hours: 24
error_handling:
global_fallback: true
agent_fallbacks:
agent_1: fallback_agent_1
agent_2: fallback_agent_2
observability:
log_level: INFO
trace_sampling: 0.1
metrics_interval: 60
9.7 企业级配置清单
完整配置示例
yaml
# application-agent.yml
spring:
ai:
.alibaba:
agent:
# Agent 配置
agents:
customer-service:
name: customer_service
type: routing
llm:
provider: dashscope
model: qwen-max
temperature: 0.8
max_tokens: 3000
timeout: 60s
retry:
max_attempts: 3
backoff: exponential
initial_interval: 1s
multiplier: 2.0
circuit_breaker:
enabled: true
failure_rate: 0.5
slow_call_rate: 0.8
wait_duration: 60s
# 工具配置
tools:
database:
enabled: true
pool_size: 10
timeout: 30s
search:
enabled: true
max_results: 20
external_api:
enabled: true
timeout: 10s
# 内存配置
memory:
type: buffered
max_messages: 50
max_tokens: 8000
# 可观测性
observability:
logging:
level: INFO
format: json
tracing:
enabled: true
sampler: always_on
metrics:
enabled: true
export_interval: 60
# 安全配置
security:
rate_limit:
enabled: true
requests_per_minute: 60
input_validation:
max_length: 10000
allowed_patterns: [...]
output_filter:
sensitive_patterns: [...]
9.8 知识资产沉淀
术语表
json
{
"terminology": [
{
"term": "SequentialAgent",
"definition": "顺序执行模式,多个 Agent 按定义顺序依次执行",
"example": "Research → Analysis → Summary"
},
{
"term": "ParallelAgent",
"definition": "并行执行模式,多个 Agent 同时执行后聚合结果",
"example": "[A, B, C] 并行 → 聚合"
},
{
"term": "RoutingAgent",
"definition": "路由模式,根据输入分类选择对应 Agent 处理",
"example": "输入 → 分类 → 专用 Agent"
},
{
"term": "LoopAgent",
"definition": "循环模式,Agent 反复执行直到满足终止条件",
"example": "执行 → 评估 → 继续/终止"
},
{
"term": "StateGraph",
"definition": "状态图,Graph API 的核心组件,用于定义复杂工作流",
"example": "自定义节点、边、状态的图结构"
},
{
"term": "A2A",
"definition": "Agent to Agent,Agent 间通信协议",
"example": "跨服务的 Agent 协作"
},
{
"term": "MCP",
"definition": "Model Context Protocol,标准化工具调用协议",
"example": "Agent 调用外部工具"
}
]
}
架构沉淀
markdown
## 架构模式沉淀
### 1. Agent 专业化分工
- 单一职责
- 清晰的输入输出定义
- 通过接口通信
### 2. 分层编排
- 编排层负责路由和协调
- Agent 层负责具体执行
- 工具层负责能力扩展
### 3. 状态管理
- 短期状态:内存
- 长期状态:持久化存储
- 敏感状态:加密
### 4. 错误处理
- 分层错误处理
- 降级策略
- 告警机制
### 5. 可观测性
- 结构化日志
- 全链路追踪
- 指标监控
9.9 本章小结
| 内容 | 说明 |
|---|---|
| 企业级设计原则 | 职责单一、清晰边界、可观测性、韧性、安全、可扩展 |
| 分层架构 | 展示层 → 网关层 → 编排层 → Agent 层 → 工具层 → LLM 层 |
| 案例一 | 智能客服系统(Routing + 情感识别 + 升级机制) |
| 案例二 | 数据分析平台(NL2SQL + Python 分析 + 报告生成) |
| A2A 协议 | Agent 间通信协议,支持服务发现和任务协作 |
| MCP 协议 | 标准化工具调用协议 |
| 设计模板 | 基础 Agent 模板、多 Agent 协作模板 |
| 配置清单 | 完整的生产环境配置示例 |
| 知识沉淀 | 术语表、架构模式沉淀 |
下章预告
Chapter 10 将进行 总结与扩展路径,包括:
- 技术全景图
- 学习路径
- 深入方向建议