Gemini API 代码执行功能可让模型生成和运行 Python 代码,并从结果中迭代学习,直到获得最终输出。您可以使用此代码执行功能来构建可从基于代码的推理中受益并生成文本输出的应用。例如,您可以将此项功能用于求解方程式或处理文本方面的应用。
Gemini API 提供代码执行作为工具,类似于函数调用。将代码执行作为工具添加后,模型会决定何时使用它。
支持的模型
限制
- 该功能不支持文件 I/O。
- 代码执行最长可运行 30 秒,超出这一时间即会超时。
示例语法
curl
PROJECT_ID = myproject REGION = us-central1 MODEL_ID = gemini-2.0-flash-001 https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \ -d '{ "contents": [{ ... }], "tools": [{ "code_execution": {} }] }'
参数列表
如需了解实现详情,请参阅示例。
Python
如需启用代码执行,请在请求中指定代码执行 tool
。
CodeExecution
用于执行模型生成的代码并自动将结果返回给模型的工具。另请参阅 ExecutableCode 和 CodeExecutionResult,它们是此工具的输入和输出。
Part
| 可选: 模型生成的要执行的代码。
|
| 可选: 执行 [ExecutableCode] 的结果。
|
ExecutableCode
| 必需: 生成的 支持:
|
| 必需: 要执行的代码。
|
CodeExecutionResult
| 必需: 代码执行结果。 可能的结果:
|
| 必需: 如果代码执行成功,则包含 |
示例
以下插图展示了如何向模型提交查询和函数声明。
基本用例
curl
PROJECT_ID = myproject REGION = us-central1 MODEL_ID = gemini-2.0-flash-001 curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \ -d '{ "contents": [{ "role": "user", "parts": [{ "text": "Calculate 20th fibonacci number. Then find the nearest palindrome to it." }] }], "tools": [{'codeExecution': {}}], }'
Python
from google import genai from google.genai.types import Tool, ToolCodeExecution, GenerateContentConfig client = genai.Client() model_id = "gemini-2.0-flash-001" code_execution_tool = Tool( code_execution=ToolCodeExecution() ) response = client.models.generate_content( model=model_id, contents="Calculate 20th fibonacci number. Then find the nearest palindrome to it.", config=GenerateContentConfig( tools=[code_execution_tool], temperature=0, ), ) for part in response.candidates[0].content.parts: if part.executable_code: print(part.executable_code) if part.code_execution_result: print(part.code_execution_result) # Example response: # code='...' language='PYTHON' # outcome='OUTCOME_OK' output='The 20th Fibonacci number is: 6765\n' # code='...' language='PYTHON' # outcome='OUTCOME_OK' output='Lower Palindrome: 6666\nHigher Palindrome: 6776\nNearest Palindrome to 6765: 6776\n'
在模型上启用代码执行
如需启用基本代码执行,请参阅代码执行。
后续步骤
- 详细了解 Gemini API。
- 详细了解函数调用。
- 详细了解如何使用 Gemini 生成内容。