Google Cloud Generative AI 仓库实战:使用 Gemini Code Execution 让 Gemini 3 Flash 生成并执行 Python 代码
Google Cloud Generative AI 仓库实战使用 Gemini Code Execution 让 Gemini 3 Flash 生成并执行 Python 代码【免费下载链接】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/code-execution 目录下的 Code Execution in Gemini 能力展开介绍如何通过一次 API 调用让 Gemini 模型自动生成并执行 Python 代码、观察运行结果、必要时修正代码并迭代学习直到产出最终答案。读完本文你将掌握在 Vertex AI 上基于 Google Gen AI SDK 配置代码执行工具、在单次调用/多轮对话/流式会话中使用代码执行以及将代码执行用于图像理解Agentic Vision的完整实战方法。Code Execution in Gemini模型自己写代码、跑代码、看结果README.md 对 Code Execution 的定义非常精炼它让开发者通过一次 API 调用a single API call就获得 Gemini 模型生成并执行代码的能力。你可以利用这种能力构建受益于基于代码的推理code-based reasoning的应用例如解方程、处理文本等场景。其内部工作方式是一条可自校正的闭环模型根据提示词生成一段 Python 代码代码在受控的沙箱环境中被执行模型观察执行结果若结果不理想模型可以修正代码反复迭代直至给出最终输出。这一点在 intro_code_execution.ipynb 中有明确说明代码执行能力使模型能够生成代码、执行并观察结果、必要时修正代码并从结果中迭代学习直到产生最终输出。这对于求解数学方程或处理文本这类依赖代码推理的应用尤为适用。仓库中该目录提供了两个可直接运行的 Notebook对应两种典型用法描述示例 Notebook使用 Gemini 生成并执行 Python 代码入门intro_code_execution.ipynbGemini Agentic Vision基于代码执行的图像推理入门intro_agentic_vision.ipynb准备环境安装 SDK、鉴权并创建客户端两个 Notebook 都基于Gemini 3 Flash 模型gemini-3.7-flash与Google Gen AI SDK for Python编写。首先安装 SDK%pip install --upgrade --quiet google-genai如果在 Google Colab 中运行需要先完成环境鉴权import sys if google.colab in sys.modules: from google.colab import auth auth.authenticate_user()接下来导入所需的库与类型。注意代码执行涉及的关键类型都来自google.genai.typesimport os from IPython.display import Markdown, display from google import genai from google.genai.types import GenerateContentConfig, Tool, ToolCodeExecutionGoogle Gen AI 的 API 与模型含 Gemini同时提供两种服务Google AI for Developers适合实验、原型与小型项目和Vertex AI适合在 Google Cloud 上构建企业级项目。Google Gen AI SDK 为这两个服务提供了统一接口本仓库的 Notebook 演示的是通过Vertex AI使用。创建客户端之前需要指定 Google Cloud 项目 IDPROJECT_ID与区域。Notebook 的默认处理是优先使用代码中的PROJECT_ID占位符若未设置则回退到环境变量GOOGLE_CLOUD_PROJECT区域则默认取global# fmt: off PROJECT_ID [your-project-id] # param {type: string, placeholder: [your-project-id], isTemplate: true} # fmt: on if not PROJECT_ID or PROJECT_ID [your-project-id]: PROJECT_ID str(os.environ.get(GOOGLE_CLOUD_PROJECT)) LOCATION os.environ.get(GOOGLE_CLOUD_REGION, global)随后创建 Vertex AI 客户端enterpriseTrue表示使用企业级端点并加载模型client genai.Client(enterpriseTrue, projectPROJECT_ID, locationLOCATION) MODEL_ID gemini-3.7-flash # param {type: string}定义代码执行工具使用代码执行的关键一步是把ToolCodeExecution包装进Tool对象中之后把它注册到模型调用上。这个工具就是告诉模型你可以生成并执行 Python 代码的信号code_execution_tool Tool(code_executionToolCodeExecution())单次调用让模型生成并执行代码先看最基础的用法直接向模型发送提示词要求生成并运行代码来计算前 50 个质数的和PROMPT What is the sum of the first 50 prime numbers? Generate and run code for the calculation. response client.models.generate_content( modelMODEL_ID, contentsPROMPT, configGenerateContentConfig( tools[code_execution_tool], ), )模型会返回一个多部件multi-part响应其中既包含可执行代码也包含执行结果。这正是代码执行与普通文本生成的本质区别。查看模型生成的代码遍历响应的parts通过判断part.executable_code来筛选并展示模型生成的 Python 代码for part in response.candidates[0].content.parts: if part.executable_code: display( Markdown( f py {part.executable_code.code} ) )在示例运行中模型生成的代码如下这是一个经典的素数求和实现 py def is_prime(n): if n 2: return False for i in range(2, int(n**0.5) 1): if n % i 0: return False return True primes [] num 2 while len(primes) 50: if is_prime(num): primes.append(num) num 1 sum_primes sum(primes) print(fThe first 50 prime numbers are: {primes}) print(fThe sum of the first 50 prime numbers is: {sum_primes})查看代码执行结果执行结果位于part.code_execution_result其中output保存代码的 stdout 输出outcome表示执行结果状态示例输出为Outcome.OUTCOME_OK即执行成功for part in response.candidates[0].content.parts: if part.code_execution_result: display(Markdown(f{part.code_execution_result.output})) print(\nOutcome:, part.code_execution_result.outcome)示例运行得到The first 50 prime numbers are: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229] The sum of the first 50 prime numbers is: 5117此时你既拿到了答案5117也拿到了经过真实执行验证的 Python 代码。在实际应用中你可以把输出的代码、结果或状态保存下来展示给最终用户或在应用的下游流程中继续使用——这正是 Notebook 在示例末尾给出的建议。多轮对话带历史的代码执行代码执行同样适用于带上下文的交互式聊天场景。使用client.chats.create创建会话并把代码执行工具传入配置之后每次chat.send_message都会保留历史上下文chat client.chats.create( modelMODEL_ID, configGenerateContentConfig( tools[code_execution_tool], ), )Notebook 用一个测试炉温度时间序列的探索性数据分析案例演示了三轮连续的代码执行第一轮生成带噪声的时间序列数据并输出前 10 个数据点。PROMPT Generate and run code to create sample time series data of temperature vs. time in a test furnace. Add noise to the data. Output a sample of 10 data points from the time series data. response chat.send_message(PROMPT)模型生成的代码使用numpy与pandas基于牛顿冷却定律公式T(t) T_ambient (T_target - T_ambient) * (1 - exp(-k * t))生成理想温度曲线再叠加标准差为 2.5 的高斯噪声最后输出前 10 个数据点。运行结果形如Time (min) Temperature (C) 0 0 26.241785 1 1 62.451535 2 2 100.370222 3 3 136.758893 4 4 164.898283 5 5 195.844051 6 6 229.813911 7 7 255.785317 8 8 279.328278 9 9 307.194583第二轮要求基于已有数据新增一条平滑序列模型使用rolling(window5, min_periods1, centerTrue).mean()计算 5 分钟滑动平均得到Smoothed Temp (C)列。第三轮要求生成描述性统计模型调用df.describe()并额外追加方差行输出 count、mean、std、min、四分位数、max 与 variance 等统计量。每一轮都可以用同样的方式解析响应中的part.executable_code与part.code_execution_result将代码与结果同时展示。这个示例说明借助代码执行Gemini API 可以成为**探索性数据分析EDA**的强大工具你可以把这一套交互模式直接迁移到自己的项目与场景中。流式会话边生成边执行generate_content_stream允许模型在生成内容的同时执行代码并把结果以流式块chunk逐步返回。Notebook 以生成 20 个随机姓名并筛选出含字母 a 的姓名为例PROMPT Generate and run code to create a list of 20 random names, then create a new list with just the names containing the letter a, then output the number of names that contain a, and finally show me that new list. for chunk in client.models.generate_content_stream( modelMODEL_ID, contentsPROMPT, configGenerateContentConfig( tools[code_execution_tool], ), ): if chunk.candidates and chunk.candidates[0].content: if chunk.candidates[0].content.parts is not None: for part in chunk.candidates[0].content.parts: if part.text: display(Markdown(#### Natural language stream)) display(Markdown(part.text)) display(Markdown(---)) if part.executable_code: display(Markdown(#### Code stream)) display( Markdown( f py {part.executable_code.code} ) ) display(Markdown(---)) if part.code_execution_result: display(Markdown(#### Code result)) display( Markdown( f{part.code_execution_result.output} ) ) display(Markdown(---))在流式返回中同一个请求会产生三类内容块按出现顺序大致为**自然语言流Natural language stream**、**代码流Code stream**与**代码结果Code result**。示例运行中模型生成的代码用 random.sample 从常见英文姓名列表中抽取 20 个名字再以列表推导式筛选含字母 a不区分大小写的名字最终输出计数 14 与完整筛选列表。从 Notebook 的流式输出可以看到模型甚至会在自然语言流中逐步汇报自己的处理进度这为构建逐 token 呈现结果的交互式应用提供了基础。 ## 进阶应用Agentic Vision——把代码执行用到图像上 [cx] [intro_agentic_vision.ipynb](https://link.gitcode.com/i/c625404251f0cc2b34a219036b8e0e70) 展示了代码执行的另一类高价值用法**Agentic Vision**。开启代码执行后模型不再只是看一张静态图片而是像 Agent 一样主动编写代码去**操作、裁剪、检查图像**从而发现单靠视觉可能遗漏的细节。文档明确列出了三类典型应用 - **Zoom and Inspect缩放检查**隐式识别到目标物体过小时自动裁剪图像放大查看 - **Visual Math and Plotting视觉数学与绘图**执行精确的多步计算或准确重绘数据 - **Image Annotation图像标注**以编程方式识别并框出物体。 示例的提示词与图片如下 - **Prompt**Locate the ESMT chip. What are the numbers on the chip? - **Image**仓库外部的云存储示例图chips.jpeg 调用方式与单次调用基本一致只是把图片通过 types.Part.from_bytes 作为输入的一部分传入工具定义为 types.Tool(code_executiontypes.ToolCodeExecution) python image_path ( https://storage.googleapis.com/cloud-samples-data/generative-ai/image/chips.jpeg ) image_bytes requests.get(image_path).content image types.Part.from_bytes(dataimage_bytes, mime_typeimage/jpeg) response client.models.generate_content( modelMODEL_ID, contents[image, Locate the ESMT chip. What are the numbers on the chip?], configtypes.GenerateContentConfig( tools[types.Tool(code_executiontypes.ToolCodeExecution)] ), )模型的推理链路充分体现了 Agentic Vision 的特征判断看不清意识到在全分辨率图像上无法准确读取芯片上的小字写代码生成 PIL 代码定位 ESMT 芯片的边界框把归一化坐标转换为像素坐标并裁剪出局部区域执行代码保存裁剪后的放大图esmt_chip_zoom.png继续迭代发现方向仍不便阅读后再次执行crop_img.rotate(180)旋转图像给出结论基于放大后的图像读取芯片上的编码回答出制造商 ESMT、型号 M12L64164A、速度等级 7T、批次号 SZB1C30C9 与日期码 0325。响应解析同样是遍历parts分别处理part.text模型推理文本、part.executable_code生成的代码与part.code_execution_result执行输出。这类自动写代码操作图像再回答的模式正是代码执行支撑 Agentic Vision 的直观体现。小结与进一步阅读Code Execution in Gemini 让模型跨越生成代码与运行代码之间的鸿沟单次 API 调用即可完成生成—执行—观察—修正的闭环既可以处理素数求和这类精确计算也可以在带历史的多轮对话中完成数据探索还能在流式会话中逐步交付结果配合图像输入它还能支撑 Zoom and Inspect 等 Agentic Vision 应用。你可以按需深入学习本仓库中的对应 Notebook完整代码与运行结果intro_code_execution.ipynbAgentic Vision 完整示例intro_agentic_vision.ipynb本目录说明README.md值得一提的是intro_code_execution.ipynb 的总结部分提醒读者官方文档对代码执行 vs 函数调用function calling的使用选择给出了具体建议构建应用时建议结合自身场景判断何时使用代码执行、何时使用函数调用。此外Google Gen AI SDK 的参考文档与 Model Garden 中的各类模型列表可作为继续探索的入口。【免费下载链接】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),仅供参考