使用 Gemini API 执行代码

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

用于执行模型生成的代码并自动将结果返回给模型的工具。另请参阅 ExecutableCodeCodeExecutionResult,它们是此工具的输入和输出。

Part

executable_code

可选:ExecutableCode

模型生成的要执行的代码。
请参阅代码执行 [API]。

code_execution_result

可选:CodeExecutionResult

执行 [ExecutableCode] 的结果。
请参阅代码执行 [API]。

ExecutableCode

language

必需:string (enum)

生成的 code 支持的编程语言。


支持:
  • PYTHON

code

必需:string

要执行的代码。
请参阅代码执行 [API]。

CodeExecutionResult

outcome

必需:string (enum)

代码执行结果。


可能的结果:
  • 代码执行已成功完成。(OUTCOME_OK)
  • 代码已执行完毕,但失败了。stderr 应包含原因。(OUTCOME_FAILED)
  • 代码执行时间过长,已被取消。系统可能会或可能不会显示部分输出。(OUTCOME_DEADLINE_EXCEEDED)

output

必需:string

如果代码执行成功,则包含 stdout;否则,包含 stderr 或其他说明。
请参阅代码执行 [API]。

示例

以下插图展示了如何向模型提交查询和函数声明。

基本用例

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'

在模型上启用代码执行

如需启用基本代码执行,请参阅代码执行

后续步骤