การเรียกใช้โค้ด

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-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)]
    ),
)

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({ apiKey: "GOOGLE_API_KEY" });

let response = await ai.models.generateContent({
  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: {
    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);
  }
});

Go

package main

import (
    "context"
    "fmt"
    "os"
    "google.golang.org/genai"
)

func main() {

    ctx := context.Background()
    client, _ := genai.NewClient(ctx, &genai.ClientConfig{
        APIKey:  os.Getenv("GOOGLE_API_KEY"),
        Backend: genai.BackendGeminiAPI,
    })

    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {CodeExecution: &genai.ToolCodeExecution{}},
        },
    }

    result, _ := client.Models.GenerateContent(
        ctx,
        "gemini-2.0-flash",
        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-2.0-flash:generateContent?key=$GOOGLE_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: ผลลัพธ์ของโค้ดที่เรียกใช้ได้

รูปแบบการตั้งชื่อของส่วนเหล่านี้จะแตกต่างกันไปตามภาษาโปรแกรม

ใช้การเรียกใช้โค้ดในแชท

นอกจากนี้ คุณยังใช้การเรียกใช้โค้ดเป็นส่วนหนึ่งของแชทได้ด้วย

Python

from google import genai
from google.genai import types

client = genai.Client()

chat = client.chats.create(
    model="gemini-2.0-flash",
    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({ apiKey: "GOOGLE_API_KEY" });

const chat = ai.chats.create({
  model: "gemini-2.0-flash",
  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);

Go

package main

import (
    "context"
    "fmt"
    "os"
    "google.golang.org/genai"
)

func main() {

    ctx := context.Background()
    client, _ := genai.NewClient(ctx, &genai.ClientConfig{
        APIKey:  os.Getenv("GOOGLE_API_KEY"),
        Backend: genai.BackendGeminiAPI,
    })

    config := &genai.GenerateContentConfig{
        Tools: []*genai.Tool{
            {CodeExecution: &genai.ToolCodeExecution{}},
        },
    }

    chat, _ := client.Chats.Create(
        ctx,
        "gemini-2.0-flash",
        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-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{"tools": [{"code_execution": {}}],
    "contents": [
        {
            "role": "user",
            "parts": [{
                "text": "Can you print \"Hello world!\"?"
            }]
        },{
            "role": "model",
            "parts": [
              {
                "text": ""
              },
              {
                "executable_code": {
                  "language": "PYTHON",
                  "code": "\nprint(\"hello world!\")\n"
                }
              },
              {
                "code_execution_result": {
                  "outcome": "OUTCOME_OK",
                  "output": "hello world!\n"
                }
              },
              {
                "text": "I have printed \"hello world!\" using the provided python code block. \n"
              }
            ],
        },{
            "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)

ตั้งแต่ Gemini 2.0 Flash ���ป็นต้นไป การดำเนินการโค้ดจะรองรับอินพุตไฟล์และเอาต์พุตกราฟ ความสามารถในการรับและส่งออกเหล่านี้ช่วยให้คุณอัปโหลดไฟล์ CSV และไฟล์ข้อความ ถามคําถามเกี่ยวกับไฟล์ และสร้างกราฟ Matplotlib เป็นส่วนหนึ่งของคําตอบได้ ระบบจะแสดงไฟล์เอาต์พุตเป็นรูปภาพที่แทรกในหน้าคำตอบ

ราคา I/O

เมื่อใช้ I/O การดำเนินการของโค้ด ระบบจะเรียกเก็บเงินจากคุณสำหรับโทเค็นอินพุตและโทเค็นเอาต์พุต ดังนี้

โทเค็นอินพุต:

  • พรอมต์ของผู้ใช้

โทเค็นเอาต์พุต:

  • โค้ดที่โมเดลสร้างขึ้น
  • เอาต์พุตการเรียกใช้โค้ดในสภาพแวดล้อมโค้ด
  • ข้อมูลสรุปที่โมเดลสร้างขึ้น

รายละเอียด I/O

เมื่อทํางานกับ I/O ของการดำเนินการโค้ด โปรดคำนึงถึงรายละเอียดทางเทคนิคต่อไปนี้

  • รันไทม์สูงสุดของสภาพแวดล้อมโค้ดคือ 30 วินาที
  • หากสภาพแวดล้อมโค้ดสร้างข้อผิดพลาดขึ้น โมเดลอาจตัดสินใจที่จะสร้างเอาต์พุตโค้ดอีกครั้ง ซึ่งอาจเกิดขึ้นได้สูงสุด 5 ครั้ง
  • ขนาดอินพุตไฟล์สูงสุดถูกจํากัดโดยกรอบเวลาโทเค็นโมเดล ใน AI Studio ที่ใช้ Gemini Flash 2.0 ขนาดไฟล์อินพุตสูงสุดคือ 1 ล้านโทเค็น (ประมาณ 2 MB สำหรับไฟล์ข้อความของประเภทอินพุตที่รองรับ) หากคุณอัปโหลดไฟล์ที่มีขนาดใหญ่เกินไป AI Studio จะไม่อนุญาตให้คุณส่งไฟล์
  • การดำเนินการโค้ดจะทำงานได้ดีที่สุดกับไฟล์ข้อความและ CSV
  • ไฟล์อินพุตสามารถส่งเป็น part.inlineData หรือ part.fileData (อัปโหลดผ่าน Files API) และระบบจะแสดงผลไฟล์เอาต์พุตเป็น part.inlineData เสมอ
เลี้ยวครั้งเดียว การรับส่งข้อมูลแบบ 2 ทิศทาง (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 เพื่อให้คุณทราบว่าเหตุใดคุณจึงได้รับโทเค็นอินพุตเพิ่มเติมนอกเหนือจากพรอมต์แรก

ข้อจำกัด

  • โดยโ��เดลจะสร้างและเรียกใช้โค้ดได้เท่านั้น แต่จะไม่แสดงรายการอื่นๆ เช่น ไฟล์สื่อ
  • ในบางกรณี การเปิดใช้การเรียกใช้โค้ดอาจทําให้เอาต์พุตของโมเดลในด้านอื่นๆ ถดถอย (เช่น การเขียนเรื่องราว)
  • ความสามารถของโมเดลต่างๆ ในการใช้การเรียกใช้โค้ดให้สําเร็จนั้นแตกต่างกันไป

ไลบรารีที่รองรับ

สภาพแวดล้อมการเรียกใช้โค้ดประกอบด้วยไลบรารีต่อไปนี้

  • attrs
  • หมากรุก
  • contourpy
  • fpdf
  • geopandas
  • imageio
  • jinja2
  • joblib
  • jsonschema
  • jsonschema-specifications
  • lxml
  • matplotlib
  • mpmath
  • numpy
  • opencv-python
  • openpyxl
  • การสร้างแพ็กเกจ
  • แพนด้า
  • หมอน
  • protobuf
  • pylatex
  • pyparsing
  • PyPDF2
  • python-dateutil
  • python-docx
  • python-pptx
  • reportlab
  • scikit-learn
  • scipy
  • seaborn
  • หก
  • striprtf
  • sympy
  • จัดตาราง
  • tensorflow
  • toolz
  • xlrd

คุณติดตั้งไลบรารีของคุณเองไม่ได้

ขั้นตอนถัดไป