UniterRouter
API 参考Google 兼容

代码执行

Gemini 代码执行 API - 让 Gemini 2.0 编写并运行 Python 代码。解决数学、数据分析和复杂问题,AI 生成可执行代码。

代码执行

Gemini 可以在沙箱环境中生成并执行 Python 代码。这对于数学计算、数据分析以及受益于程序化解决方案的任务非常有用。

支持的模型: 代码执行在 Gemini 1.5+ 模型上可用。

工作原理

  1. 启用代码执行工具
  2. 模型编写 Python 代码来解决您的问题
  3. 代码在安全沙箱中执行
  4. 结果在响应中返回

启用代码执行

curl -X POST "https://api.uniterouter.ai/v1beta/models/gemini-2.0-flash:generateContent" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $UNITEROUTER_API_KEY" \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [{"text": "计算前20个斐波那契数"}]
      }
    ],
    "tools": [
      {
        "codeExecution": {}
      }
    ]
  }'
import google.generativeai as genai

genai.configure(
    api_key="your_uniterouter_api_key",
    transport="rest",
    client_options={"api_endpoint": "api.uniterouter.ai"}
)

model = genai.GenerativeModel(
    "gemini-2.0-flash",
    tools=["code_execution"]
)

response = model.generate_content(
    "计算前20个斐波那契数"
)

# 打印所有部分,包括代码和输出
for part in response.candidates[0].content.parts:
    if hasattr(part, 'executable_code'):
        print("代码:")
        print(part.executable_code.code)
    elif hasattr(part, 'code_execution_result'):
        print("输出:")
        print(part.code_execution_result.output)
    else:
        print("文本:", part.text)
import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI("your_uniterouter_api_key", {
  baseUrl: "https://api.uniterouter.ai"
});

const model = genAI.getGenerativeModel({
  model: "gemini-2.0-flash",
  tools: [{ codeExecution: {} }]
});

const result = await model.generateContent(
  "计算前20个斐波那契数"
);

console.log(result.response.text());

响应格式

{
  "candidates": [{
    "content": {
      "parts": [
        {
          "text": "我将使用 Python 来计算斐波那契数列:"
        },
        {
          "executableCode": {
            "language": "PYTHON",
            "code": "def fibonacci(n):\n    fib = [0, 1]\n    for i in range(2, n):\n        fib.append(fib[-1] + fib[-2])\n    return fib[:n]\n\nprint(fibonacci(20))"
          }
        },
        {
          "codeExecutionResult": {
            "outcome": "OUTCOME_OK",
            "output": "[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]"
          }
        },
        {
          "text": "前20个斐波那契数是: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181"
        }
      ],
      "role": "model"
    }
  }]
}

可用库

沙箱包含常用的 Python 库:

类别库
数学numpy, scipy, sympy
数据pandas
可视化matplotlib(保存为图像)
标准库math, datetime, collections, itertools

使用场景

使用场景示例
数学"解方程 x^2 - 5x + 6 = 0"
统计"计算 [数据] 的均值和标准差"
数据处理"解析这个 CSV 并找出平均值"
算法"实现快速排序并对这个列表排序"
转换"将100英里转换为公里"

与其他工具结合

代码执行可以与函数调用结合:

model = genai.GenerativeModel(
    "gemini-2.0-flash",
    tools=[
        "code_execution",
        {
            "function_declarations": [
                {
                    "name": "get_stock_price",
                    "description": "获取当前股票价格",
                    "parameters": {...}
                }
            ]
        }
    ]
)

执行结果

结果描述
OUTCOME_OK代码执行成功
OUTCOME_FAILED代码执行失败
OUTCOME_DEADLINE_EXCEEDED执行超时

限制

  • 超时: 最大执行时间 30 秒
  • 内存: 有限的内存分配
  • 网络: 无网络访问
  • 文件系统: 无持久文件系统
  • 部分库: 并非所有 Python 库都可用

最佳实践

  1. 清晰的提示 - 描述您想要计算的内容
  2. 提供数据 - 在提示中包含要处理的数据
  3. 迭代 - 如果第一次尝试失败,模型可以改进代码
  4. 组合工具 - 与函数调用结合实现复杂工作流

相关文档

How is this guide?