SPB Git forge

spb/doc-api

Public
2commits 1branches 0releases
15.7 MBsize
maindefault branch
13 days agolast push
Python 88.3% TypeScript 7.6% Shell 4.1%
5.0 KB · 72 lines markdown
Rendered Raw Blame History
1# Gemini — Code execution (`tools[].codeExecution`)23**Status:** DOCUMENTED + LIVE_VERIFIED (2026-09-18 run — see "Live verification" section at the end)45Sources:6- https://ai.google.dev/gemini-api/docs/generate-content/code-execution · https://ai.google.dev/gemini-api/docs/code-execution7- https://ai.google.dev/api/generate-content (#CodeExecution #ExecutableCode #Language #CodeExecutionResult #Outcome)8- https://ai.google.dev/gemini-api/docs/pricing · https://ai.google.dev/gemini-api/docs/tool-combination910Last verified: 2026-09-18 (docs only)1112## 1. Request1314`tools: [{"codeExecution": {}}]` — no fields. Interactions API: `{"type":"code_execution"}`. Input files: `part.inlineData` or `part.fileData` (Files API); best with text/CSV. Prompt explicitly for non-obvious uses ("write code to …").1516## 2. Response parts1718| Part | Fields | Notes |19|---|---|---|20| `executableCode` | `language: PYTHON` (only enum value besides UNSPECIFIED; "Python ≥3.10"), `code`, `id?` | generated code |21| `codeExecutionResult` | `outcome: OUTCOME_OK \| OUTCOME_FAILED \| OUTCOME_DEADLINE_EXCEEDED`, `output` (stdout / stderr), `id?` (matches executableCode.id) | result |22| `inlineData` | `mimeType: image/png`, `data` | matplotlib graphs / image manipulations (Gemini 3 Flash "code execution with images", requires thinking enabled) |23| `text` | | final summary |24| `thoughtSignature` | | on parts; echo in multi-turn history together with `id` (required for Gemini 3 tool combination) |2526Streaming (`streamGenerateContent`): parts arrive as produced. Chat/multi-turn: append the whole model content (code + result parts) to history.2728## 3. Limits2930| Limit | Value |31|---|---|32| Language | Python only (other languages can be generated, not run) |33| Runtime | 30 s per execution |34| Retries | up to 5 automatic regenerations on error |35| Libraries (fixed, no pip) | attrs, chess, contourpy, fpdf, geopandas, imageio, jinja2, joblib, jsonschema, jsonschema-specifications, lxml, matplotlib, mpmath, numpy, opencv-python, openpyxl, packaging, pandas, pillow, protobuf, pylatex, pyparsing, PyPDF2, python-dateutil, python-docx, python-pptx, reportlab, scikit-learn, scipy, seaborn, six, striprtf, sympy, tabulate, tensorflow, toolz, xlrd |36| Graphs | matplotlib only; returned as `inlineData` |37| Input size | bounded by the model context window (AI Studio: ~1M tokens ≈ 2 MB text) |38| Artifacts | cannot return media files other than images |39| Quality | may regress other outputs (e.g. creative writing); model-dependent reliability |40| Live API | not supported |4142## 4. Billing4344No fee. Input tokens: your prompt. Output tokens: generated code, execution output, thinking, summary. When the model re-reads prompt + code + results they are "intermediate" **input** tokens (reported in `usageMetadata`). Session runtime is not billed. Free tier: free.4546## 5. Models and combinations4748All current text models per model pages (Gemini 3.8/3.7/3.6/3.5 Flash, 3.5 Flash-Lite, 3.1 Pro Preview, 3.1 Flash-Lite, 3 Flash/Pro Preview, 2.5 Pro/Flash/Flash-Lite, robotics ER 2). Combinable with `googleSearch` (since 2025-05), with function calling on Gemini 3 (echo `id` + `thoughtSignature`), with structured outputs (Gemini 3). Not with `fileSearch`.4950## 6. Examples5152```bash53curl -s "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash-lite:generateContent" \54  -H "x-goog-api-key: $GEMINI_API_KEY" -H "Content-Type: application/json" \55  -d '{"contents":[{"parts":[{"text":"Sum of the first 50 integers, use code."}]}],"tools":[{"codeExecution":{}}]}'56```57```python58r = client.models.generate_content(model="gemini-3.5-flash-lite", contents="Sum of the first 50 integers, use code.",59      config=types.GenerateContentConfig(tools=[types.Tool(code_execution=types.ToolCodeExecution())]))60for p in r.candidates[0].content.parts:61    if p.executable_code: print(p.executable_code.code)62    if p.code_execution_result: print(p.code_execution_result.outcome, p.code_execution_result.output)63```64```ts65const r = await ai.models.generateContent({ model: 'gemini-3.5-flash-lite', contents: 'Sum of the first 50 integers, use code.',66  config: { tools: [{ codeExecution: {} }] } });67for (const p of r.candidates?.[0]?.content?.parts ?? []) { if (p.executableCode) console.log(p.executableCode.code); if (p.codeExecutionResult) console.log(p.codeExecutionResult.output); }68```6970## Live verification (2026-09-18)71**LIVE_VERIFIED** on `gemini-3.5-flash-lite` (`tmp-live/gemini-tools/d_code_execution.json`): `tools:[{"codeExecution":{}}]` + `"Run print(2+2) in Python and report the output."` → HTTP 200 with parts `[{executableCode:{language:"PYTHON", code:"print(2+2)", id:"call_348726"}, thoughtSignature}, {codeExecutionResult:{outcome:"OUTCOME_OK", output:"4\n", id:"call_348726"}}, {text:"4", thoughtSignature}]`. Note the `id` field on both parts (same value) — not shown in the guide. `usageMetadata.toolUsePromptTokenCount: 34`. Examples `examples/gemini/tools/code-execution/code_execution.{py,sh}` (both executed), test `tests/gemini/test_tools.py::test_code_execution_parts`.72