ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

基于 adk-python 官方示例掌握 Interactions API:有状态对话链与工具调用实战指南

基于 adk-python 官方示例掌握 Interactions API:有状态对话链与工具调用实战指南 基于 adk-python 官方示例掌握 Interactions API有状态对话链与工具调用实战指南【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-python本文以 adk-python 仓库中的官方示例contributing/samples/models/interactions_api/为主体系统讲解 Google ADK 对 Interactions API 的集成方式如何用previous_interaction_id实现有状态的链式对话、如何在该模式下正确配置搜索与自定义函数工具以及 ADK 底层如何从会话事件中提取 interaction 链并压缩每轮请求内容。读完本文你可以独立运行该示例验证多轮状态保持并理解use_interactions_apiTrue在请求链路中的实际作用与限制条件。一、Interactions API 的核心概念Interactions API 为模型调用提供了**有状态对话stateful conversation**能力。与传统generate_content每次都要把完整会话历史随请求发送不同Interactions API 允许通过previous_interaction_id把多次交互链接起来每次响应会返回一个interaction_id下一轮请求只需携带上一次的interaction_id作为previous_interaction_id服务端即基于既有状态继续对话因此链式调用时只需发送当前轮current turn的内容无需重发全部历史对长对话场景尤其友好与标准 API 不同Interactions API不使用上下文缓存context caching因为其自身通过 interaction 链维护状态。示例 README.md 中对两种模式的差异归纳如下这里完整保留并补充说明维度Interactions APIuse_interactions_apiTrue标准 APIuse_interactions_apiFalse会话方式通过previous_interaction_id做有状态链式调用无状态的generate_content调用每轮发送内容链式调用时只发送当前轮内容每次都发送完整会话历史响应标识响应返回interaction_id供下一轮链接响应不含 interaction ID适用场景轮次较多的长对话通用场景上下文缓存不使用状态由 interaction 链维护可以使用二、示例工程的文件组织示例位于 contributing/samples/models/interactions_api/当前仓库中的实际文件结构如下interactions_api/ ├── __init__.py # 包初始化 ├── agent.py # 启用 Interactions API 的 Agent 定义 ├── main.py # 测试运行入口自动化测试 交互模式 ├── tests/ # 各测试用例的会话/期望内容 JSON │ ├── basic_text.json │ ├── google_search_france.json │ ├── google_search_1984.json │ ├── multi_turn.json │ └── custom_function_weather.json └── README.md # 本文的主体文档agent.py定义root_agent挂载 Gemini 模型use_interactions_apiTrue、Google Search 工具和一个模拟天气查询的自定义函数工具main.py测试运行器通过InMemoryRunner创建会话并依次执行自动化断言测试同时提供interactive手工调试模式tests/目录下的 JSON 文件如 multi_turn.json为各测试场景的对话内容与期望结果的示例数据。需要说明的是README 的 Code Structure 一节中还列出了test_interactions_curl.sh与test_interactions_direct.py两个文件从当前仓库的目录内容看这两个文件已不在示例中实际运行入口统一为main.py。三、Agent 配置开启 Interactions API 与工具兼容性处理3.1 基本配置README 给出的核心配置如下from google.adk.agents.llm_agent import Agent from google.adk.models.google_llm import Gemini from google.adk.tools.google_search_tool import GoogleSearchTool root_agent Agent( modelGemini( modelgemini-2.5-flash, use_interactions_apiTrue, # 启用 Interactions API ), nameinteractions_test_agent, tools[ GoogleSearchTool(bypass_multi_tools_limitTrue), # 转换为函数调用工具 get_current_weather, # 自定义函数工具 ], )use_interactions_api是Gemini模型类上的布尔字段默认为False。在 google_llm.py 的字段文档中明确写道启用后模型调用将走client.aio.interactions.create()而非传统的generate_contentAPI且响应格式会被转换为既有的LlmResponse结构以保持兼容——这意味着上层 Runner、Session、回调等 ADK 机制无需感知底层 API 的切换。从当前仓库 agent.py 的实际代码看示例已演进为使用gemini-3.1-flash-lite模型并直接以GoogleSearchTool()挂载工具兼容处理见下一节的源码说明README 中的配置保留了bypass_multi_tools_limitTrue这一关键参数的示范用法两者可互为参照。3.2 关键限制内置工具与自定义函数工具不能混用README 中特别强调了Tool Compatibility工具兼容性这一重要限制Interactions API不支持在同一 Agent 中混用自定义函数调用工具与内置工具如google_search。规避方式是使用bypass_multi_tools_limitTrue参数# 将 google_search 转换为函数调用工具从而可与自定义函数工具共存 GoogleSearchTool(bypass_multi_tools_limitTrue)该参数会触发GoogleSearchTool通过GoogleSearchAgentTool把内置google_search能力转换成一个普通的函数调用工具function calling tool从而与get_current_weather这类自定义函数工具在同一 Agent 下协同工作。这一参数在 google_search_tool.py 中定义对应的转换实现在 google_search_agent_tool.py 的GoogleSearchAgentTool类中。3.3 自定义函数工具模拟天气查询示例中的get_current_weather(city: str) - dict是一个 mock 实现见 agent.py内置了 New York、London、Tokyo、Paris、Sydney 五个城市的温度/天气/湿度数据未知城市返回默认值并附带note说明。测试断言正是围绕这些固定值编写的例如 Tokyo 断言68或Partly Cloudy这使得测试结果可复现、不依赖外部天气服务。此外agent.py与main.py的注释中记录了另一个实践结论代码执行器如UnsafeLocalCodeExecutor与函数调用模式不兼容——模型会尝试调用run_code之类的函数而不是按 code-executor 的预期在 markdown 中输出代码。因此示例未挂载代码执行工具。四、运行示例前置条件与命令4.1 前置条件按 README 的 Prerequisites 一节在 adk-python 根目录执行# 从 adk-python 根目录执行 uv sync --all-extras source .venv/bin/activate # 配置认证二选一 # 方式 1Google Cloud 凭据 export GOOGLE_CLOUD_PROJECTyour-project-id # 方式 2API Key export GOOGLE_API_KEYyour-api-key4.2 运行自动化测试cd contributing/samples # 使用 Interactions API 运行自动化测试 python -m interactions_api.mainmain.py通过 argparse 提供了两个运行参数见 main.py--mode test默认依次执行全部自动化断言测试任一断言失败即退出码为 1--mode interactive进入手工交互模式输入new创建新会话quit退出--debug将 ADK 日志级别提升到 DEBUG可观察完整的 Interactions API 请求/响应日志。4.3 SDK 可用性检查main.py在启动测试前会执行check_interactions_api_available()main.py构造google.genai.Client并检查client.aio上是否存在interactions属性。Interactions API 要求安装了支持该功能的 google-genai SDK 版本若当前 SDK 不具备该能力脚本会明确报错并终止而不是抛出难以理解的运行时异常。这是运行示例时最常见的门槛需要优先确认。五、测试覆盖范围与输出解读README 的 Features Tested 列出了 4 项能力main.py的实际测试函数扩展为 6 个TEST 1~6基础文本生成无工具发送 Hello! What can you help me with?断言响应非空Google Search 工具函数调用Search for the capital of France.断言响应包含 paris多轮有状态对话三轮对话——先告知 My favorite color is blue再询问伦敦天气触发get_current_weather最后询问 What is my favorite color...断言模型能回忆出 blue并打印id1 - id2 - id3的 interaction 链验证上下文保持Google Search 补充覆盖who wrote the novel 1984断言出现 orwell 或 george自定义函数工具Whats the weather like in Tokyo?断言出现 68/Partly Cloudy/Tokyo验证bypass_multi_tools_limit模式下函数工具可用PDF 摘要main.py新增README 未列入用 httpx 下载一份公开 PDF以types.Part.from_bytes(..., mime_typeapplication/pdf)作为附加内容部件传入验证多模态输入在 Interactions API 下可用。README 给出的典型输出片段如下节选其中[Interaction ID: v1_xxx]行正是链式对话的凭证 TEST 3: Multi-Turn Conversation (Stateful) User: Remember the number 42. Agent: Ill remember that number - 42. [Interaction ID: v1_ghi789...] User: What number did I ask you to remember? Agent: You asked me to remember the number 42. [Interaction ID: v1_jkl012...] PASSED: Multi-turn conversation works with context retention ALL TESTS PASSED (Interactions API)main.py的call_agent_async()main.py展示了在 ADK 中读取这些信息的标准姿势遍历runner.run_async()产生的Event流从event.interaction_id收集最新 interaction ID用event.get_function_calls()/event.get_function_responses()打印工具调用轨迹并按author ! user且非 partial 的事件聚合最终文本。六、底层实现ADK 如何驱动 Interactions API 链路以下结论均来自当前仓库源码用于印证 README 所述机制的落地细节。6.1 模型层的分支切换在 google_llm.py 的generate_content_async()中use_interactions_apiTrue时请求被转发给_generate_content_via_interactions()其内部调用 interactions_utils.py 的generate_content_via_interactions()否则走原有的generate_content/generate_content_stream路径。同时可以注意到一个与 README 表格Context caching can be used / not used对应的实现google_llm.py 中上下文缓存处理被条件if llm_request.cache_config and not self.use_interactions_api守卫——启用 Interactions API 时GeminiContextCacheManager完全不会参与与文档声明一致。6.2 previous_interaction_id 从哪来previous_interaction_id不需要用户手工维护。interactions_processor.py 中的InteractionsRequestProcessor是一个 LLM 请求处理器它先确认当前 Agent 的canonical_model是Gemini且use_interactions_api为真否则直接跳过然后通过_find_previous_interaction_state()从会话事件列表中逆序扫描跳过不属于当前 branch 的事件找到该 Agent 最近一条携带interaction_id的事件取出(interaction_id, environment_id)最终把找到的 ID 写入llm_request.previous_interaction_id。这解释了示例中多轮对话开箱即用的原因每一轮interaction_id已随Event落盘到会话历史下一轮处理器自动完成链接。6.3 每轮只发当前 turn 的实现generate_content_via_interactions()interactions_utils.py中当llm_request.previous_interaction_id存在时会调用_get_latest_user_contents()压缩内容从contents末尾向前收集连续的用户消息当前轮输入特殊处理若前一条 model turn 的部件带有thought_signature思维签名只把这些签名部件补回请求头部其余历史视为已由服务端previous_interaction_id状态承载其余全部历史不发送这正是 README 中 Only sends current turn contents when chaining interactions 的代码级落地。请求最终经_create_interactions()interactions_utils.py以model / input / system_instruction / tools / generation_config / previous_interaction_id组装 kwargs调用api_client.aio.interactions.create()流式模式下逐条消费 SSE 事件interaction.created、step.delta、interaction.completed等由convert_interaction_event_to_llm_response()归一化为 ADK 的LlmResponse并把interaction_id、environment_id透传到响应上供下一轮处理器链使用。6.4 参数透传的边界采样参数interactions_utils.py顶部interactions_utils.py定义了两类采样参数清单_UNDECLARED_SAMPLING_PARAMStemperature、top_p、top_k当前已安装的 google-genai 版本请求模型未声明这些字段序列化时会被静默丢弃——设置它们与不设置效果相同_UNSUPPORTED_SAMPLING_PARAMSpresence_penalty、frequency_penaltyInteractions API 本身会作为未知参数拒绝调用方必须停止设置。从源码结构看ADK 对这两类参数会做降级/告警处理每进程仅告警一次。实践含义在 Interactions API 模式下不要依赖 temperature/top_p 等采样参数实际生效这是与标准generate_content路径的显著行为差异。6.5 内容处理的协同在 contents.py 中内容处理器同样会依据canonical_model.use_interactions_api决定过滤策略——即InteractionsRequestProcessor负责提取链式 ID内容处理器负责保证只保留必要的最新用户消息两者按处理器链顺序协作这与interactions_processor.py模块 docstring 中content filtering is done by the content request processor after this processor runs的描述吻合。七、实践要点与限制清单结合 README 声明与源码印证使用该模式时应注意工具类型一致性自定义函数工具与内置工具如原生google_search不能在同一 Agent 混用确需搜索能力时优先用GoogleSearchTool(bypass_multi_tools_limitTrue)将其转为函数调用工具。上下文缓存不生效启用 Interactions API 后cache_config相关的上下文缓存逻辑被跳过长上下文成本由 interaction 链机制自身承担选型时需与标准 API 的成本模型区分开。SDK 版本依赖Interactions API 需要包含client.aio.interactions能力的 google-genai SDK示例脚本会先行探测并在不可用时给出明确报错自定义集成时建议做同样的能力探测。代码执行器不兼容如示例注释所述code_executor类工具在函数调用模式下行为异常二者不要同时挂载。采样参数受限presence_penalty/frequency_penalty会被 API 拒绝temperature/top_p/top_k在部分 SDK 版本中不生效。多模态输入可用示例 TEST 6 验证了 PDF 以 bytes Part 形式附加在用户消息中同样能走通 Interactions API 链路。八、延伸阅读围绕本主题仓库中可继续深入的入口示例本体README.md、agent.py、main.py模型层实现google_llm.pyuse_interactions_api字段与分支逻辑、interactions_utils.py类型转换、请求组装、流式事件归一化;请求处理链interactions_processor.pyinteraction 链 ID 提取工具层google_search_tool.py 与 google_search_agent_tool.pybypass_multi_tools_limit的转换机制。Interactions API 模式的价值在于把会话状态从客户端请求体转移到服务端的 interaction 链上ADK 通过请求处理器自动完成链式 ID 的提取与续接开发者只需在模型上打开use_interactions_api即可获得更轻量、可扩展的多轮对话同时保留 ADK 原有的工具、会话与事件体系。【免费下载链接】adk-pythonAn open-source, code-first Python toolkit for building, evaluating, and deploying sophisticated AI agents with flexibility and control.项目地址: https://gitcode.com/GitHub_Trending/ad/adk-python创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表