代码执行

Gemini API 代码执行功能可让模型生成和运行 Python 代码,并从结果中迭代学习,直到获得最终输出。您可以使用此代码执行功能来构建可从基于代码的推理中受益并生成文本输出的应用。例如,您可以将此项功能用于求解方程式或处理文本方面的应用。

Gemini API 提供代码执行作为工具,类似于函数调用。将代码执行添加为工具后,模型会决定何时使用它。

代码执行环境包含以下库。您无法安装自己的库。

支持的模型

以下模型支持代码执行:

开始使用代码执行

本部分假定您已完成 Gemini API 快速入门中所述的设置和配置步骤。

在模型上启用代码执行功能

您可以按以下所述启用基本代码执行:

Python

安装

pip install --upgrade google-genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values # with appropriate values for your project. export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT export GOOGLE_CLOUD_LOCATION=global export GOOGLE_GENAI_USE_VERTEXAI=True

from google import genai from google.genai.types import (     HttpOptions,     Tool,     ToolCodeExecution,     GenerateContentConfig, )  client = genai.Client(http_options=HttpOptions(api_version="v1")) model_id = "gemini-2.5-flash"  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,     ), ) print("# Code:") print(response.executable_code) print("# Outcome:") print(response.code_execution_result)  # Example response: # # Code: # def fibonacci(n): #     if n <= 0: #         return 0 #     elif n == 1: #         return 1 #     else: #         a, b = 0, 1 #         for _ in range(2, n + 1): #             a, b = b, a + b #         return b # # fib_20 = fibonacci(20) # print(f'{fib_20=}') # # # Outcome: # fib_20=6765

Go

了解如何安装或更新 Go

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values # with appropriate values for your project. export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT export GOOGLE_CLOUD_LOCATION=global export GOOGLE_GENAI_USE_VERTEXAI=True

import ( 	"context" 	"fmt" 	"io"  	genai "google.golang.org/genai" )  // generateWithCodeExec shows how to generate text using the code execution tool. func generateWithCodeExec(w io.Writer) error { 	ctx := context.Background()  	client, err := genai.NewClient(ctx, &genai.ClientConfig{ 		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"}, 	}) 	if err != nil { 		return fmt.Errorf("failed to create genai client: %w", err) 	}  	prompt := "Calculate 20th fibonacci number. Then find the nearest palindrome to it." 	contents := []*genai.Content{ 		{Parts: []*genai.Part{ 			{Text: prompt}, 		}, 			Role: "user"}, 	} 	config := &genai.GenerateContentConfig{ 		Tools: []*genai.Tool{ 			{CodeExecution: &genai.ToolCodeExecution{}}, 		}, 		Temperature: genai.Ptr(float32(0.0)), 	} 	modelName := "gemini-2.5-flash"  	resp, err := client.Models.GenerateContent(ctx, modelName, contents, config) 	if err != nil { 		return fmt.Errorf("failed to generate content: %w", err) 	}  	for _, p := range resp.Candidates[0].Content.Parts { 		if p.Text != "" { 			fmt.Fprintf(w, "Gemini: %s", p.Text) 		} 		if p.ExecutableCode != nil { 			fmt.Fprintf(w, "Language: %s\n%s\n", p.ExecutableCode.Language, p.ExecutableCode.Code) 		} 		if p.CodeExecutionResult != nil { 			fmt.Fprintf(w, "Outcome: %s\n%s\n", p.CodeExecutionResult.Outcome, p.CodeExecutionResult.Output) 		} 	}  	// Example response: 	// Gemini: Okay, I can do that. First, I'll calculate the 20th Fibonacci number. Then, I need ... 	// 	// Language: PYTHON 	// 	// def fibonacci(n): 	//    ... 	// 	// fib_20 = fibonacci(20) 	// print(f'{fib_20=}') 	// 	// Outcome: OUTCOME_OK 	// fib_20=6765 	// 	// Now that I have the 20th Fibonacci number (6765), I need to find the nearest palindrome. ... 	// ...  	return nil } 

Node.js

安装

npm install @google/genai

如需了解详情,请参阅 SDK 参考文档

设置环境变量以将 Gen AI SDK 与 Vertex AI 搭配使用:

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values # with appropriate values for your project. export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT export GOOGLE_CLOUD_LOCATION=global export GOOGLE_GENAI_USE_VERTEXAI=True

const {GoogleGenAI} = require('@google/genai');  const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT; const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';  async function generateContent(   projectId = GOOGLE_CLOUD_PROJECT,   location = GOOGLE_CLOUD_LOCATION ) {   const ai = new GoogleGenAI({     vertexai: true,     project: projectId,     location: location,   });    const response = await ai.models.generateContent({     model: 'gemini-2.5-flash-preview-05-20',     contents:       'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.',     config: {       tools: [{codeExecution: {}}],       temperature: 0,     },   });    console.debug(response.executableCode);   console.debug(response.codeExecutionResult);    return response.codeExecutionResult; }

REST

在使用任何请求数据之前,请先进行以下替换:

  • GENERATE_RESPONSE_METHOD:您希望模型生成的回答类型。选择一种方法来生成您希望返回模型回答的方式:
    • streamGenerateContent:在生成回答时进行流式传输,以降低真人受众群体对于延迟的感知度。
    • generateContent:回答在完全生成后返回。
  • LOCATION:处理请求的区域。可用的选项包括:

    点击即可展开可用区域的部分列表

    • us-central1
    • us-west4
    • northamerica-northeast1
    • us-east4
    • us-west1
    • asia-northeast3
    • asia-southeast1
    • asia-northeast1
  • PROJECT_ID:您的项目 ID
  • MODEL_ID:您要使用的模型的模型 ID。
  • ROLE:与内容关联的对话中的角色。即使在单轮应用场景中,也需要指定角色。 可接受的值包括:
    • USER:指定由您发送的内容。
    • MODEL:指定模型的响应。
  • TEXT
    要包含在提示中的文本指令。

如需发送请求,请选择以下方式之一:

curl

将请求正文保存在名为 request.json 的文件中。在终端中运行以下命令,在当前目录中创建或覆盖此文件:

cat > request.json << 'EOF' {   "tools": [{'codeExecution': {}}],   "contents": {     "role": "ROLE",     "parts": { "text": "TEXT" }   }, } EOF

然后,执行以下命令以发送 REST 请求:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD"

PowerShell

将请求正文保存在名为 request.json 的文件中。在终端中运行以下命令,在当前目录中创建或覆盖此文件:

@' {   "tools": [{'codeExecution': {}}],   "contents": {     "role": "ROLE",     "parts": { "text": "TEXT" }   }, } '@  | Out-File -FilePath request.json -Encoding utf8

然后,执行以下命令以发送 REST 请求:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:GENERATE_RESPONSE_METHOD" | Select-Object -Expand Content

您应该收到类似以下内容的 JSON 响应。

在对话中使用代码执行

您还可以在对话中使用代码执行。

REST

curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://aiplatform.googleapis.com/v1/projects/test-project/locations/global/publishers/google/models/gemini-2.0-flash-001:generateContent -d \ $'{     "tools": [{'code_execution': {}}],     "contents": [       {         "role": "user",         "parts": {           "text": "Can you print \"Hello world!\"?"         }       },       {         "role": "model",         "parts": [           {             "text": ""           },           {             "executable_code": {               "language": "PYTHON",               "code": "\nprint(\"hello world!\")\n"             }           },           {             "code_execution_result": {               "outcome": "OUTCOME_OK",               "output": "hello world!\n"             }           },           {             "text": "I have printed \"hello world!\" using the provided python code block. \n"           }         ],       },       {         "role": "user",         "parts": {           "text": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50."         }       }     ]   }' 

代码执行与函数调用

代码执行和函数调用是两个类似的功能:

  • 通过代码执行,模型可以在固定隔离的环境的 API 后端中运行代码。
  • 通过函数调用,您可以在所需的任何环境中运行模型请求的函数。

通常,如果代码执行可以处理您的使用场景,您应优先使用代码执行。代码执行的使用更简单(只需启用即可),并且会在单个 GenerateContent 请求中进行解析。函数调用需要额外的 GenerateContent 请求才能将每次函数调用的输出结果发送回去。

在大多数情况下,如果您具有要在本地运行的自己的函数,则应使用函数调用;如果您希望 API 为您编写和运行 Python 代码并返回结果,则应使用代码执行。

结算

通过 Gemini API 启用代码执行不会产生额外的费用。系统会根据您使用的 Gemini 模型,按当前的输入和输出令牌费率向您收费。

以下是关于代码执行结算的一些其他注意事项:

  • 您只需为您传递给模型的输入 token 以及代码执行工具使用的中间输入 token 支付一次费用。
  • 您需要为 API 响应中返回给您的最终输出 token 支付费用。

针对代码执行工具使用情况的结算流程图,如以下文本所述。

  • 系统会根据您使用的 Gemini 模型,按当前的输入和输出令牌费率向您收费。
  • 如果 Gemini 在生成响应时使用代码执行,则原始提示、生成的代码以及执行的代码的结果会被标记为中间令牌,并按输入令牌计费。
  • 然后,Gemini 会生成摘要,并返回生成的代码、执行的代码的结果以及最终摘要。这些数据按输出令牌计费。
  • Gemini API 在 API 响应中包含中间 token 数,因此您可以跟踪除初始提示中传递的 token 之外的任何其他输入 token。

生成的代码可以包含文本和多模态输出(例如图片)。

限制

  • 模型只能生成和执行代码。它无法返回其他制品,例如媒体文件。
  • 代码执行工具不支持文件 URI 作为输入/输出。不过,代码执行工具支持以内嵌字节的形式输入文件和输出图表。利用这些输入和输出功能,您可以上传 CSV 和文本文件,询问有关这些文件的问题,并让系统生成 Matplotlib 图表作为代码执行结果的一部分显示出来。内嵌字节支持的 MIME 类型包括 .cpp.csv.java.jpeg.js.png.py.ts.xml
  • 代码执行最长可运行 30 秒,超出这一时间即会超时。
  • 在某些情况下,启用代码执行可能会导致模型输出的其他方面(例如,撰写故事)出现回归问题。