Ekzekutimi i kodit

API-ja Gemini ofron një mjet ekzekutimi kodi që i mundëson modelit të gjenerojë dhe ekzekutojë kod Python. Modeli më pas mund të mësojë në mënyrë iterative nga rezultatet e ekzekutimit të kodit derisa të arrijë në një rezultat përfundimtar. Ju mund të përdorni ekzekutimin e kodit për të ndërtuar aplikacione që përfitojnë nga arsyetimi i bazuar në kod. Për shembull, ju mund të përdorni ekzekutimin e kodit për të zgjidhur ekuacione ose për të përpunuar tekst. Ju gjithashtu mund të përdorni libraritë e përfshira në mjedisin e ekzekutimit të kodit për të kryer detyra më të specializuara.

Gemini është në gjendje të ekzekutojë kod vetëm në Python. Ju prapë mund t'i kërkoni Gemini-t të gjenerojë kod në një gjuhë tjetër, por modeli nuk mund ta përdorë mjetin e ekzekutimit të kodit për ta ekzekutuar atë.

Aktivizo ekzekutimin e kodit

Për të aktivizuar ekzekutimin e kodit, konfiguroni mjetin e ekzekutimit të kodit në model. Kjo i lejon modelit të gjenerojë dhe ekzekutojë kod.

Python

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input="What is the sum of the first 50 prime numbers? "
          "Generate and run code for the calculation, and make sure you get all 50.",
    tools=[{"type": "code_execution"}]
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
    elif step.type == "code_execution_call":
        print(step.arguments.code)
    elif step.type == "code_execution_result":
        print(step.result)

JavaScript

import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

const interaction = await client.interactions.create({
    model: "gemini-3-flash-preview",
    input: "What is the sum of the first 50 prime numbers? " +
           "Generate and run code for the calculation, and make sure you get all 50.",
    tools: [{ type: "code_execution" }]
});

for (const step of interaction.steps) {
    if (step.type === "model_output") {
        for (const contentBlock of step.content) {
            if (contentBlock.type === "text") {
                console.log(contentBlock.text);
            }
        }
    } else if (step.type === "code_execution_call") {
        console.log(step.arguments.code);
    } else if (step.type === "code_execution_result") {
        console.log(step.result);
    }
}

PUSHTIM

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.",
    "tools": [{"type": "code_execution"}]
}'

Rezultati mund të duket diçka si më poshtë, i cili është formatuar për lexueshmëri:

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.

Ky rezultat kombinon disa pjesë përmbajtjeje që modeli i kthen kur përdor ekzekutimin e kodit:

  • text : Tekst i brendshëm i gjeneruar nga modeli
  • code_execution_call : Kodi i gjeneruar nga modeli që është menduar të ekzekutohet
  • code_execution_result : Rezultati i kodit të ekzekutueshëm

Ekzekutimi i Kodit me imazhe (Binjakët 3)

Modeli Gemini 3 Flash tani mund të shkruajë dhe ekzekutojë kod Python për të manipuluar dhe inspektuar në mënyrë aktive imazhet.

Rastet e përdorimit

  • Zmadhoni dhe inspektoni : Modeli zbulon në mënyrë implicite kur detajet janë shumë të vogla (p.sh., duke lexuar një matës në distancë) dhe shkruan kod për ta prerë dhe rishqyrtuar zonën me rezolucion më të lartë.
  • Matematikë vizuale : Modeli mund të kryejë llogaritje me shumë hapa duke përdorur kod (p.sh., duke mbledhur artikujt e rreshtit në një faturë).
  • Shënimi i imazhit : Modeli mund të shënojë imazhe për t'iu përgjigjur pyetjeve, siç është vizatimi i shigjetave për të treguar marrëdhëniet.

Aktivizo Ekzekutimin e Kodit me imazhe

Ekzekutimi i Kodit me imazhe mbështetet zyrtarisht në Gemini 3 Flash. Mund ta aktivizoni këtë sjellje duke aktivizuar si Ekzekutimin e Kodit si mjet ashtu edhe Të Menduarit.

Python

from google import genai
import requests
import base64
from PIL import Image
import io

image_path = "https://goo.gle/instrument-img"
image_bytes = requests.get(image_path).content

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview",
    input=[
        {"type": "image", "data": base64.b64encode(image_bytes).decode('utf-8'), "mime_type": "image/jpeg"},
        {"type": "text", "text": "Zoom into the expression pedals and tell me how many pedals are there?"}
    ],
    tools=[{"type": "code_execution"}]
)

for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
            elif content_block.type == "image":
                # Display generated image
                display(Image.open(io.BytesIO(base64.b64decode(content_block.data))))
    elif step.type == "code_execution_call":
        print(step.arguments.code)
    elif step.type == "code_execution_result":
        print(step.result)

JavaScript

async function main() {
  const client = 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 interaction = await client.interactions.create({
    model: "gemini-3-flash-preview",
    input: [
      {
        type: "image",
        data: base64ImageData,
        mimeType: "image/jpeg"
      },
      { type: "text", text: "Zoom into the expression pedals and tell me how many pedals are there?" }
    ],
    tools: [{ type: "code_execution" }]
  });

  // 3. Process the response (Text, Code, and Execution Results)
  for (const step of interaction.steps) {
    if (step.type === "model_output") {
      for (const contentBlock of step.content) {
        if (contentBlock.type === "text") {
          console.log("Text:", contentBlock.text);
        }
      }
    } else if (step.type === "code_execution_call") {
      console.log(`\nGenerated Code:\n`, step.arguments.code);
    } else if (step.type === "code_execution_result") {
      console.log(`\nExecution Output:\n`, step.result);
    }
  }
}

main();

PUSHTIM

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 -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "gemini-3-flash-preview",
      "input": [
        {
          "type": "image",
          "data": "'"$IMAGE_B64"'",
          "mime_type": "'"$MIME_TYPE"'"
        },
        {"type": "text", "text": "Zoom into the expression pedals and tell me how many pedals are there?"}
      ],
      "tools": [{"type": "code_execution"}]
    }'

Përdorni ekzekutimin e kodit në ndërveprimet me shumë kthesa

Mund të përdorni gjithashtu ekzekutimin e kodit si pjesë të një bisede me shumë kthesa duke përdorur previous_interaction_id .

Python

from google import genai

client = genai.Client()

# First turn
interaction1 = client.interactions.create(
    model="gemini-3-flash-preview",
    input="I have a math question for you.",
    tools=[{"type": "code_execution"}]
)
print(interaction1.steps[-1].content[0].text)

# Second turn - follow-up with code execution
interaction2 = client.interactions.create(
    model="gemini-3-flash-preview",
    previous_interaction_id=interaction1.id,
    input="What is the sum of the first 50 prime numbers? "
          "Generate and run code for the calculation, and make sure you get all 50.",
    tools=[{"type": "code_execution"}]
)

for step in interaction2.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)
    elif step.type == "code_execution_call":
        print(step.arguments.code)
    elif step.type == "code_execution_result":
        print(step.result)

JavaScript

import { GoogleGenAI } from "@google/genai";

const client = new GoogleGenAI({});

// First turn
const interaction1 = await client.interactions.create({
    model: "gemini-3-flash-preview",
    input: "I have a math question for you.",
    tools: [{ type: "code_execution" }]
});
console.log(interaction1.steps.at(-1).content[0].text);

// Second turn - follow-up with code execution
const interaction2 = await client.interactions.create({
    model: "gemini-3-flash-preview",
    previousInteractionId: interaction1.id,
    input: "What is the sum of the first 50 prime numbers? " +
           "Generate and run code for the calculation, and make sure you get all 50.",
    tools: [{ type: "code_execution" }]
});

for (const step of interaction2.steps) {
    if (step.type === "model_output") {
        for (const contentBlock of step.content) {
            if (contentBlock.type === "text") {
                console.log(contentBlock.text);
            }
        }
    } else if (step.type === "code_execution_call") {
        console.log(step.arguments.code);
    } else if (step.type === "code_execution_result") {
        console.log(step.result);
    }
}

PUSHTIM

# First turn
RESPONSE1=$(curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "gemini-3-flash-preview",
    "input": "I have a math question for you.",
    "tools": [{"type": "code_execution"}]
}')

INTERACTION_ID=$(echo $RESPONSE1 | jq -r '.id')

# Second turn with previous_interaction_id
curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
    "model": "gemini-3-flash-preview",
    "previous_interaction_id": "'"$INTERACTION_ID"'",
    "input": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.",
    "tools": [{"type": "code_execution"}]
}'

Hyrje/dalje (I/O)

Duke filluar me Gemini 2.0 Flash , ekzekutimi i kodit mbështet hyrjen e skedarëve dhe daljen e grafikëve. Duke përdorur këto aftësi hyrjeje dhe daljeje, ju mund të ngarkoni skedarë CSV dhe teksti, të bëni pyetje në lidhje me skedarët dhe të gjeneroni grafikë Matplotlib si pjesë të përgjigjes. Skedarët e daljes kthehen si imazhe të integruara në përgjigje.

Çmimi i I/O-së

Kur përdorni I/O për ekzekutimin e kodit, ju ngarkoheni për tokenët hyrës dhe dalës:

Shenjat hyrëse:

  • Kërkesa e përdoruesit

Tokenat e daljes:

  • Kodi i gjeneruar nga modeli
  • Rezultati i ekzekutimit të kodit në mjedisin e kodit
  • Shenjat e të menduarit
  • Përmbledhje e gjeneruar nga modeli

Detajet e I/O-së

Kur punoni me I/O për ekzekutimin e kodit, kini parasysh detajet teknike të mëposhtme:

  • Koha maksimale e ekzekutimit të mjedisit të kodit është 30 sekonda.
  • Nëse mjedisi i kodit gjeneron një gabim, modeli mund të vendosë të rigjenerojë rezultatin e kodit. Kjo mund të ndodhë deri në 5 herë.
  • Madhësia maksimale e futjes së skedarit është e kufizuar nga dritarja e tokenit të modelit. Në AI Studio, duke përdorur Gemini Flash 2.0, madhësia maksimale e skedarit të futur është 1 milion token (afërsisht 2MB për skedarët tekstualë të llojeve të mbështetura të futjes). Nëse ngarkoni një skedar që është shumë i madh, AI Studio nuk do t'ju lejojë ta dërgoni atë.
  • Ekzekutimi i kodit funksionon më mirë me skedarët tekst dhe CSV.
  • Skedari hyrës mund të kalohet si të dhëna të brendshme ose të ngarkohet duke përdorur API-n e Skedarëve , dhe skedari dalës kthehet gjithmonë si të dhëna të brendshme.

Faturimi

Nuk ka pagesë shtesë për aktivizimin e ekzekutimit të kodit nga Gemini API. Do të faturoheni me çmimin aktual të tokenëve hyrës dhe dalës bazuar në modelin Gemini që po përdorni.

Ja disa gjëra të tjera që duhet të dini rreth faturimit për ekzekutimin e kodit:

  • Ju faturoheni vetëm një herë për tokenët hyrës që i kaloni modelit dhe ju faturoheni për tokenët përfundimtarë dalës që ju kthehen nga modeli.
  • Tokenët që përfaqësojnë kodin e gjeneruar llogariten si tokena dalës. Kodi i gjeneruar mund të përfshijë tekst dhe dalje multimodale si imazhe.
  • Rezultatet e ekzekutimit të kodit llogariten gjithashtu si tokena dalëse.

Modeli i faturimit është paraqitur në diagramin e mëposhtëm:

modeli i faturimit të ekzekutimit të kodit

  • Ju faturoheni me çmimin aktual të tokenëve hyrës dhe dalës bazuar në modelin Gemini që po përdorni.
  • Nëse Gemini përdor ekzekutimin e kodit kur gjeneron përgjigjen tuaj, kërkesa origjinale, kodi i gjeneruar dhe rezultati i kodit të ekzekutuar etiketohen si tokena të ndërmjetëm dhe faturohen si tokena hyrëse .
  • Pastaj Gemini gjeneron një përmbledhje dhe kthen kodin e gjeneruar, rezultatin e kodit të ekzekutuar dhe përmbledhjen përfundimtare. Këto faturohen si tokena dalës .
  • API-ja Gemini përfshin një numër të ndërmjetëm tokenësh në përgjigjen e API-t, kështu që ju e dini pse po merrni tokena shtesë hyrës përtej kërkesës fillestare.

Kufizime

  • Modeli mund të gjenerojë dhe ekzekutojë vetëm kod. Nuk mund të kthejë objekte të tjera si skedarët mediatikë.
  • Në disa raste, aktivizimi i ekzekutimit të kodit mund të çojë në regresione në fusha të tjera të rezultatit të modelit (për shembull, shkrimi i një historie).
  • Ekzistojnë disa ndryshime në aftësinë e modeleve të ndryshme për të përdorur me sukses ekzekutimin e kodit.

Kombinimet e mjeteve të mbështetura

Mjeti i ekzekutimit të kodit mund të kombinohet me Grounding me Google Search për të mundësuar raste përdorimi më komplekse.

Modelet Gemini 3 mbështesin kombinimin e mjeteve të integruara (si Ekzekutimi i Kodit) me mjete të personalizuara (thirrja e funksioneve).

Bibliotekat e mbështetura

Mjedisi i ekzekutimit të kodit përfshin libraritë e mëposhtme:

  • atrimet
  • shah
  • konturor
  • fpdf
  • gjeopandat
  • imageio
  • jinja2
  • libraria e punës
  • jsonschema
  • specifikimet-e-jsonschema-s
  • lxml
  • matplotlib
  • mpmath
  • i paqëndrueshëm
  • opencv-python
  • openpyxl
  • paketim
  • pandat
  • jastëk
  • protobuf
  • pilateks
  • pyparsing
  • PyPDF2
  • python-dateutil
  • python-docx
  • python-pptx
  • raportlaboratori
  • scikit-learn
  • scipy
  • detar
  • gjashtë
  • striptf
  • sympy
  • tabeloj
  • rrjedha tensorike
  • mjete
  • xlrd

Nuk mund të instaloni bibliotekat tuaja.

Çfarë vjen më pas