ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Gemini Function Calling 实战指南:从基础声明到并行调用、强制工具配置与多模态输入

Gemini Function Calling 实战指南:从基础声明到并行调用、强制工具配置与多模态输入 Gemini Function Calling 实战指南从基础声明到并行调用、强制工具配置与多模态输入【免费下载链接】generative-aiSample code and notebooks for Generative AI on Google Cloud, with Gemini Enterprise Agent Platform项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai导读本指南以 gemini/function-calling/ 目录下的 README.md 及其 5 个配套 Jupyter Notebook 为技术骨架系统讲解 Google Cloud Generative AIVertex AI Gemini中的 Function Calling函数调用能力。你将掌握如何用FunctionDeclaration描述函数、用Tool封装工具、通过Part.from_function_response闭环调用外部 API并进阶掌握并行函数调用、AUTO/ANY/NONE三种工具配置模式以及基于图像、视频、音频、PDF 的多模态函数调用。读完本指南你可以直接复用仓库中的代码示例构建能连接外部系统的 Agent 应用。什么是 Gemini Function Callinggemini/function-calling/README.md 对 Function Calling 给出了精确定义开发者先在代码中创建对某个函数的描述然后将该描述随请求一起传给语言模型模型的响应中会包含与描述匹配的函数名以及调用它所需的参数。也就是说模型本身不执行你的业务代码它只负责做两件事从你提供的函数描述集中挑选最合适的函数、从用户的自然语言中抽取该函数所需的参数然后以结构化的FunctionCall返回。真正的执行发生在你的应用代码里调用外部 REST API、查询数据库、下单、发邮件等执行结果再回传给模型由模型生成面向最终用户的自然语言回复。为什么需要函数调用告别解析自由文本的痛点在 intro_function_calling.ipynb 的 Overview 中作者用一个形象的比喻解释了动机让一个人写下重要信息却不提供任何表单或结构约束你会得到一段漂亮的散文但想从中精确提取姓名、日期、数字会非常痛苦。直接要求生成式文本模型输出 JSON 也往往不一致、不可靠。Function Calling 正是解决这一痛点的表单你定义带有具体参数与数据类型的函数声明它们成为引导模型的结构化约束模型输出被规范化为可预测、可直接使用的结构化对象无需再解析自由文本它架起了人类语言与外部系统所需的结构化数据之间的桥梁需要查数据库就定义search_db需要对接天气 API 就定义get_weather。核心工作流五个步骤从 multimodal_function_calling.ipynb 的 How It Works 小节可以提炼出完整的调用闭环定义函数与工具用FunctionDeclaration描述函数并分组打包成Tool对象发送输入与提示将多模态输入文本、图像、音频、PDF 等与提示词一起发送给 Gemini模型预测动作Gemini 分析输入并预测要调用的函数及其参数执行并回传在应用代码中执行真实 API 调用把结果通过Part.from_function_response发回给 Gemini生成回复Gemini 基于 API 结果生成最终自然语言回复。环境准备SDK、认证与项目初始化目录下所有 notebook 的环境准备步骤完全一致是可直接复用的最小化启动流程。1. 安装 Google Gen AI SDK%pip install --upgrade --quiet google-genaiparallel_function_calling.ipynb 和 forced_function_calling.ipynb 还会额外安装第三方库wikipedia、arxiv用于演示真实的外部 API 调用环节%pip install --upgrade --quiet google-genai wikipedia2. 认证仅 Colab 环境需要如果运行在 Google Colab 上需要执行认证使用 Vertex AI Workbench 或本地环境则不需要import sys if google.colab in sys.modules: from google.colab import auth auth.authenticate_user()3. 设置项目信息并创建客户端使用 Vertex AI 的前提是拥有 Google Cloud 项目并启用 Vertex AI APIaiplatform.googleapis.com。初始化代码在各个 notebook 中几乎一致import os PROJECT_ID [your-project-id] if not PROJECT_ID or PROJECT_ID [your-project-id]: PROJECT_ID str(os.environ.get(GOOGLE_CLOUD_PROJECT)) LOCATION global from google import genai client genai.Client(enterpriseTrue, projectPROJECT_ID, locationLOCATION)需要注意两点PROJECT_ID支持通过GOOGLE_CLOUD_PROJECT环境变量回退获取方便在 CI 或本地环境中免改代码运行目录内 notebook 在genai.Client()的构造上存在enterpriseTrue如 intro_function_calling.ipynb、forced_function_calling.ipynb与vertexaiTrue如 parallel_function_calling.ipynb两种写法两者都指向 Vertex AI 上的 Gemini API读者可按实际使用的 Gemini Enterprise Agent Platform 或 Vertex AI 环境选择。4. 选择模型本目录示例使用的模型为gemini-3.7-flash与gemini-3.5-flash不同 notebook 略有差异例如MODEL_ID gemini-3.7-flash模型的选型会影响 Function Calling 的能力边界如是否支持并行函数调用、是否支持工具配置官方文档对此有明确说明具体以当前模型版本的 Gemini Function Calling 文档为准。三大核心 API 类型FunctionDeclaration、Tool 与 Part所有示例都建立在google.genai.types提供的几个类型之上。导入语句统一为from google.genai.types import FunctionDeclaration, GenerateContentConfig, Part, ToolFunctionDeclaration用 JSON Schema 描述函数函数声明由三部分组成函数名、功能描述、参数 Schema。参数遵循 OpenAPI JSON Schema 格式以 Python 字典书写这一点在 intro_function_calling.ipynb 中有明确说明get_product_info FunctionDeclaration( nameget_product_info, descriptionGet the stock amount and identifier for a given product, parameters{ type: object, properties: { product_name: {type: string, description: Product name} }, }, )函数名与描述的质量直接决定模型能否准确选择函数、正确抽取参数——描述越精确模型的预测越可靠。Tool函数声明的容器一个Tool可以打包多个函数声明模型会从其中选择要调用的函数retail_tool Tool( function_declarations[ get_product_info, get_store_location, place_order, ], )GenerateContentConfig 与 Part配置与回传GenerateContentConfig负责携带tools与temperature等生成参数Part.from_function_response()则把外部 API 的执行结果以工具响应的形式回传给模型response chat.send_message( Part.from_function_response( nameget_product_info, response{ content: api_response, }, ), )在 forced_function_calling.ipynb 中还引入了更底层的Content(roletool, parts[...])构造方式同样用于回传工具执行结果。实战一多轮对话中的函数调用Google Store 场景intro_function_calling.ipynb 的核心示例是构建一个面向 Google Store 的客服机器人。它演示了 Function Calling 在多轮会话中的完整工作方式。定义三个业务函数客服机器人需要三种能力查询库存、查找最近门店、下单get_product_info FunctionDeclaration( nameget_product_info, descriptionGet the stock amount and identifier for a given product, parameters{ type: object, properties: { product_name: {type: string, description: Product name} }, }, ) get_store_location FunctionDeclaration( nameget_store_location, descriptionGet the location of the closest store, parameters{ type: object, properties: {location: {type: string, description: Location}}, }, ) place_order FunctionDeclaration( nameplace_order, descriptionPlace an order, parameters{ type: object, properties: { product: {type: string, description: Product name}, address: {type: string, description: Shipping address}, }, }, )初始化带工具的聊天会话关键技巧在client.chats.create()初始化时通过config指定tools避免在后续每一轮请求中重复携带chat client.chats.create( modelMODEL_ID, configGenerateContentConfig( temperature0, tools[retail_tool], ), )temperature参数用于控制生成随机性较低温度适合需要确定性参数值的函数调用场景如库存查询较高温度适合参数更开放、更多样的场景temperature0表示确定性输出但即使如此同一提示词下的响应仍可能存在极小的波动notebook 中的原话是mostly deterministic, but a small amount of variation is still possible。第一轮单函数调用用户提问Pixel 9 有货吗模型返回结构化调用请求prompt Do you have the Pixel 9 in stock? response chat.send_message(prompt) response.function_calls[0]返回结果是一个FunctionCall对象FunctionCall( args{product_name: Pixel 9}, nameget_product_info )notebook 在此处用合成数据模拟外部 API 响应真实场景中应使用自己的客户端库或 REST API 调用库存系统api_response {sku: GA04834-US, in_stock: yes}随后回传给模型并展示最终回答response chat.send_message( Part.from_function_response( nameget_product_info, response{content: api_response}, ), ) display(Markdown(response.text))模型输出Yes, the Pixel 9 is currently in stock.第二轮一次对话触发两个函数调用当用户同时询问Pixel 9 Pro XL 有货吗山景城有店可以试机吗Gemini 在单个响应对象中返回了两个FunctionCall[FunctionCall(args{product_name: Pixel 9 Pro XL}, nameget_product_info), FunctionCall(args{location: Mountain View, CA}, nameget_store_location)]这正是并行函数调用的体现详见后文。处理方式同样简单分别构造两个外部 API 的模拟响应然后一次性回传response chat.send_message( [ Part.from_function_response( nameget_product_info, response{content: product_info_api_response}, ), Part.from_function_response( nameget_store_location, response{content: store_location_api_response}, ), ] ) display(Markdown(response.text))第三轮多参数抽取与下单用户说我要订一台 Pixel 9 Pro XL送到 1155 Borregas Ave, Sunnyvale, CA 94089模型自动抽取出product与address两个参数并调用place_order。模拟下单 API 返回payment_status、order_number、est_arrival后模型最终生成Your order for a Pixel 9 Pro XL has been placed! Your order number is 12345 and it is estimated to arrive in 2 days.这三轮对话完整覆盖了 Function Calling 的典型闭环结构化请求 → 外部执行 → 结构化回传 → 自然语言总结是后续所有高级技巧的基础范式。实战二函数参数的数据结构与 Schemafunction_calling_data_structures.ipynb 专注于回答一个问题函数参数到底能有多复杂它用递进式的四个示例给出了答案。单参数最简单的场景——从提示词中抽取一个目的地get_destination FunctionDeclaration( nameget_destination, descriptionGet directions to a destination, parameters{ type: object, properties: { destination: { type: string, description: Destination that the user wants to go to, }, }, }, )发送Id like to travel to Paris返回{destination: Paris}。多参数在properties中增加多个键即可。示例定义了destination、mode_of_transportation、departure_time三个参数get_destination_params FunctionDeclaration( nameget_destination_params, descriptionGet directions to a destination, parameters{ type: object, properties: { destination: { type: string, description: Destination that the user wants to go to, }, mode_of_transportation: { type: string, description: Mode of transportation to use, }, departure_time: { type: string, description: Time that the user will leave for the destination, }, }, }, )发送Id like to travel to Paris by train and leave at 9:00 am模型一次性抽取全部三个键值对{departure_time: 9:00 am, destination: Paris, mode_of_transportation: train}。参数列表array 嵌套 object当需要在一次函数调用内处理多个地点时可以使用array类型其items为嵌套的object并可通过required指定必填字段get_multiple_location_coordinates FunctionDeclaration( nameget_location_coordinates, descriptionGet coordinates of multiple locations, parameters{ type: object, properties: { locations: { type: array, description: A list of locations, items: { description: Components of the location, type: object, properties: { point_of_interest: { type: string, description: Name or type of point of interest, }, city: {type: string, description: City}, country: {type: string, description: Country}, }, required: [ point_of_interest, city, country, ], }, } }, }, )发送包含埃菲尔铁塔、自由女神像、道格拉斯港三个地点的提示词后模型返回一个包含三个完整对象的locations数组。notebook 特别指出因为这三个字段都被标记为required模型为每个地点都填齐了全部字段——这体现了required约束对输出完整性的保障作用。嵌套数据结构最复杂的场景——用几句话说清楚商品信息模型负责填好嵌套的product对象含name、price、category、descriptioncreate_product_listing FunctionDeclaration( namecreate_product_listing, descriptionCreate a product listing using the details provided by the user., parameters{ type: object, properties: { product: { type: object, properties: { name: {type: string}, price: {type: number}, category: {type: string}, description: {type: string}, }, } }, }, )提示词Create a listing for noise-canceling headphones for $149.99. These headphones create a distraction-free environment.被完整抽取为{product: {category: Electronics, description: These headphones create a distraction-free environment., name: Noise-canceling headphones, price: 149.99}}小结JSON Schema 表达力有多强函数调用就能支持多复杂的数据结构。从单参数到多层嵌套模型都会严格按照 Schema 约束输出。实战三并行函数调用Parallel Function Callingparallel_function_calling.ipynb 深入讲解了并行函数调用这一高级特性并给出了清晰的历史背景。什么是并行函数调用在 2024 年 5 月之前的旧版 Gemini 中如果模型判断需要多次调用函数只能采用链式模式拿到第一个函数调用 → 回传结果 → 再拿第二个函数调用 → 再回传……如此往返。而从 2024 年 5 月起的新版本模型具体版本以官方文档为准支持在同一个响应对象内返回两个或更多函数调用。并行调用的核心价值在于它允许你在应用代码中扇出fan out并并行执行多个 API 请求而不是逐个串行往返从而显著减少与 Gemini API 的交互轮次改善端到端延迟。场景一同一函数的重复并行调用典型的适用场景是某个函数每次只能接收一个参数但一次请求需要处理多个条目。示例用 Wikipedia 搜索演示——单个search_wikipedia函数、三条查询solar panels、renewable energy、battery storage一次提示词返回三个FunctionCall。notebook 提供了一个通用的提取辅助函数可以自行改写为任意目标格式def extract_function_calls(response: GenerateContentResponse) - list[dict]: function_calls: list[dict] [] for function_call in response.function_calls: function_call_dict: dict[str, dict[str, Any]] {function_call.name: {}} for key, value in function_call.args.items(): function_call_dict[function_call.name][key] value function_calls.append(function_call_dict) return function_calls提取结果[{search_wikipedia: {query: solar panel}}, {search_wikipedia: {query: renewable energy}}, {search_wikipedia: {query: battery storage power station}}]然后在应用代码中循环执行外部 API 调用api_response [] for function_call in function_calls: print(function_call) result wikipedia.summary(function_call[search_wikipedia][query]) api_response.append(result)最后一次性批量回传所有结果三个Part.from_function_response装入一个列表Gemini 据此生成综合总结。整个过程无需任何额外配置——不需要修改函数声明、工具或请求参数。场景二多个独立函数的并行调用第二个场景定义三个独立函数search_wikipedia、suggest_wikipedia、summarize_wikipedia提示词要求搜索太阳系、推荐相关术语、总结主文章模型在一个响应内并行返回对三个函数的调用[{search_wikipedia: {query: Solar System}}, {suggest_wikipedia: {query: Solar System}}, {summarize_wikipedia: {topic: Solar System}}]执行阶段按函数名分发到对应的 Wikipedia APIfor function_call in function_calls: for function_name, function_args in function_call.items(): if function_name search_wikipedia: result wikipedia.search(function_args[query]) if function_name suggest_wikipedia: result wikipedia.suggest(function_args[query]) if function_name summarize_wikipedia: result wikipedia.summary(function_args[topic], auto_suggestFalse) api_response[function_name] result最后按函数名将结果批量回传使用api_response.get(function_name, )防缺失。重要提示notebook 原文强调Gemini 会根据FunctionDeclaration中的信息自主决定哪些调用可以并行、哪些调用必须在其他调用之后执行即存在依赖关系时。因此你的应用逻辑必须同时兼容并行响应与串行依赖两种情况。实战四强制函数调用与工具配置AUTO / ANY / NONEforced_function_calling.ipynb 展示了用ToolConfig控制模型行为的三种模式。其示例围绕 arXiv 论文搜索函数search_arxiv展开该函数声明使用了Schema/Type类型的替代写法与字典写法等价。三种模式的语义tool_config ToolConfig( function_calling_configFunctionCallingConfig( modeFunctionCallingConfigMode.AUTO, # 默认行为模型自行决定是预测函数调用还是自然语言回复 allowed_function_names[function_to_call], # ANY 模式下允许调用的函数子集为空则允许调用任一已提供函数 ) )模式行为AUTO默认模型根据提示词自主决定是否调用函数、调用哪个函数也可直接输出自然语言回复ANY强制模型从allowed_function_names指定的函数子集中预测一个函数调用列表为空则从全部已声明函数中选NONE禁用函数调用等价于未提供任何函数声明模型仅生成自然语言回复AUTO 模式默认行为不设置tool_config时即为AUTO。示例中显式设置以便对照config.tool_config ToolConfig( function_calling_configFunctionCallingConfig( modeFunctionCallingConfigMode.AUTO, ) )对提示词用几句话解释强化学习并给出 arXiv 上的论文——模型直接返回了自然语言总结没有调用search_arxiv。这正是 AUTO 模式的特性是否调用函数完全由模型判断结果并不总是符合开发者的预期。ANY 模式强制调用设置ANY并指定allowed_function_names[search_arxiv]后同样的提示词被强制触发函数调用config.tool_config ToolConfig( function_calling_configFunctionCallingConfig( modeFunctionCallingConfigMode.ANY, allowed_function_names[search_arxiv], ) )模型返回FunctionCall( args{query: Deep Reinforcement Learning survey overview introduction}, namesearch_arxiv )随后应用代码用arxiv包执行真实搜索arxiv.Search(queryparams[query], max_results3, sort_byarxiv.SortCriterion.Relevance)再把结果构造为Content(roletool, parts[Part.from_function_response(...)])回传模型最终生成包含真实论文清单与推荐理由的回复。NONE 模式完全禁用config.tool_config ToolConfig( function_calling_configFunctionCallingConfig( modeFunctionCallingConfigMode.NONE, ) )NONE模式下模型只依赖训练数据生成回答即使提示词明确索要 arXiv 论文也不会调用search_arxiv。notebook 用它直观地对比出调用工具获取实时数据与纯模型知识作答的差异。适用场景总结AUTO大多数常规场景让模型智能判断ANY流程要求必须触发函数调用的场景如先查数据库再回答、结构化信息抽取管线、按固定流程执行的 AgentNONE临时禁用工具如某些回复希望走纯模型通道、A/B 对比、调试。实战五多模态函数调用图像 / 视频 / 音频 / PDFmultimodal_function_calling.ipynb 是目录中最具前瞻性的示例展示了Gemini 的输入模态不止于文本——函数调用可以基于图像、视频、音频和 PDF 触发。notebook 明确指出这一能力也被称为带受控生成的函数调用function calling with controlled generation保证输出始终符合特定 Schema。它用一个 API 调用取代了以往先抽取媒体信息文本、再生成函数调用的两段式流程避免了信息损失与工程复杂度。所有多模态示例的统一模式是用Part.from_uri(file_uri..., mime_type...)注入媒体文件配合提示词与tools配置调用client.models.generate_content。图像输入识别动物并查询栖息地定义get_wildlife_region函数输入一张鸟类图片多色鸟Lilac-breasted Rollerresponse client.models.generate_content( modelMODEL_ID, contents[ Part.from_uri( file_urigs://github-repo/generative-ai/gemini/function-calling/multi-color-bird.jpg, mime_typeimage/jpeg, ), What is the typical habitat or region where this animal lives?, ], configGenerateContentConfig(temperature0, tools[image_tool]), )模型返回{animal: Lilac-breasted Roller}。随后用wikipedia.page(function_args[animal]).content做真实 API 调用将结果以Content(roletool, ...)回传Gemini 最终生成包含分布区域、典型栖息地描述的完整回答。注意最终回传时需要在contents中带上原始的UserContent图片 提示与模型的model_response_content函数调用保持多轮上下文完整。视频输入识别产品特性用get_feature_info函数从一段 Made by Google 发布视频MP4中提取产品功能列表返回的features数组中包含了 Gemini、Gemini Live、Pixel 9 系列、Pixel Studio、Pixel Watch 3、Pixel Buds Pro 2 等结构化条目——这些参数严格遵循FunctionDeclaration中定义的 JSON Schema。音频输入基于播客内容推荐书目get_recommended_books函数接收播客音频MP3模型从中识别出 Site Reliability Engineering、System Thinking、Scalability、Incident Response 等主题词列表可用于后续的书籍推荐 API。PDF 输入从发票中抽取公司名get_company_information函数同时接收5 份合成发票 PDF模型一次调用即抽取出全部虚构公司名AMNOSH SUPPLIERS、BIKBEAR LAW FIRM 等展示了文档处理场景如财务自动化、KYC中文档 → 结构化数据的直接通路。综合示例多模态聊天机器人最后notebook 把多模态与多轮对话结合构建了一个看图聊天机器人定义get_animal_details、search_similar_images、check_color_palette三个函数在client.chats.create()中注入工具后用户依次发送同一张狐狸图片的不同指令——介绍图中的动物触发get_animal_details、找相似图片触发search_similar_images抽取query: red fox in a grassy field with flowers、提取色板并检查可访问性触发check_color_palette返回十六进制色值数组。该示例虽未真正执行函数但完整演示了多模态输入 函数调用 聊天的交互式 Agent 形态。仓库内配套资源一览gemini/function-calling/README.md目录总览含四个官方入口 notebook 的描述表格gemini/function-calling/intro_function_calling.ipynb入门必读多轮对话 地理编码两大实战gemini/function-calling/function_calling_data_structures.ipynb参数 Schema 从简到繁的完整演进gemini/function-calling/parallel_function_calling.ipynb并行调用的两个典型场景与批量回传范式gemini/function-calling/forced_function_calling.ipynbAUTO/ANY/NONE三种工具配置模式的对照实验gemini/function-calling/multimodal_function_calling.ipynb图像、视频、音频、PDF 四类多模态输入 多模态聊天机器人。在整个仓库的上下文中Function Calling 是 gemini/ 目录下的核心能力之一gemini/README.md 在 Using this repository 一节将其单列为function-calling/学习入口并与仓库中的 Agent Engine、MCP、Agent 示例如 agents/adk/、gemini/agent-engine/共同构成 Gemini 驱动的智能体应用技术栈——函数调用正是这些 Agent 与外部世界交互的手和脚。总结与进阶路径通过本指南你已经掌握了 Gemini Function Calling 的完整技能栈基础闭环FunctionDeclaration声明 →Tool打包 → 聊天/内容生成 →Part.from_function_response回传 → 自然语言总结Schema 设计单参数、多参数、数组、嵌套对象与required约束覆盖绝大多数结构化输出需求并行调用一次响应内处理多个同函数或跨函数调用并批量回传降低交互延迟工具配置AUTO/ANY/NONE三种模式精确控制模型行为适配不同业务流程多模态扩展图像、视频、音频、PDF 均可作为函数调用决策的输入开启能看、能听、能读的智能应用。建议的进阶路线先完整运行 intro_function_calling.ipynb 打牢基础再根据业务需要选读 function_calling_data_structures.ipynb结构化输出与 parallel_function_calling.ipynb性能优化随后用 forced_function_calling.ipynb 精细化控制行为最后通过 multimodal_function_calling.ipynb 突破纯文本限制。更进一步可将函数调用能力与仓库中的 Agent Engine 结合构建生产级的 Agent 应用。【免费下载链接】generative-aiSample code and notebooks for Generative AI on Google Cloud, with Gemini Enterprise Agent Platform项目地址: https://gitcode.com/GitHub_Trending/ge/generative-ai创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表