Gemini API, कोड को चलाने वाला एक टूल उपलब्ध कराता है. इसकी मदद से, मॉडल Python कोड जनरेट और रन कर सकता है. इसके बाद, मॉडल कोड को चलाने के नतीजों से बार-बार सीख सकता है. यह प्रोसेस तब तक चलती है, जब तक मॉडल को फ़ाइनल आउटपुट नहीं मिल जाता. कोड को चलाने की सुविधा का इस्तेमाल करके, ऐसे ऐप्लिकेशन बनाए जा सकते हैं जिनमें कोड के आधार पर तर्क करने की सुविधा होती है. उदाहरण के लिए, कोड को चलाने की सुविधा का इस्तेमाल करके, समीकरण हल किए जा सकते हैं या टेक्स्ट को प्रोसेस किया जा सकता है. इसके अलावा, कोड को चलाने के एनवायरमेंट में शामिल लाइब्रेरी का इस्तेमाल करके, ज़्यादा खास टास्क पूरे किए जा सकते हैं.
Gemini, सिर्फ़ Python में कोड चला सकता है. आपके पास Gemini से किसी दूसरी भाषा में कोड जनरेट करने के लिए कहने का विकल्प है. हालांकि, मॉडल इसे रन करने के लिए, कोड को चलाने वाले टूल का इस्तेमाल नहीं कर सकता.
कोड को चलाने की सुविधा चालू करना
कोड को चलाने की सुविधा चालू करने के लिए, मॉडल पर कोड को चलाने वाले टूल को कॉन्फ़िगर करें. इससे मॉडल, कोड जनरेट और रन कर सकता है.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-3-flash-preview",
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)]
),
)
for part in response.candidates[0].content.parts:
if part.text is not None:
print(part.text)
if part.executable_code is not None:
print(part.executable_code.code)
if part.code_execution_result is not None:
print(part.code_execution_result.output)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
let response = await ai.models.generateContent({
model: "gemini-3-flash-preview",
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: {} }],
},
});
const parts = response?.candidates?.[0]?.content?.parts || [];
parts.forEach((part) => {
if (part.text) {
console.log(part.text);
}
if (part.executableCode && part.executableCode.code) {
console.log(part.executableCode.code);
}
if (part.codeExecutionResult && part.codeExecutionResult.output) {
console.log(part.codeExecutionResult.output);
}
});
ऐप पर जाएं
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
config := &genai.GenerateContentConfig{
Tools: []*genai.Tool{
{CodeExecution: &genai.ToolCodeExecution{}},
},
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-3-flash-preview",
genai.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."),
config,
)
fmt.Println(result.Text())
fmt.Println(result.ExecutableCode())
fmt.Println(result.CodeExecutionResult())
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d ' {"tools": [{"code_execution": {}}],
"contents": {
"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."
}
},
}'
आउटपुट कुछ इस तरह दिख सकता है. इसे पढ़ने में आसानी के लिए फ़ॉर्मैट किया गया है:
Okay, I need to calculate the sum of the first 50 prime numbers. Here's how I'll
approach this:
1. **Generate Prime Numbers:** I'll use an iterative method to find prime
numbers. I'll start with 2 and check if each subsequent number is divisible
by any number between 2 and its square root. If not, it's a prime.
2. **Store Primes:** I'll store the prime numbers in a list until I have 50 of
them.
3. **Calculate the Sum:** Finally, I'll sum the prime numbers in the list.
Here's the Python code to do this:
def is_prime(n):
"""Efficiently checks if a number is prime."""
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i += 6
return True
primes = []
num = 2
while len(primes) < 50:
if is_prime(num):
primes.append(num)
num += 1
sum_of_primes = sum(primes)
print(f'{primes=}')
print(f'{sum_of_primes=}')
primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,
71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229]
sum_of_primes=5117
The sum of the first 50 prime numbers is 5117.
इस आउटपुट में, कॉन्टेंट के कई ऐसे हिस्से शामिल हैं जो कोड को चलाने की सुविधा का इस्तेमाल करते समय, मॉडल दिखाता है:
text: मॉडल से जनरेट किया गया इनलाइन टेक्स्टexecutableCode: मॉडल से जनरेट किया गया कोड, जिसे रन किया जाना हैcodeExecutionResult: रन किए जा सकने वाले कोड का नतीजा
इन हिस्सों के लिए, नाम रखने के नियम प्रोग्रामिंग भाषा के हिसाब से अलग-अलग होते हैं.
इमेज के साथ कोड को चलाने की सुविधा (Gemini 3)
Gemini 3 Flash मॉडल, अब Python कोड लिख और रन कर सकता है. इससे इमेज में बदलाव किया जा सकता है और उनकी जांच की जा सकती है.
इस्तेमाल के उदाहरण
- ज़ूम करना और जांच करना: मॉडल, इस बात का पता लगा लेता है कि कब कोई जानकारी बहुत छोटी है उदाहरण के लिए, दूर से किसी गेज को पढ़ना. इसके बाद, मॉडल कोड लिखकर, उस हिस्से को क्रॉप करता है और ज़्यादा रिज़ॉल्यूशन पर उसकी फिर से जांच करता है.
- विज़ुअल मैथ: मॉडल, कोड का इस्तेमाल करके, कई चरणों वाली कैलकुलेशन कर सकता है. उदाहरण के लिए, रसीद पर मौजूद लाइन आइटम को जोड़ना.
- इमेज में एनोटेशन जोड़ना: मॉडल, सवालों के जवाब देने के लिए इमेज में एनोटेशन जोड़ सकता है. जैसे रिलेशनशिप दिखाने के लिए तीर के निशान बनाना.
इमेज के साथ कोड को चलाने की सुविधा चालू करना
Gemini 3 Flash में, इमेज के साथ कोड को चलाने की सुविधा आधिकारिक तौर पर उपलब्ध है. इस सुविधा को चालू करने के लिए, आपको कोड को चलाने की सुविधा और सूझ-बूझ से जवाब तैयार करने की सुविधा, दोनों को चालू करना होगा.
Python
from google import genai
from google.genai import types
import requests
from PIL import Image
import io
image_path = "https://goo.gle/instrument-img"
image_bytes = requests.get(image_path).content
image = types.Part.from_bytes(
data=image_bytes, mime_type="image/jpeg"
)
# Ensure you have your API key set
client = genai.Client()
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents=[image, "Zoom into the expression pedals and tell me how many pedals are there?"],
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution)]
),
)
for part in response.candidates[0].content.parts:
if part.text is not None:
print(part.text)
if part.executable_code is not None:
print(part.executable_code.code)
if part.code_execution_result is not None:
print(part.code_execution_result.output)
if part.as_image() is not None:
# display() is a standard function in Jupyter/Colab notebooks
display(Image.open(io.BytesIO(part.as_image().image_bytes)))
JavaScript
async function main() {
const ai = new GoogleGenAI({ });
// 1. Prepare Image Data
const imageUrl = "https://goo.gle/instrument-img";
const response = await fetch(imageUrl);
const imageArrayBuffer = await response.arrayBuffer();
const base64ImageData = Buffer.from(imageArrayBuffer).toString('base64');
// 2. Call the API with Code Execution enabled
const result = await ai.models.generateContent({
model: "gemini-3-flash-preview",
contents: [
{
inlineData: {
mimeType: 'image/jpeg',
data: base64ImageData,
},
},
{ text: "Zoom into the expression pedals and tell me how many pedals are there?" }
],
config: {
tools: [{ codeExecution: {} }],
},
});
// 3. Process the response (Text, Code, and Execution Results)
const candidates = result.candidates;
if (candidates && candidates[0].content.parts) {
for (const part of candidates[0].content.parts) {
if (part.text) {
console.log("Text:", part.text);
}
if (part.executableCode) {
console.log(`\nGenerated Code (${part.executableCode.language}):\n`, part.executableCode.code);
}
if (part.codeExecutionResult) {
console.log(`\nExecution Output (${part.codeExecutionResult.outcome}):\n`, part.codeExecutionResult.output);
}
}
}
}
main();
ऐप पर जाएं
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
// Initialize Client (Reads GEMINI_API_KEY from env)
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
// 1. Download the image
imageResp, err := http.Get("https://goo.gle/instrument-img")
if err != nil {
log.Fatal(err)
}
defer imageResp.Body.Close()
imageBytes, err := io.ReadAll(imageResp.Body)
if err != nil {
log.Fatal(err)
}
// 2. Configure Code Execution Tool
config := &genai.GenerateContentConfig{
Tools: []*genai.Tool{
{CodeExecution: &genai.ToolCodeExecution{}},
},
}
// 3. Generate Content
result, err := client.Models.GenerateContent(
ctx,
"gemini-3-flash-preview",
[]*genai.Content{
{
Parts: []*genai.Part{
{InlineData: &genai.Blob{MIMEType: "image/jpeg", Data: imageBytes}},
{Text: "Zoom into the expression pedals and tell me how many pedals are there?"},
},
Role: "user",
},
},
config,
)
if err != nil {
log.Fatal(err)
}
// 4. Parse Response (Text, Code, Output)
for _, cand := range result.Candidates {
for _, part := range cand.Content.Parts {
if part.Text != "" {
fmt.Println("Text:", part.Text)
}
if part.ExecutableCode != nil {
fmt.Printf("\nGenerated Code (%s):\n%s\n",
part.ExecutableCode.Language,
part.ExecutableCode.Code)
}
if part.CodeExecutionResult != nil {
fmt.Printf("\nExecution Output (%s):\n%s\n",
part.CodeExecutionResult.Outcome,
part.CodeExecutionResult.Output)
}
}
}
}
REST
IMG_URL="https://goo.gle/instrument-img"
MODEL="gemini-3-flash-preview"
MIME_TYPE=$(curl -sIL "$IMG_URL" | grep -i '^content-type:' | awk -F ': ' '{print $2}' | sed 's/\r$//' | head -n 1)
if [[ -z "$MIME_TYPE" || ! "$MIME_TYPE" == image/* ]]; then
MIME_TYPE="image/jpeg"
fi
if [[ "$(uname)" == "Darwin" ]]; then
IMAGE_B64=$(curl -sL "$IMG_URL" | base64 -b 0)
elif [[ "$(base64 --version 2>&1)" = *"FreeBSD"* ]]; then
IMAGE_B64=$(curl -sL "$IMG_URL" | base64)
else
IMAGE_B64=$(curl -sL "$IMG_URL" | base64 -w0)
fi
curl "https://generativelanguage.googleapis.com/v1beta/models/$MODEL:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{
"inline_data": {
"mime_type":"'"$MIME_TYPE"'",
"data": "'"$IMAGE_B64"'"
}
},
{"text": "Zoom into the expression pedals and tell me how many pedals are there?"}
]
}],
"tools": [
{
"code_execution": {}
}
]
}'
चैट में कोड को चलाने की सुविधा का इस्तेमाल करना
चैट के दौरान भी, कोड को चलाने की सुविधा का इस्तेमाल किया जा सकता है.
Python
from google import genai
from google.genai import types
client = genai.Client()
chat = client.chats.create(
model="gemini-3-flash-preview",
config=types.GenerateContentConfig(
tools=[types.Tool(code_execution=types.ToolCodeExecution)]
),
)
response = chat.send_message("I have a math question for you.")
print(response.text)
response = chat.send_message(
"What is the sum of the first 50 prime numbers? "
"Generate and run code for the calculation, and make sure you get all 50."
)
for part in response.candidates[0].content.parts:
if part.text is not None:
print(part.text)
if part.executable_code is not None:
print(part.executable_code.code)
if part.code_execution_result is not None:
print(part.code_execution_result.output)
JavaScript
import {GoogleGenAI} from "@google/genai";
const ai = new GoogleGenAI({});
const chat = ai.chats.create({
model: "gemini-3-flash-preview",
history: [
{
role: "user",
parts: [{ text: "I have a math question for you:" }],
},
{
role: "model",
parts: [{ text: "Great! I'm ready for your math question. Please ask away." }],
},
],
config: {
tools: [{codeExecution:{}}],
}
});
const response = await chat.sendMessage({
message: "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50."
});
console.log("Chat response:", response.text);
ऐप पर जाएं
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
config := &genai.GenerateContentConfig{
Tools: []*genai.Tool{
{CodeExecution: &genai.ToolCodeExecution{}},
},
}
chat, _ := client.Chats.Create(
ctx,
"gemini-3-flash-preview",
config,
nil,
)
result, _ := chat.SendMessage(
ctx,
genai.Part{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.",
},
)
fmt.Println(result.Text())
fmt.Println(result.ExecutableCode())
fmt.Println(result.CodeExecutionResult())
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"tools": [{"code_execution": {}}],
"contents": [
{
"role": "user",
"parts": [{
"text": "Write code to print \"Hello world!\" and execute it"
}]
},{
"role": "model",
"parts": [
{
"executable_code": {
"id": "a1b2c3d4",
"language": "PYTHON",
"code": "\nprint(\"hello world!\")\n"
}
"thought_signature": "..."
},
{
"code_execution_result": {
"id": "a1b2c3d4",
"outcome": "OUTCOME_OK",
"output": "hello world!\n"
}
},
{
"text": "I have printed \"hello world!\" using the provided python code block. \n",
"thought_signature": "..."
}
],
},{
"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."
}]
}
]
}'
इनपुट/आउटपुट (I/O)
कोड को चलाने की सुविधा में, फ़ाइल इनपुट और ग्राफ़ आउटपुट की सुविधा उपलब्ध है. इनपुट और आउटपुट की इन सुविधाओं का इस्तेमाल करके, CSV और टेक्स्ट फ़ाइलें अपलोड की जा सकती हैं. साथ ही, इन फ़ाइलों के बारे में सवाल पूछे जा सकते हैं. इसके अलावा, रिस्पॉन्स के तौर पर, Matplotlib ग्राफ़ जनरेट किए जा सकते हैं. आउटपुट फ़ाइलें, रिस्पॉन्स में इनलाइन इमेज के तौर पर दिखती हैं.
I/O की कीमत
कोड को चलाने की सुविधा के I/O का इस्तेमाल करने पर, आपसे इनपुट टोकन और आउटपुट टोकन के लिए शुल्क लिया जाता है:
इनपुट टोकन:
- उपयोगकर्ता का प्रॉम्प्ट
आउटपुट टोकन:
- मॉडल से जनरेट किया गया कोड
- कोड एनवायरमेंट में, कोड को चलाने का आउटपुट
- सूझ-बूझ से जवाब तैयार करने के टोकन
- मॉडल से जनरेट की गई खास जानकारी
I/O की जानकारी
कोड को चलाने की सुविधा के I/O का इस्तेमाल करते समय, इन तकनीकी पहलुओं का ध्यान रखें:
- कोड एनवायरमेंट का ज़्यादा से ज़्यादा रनटाइम 30 सेकंड है.
- अगर कोड एनवायरमेंट में कोई गड़बड़ी होती है, तो मॉडल, कोड आउटपुट को फिर से जनरेट कर सकता है. ऐसा ज़्यादा से ज़्यादा पांच बार हो सकता है.
- फ़ाइल इनपुट का ज़्यादा से ज़्यादा साइज़, मॉडल टोकन विंडो से तय होता है. AI Studio में, इनपुट फ़ाइल का ज़्यादा से ज़्यादा साइज़ 10 लाख टोकन है. यह, सहायता वाले इनपुट टाइप की टेक्स्ट फ़ाइलों के लिए, करीब 2 एमबी है. अगर कोई बहुत बड़ी फ़ाइल अपलोड की जाती है, तो AI Studio उसे भेजने की अनुमति नहीं देगा.
- कोड को चलाने की सुविधा, टेक्स्ट और CSV फ़ाइलों के साथ सबसे अच्छी तरह काम करती है.
- इनपुट फ़ाइल को
part.inlineDataयाpart.fileDataमें पास किया जा सकता है. इसे Files API के ज़रिए अपलोड किया जाता है. वहीं, आउटपुट फ़ाइल हमेशाpart.inlineDataके तौर पर दिखती है.
बिलिंग
Gemini API से कोड को चलाने की सुविधा चालू करने के लिए, कोई अतिरिक्त शुल्क नहीं लिया जाता. जिस Gemini मॉडल का इस्तेमाल किया जा रहा है उसके आधार पर, आपसे इनपुट और आउटपुट टोकन की मौजूदा दर के हिसाब से शुल्क लिया जाएगा.
कोड को चलाने की सुविधा के लिए बिलिंग के बारे में कुछ अन्य बातें:
- मॉडल को पास किए गए इनपुट टोकन के लिए, आपसे सिर्फ़ एक बार शुल्क लिया जाता है. वहीं, मॉडल से मिले फ़ाइनल आउटपुट टोकन के लिए, आपसे शुल्क लिया जाता है.
- जनरेट किए गए कोड को दिखाने वाले टोकन, आउटपुट टोकन के तौर पर गिने जाते हैं. जनरेट किए गए कोड में, टेक्स्ट और मल्टीमॉडल आउटपुट शामिल हो सकता है. जैसे, इमेज.
- कोड को चलाने के नतीजों को भी आउटपुट टोकन के तौर पर गिना जाता है.
बिलिंग मॉडल को इस डायग्राम में दिखाया गया है:

- जिस Gemini मॉडल का इस्तेमाल किया जा रहा है उसके आधार पर, आपसे इनपुट और आउटपुट टोकन की मौजूदा दर के हिसाब से शुल्क लिया जाएगा.
- अगर Gemini, आपका रिस्पॉन्स जनरेट करते समय, कोड को चलाने की सुविधा का इस्तेमाल करता है, तो ओरिजनल प्रॉम्प्ट, जनरेट किया गया कोड, और रन किए गए कोड का नतीजा इंटरमीडिएट टोकन के तौर पर लेबल किया जाता है. साथ ही, इनके लिए इनपुट टोकन के तौर पर शुल्क लिया जाता है.
- इसके बाद, Gemini एक खास जानकारी जनरेट करता है. साथ ही, जनरेट किया गया कोड, रन किए गए कोड का नतीजा, और फ़ाइनल खास जानकारी दिखाता है. इनके लिए आउटपुट टोकन के तौर पर शुल्क लिया जाता है.
- Gemini API, एपीआई रिस्पॉन्स में इंटरमीडिएट टोकन की संख्या शामिल करता है. इससे आपको पता चलता है कि शुरुआती प्रॉम्प्ट के अलावा, आपसे अतिरिक्त इनपुट टोकन के लिए शुल्क क्यों लिया जा रहा है.
सीमाएं
- मॉडल, सिर्फ़ कोड जनरेट और रन कर सकता है. यह मीडिया फ़ाइलों जैसे अन्य आर्टफ़ैक्ट नहीं दिखा सकता.
- कुछ मामलों में, कोड को चलाने की सुविधा चालू करने से, मॉडल के आउटपुट के अन्य हिस्सों में गड़बड़ियां हो सकती हैं. उदाहरण के लिए, कहानी लिखना.
- अलग-अलग मॉडल, कोड को चलाने की सुविधा का इस्तेमाल अलग-अलग तरीके से कर सकते हैं.
टूल के ऐसे कॉम्बिनेशन जिन्हें इस्तेमाल किया जा सकता है
कोड को चलाने वाले टूल को, Google Search की मदद से ज़्यादा जानकारी पाने की सुविधा के साथ जोड़ा जा सकता है. इससे ज़्यादा मुश्किल इस्तेमाल के उदाहरणों को पूरा किया जा सकता है.
Gemini 3 मॉडल, बिल्ट-इन टूल (जैसे, कोड को चलाने की सुविधा) को कस्टम टूल (फ़ंक्शन कॉल) के साथ जोड़ने की सुविधा देते हैं. टूल के कॉम्बिनेशन के लिए, आपको id और thought_signature फ़ील्ड वापस भेजने होंगे. टूल के कॉम्बिनेशन वाले पेज पर ज़्यादा जानें.
इस्तेमाल की जा सकने वाली लाइब्रेरी
कोड को चलाने के एनवायरमेंट में ये लाइब्रेरी शामिल हैं:
- 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
आपके पास अपनी लाइब्रेरी इंस्टॉल करने का विकल्प नहीं होता.
आगे क्या करना है
- कोड को चलाने की सुविधा वाले Colab को आज़माएं.
- Gemini API के अन्य टूल के बारे में जानें: