Google GenAI SDK `Tool` 类型全解:12 类工具 JSON 结构与 Phoenix 落地实践
可观测性AI 评测LLMOpsAI 应用人工智能【免费下载链接】phoenixAI Observability Evaluation项目地址https://gitcode.com/gh_mirrors/phoenix13/phoenix点击查看免费下载本文以google-genaiPython SDK 中Tool及其嵌套工具类型的 JSON/dict 形状为骨架逐一拆解function_declarations、google_search、google_maps、url_context、file_search、code_execution、computer_use、mcp_servers等全部顶层键的实用负载结构并结合本仓库 Phoenix 的 playground 客户端转换逻辑与集成测试说明这些工具定义如何在 AI Observability 平台中被规范化、保真回放与执行。读完本文你将能按 Gemini API / Vertex AI 双面区分正确构造GenerateContentConfig.tools并理解 Phoenix 中函数工具可移植与原始工具供应商专属透传的双模型设计。背景一个Tool对象承载多种可选能力与 OpenAI 的ToolParam或 Anthropic 的ToolUnionParam不同Google GenAI SDK 中tools列表的每个元素都是一个Tool对象其内部包含大量可选键——你只需启用当前场景所需的能力例如只填function_declarations或只填google_search。这些工具定义会喂给GenerateContentConfig.tools/tools参数models.generate_content及其相关 API在客户端归一化之后随请求发出。两个关键的类型事实见 google-genai-tools-illustration.md模型与字典一致请求负载与Tool/ToolDict对齐即 Pydantic 模型与 TypedDict 共享同一组键。ToolListUniontools列表的每个元素可以是一个Tool、一个callable会被包装为函数声明或在 MCP 扩展可导入时使用 MCP 客户端类型。Gemini API 与 Vertex AI 的字段差异SDK 的字段 docstring 会对每个字段标注支持面例如not supported in Gemini API或not supported in Vertex AI。这是最快的兼容性过滤手段——若某个键标注不支持 Gemini API就不要把依赖它的功能规划为可移植特性。多个键在同一个Tool中组合在 JSON 语法上合法但在特定面surface上运行时可能失败。注意SDK 类型定义随版本演进行号会移动升级google-genai后应以你本地安装的google/genai/types.py为准重新核对字段。Tool顶层键速查表键嵌套类型PythonSDK 说明缩写function_declarationslist[FunctionDeclaration]客户端执行的函数google_searchGoogleSearch模型内 Google 搜索google_mapsGoogleMapsMaps 接地groundingurl_contextUrlContextURL 上下文检索file_searchFileSearch语义文件搜索存储SDK不支持 Vertex AIcode_executionToolCodeExecution模型代码执行SDK不支持 Gemini APIenterprise_web_searchEnterpriseWebSearchVertex AI Search / Sec4SDK不支持 Gemini APIretrievalRetrieval外部 / Vertex 检索SDK不支持 Gemini APIgoogle_search_retrievalGoogleSearchRetrieval通过 Google 搜索接地parallel_ai_searchToolParallelAiSearchParallel.aiSDK不支持 Gemini APIcomputer_useComputerUse计算机使用 自动函数声明mcp_serverslist[McpServer]基于 HTTP 的 MCPSDK不支持 Vertex AI1.function_declarations— 用户定义函数FunctionDeclaration是 OpenAPI 风格的函数声明。其中parametersSDKSchema与parameters_json_schema互斥同理response与response_json_schema互斥。使用 SDK 风格Schema字典的示例type取值为OBJECT、STRING、INTEGER等枚举风格大写值{ function_declarations: [ { name: get_weather, description: Get the current weather for a location., parameters: { type: OBJECT, properties: { city: { type: STRING, description: City name }, unit: { type: STRING, enum: [celsius, fahrenheit] } }, required: [city] } } ] }使用单对象JSON Schema参数的替代写法与parameters互斥{ function_declarations: [ { name: register_user, description: Register a user., parameters_json_schema: { type: object, properties: { name: { type: string }, age: { type: integer } }, additionalProperties: false, required: [name, age], propertyOrdering: [name, age] } } ] }可选字段response/response_json_schema声明输出 schemabehaviorBidi 场景按 SDK docstring 可能仅 Vertex 支持。实践要点parameters枚举风格Schema与parameters_json_schema二选一二者 API 无法合并输出 schemaresponse*用于让下游解析器直接获得类型化工具输出无需第二次模型调用。Phoenix 侧印证在 playground_clients.py 的_google_prepare_generate_content中Phoenix 把规范化函数工具转换为types.FunctionDeclaration且优先使用parameters_json_schema传递参数 JSON Schema与本文上述第二种写法完全一致转换后的声明被聚合进单个types.Tool(function_declarations...)追加到工具列表。2.google_search— 模型内 Google 搜索启用搜索能力省略search_types时默认走网页搜索。嵌套的web_search/image_search是空标记对象模型定义中为pass。{ google_search: { search_types: { web_search: {}, image_search: {} } } }默认写法隐含网页搜索{ google_search: {} }可选嵌套字段并非所有面都支持每个字段需以 SDK docstring 与 Google 官方文档为准blocking_confidence、exclude_domains、time_range_filterstart_time/end_timeISO 时间格式。实践要点响应会携带groundingMetadata查询词、网页片段、引用 span应在 UX 中呈现以增强可信度与可调试性。image_search会切换多模态搜索的成本与延迟仅需网页搜索默认行为时省略search_types即可。Phoenix 侧印证集成测试 test_prompts.py 中的google-genai-built-in-tool用例以genai_types.Tool(google_searchgenai_types.GoogleSearch())构造负载验证了这种空标记启用形状在 prompt 版本 round-trip 中完整保真。3.google_maps— Maps 接地{ google_maps: { enable_widget: true } }可选auth_config按 SDK docstringGemini API 不支持。实践要点Maps 接地最适合查询中含位置信息的任务营业时间、导航、附近enable_widget用于支持交互式地图 UI 的产品。Gemini API 无auth_config时可假定只能访问公开地图数据。4.url_context— URL 上下文检索空负载出现即启用{ url_context: {} }实践要点检查响应的url_context_metadata可确认实际检索了哪些 URL以及命中缓存还是实时抓取。与google_search搭配效果佳模型先发现链接再对其中少数做深度读取。5.file_search— 托管 RAG / 文件搜索存储{ file_search: { file_search_store_names: [ fileSearchStores/my-file-search-store-123 ], top_k: 8, metadata_filter: optional-filter-expression } }实践要点File Search 是托管式 RAG——把分块/嵌入的管道复杂度换成存储与导入的配置成本。metadata_filter用于实现租户或文档类型粒度的范围隔离无需为每个客户单独建存储。6.code_execution— 模型代码执行类型定义中为空对象{ code_execution: {} }按 SDK docstringGemini API 不支持。实践要点该字段面向Vertex / AI Studio类面。若你的应用走消费级 Gemini API应省略code_execution或在运行时探测能力——发送该字段可能导致请求报错。7.enterprise_web_search— 企业级网页搜索{ enterprise_web_search: { exclude_domains: [example.com], blocking_confidence: BLOCK_HIGH_AND_ABOVE } }按 SDK docstringGemini API 不支持。blocking_confidence在 SDK 中使用PhishBlockThreshold。实践要点这是 Vertex 上的企业 / Sec4 网页搜索路径合规与计费模式均不同于消费级 Gemini。exclude_domains是对已知恶意或品牌外域名做滥用控制的简单杠杆。8.retrieval— Vertex 检索三分支定义 Vertex 风格检索需从vertex_ai_search、vertex_rag_store、external_api中选择其一每种在types.py中都有各自嵌套形状。最小占位写法{ retrieval: { vertex_ai_search: {} } }按 SDK docstringGemini API 不支持。实践要点vertex_ai_search、vertex_rag_store、external_api是三种不同架构——只选一个分支并按该路径建模鉴权与延迟预期不要三个全填指望 API 合并。9.google_search_retrieval— 动态检索接地{ google_search_retrieval: { dynamic_retrieval_config: { mode: MODE_DYNAMIC, dynamic_threshold: 0.3 } } }mode在 SDK 中为DynamicRetrievalConfigMode。实践要点动态检索即按需搜索——若模型对琐碎问题过度接地调高dynamic_threshold若模型在需要新鲜度的事实性查询上跳过搜索则调低该阈值。10.parallel_ai_search— Parallel.ai 搜索{ parallel_ai_search: { api_key: optional-parallel-ai-key, custom_configs: { source_policy: { include_domains: [google.com, wikipedia.org], exclude_domains: [example.com] }, fetch_policy: { max_age_seconds: 3600 } } } }按 SDK docstringGemini API 不支持。实践要点需要Parallel.ai凭据与 Vertex 启用应视为可选的企业集成而非google_search的默认替代。fetch_policy.max_age_seconds在新鲜度与缓存命中率之间权衡。11.computer_use— 计算机使用environment使用Environment枚举例如ENVIRONMENT_BROWSER。{ computer_use: { environment: ENVIRONMENT_BROWSER, excluded_predefined_functions: [some_predefined_action] } }实践要点启用computer_use会同时注入预定义的 UI 操作函数声明——你的客户端必须实现真正的自动化循环截图 → 模型 → 动作。excluded_predefined_functions可从声明面中移除高风险动作例如支付类。12.mcp_servers— 基于 HTTP Streamable 的 MCP按 SDK docstringVertex AI 不支持。{ mcp_servers: [ { name: my-mcp-server, streamable_http_transport: { url: https://api.example.com/mcp, headers: { Authorization: Bearer token }, timeout: 30s, sse_read_timeout: 60s, terminate_on_close: true } } ] }实践要点Gemini API 上的 MCP 使用HTTP streamable传输——你的服务端必须可靠实现 MCP 协议超时过短会表现为模型侧工具调用停滞。由于 Vertex AI 在上述 SDK 类型中不支持该键若同时面向 Gemini API 与 Vertex必须对Tool负载做分支。附录 AToolType— 服务端工具调用判别枚举枚举ToolType映射服务端工具种类例如GOOGLE_SEARCH_WEB/GOOGLE_SEARCH_IMAGE→Tool.google_searchURL_CONTEXT→Tool.url_contextGOOGLE_MAPS→Tool.google_mapsFILE_SEARCH→Tool.file_search它用于ToolCall/ToolResponse响应的工具调用判别而非请求端Tool定义本身。实践要点排查调错工具时对比请求Tool键与响应ToolType——服务端执行的工具会以专用枚举值出现而不是你的function_declarations名称。附录 BToolConfig— 请求级共享配置ToolConfig/ToolConfigDict的完整形状{ function_calling_config: { mode: AUTO, allowed_function_names: [get_weather], stream_function_call_arguments: false }, retrieval_config: { lat_lng: { latitude: 37.7749, longitude: -122.4194 }, language_code: en-US }, include_server_side_tool_invocations: true }mode为FunctionCallingConfigMode按 SDK docstring部分嵌套字段仅 Vertex 支持。实践要点function_calling_config作用于请求中的全部工具——allowed_function_names是 demo 与生产 canary 的廉价安全护栏include_server_side_tool_invocations让你能在响应Content中记录Google 托管的工具步骤用于审计。工具选择配置ToolConfig/function_calling_config在 Gemini API 中函数式工具的选择策略位于tool_configREST/ToolConfigSDK重点是function_calling_config。它与tools列表互补tools描述声明function_calling_config.mode及相关字段决定该请求中模型是否可以省略调用、必须调用或遵循其他调用规则。FunctionCallingConfigMode枚举包含AUTO、ANY、NONE、VALIDATED等取值。实践要点模式对整个请求是全局的——若需按工具差异化行为请拆分为多次generate_content调用或收窄allowed_function_names。托管工具google_search、url_context等仍会以工具调用形式出现在响应中将include_server_side_tool_invocations与你的可观测性方案配合使用。Phoenix 侧印证在 google.py 中Phoenix 将规范化的工具选择映射为 Google 的ToolConfignone → {mode: none}、zero_or_more → {mode: auto}、one_or_more → {mode: any}、specific_function → {mode: any, allowed_function_names: [name]}反向解析时会把 mode 归一化为小写Google API 大小写不敏感且当前仅支持单个allowed_function_names只能配合any模式使用。Phoenix 中的落地从双模型工具存储到 Google 负载本文档所述的工具形状在本仓库 Phoenix 中有直接落地可作深入参考双模型函数工具 vs 原始工具internal_docs/specs/vendor-specific-tools.md 定义了 Phoenix 的工具数据模型单个有序列表中混排两类变体——函数工具归一化、跨供应商可移植的name/description/parameters/strict与原始工具供应商专属 JSON 透传值。其核心原则与本文一致Phoenix 不试图理解每个供应商的 schema无法无损归一化的工具定义以原始 JSON 保真存储与回放。原始工具不可移植切换供应商或供应商 API 类型如 OpenAI Responses → Chat Completions时会被丢弃而函数工具保留。原始工具可能含供应商配置但不应作为凭据存储使用。运行时转换_google_prepare_generate_content在 playground_clients.py 的_google_prepare_generate_content中可以看到完整的转换路径原始工具types.Tool.model_validate(tool.raw)直接透传——正是原始工具不转换、原样发送的规范实现。函数工具提取name、description、parameters以parameters_json_schema构造types.FunctionDeclaration再聚合为一个types.Tool(function_declarations...)。关键约束源码注释明确function_calling_config仅当存在function_declarations时才设置——Google 会拒绝将其用于google_search等内置工具。这与本文function_calling_config作用于函数式工具的说明互相印证。工具选择映射与 google.py 完全一致none→NONE、zero_or_more→AUTO、one_or_more→ANY、specific_function→ANY allowed_function_names。转换完成后每个FunctionDeclaration会以llm.tools.idx.tool.json_schema属性写入 OpenInference span见同一函数 playground_clients.py使工具定义对可观测性链路可见。集成测试验证tests/integration/client/test_prompts.py 提供了一组 round-trip 参数化用例直接对应本文形状google-genai-tools-and-configFunctionDeclaration(nameget_weather, parameters_json_schema{...})ToolConfig(function_calling_configFunctionCallingConfig(modeANY))response_mime_typeapplication/jsonresponse_json_schema。google-genai-tool-choice-nonemodeNONE的不要调用任何工具场景。google-genai-built-in-toolTool(google_searchGoogleSearch())内置工具保真。测试通过PromptVersion.from_google_genai导入再经 GraphQL / client API round-trip并用DeepDiff断言负载完全一致验证了上述所有工具形状在 Phoenix prompt 版本中的无损往返。小结一个Tool对象、多个可选键——只组合你的 API 面支持的键。用户定义工具→function_declarationsFunctionDeclarationSchema或parameters_json_schema。内置工具→google_search、google_maps、url_context、file_search、code_execution等如上文逐一所述。服务端判别→ 响应中的ToolType枚举请求级策略→ToolConfig.function_calling_config全局模式 allowed_function_names白名单。兼容性真相源→ 安装包内的google/genai/types.pydocstring 标注 Gemini API / Vertex AI 支持面版本升级后需重新核对行号与字段。推荐实践当需要不同缓存或计费语义时例如一个工具 dict 放google_search、另一个放function_declarations优先使用独立的Tool列表条目而非难以按面surface推理的单一大 dict。在 Phoenix 中这正对应函数工具可移植、原始工具按供应商透传、切换供应商时原始工具被丢弃的既有行为可结合 vendor-specific-tools.md 与上述源码路径进一步研读。赞分享可观测性AI 评测LLMOpsAI 应用人工智能【免费下载链接】phoenixAI Observability Evaluation项目地址https://gitcode.com/gh_mirrors/phoenix13/phoenix点击查看免费下载相关推荐Gemini 结构化输出实战使用 Instructor 与 Google GenAI SDK 构建类型安全的数据提取Gemini 结构化输出实战使用 Instructor 与 Google GenAI SDK 构建类型安全的数据提取 本指南以 Instructor 的 Go人工智能大模型AI 应用LlamaIndex Google GenAI 嵌入集成实战GoogleGenAIEmbedding 类全解LlamaIndex Google GenAI 嵌入集成实战GoogleGenAIEmbedding 类全解 本文基于 LlamaIndex 官方 API 参人工智能RAG大模型大麦自动抢票部署教程网页与 App 双路线3 步完成配置与运行大麦自动抢票部署教程网页与 App 双路线3 步完成配置与运行 ticket purchase 是一款面向大麦网的开源自动抢票工具能自动完成选票、勾选观演GUI 自动化RPA上一篇ESP-IDFESP32-P4烧录报错5分钟搞定下一篇终极图神经网络实战指南7大应用场景深度解析与入门教程创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考