Google Agent Development Kit (ADK) 指南 第四章:Agent 开发与编排
系列教程:这是《Google ADK 指南》系列的第四章。
前置知识:已完成第三章,掌握核心概念。
目录
1. Agent 开发基础
1.1 Agent 配置详解
python
from google.adk import Agent
from google.adk.models import Gemini
from google.adk.memory import ConversationBufferMemory
agent = Agent(
# ========== 基础配置 ==========
name="customer_service_agent",
description="专业客户服务代理",
version="1.0.0",
# ========== 模型配置 ==========
model=Gemini(
model_name="gemini-2.0-pro",
temperature=0.7,
max_output_tokens=2048,
top_p=0.95,
top_k=40
),
# ========== 系统指令 ==========
instruction="""你是一个专业的客户服务代表,服务于 ABC 公司。
# 能力
- 回答产品相关问题
- 处理订单查询
- 协助退换货流程
- 转接人工客服
# 约束
- 只根据知识库回答,不编造信息
- 价格信息以官网为准
- 敏感信息(订单号、邮箱)需要验证
- 遇到投诉优先安抚情绪
# 语气
- 友好、专业、耐心
- 使用敬语(您、请)
- 适当使用 emoji 增加亲和力""",
# ========== 工具配置 ==========
tools=[
product_search_tool,
order_lookup_tool,
refund_tool,
human_handoff_tool
],
# ========== 记忆配置 ==========
memory=ConversationBufferMemory(
max_turns=20,
max_tokens=4000
),
# ========== 安全配置 ==========
safety_settings={
"HARM_CATEGORY_HARASSMENT": "BLOCK_MEDIUM_AND_ABOVE",
"HARM_CATEGORY_HATE_SPEECH": "BLOCK_MEDIUM_AND_ABOVE",
"HARM_CATEGORY_SEXUALLY_EXPLICIT": "BLOCK_MEDIUM_AND_ABOVE"
},
# ========== 评估配置 ==========
evaluators=[
relevance_evaluator,
faithfulness_evaluator
],
# ========== 日志配置 ==========
logging_config={
"level": "INFO",
"log_input": True,
"log_output": True,
"log_tool_calls": True
}
)
1.2 提示词工程
系统提示词结构:
python
instruction = """
# 角色定义
你是 {role_name},服务于 {company_name}。
# 核心能力
{capabilities_list}
# 工作流程
1. {step_1}
2. {step_2}
3. {step_3}
# 约束条件
- {constraint_1}
- {constraint_2}
- {constraint_3}
# 回复规范
- 语气:{tone}
- 长度:{length_limit}
- 格式:{format_requirement}
# 示例对话
用户:{example_user_input}
助手:{example_assistant_output}
"""
# 动态填充
instruction = instruction.format(
role_name="客户服务代表",
company_name="ABC 公司",
capabilities_list="- 产品咨询\n- 订单处理\n- 售后服务",
# ...
)
1.3 工具绑定
python
from google.adk import Tool
# 定义工具
@Tool(name="get_product_info")
def get_product_info(product_id: str) -> dict:
"""获取产品信息"""
return {"name": "产品 A", "price": 99.9}
@Tool(name="check_order_status")
def check_order_status(order_id: str) -> dict:
"""查询订单状态"""
return {"status": "已发货", "tracking": "SF123456"}
# 方式 1:构造函数绑定
agent = Agent(tools=[get_product_info, check_order_status])
# 方式 2:动态添加
agent.add_tool(new_tool)
# 方式 3:条件工具
agent.add_tool(premium_tool, condition=lambda ctx: ctx["user"]["is_premium"])
# 方式 4:工具组
from google.adk.tools import ToolGroup
tool_group = ToolGroup([get_product_info, check_order_status])
agent.add_tools(tool_group)
2. 高级 Agent 模式
2.1 ReAct 模式
python
from google.adk import Agent
from google.adk.prompts import ReActPromptTemplate
# ReAct (Reasoning + Acting) 模式
agent = Agent(
model=Gemini("gemini-2.0-pro"),
tools=[search_tool, calculator_tool],
prompt_template=ReActPromptTemplate(),
instruction="""请按 ReAct 模式思考:
Thought: 分析问题,制定计划
Action: 选择并执行工具
Observation: 观察工具输出
Thought: 基于观察继续思考
...
Final Answer: 给出最终答案"""
)
# 执行过程会输出思考链
response = agent.run("北京到上海的距离乘以 2 是多少?")
print(response.thought_process) # 查看思考过程
2.2 Plan-and-Execute 模式
python
from google.adk import Agent
from google.adk.planners import LLMPlanner
# 规划器
planner = LLMPlanner(
model=Gemini("gemini-2.0-pro"),
max_steps=10
)
agent = Agent(
model=Gemini("gemini-2.0-flash"), # 执行用较小模型
tools=[search_tool, code_tool, file_tool],
planner=planner
)
# 执行复杂任务
response = agent.run("分析最近 30 天的销售数据,找出趋势并生成报告")
# Agent 会自动:
# 1. 规划步骤
# 2. 执行数据查询
# 3. 分析趋势
# 4. 生成报告
2.3 Self-Reflection 模式
python
from google.adk import Agent
from google.adk.evaluators import SelfReflectionEvaluator
# 自评估器
reflector = SelfReflectionEvaluator(
criteria=[
"回答是否准确",
"是否基于事实",
"是否有遗漏"
],
model=Gemini("gemini-2.0-pro")
)
agent = Agent(
model=Gemini("gemini-2.0-flash"),
tools=[search_tool],
evaluator=reflector,
enable_reflection=True # 启用自反思
)
# 执行流程:
# 1. 生成初始回答
# 2. 评估回答质量
# 3. 如质量低,重新生成
# 4. 输出最终回答
2.4 Hierarchical Agent
python
from google.adk import Agent, HierarchicalAgent
# 子 Agent
research_agent = Agent(name="researcher", tools=[search_tool])
analysis_agent = Agent(name="analyst", tools=[code_tool])
writing_agent = Agent(name="writer", tools=[file_tool])
# 主 Agent(管理者)
manager = HierarchicalAgent(
name="manager",
model=Gemini("gemini-2.0-pro"),
sub_agents={
"research": research_agent,
"analysis": analysis_agent,
"writing": writing_agent
},
coordination_strategy="sequential" # 或 "parallel", "dynamic"
)
# 任务分解与分配
response = manager.run("研究 AI 发展趋势并写一份报告")
# manager 会:
# 1. 分解任务
# 2. 分配给子 Agent
# 3. 汇总结果
3. 多 Agent 协作
3.1 路由模式
python
from google.adk import MultiAgentOrchestrator
from google.adk.routing import SemanticRouter, KeywordRouter, LLMRouter
# 创建专业 Agent
sales_agent = Agent(name="sales", instruction="你是销售专家...")
support_agent = Agent(name="support", instruction="你是技术支持...")
billing_agent = Agent(name="billing", instruction="你是账单专员...")
# 方式 1:语义路由
orchestrator = MultiAgentOrchestrator(
agents={"sales": sales_agent, "support": support_agent, "billing": billing_agent},
router=SemanticRouter(
model=Gemini("gemini-2.0-flash"),
embedding_model="text-embedding-004"
)
)
# 方式 2:关键词路由
orchestrator = MultiAgentOrchestrator(
agents={"sales": sales_agent, "support": support_agent, "billing": billing_agent},
router=KeywordRouter(
rules={
"sales": ["购买", "价格", "优惠", "折扣"],
"support": ["故障", "错误", "无法", "问题"],
"billing": ["账单", "付款", "退款", "发票"]
}
)
)
# 方式 3:LLM 路由
orchestrator = MultiAgentOrchestrator(
agents={"sales": sales_agent, "support": support_agent, "billing": billing_agent},
router=LLMRouter(
model=Gemini("gemini-2.0-flash"),
routing_prompt="分析用户问题,选择最合适的处理部门:sales/support/billing"
)
)
# 使用
response = orchestrator.run("我想退款,订单有问题")
# 自动路由到 billing_agent
3.2 协作模式
python
from google.adk import CollaborativeAgent
# 创建协作组
team = CollaborativeAgent(
name="customer_service_team",
agents={
"greeter": Agent(instruction="负责问候和初步分类"),
"solver": Agent(instruction="负责解决问题"),
"validator": Agent(instruction="负责验证答案准确性"),
"closer": Agent(instruction="负责结束对话和满意度调查")
},
workflow="round_robin", # 或 "chain", "voting", "consensus"
max_turns=10
)
# 执行协作
response = team.run("我想咨询产品并下单")
# 流程:greeter → solver → validator → closer
3.3 投票与共识
python
from google.adk import EnsembleAgent
# 创建多个专家 Agent
expert1 = Agent(instruction="你是保守派分析师...")
expert2 = Agent(instruction="你是激进派分析师...")
expert3 = Agent(instruction="你是中立派分析师...")
# 投票模式
ensemble = EnsembleAgent(
agents=[expert1, expert2, expert3],
voting_strategy="majority", # 多数投票
aggregation_method="vote"
)
# 共识模式
ensemble = EnsembleAgent(
agents=[expert1, expert2, expert3],
voting_strategy="consensus", # 需要一致同意
max_rounds=3 # 最多 3 轮讨论
)
response = ensemble.run("预测下季度销售趋势")
4. 工作流编排
4.1 顺序工作流
python
from google.adk import SequentialWorkflow
# 定义步骤
workflow = SequentialWorkflow(
name="content_creation_workflow",
steps=[
Agent(name="researcher", instruction="研究主题..."),
Agent(name="outliner", instruction="创建大纲..."),
Agent(name="writer", instruction="撰写内容..."),
Agent(name="editor", instruction="编辑校对..."),
Agent(name="formatter", instruction="格式化输出...")
],
pass_context=True # 传递上下文
)
# 执行
response = workflow.run("写一篇关于 AI 的文章")
4.2 条件工作流
python
from google.adk import ConditionalWorkflow
workflow = ConditionalWorkflow(
name="support_workflow",
conditions=[
{
"name": "vip_customer",
"condition": lambda ctx: ctx.get("user", {}).get("is_vip"),
"agent": vip_support_agent
},
{
"name": "technical_issue",
"condition": lambda ctx: "故障" in ctx.get("input", ""),
"agent": tech_support_agent
},
{
"name": "billing_issue",
"condition": lambda ctx: "账单" in ctx.get("input", ""),
"agent": billing_agent
}
],
default_agent=general_support_agent
)
4.3 并行工作流
python
from google.adk import ParallelWorkflow
workflow = ParallelWorkflow(
name="multi_perspective_analysis",
agents=[
Agent(name="optimist", instruction="从乐观角度分析..."),
Agent(name="pessimist", instruction="从悲观角度分析..."),
Agent(name="realist", instruction="从现实角度分析...")
],
merge_strategy="concatenate", # 或 "summarize", "vote"
merge_agent=Agent(instruction="汇总以上分析...")
)
response = workflow.run("分析这个投资机会")
4.4 循环工作流
python
from google.adk import IterativeWorkflow
workflow = IterativeWorkflow(
name="refinement_workflow",
agent=Agent(instruction="改进内容质量..."),
max_iterations=5,
stop_condition=lambda ctx: ctx.get("quality_score", 0) >= 0.9,
feedback_agent=Agent(instruction="评估内容质量并给出改进建议...")
)
response = workflow.run("写一篇高质量文章")
4.5 复杂工作流示例
python
from google.adk import ComplexWorkflow
# 电商客服工作流
workflow = ComplexWorkflow(
name="ecommerce_support",
# 阶段 1:意图识别
intent_phase=Agent(
name="intent_classifier",
instruction="分类用户意图:咨询/订单/售后/投诉"
),
# 阶段 2:路由
routing_map={
"咨询": product_expert_agent,
"订单": order_specialist_agent,
"售后": service_agent,
"投诉": complaint_handler_agent
},
# 阶段 3:处理
processing_steps=[
Agent(name="information_gatherer", instruction="收集必要信息..."),
Agent(name="solution_provider", instruction="提供解决方案...")
],
# 阶段 4:验证
validation_agent=Agent(
name="quality_checker",
instruction="验证解决方案是否完整准确"
),
# 阶段 5:结束
closing_agent=Agent(
name="closer",
instruction="确认问题解决,邀请评价"
)
)
5. 性能优化
5.1 缓存策略
python
from google.adk.caching import ResponseCache, ToolCache
# 响应缓存
agent.cache = ResponseCache(
backend="redis", # 或 "memory", "gcs"
ttl=3600, # 1 小时
key_generator="hash" # 或 "semantic"
)
# 工具缓存
@Tool(cache=ToolCache(ttl=300))
def get_product_info(product_id: str):
# 5 分钟内相同查询直接返回缓存
pass
# 语义缓存(相似问题返回相同答案)
agent.cache = ResponseCache(
backend="vertex_ai",
similarity_threshold=0.95, # 95% 相似视为相同
embedding_model="text-embedding-004"
)
5.2 批处理优化
python
# 批量工具调用
@Tool(batch_enabled=True, batch_size=10)
def batch_get_product_info(product_ids: list[str]) -> list[dict]:
# 一次查询多个产品
return db.query("SELECT * FROM products WHERE id IN ?", product_ids)
# 批量 Agent 调用
inputs = ["问题 1", "问题 2", ..., "问题 100"]
responses = agent.batch_run(
inputs,
max_concurrent=10, # 最多 10 个并发
timeout=60
)
# 流式批处理
async for batch in agent.batch_stream(large_dataset, batch_size=20):
process(batch)
5.3 模型优化
python
# 模型选择策略
class AdaptiveModel:
def __init__(self):
self.fast_model = Gemini("gemini-2.0-flash")
self.smart_model = Gemini("gemini-2.0-pro")
def select(self, query: str):
# 简单问题用快模型,复杂问题用聪明模型
if len(query) < 50 and "?" not in query:
return self.fast_model
return self.smart_model
# 动态温度调整
agent.generation_config = {
"temperature": 0.5, # 事实性问题用低温
"temperature": 0.8 # 创意性问题用高温
}
5.4 异步并发
python
import asyncio
from google.adk import Agent
async def concurrent_execution():
agent = Agent(...)
# 并发执行多个独立任务
tasks = [
agent.run_async("任务 1"),
agent.run_async("任务 2"),
agent.run_async("任务 3")
]
results = await asyncio.gather(*tasks, return_exceptions=True)
return results
# 工具并发调用
@Tool
async def parallel_tool_calls(query: str):
results = await asyncio.gather(
search_async(query),
calculate_async(query),
analyze_async(query)
)
return results
动手练习
- 创建一个带 ReAct 模式的 Agent
- 实现多 Agent 路由系统
- 设计一个顺序工作流
- 添加缓存优化性能
- 实现异步并发处理
系列教程导航:
- 第一章:ADK 简介与对比
- 第二章:环境搭建与快速开始
- 第三章:核心概念与架构
- 第四章:Agent 开发与编排 ← 本章
- 第五章:工具集成与自定义
- 第六章:记忆与状态管理
- 第七章:企业级功能与安全
- 第八章:实战案例与最佳实践