借助 Gemini API 代码执行功能,模型可以生成和运行 Python 代码,并根据结果迭代学习,直到得出最终输出。您可以使用此代码执行功能来构建可从基于代码的推理中受益并生成文本输出的应用。例如,您可以在用于解题或处理文本的应用中使用代码执行功能。
代码执行功能可在 AI Studio 和 Gemini API 中使用。在 AI Studio 中,您可以在右侧面板的工具下方启用代码执行。Gemini API 提供代码执行作为工具,类似于函数调用。将代码执行添加为工具后,模型会决定何时使用它。
代码执行环境包含以下库:altair
、chess
、cv2
、matplotlib
、mpmath
、numpy
、pandas
、pdfminer
、reportlab
、seaborn
、sklearn
、statsmodels
、striprtf
、sympy
和 tabulate
。您无法安装自己的库。
代码执行入门
您还可以使用代码执行笔记本:
本部分假定您已完成快速入门中显示的设置和配置步骤。
在模型上启用代码执行
您可以启用对模型的代码执行,如下所示:
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY ")
response = client.models.generate_content(
model='gemini-2.0-flash',
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=types.GenerateContentConfig(
tools=[types.Tool(
code_execution=types.ToolCodeExecution
)]
)
)
在笔记本中,您可以使用以下辅助函数以 Markdown 格式显示所有内容:
def display_code_execution_result(response):
for part in response.candidates[0].content.parts:
if part.text is not None:
display(Markdown(part.text))
if part.executable_code is not None:
code_html = f'<pre style="background-color: #BBBBEE;">{part.executable_code.code}</pre>' # Change code color
display(HTML(code_html))
if part.code_execution_result is not None:
display(Markdown(part.code_execution_result.output))
if part.inline_data is not None:
display(Image(data=part.inline_data.data, format="png"))
display(Markdown("---"))
display_code_execution_result(response)
输出可能如下所示:
好的,我需要计算前 50 个素数的和。我将使用 Python 脚本生成前 50 个质数,然后对它们进行求和。
```python def is_prime(n): """Checks if a number is prime.""" if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def sum_of_primes(n): """Calculates the sum of the first n prime numbers.""" primes = [] i = 2 while len(primes) < n: if is_prime(i): primes.append(i) i += 1 return sum(primes) # Calculate the sum of the first 50 prime numbers sum_of_first_50_primes = sum_of_primes(50) print(f"The sum of the first 50 prime numbers is: {sum_of_first_50_primes}") ``` **Output:** ``` The sum of the first 50 prime numbers is: 5117 ```
在聊天中使用代码执行
您还可以在聊天过程中使用代码执行功能。
from google import genai
from google.genai import types
client = genai.Client(api_key="GEMINI_API_KEY ")
chat = client.chats.create(
model='gemini-2.0-flash',
config=types.GenerateContentConfig(
tools=[types.Tool(
code_execution=types.ToolCodeExecution
)]
)
)
response = chat.send_message("Can you run some code to bogo-sort this list of numbers?: [2,34,1,65,4]")
display_code_execution_result(response)
对话可能会这样继续:
我了解到,您想让我对列表 [2, 34, 1, 65, 4] 进行 Bogo 排序。Bogo 排序是一种效率极低的排序算法。其工作原理是反复洗牌列表,直到列表恰好排序为止。由于其性能极差,因此不适用于任何大规模的列表。
不过,出于演示目的,我可以运行一个简化版本,并进行非常有限的迭代,以便展示该过程。我可以继续吗?
response = chat.send_message("Yes, please create the code.")
display_code_execution_result(response)
好的,我将继续使用一个函数来打乱列表并检查它是否已排序。我将最多运行 10 次迭代。…
输入/输出 (I/O)
从 Gemini 2.0 Flash 开始,代码执行支持文件输入和图表输出。借助这些新的输入和输出功能,您可以上传 CSV 和文本文件、询问与文件相关的问题,并在回答中生成 Matplotlib 图表。
I/O 价格
使用代码执行 I/O 时,您需要为输入令牌和输出令牌支付费用:
输入令牌:
- 用户提示
输出令牌:
- 模型生成的代码
- 代码环境中的代码执行输出
- 模型生成的摘要
I/O 详情
使用代码执行 I/O 时,请注意以下技术细节:
- 代码环境的运行时长上限为 30 秒。
- 如果代码环境生成错误,模型可能会决定重新生成代码输出。最多可以重试 5 次。
- 文件输入大小上限受模型令牌窗口的限制。在 AI Studio 中,使用 Gemini Flash 2.0 时,输入文件大小上限为 100 万个令牌(对于支持的输入类型的文本文件,大约为 2MB)。如果您上传的文件过大,AI Studio 将不允许您发送。
单轮 | 双向(Multimodal Live API) | |
---|---|---|
支持的模型 | 所有 Gemini 2.0 模型 | 仅限 Flash 实验性模型 |
支持的文件输入类型 | .png、.jpeg、.csv、.xml、.cpp、.java、.py、.js、.ts | .png、.jpeg、.csv、.xml、.cpp、.java、.py、.js、.ts |
支持的绘图库 | Matplotlib | Matplotlib |
多工具使用 | 否 | 是 |
结算
通过 Gemini API 启用代码执行不会产生额外费用。系统会根据您使用的 Gemini 模型,按当前的输入和输出令牌费率向您收费。
以下是关于代码执行结算的一些其他注意事项:
- 系统只会针对您传递给模型的输入令牌收费一次,并针对模型返回给您的最终输出令牌收费。
- 代表生成的代码的令牌会计为输出令牌。生成的代码可以包含文本和多模态输出(例如图片)。
- 代码执行结果也会计为输出令牌。
结算模型如下图所示:
- 系统会根据您使用的 Gemini 模型,按当前的输入和输出令牌费率向您收费。
- 如果 Gemini 在生成响应时使用代码执行,则原始提示、生成的代码以及执行的代码的结果会被标记为中间令牌,并按输入令牌计费。
- 然后,Gemini 会生成摘要,并返回生成的代码、执行的代码的结果和最终摘要。这些数据按输出令牌计费。
- Gemini API 会在 API 响应中包含中间令牌数,以便您了解为何会在初始提示之外收到其他输入令牌。
限制
- 该模型只能生成和执行代码。它无法返回媒体文件等其他工件。
- 在某些情况下,启用代码执行可能会导致模型输出的其他方面(例如撰写故事)出现回归问题。
- 不同模型成功使用代码执行功能的能力有所不同。