Google Agent Development Kit (ADK) 指南 第四章:Agent 开发与编排
Google Agent Development Kit (ADK) 指南 第四章Agent 开发与编排系列教程这是《Google ADK 指南》系列的第四章。前置知识已完成第三章掌握核心概念。目录Agent 开发基础高级 Agent 模式多 Agent 协作工作流编排性能优化1. Agent 开发基础1.1 Agent 配置详解fromgoogle.adkimportAgentfromgoogle.adk.modelsimportGeminifromgoogle.adk.memoryimportConversationBufferMemory agentAgent(# 基础配置 namecustomer_service_agent,description专业客户服务代理,version1.0.0,# 模型配置 modelGemini(model_namegemini-2.0-pro,temperature0.7,max_output_tokens2048,top_p0.95,top_k40),# 系统指令 instruction你是一个专业的客户服务代表服务于 ABC 公司。 # 能力 - 回答产品相关问题 - 处理订单查询 - 协助退换货流程 - 转接人工客服 # 约束 - 只根据知识库回答不编造信息 - 价格信息以官网为准 - 敏感信息订单号、邮箱需要验证 - 遇到投诉优先安抚情绪 # 语气 - 友好、专业、耐心 - 使用敬语您、请 - 适当使用 emoji 增加亲和力,# 工具配置 tools[product_search_tool,order_lookup_tool,refund_tool,human_handoff_tool],# 记忆配置 memoryConversationBufferMemory(max_turns20,max_tokens4000),# 安全配置 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 提示词工程系统提示词结构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} # 动态填充instructioninstruction.format(role_name客户服务代表,company_nameABC 公司,capabilities_list- 产品咨询\n- 订单处理\n- 售后服务,# ...)1.3 工具绑定fromgoogle.adkimportTool# 定义工具Tool(nameget_product_info)defget_product_info(product_id:str)-dict:获取产品信息return{name:产品 A,price:99.9}Tool(namecheck_order_status)defcheck_order_status(order_id:str)-dict:查询订单状态return{status:已发货,tracking:SF123456}# 方式 1构造函数绑定agentAgent(tools[get_product_info,check_order_status])# 方式 2动态添加agent.add_tool(new_tool)# 方式 3条件工具agent.add_tool(premium_tool,conditionlambdactx:ctx[user][is_premium])# 方式 4工具组fromgoogle.adk.toolsimportToolGroup tool_groupToolGroup([get_product_info,check_order_status])agent.add_tools(tool_group)2. 高级 Agent 模式2.1 ReAct 模式fromgoogle.adkimportAgentfromgoogle.adk.promptsimportReActPromptTemplate# ReAct (Reasoning Acting) 模式agentAgent(modelGemini(gemini-2.0-pro),tools[search_tool,calculator_tool],prompt_templateReActPromptTemplate(),instruction请按 ReAct 模式思考 Thought: 分析问题制定计划 Action: 选择并执行工具 Observation: 观察工具输出 Thought: 基于观察继续思考 ... Final Answer: 给出最终答案)# 执行过程会输出思考链responseagent.run(北京到上海的距离乘以 2 是多少)print(response.thought_process)# 查看思考过程2.2 Plan-and-Execute 模式fromgoogle.adkimportAgentfromgoogle.adk.plannersimportLLMPlanner# 规划器plannerLLMPlanner(modelGemini(gemini-2.0-pro),max_steps10)agentAgent(modelGemini(gemini-2.0-flash),# 执行用较小模型tools[search_tool,code_tool,file_tool],plannerplanner)# 执行复杂任务responseagent.run(分析最近 30 天的销售数据找出趋势并生成报告)# Agent 会自动# 1. 规划步骤# 2. 执行数据查询# 3. 分析趋势# 4. 生成报告2.3 Self-Reflection 模式fromgoogle.adkimportAgentfromgoogle.adk.evaluatorsimportSelfReflectionEvaluator# 自评估器reflectorSelfReflectionEvaluator(criteria[回答是否准确,是否基于事实,是否有遗漏],modelGemini(gemini-2.0-pro))agentAgent(modelGemini(gemini-2.0-flash),tools[search_tool],evaluatorreflector,enable_reflectionTrue# 启用自反思)# 执行流程# 1. 生成初始回答# 2. 评估回答质量# 3. 如质量低重新生成# 4. 输出最终回答2.4 Hierarchical Agentfromgoogle.adkimportAgent,HierarchicalAgent# 子 Agentresearch_agentAgent(nameresearcher,tools[search_tool])analysis_agentAgent(nameanalyst,tools[code_tool])writing_agentAgent(namewriter,tools[file_tool])# 主 Agent管理者managerHierarchicalAgent(namemanager,modelGemini(gemini-2.0-pro),sub_agents{research:research_agent,analysis:analysis_agent,writing:writing_agent},coordination_strategysequential# 或 parallel, dynamic)# 任务分解与分配responsemanager.run(研究 AI 发展趋势并写一份报告)# manager 会# 1. 分解任务# 2. 分配给子 Agent# 3. 汇总结果3. 多 Agent 协作3.1 路由模式fromgoogle.adkimportMultiAgentOrchestratorfromgoogle.adk.routingimportSemanticRouter,KeywordRouter,LLMRouter# 创建专业 Agentsales_agentAgent(namesales,instruction你是销售专家...)support_agentAgent(namesupport,instruction你是技术支持...)billing_agentAgent(namebilling,instruction你是账单专员...)# 方式 1语义路由orchestratorMultiAgentOrchestrator(agents{sales:sales_agent,support:support_agent,billing:billing_agent},routerSemanticRouter(modelGemini(gemini-2.0-flash),embedding_modeltext-embedding-004))# 方式 2关键词路由orchestratorMultiAgentOrchestrator(agents{sales:sales_agent,support:support_agent,billing:billing_agent},routerKeywordRouter(rules{sales:[购买,价格,优惠,折扣],support:[故障,错误,无法,问题],billing:[账单,付款,退款,发票]}))# 方式 3LLM 路由orchestratorMultiAgentOrchestrator(agents{sales:sales_agent,support:support_agent,billing:billing_agent},routerLLMRouter(modelGemini(gemini-2.0-flash),routing_prompt分析用户问题选择最合适的处理部门sales/support/billing))# 使用responseorchestrator.run(我想退款订单有问题)# 自动路由到 billing_agent3.2 协作模式fromgoogle.adkimportCollaborativeAgent# 创建协作组teamCollaborativeAgent(namecustomer_service_team,agents{greeter:Agent(instruction负责问候和初步分类),solver:Agent(instruction负责解决问题),validator:Agent(instruction负责验证答案准确性),closer:Agent(instruction负责结束对话和满意度调查)},workflowround_robin,# 或 chain, voting, consensusmax_turns10)# 执行协作responseteam.run(我想咨询产品并下单)# 流程greeter → solver → validator → closer3.3 投票与共识fromgoogle.adkimportEnsembleAgent# 创建多个专家 Agentexpert1Agent(instruction你是保守派分析师...)expert2Agent(instruction你是激进派分析师...)expert3Agent(instruction你是中立派分析师...)# 投票模式ensembleEnsembleAgent(agents[expert1,expert2,expert3],voting_strategymajority,# 多数投票aggregation_methodvote)# 共识模式ensembleEnsembleAgent(agents[expert1,expert2,expert3],voting_strategyconsensus,# 需要一致同意max_rounds3# 最多 3 轮讨论)responseensemble.run(预测下季度销售趋势)4. 工作流编排4.1 顺序工作流fromgoogle.adkimportSequentialWorkflow# 定义步骤workflowSequentialWorkflow(namecontent_creation_workflow,steps[Agent(nameresearcher,instruction研究主题...),Agent(nameoutliner,instruction创建大纲...),Agent(namewriter,instruction撰写内容...),Agent(nameeditor,instruction编辑校对...),Agent(nameformatter,instruction格式化输出...)],pass_contextTrue# 传递上下文)# 执行responseworkflow.run(写一篇关于 AI 的文章)4.2 条件工作流fromgoogle.adkimportConditionalWorkflow workflowConditionalWorkflow(namesupport_workflow,conditions[{name:vip_customer,condition:lambdactx:ctx.get(user,{}).get(is_vip),agent:vip_support_agent},{name:technical_issue,condition:lambdactx:故障inctx.get(input,),agent:tech_support_agent},{name:billing_issue,condition:lambdactx:账单inctx.get(input,),agent:billing_agent}],default_agentgeneral_support_agent)4.3 并行工作流fromgoogle.adkimportParallelWorkflow workflowParallelWorkflow(namemulti_perspective_analysis,agents[Agent(nameoptimist,instruction从乐观角度分析...),Agent(namepessimist,instruction从悲观角度分析...),Agent(namerealist,instruction从现实角度分析...)],merge_strategyconcatenate,# 或 summarize, votemerge_agentAgent(instruction汇总以上分析...))responseworkflow.run(分析这个投资机会)4.4 循环工作流fromgoogle.adkimportIterativeWorkflow workflowIterativeWorkflow(namerefinement_workflow,agentAgent(instruction改进内容质量...),max_iterations5,stop_conditionlambdactx:ctx.get(quality_score,0)0.9,feedback_agentAgent(instruction评估内容质量并给出改进建议...))responseworkflow.run(写一篇高质量文章)4.5 复杂工作流示例fromgoogle.adkimportComplexWorkflow# 电商客服工作流workflowComplexWorkflow(nameecommerce_support,# 阶段 1意图识别intent_phaseAgent(nameintent_classifier,instruction分类用户意图咨询/订单/售后/投诉),# 阶段 2路由routing_map{咨询:product_expert_agent,订单:order_specialist_agent,售后:service_agent,投诉:complaint_handler_agent},# 阶段 3处理processing_steps[Agent(nameinformation_gatherer,instruction收集必要信息...),Agent(namesolution_provider,instruction提供解决方案...)],# 阶段 4验证validation_agentAgent(namequality_checker,instruction验证解决方案是否完整准确),# 阶段 5结束closing_agentAgent(namecloser,instruction确认问题解决邀请评价))5. 性能优化5.1 缓存策略fromgoogle.adk.cachingimportResponseCache,ToolCache# 响应缓存agent.cacheResponseCache(backendredis,# 或 memory, gcsttl3600,# 1 小时key_generatorhash# 或 semantic)# 工具缓存Tool(cacheToolCache(ttl300))defget_product_info(product_id:str):# 5 分钟内相同查询直接返回缓存pass# 语义缓存相似问题返回相同答案agent.cacheResponseCache(backendvertex_ai,similarity_threshold0.95,# 95% 相似视为相同embedding_modeltext-embedding-004)5.2 批处理优化# 批量工具调用Tool(batch_enabledTrue,batch_size10)defbatch_get_product_info(product_ids:list[str])-list[dict]:# 一次查询多个产品returndb.query(SELECT * FROM products WHERE id IN ?,product_ids)# 批量 Agent 调用inputs[问题 1,问题 2,...,问题 100]responsesagent.batch_run(inputs,max_concurrent10,# 最多 10 个并发timeout60)# 流式批处理asyncforbatchinagent.batch_stream(large_dataset,batch_size20):process(batch)5.3 模型优化# 模型选择策略classAdaptiveModel:def__init__(self):self.fast_modelGemini(gemini-2.0-flash)self.smart_modelGemini(gemini-2.0-pro)defselect(self,query:str):# 简单问题用快模型复杂问题用聪明模型iflen(query)50and?notinquery:returnself.fast_modelreturnself.smart_model# 动态温度调整agent.generation_config{temperature:0.5,# 事实性问题用低温temperature:0.8# 创意性问题用高温}5.4 异步并发importasynciofromgoogle.adkimportAgentasyncdefconcurrent_execution():agentAgent(...)# 并发执行多个独立任务tasks[agent.run_async(任务 1),agent.run_async(任务 2),agent.run_async(任务 3)]resultsawaitasyncio.gather(*tasks,return_exceptionsTrue)returnresults# 工具并发调用Toolasyncdefparallel_tool_calls(query:str):resultsawaitasyncio.gather(search_async(query),calculate_async(query),analyze_async(query))returnresults动手练习创建一个带 ReAct 模式的 Agent实现多 Agent 路由系统设计一个顺序工作流添加缓存优化性能实现异步并发处理系列教程导航第一章ADK 简介与对比第二章环境搭建与快速开始第三章核心概念与架构第四章Agent 开发与编排 ← 本章第五章工具集成与自定义第六章记忆与状态管理第七章企业级功能与安全第八章实战案例与最佳实践