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


การเรียกใช้โค้ดเป็นเครื่องมือที่ช่วยให้โมเดลสร้างและรันโค้ด Python ได้ โมเดลสามารถเรียนรู้ซ้ำๆ จากผลการเรียกใช้โค้ดจนกว่าจะได้รับเอาต์พุตสุดท้าย

คุณใช้การดำเนินการโค้ดเพื่อสร้างฟีเจอร์ที่ได้รับประโยชน์จากการให้เหตุผลตามโค้ด และสร้างเอาต์พุตข้อความได้ เช่น คุณสามารถใช้การดำเนินการกับโค้ด เพื่อแก้สมการหรือประมวลผลข้อความได้ นอกจากนี้ คุณยังใช้ไลบรารีที่รวมอยู่ในสภาพแวดล้อมการเรียกใช้โค้ดเพื่อ ทำงานที่เฉพาะเจาะจงมากขึ้นได้ด้วย

เช่นเดียวกับเครื่องมือทั้งหมดที่คุณมอบให้โมเดล โมเดลจะเป็นผู้กำหนดว่าจะใช้การเรียกใช้โค้ดเมื่อใด

ข้ามไปที่การติดตั้งใช้งานโค้ด

การเปรียบเทียบการเรียกใช้โค้ดกับการเรียกใช้ฟังก์ชัน

การเรียกใช้โค้ดและการเรียกใช้ฟังก์ชันเป็นฟีเจอร์ที่คล้ายกัน โดยทั่วไป คุณควรเลือกใช้การเรียกใช้โค้ดหากโมเดลรองรับ Use Case ของคุณได้ นอกจากนี้ การดำเนินการโค้ดยังใช้งานได้ง่ายขึ้นด้วย เนื่องจากคุณเพียงแค่เปิดใช้

ความแตกต่างเพิ่มเติมระหว่างการเรียกใช้โค้ดกับการเรียกฟังก์ชันมีดังนี้

การรันโค้ด การเรียกใช้ฟังก์ชัน
ใช้การเรียกใช้โค้ดหากต้องการให้โมเดลเขียนและรันโค้ด Python ให้คุณ แล้วแสดงผลลัพธ์ ใช้การเรียกใช้ฟังก์ชันหากคุณมีฟังก์ชันของตัวเองอยู่แล้ว ที่ต้องการเรียกใช้ในเครื่อง
การเรียกใช้โค้ดช่วยให้โมเดลเรียกใช้โค้ดในแบ็กเอนด์ของ API ในสภาพแวดล้อมที่แยกไว้ต่างหากและคงที่ การเรียกใช้ฟังก์ชันช่วยให้คุณเรียกใช้ฟังก์ชันที่โมเดลร้องขอได้ ในสภาพแวดล้อมใดก็ได้ที่คุณต้องการ
การรันโค้ดจะดำเนินการในคำขอเดียว แม้ว่าคุณจะเลือกใช้การดำเนินการโค้ดกับความสามารถในการแชทได้ แต่ก็ไม่จำเป็นต้องทำ การเรียกใช้ฟังก์ชันต้องมีคำขอเพิ่มเติมเพื่อส่งเอาต์พุตจากแต่ละการเรียกใช้ฟังก์ชันกลับ ดังนั้น คุณจึงต้องใช้ความสามารถของแชท

โมเดลที่รองรับ

  • gemini-2.5-pro
  • gemini-2.5-flash
  • gemini-2.5-flash-lite
  • gemini-2.0-flash-001 (และนามแฝงที่อัปเดตอัตโนมัติ gemini-2.0-flash)
  • gemini-2.0-flash-live-preview-04-09

ใช้การรันโค้ด

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

ก่อนเริ่มต้น

คลิกผู้ให้บริการ Gemini API เพื่อดูเนื้อหาและโค้ดเฉพาะของผู้ให้บริการ ในหน้านี้

หากยังไม่ได้ดำเนินการ ให้ทำตามคู่มือเริ่มต้นใช้งาน ซึ่งอธิบายวิธี ตั้งค่าโปรเจ็กต์ Firebase, เชื่อมต่อแอปกับ Firebase, เพิ่ม SDK, เริ่มต้นบริการแบ็กเอนด์สำหรับผู้ให้บริการ Gemini API ที่เลือก และ สร้างอินสแตนซ์ GenerativeModel

สําหรับการทดสอบและทําซ้ำพรอมต์ รวมถึง การรับข้อมูลโค้ดที่สร้างขึ้น เราขอแนะนําให้ใช้ Google AI Studio

เปิดใช้การดำเนินการโค้ด

ก่อนที่จะลองใช้ตัวอย่างนี้ ให้ทำตามส่วน ก่อนที่จะเริ่มของคู่มือนี้ เพื่อตั้งค่าโปรเจ็กต์และแอป
ในส่วนนั้น คุณจะคลิกปุ่มสำหรับ ผู้ให้บริการ Gemini API ที่เลือกเพื่อให้เห็นเนื้อหาเฉพาะของผู้ให้บริการ ในหน้านี้ด้วย

เมื่อสร้างอินสแตนซ์ GenerativeModel ให้ระบุ CodeExecution เป็นเครื่องมือที่โมเดลใช้สร้างคำตอบได้ ซึ่งช่วยให้โมเดล สร้างและรันโค้ด Python ได้

Swift


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Provide code execution as a tool that the model can use to generate its response.
  tools: [.codeExecution()]
)

let prompt = """
What is the sum of the first 50 prime numbers?
Generate and run code for the calculation, and make sure you get all 50.
"""

let response = try await model.generateContent(prompt)

guard let candidate = response.candidates.first else {
  print("No candidates in response.")
  return
}
for part in candidate.content.parts {
  if let textPart = part as? TextPart {
    print("Text = \(textPart.text)")
  } else if let executableCode = part as? ExecutableCodePart {
    print("Code = \(executableCode.code), Language = \(executableCode.language)")
  } else if let executionResult = part as? CodeExecutionResultPart {
    print("Outcome = \(executionResult.outcome), Result = \(executionResult.output ?? "no output")")
  }
}

Kotlin


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    // Provide code execution as a tool that the model can use to generate its response.
    tools = listOf(Tool.codeExecution())
)

val prompt =  "What is the sum of the first 50 prime numbers? " +
        "Generate and run code for the calculation, and make sure you get all 50."

val response = model.generateContent(prompt)

response.candidates.first().content.parts.forEach {
    if(it is TextPart) {
        println("Text = ${it.text}")
    }
    if(it is ExecutableCodePart) {
        println("Code = ${it.code}, Language = ${it.language}")
    }
    if(it is CodeExecutionResultPart) {
       println("Outcome = ${it.outcome}, Result = ${it.output}")
    }
}

Java


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel("GEMINI_MODEL_NAME",
                        null,
                        null,
                        // Provide code execution as a tool that the model can use to generate its response.
                        List.of(Tool.codeExecution()));

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);

String 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.";

Content prompt = new Content.Builder()
    .addText(text)
    .build();

ListenableFuture response = model.generateContent(prompt);

Futures.addCallback(response, new FutureCallback() {
   @Override
public void onSuccess(GenerateContentResponse response)   {
    // Access the first candidate's content parts
    List parts = response.getCandidates().get(0).getContent().getParts();
    for (Part part : parts) {
        if (part instanceof TextPart) {
            TextPart textPart = (TextPart) part;
            System.out.println("Text = " + textPart.getText());
        } else if (part instanceof ExecutableCodePart) {
            ExecutableCodePart codePart = (ExecutableCodePart) part;
            System.out.println("Code = " + codePart.getCode() + ", Language = " + codePart.getLanguage());
        } else if (part instanceof CodeExecutionResultPart) {
            CodeExecutionResultPart resultPart = (CodeExecutionResultPart) part;
            System.out.println("Outcome = " + resultPart.getOutcome() + ", Result = " + resultPart.getOutput());
        }
    }
}

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(
  ai,
  {
    model: "GEMINI_MODEL_NAME",
    // Provide code execution as a tool that the model can use to generate its response.
    tools: [{ codeExecution: {} }]
  }
);

const prompt =  "What is the sum of the first 50 prime numbers? " +
        "Generate and run code for the calculation, and make sure you get all 50."

const result = await model.generateContent(prompt);
const response = await result.response;

const parts = response.candidates?.[0].content.parts;

if (parts) {
  parts.forEach((part) => {
    if (part.text) {
        console.log(`Text: ${part.text}`);
    } else if (part.executableCode) {
      console.log(
        `Code: ${part.executableCode.code}, Language: ${part.executableCode.language}`
      );
    } else if (part.codeExecutionResult) {
      console.log(
        `Outcome: ${part.codeExecutionResult.outcome}, Result: ${part.codeExecutionResult.output}`
      );
    }
  });
}

Dart

โดยจะรองรับ Flutter ในรุ่นถัดไป

Unity

การรองรับ Unity จะพร้อมใช้งานในรุ่นถัดไป

ดูวิธีเลือกโมเดล (ไม่บังคับ) ที่เหมาะสมกับกรณีการใช้งานและแอปของคุณ

ใช้การรันโค้ดในแชท

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

Swift


import FirebaseAI

// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())

// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
  modelName: "GEMINI_MODEL_NAME",
  // Provide code execution as a tool that the model can use to generate its response.
  tools: [.codeExecution()]
)

let prompt = """
What is the sum of the first 50 prime numbers?
Generate and run code for the calculation, and make sure you get all 50.
"""
let chat = model.startChat()

let response = try await chat.sendMessage(prompt)

guard let candidate = response.candidates.first else {
  print("No candidates in response.")
  return
}
for part in candidate.content.parts {
  if let textPart = part as? TextPart {
    print("Text = \(textPart.text)")
  } else if let executableCode = part as? ExecutableCodePart {
    print("Code = \(executableCode.code), Language = \(executableCode.language)")
  } else if let executionResult = part as? CodeExecutionResultPart {
    print("Outcome = \(executionResult.outcome), Result = \(executionResult.output ?? "no output")")
  }
}

Kotlin


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "GEMINI_MODEL_NAME",
    // Provide code execution as a tool that the model can use to generate its response.
    tools = listOf(Tool.codeExecution())
)

val prompt =  "What is the sum of the first 50 prime numbers? " +
        "Generate and run code for the calculation, and make sure you get all 50."
val chat = model.startChat()
val response = chat.sendMessage(prompt)

response.candidates.first().content.parts.forEach {
    if(it is TextPart) {
        println("Text = ${it.text}")
    }
    if(it is ExecutableCodePart) {
        println("Code = ${it.code}, Language = ${it.language}")
    }
    if(it is CodeExecutionResultPart) {
       println("Outcome = ${it.outcome}, Result = ${it.output}")
    }
}

Java


// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
                .generativeModel("GEMINI_MODEL_NAME",
                        null,
                        null,
                        // Provide code execution as a tool that the model can use to generate its response.
                        List.of(Tool.codeExecution()));

// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
String 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.";

Content prompt = new Content.Builder()
    .addText(text)
    .build();

ChatFutures chat = model.startChat();
ListenableFuture response = chat.sendMessage(prompt);

Futures.addCallback(response, new FutureCallback() {
   @Override
public void onSuccess(GenerateContentResponse response)   {
    // Access the first candidate's content parts
    List parts = response.getCandidates().get(0).getContent().getParts();
    for (Part part : parts) {
        if (part instanceof TextPart) {
            TextPart textPart = (TextPart) part;
            System.out.println("Text = " + textPart.getText());
        } else if (part instanceof ExecutableCodePart) {
            ExecutableCodePart codePart = (ExecutableCodePart) part;
            System.out.println("Code = " + codePart.getCode() + ", Language = " + codePart.getLanguage());
        } else if (part instanceof CodeExecutionResultPart) {
            CodeExecutionResultPart resultPart = (CodeExecutionResultPart) part;
            System.out.println("Outcome = " + resultPart.getOutcome() + ", Result = " + resultPart.getOutput());
        }
    }
}

    @Override
    public void onFailure(Throwable t) {
        t.printStackTrace();
    }
}, executor);

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";

// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(
  ai,
  {
    model: "GEMINI_MODEL_NAME",
    // Provide code execution as a tool that the model can use to generate its response.
    tools: [{ codeExecution: {} }]
  }
);

const prompt =  "What is the sum of the first 50 prime numbers? " +
        "Generate and run code for the calculation, and make sure you get all 50."
const chat = model.startChat()
const result = await chat.sendMessage(prompt);
const response = await result.response;

const parts = response.candidates?.[0].content.parts;

if (parts) {
  parts.forEach((part) => {
    if (part.text) {
        console.log(`Text: ${part.text}`);
    } else if (part.executableCode) {
      console.log(
        `Code: ${part.executableCode.code}, Language: ${part.executableCode.language}`
      );
    } else if (part.codeExecutionResult) {
      console.log(
        `Outcome: ${part.codeExecutionResult.outcome}, Result: ${part.codeExecutionResult.output}`
      );
    }
  });
}

Dart

โดยจะรองรับ Flutter ในรุ่นถัดไป

Unity

การรองรับ Unity จะพร้อมใช้งานในรุ่นถัดไป

ดูวิธีเลือกโมเดล (ไม่บังคับ) ที่เหมาะสมกับกรณีการใช้งานและแอปของคุณ

ราคา

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

แผนภาพต่อไปนี้แสดงรูปแบบการเรียกเก็บเงินสำหรับการดำเนินการโค้ด

แผนภาพแสดงวิธีเรียกเก็บเงินโทเค็นเมื่อโมเดลใช้การดำเนินการโค้ด 

สรุปวิธีการเรียกเก็บเงินโทเค็นเมื่อโมเดลใช้การเรียกใช้โค้ดมีดังนี้

  • ระบบจะเรียกเก็บเงินสำหรับพรอมต์เดิม 1 ครั้ง โทเค็นของโมเดลนี้จะติดป้ายกำกับเป็นโทเค็นระดับกลาง ซึ่งจะเรียกเก็บเงินเป็นโทเค็นอินพุต

  • ระบบจะเรียกเก็บเงินสำหรับโค้ดที่สร้างขึ้นและผลลัพธ์ของโค้ดที่เรียกใช้ดังนี้

    • เมื่อใช้ระหว่างการเรียกใช้โค้ด ระบบจะติดป้ายกำกับเป็นโทเค็นระดับกลาง ซึ่งจะเรียกเก็บเงินเป็นโทเค็นอินพุต

    • เมื่อรวมเป็นส่วนหนึ่งของคำตอบสุดท้าย ระบบจะเรียกเก็บเงินเป็นโทเค็นเอาต์พุต

  • ระบบจะเรียกเก็บเงินค่าสรุปสุดท้ายในคำตอบสุดท้ายเป็นโทเค็นเอาต์พุต

Gemini API จะรวมจำนวนโทเค็นระดับกลางไว้ในการตอบกลับจาก API เพื่อให้คุณทราบเหตุผลที่ระบบเรียกเก็บเงินสำหรับโทเค็นอินพุตที่นอกเหนือจากพรอมต์เริ่มต้น

โปรดทราบว่าโค้ดที่สร้างขึ้นอาจมีทั้งข้อความและเอาต์พุตแบบมัลติโมดัล เช่น รูปภาพ

ข้อจำกัดและแนวทางปฏิบัติแนะนำ

  • โมเดลจะสร้างและเรียกใช้ได้เฉพาะโค้ด Python แต่จะคืนค่าอาร์ติแฟกต์อื่นๆ เช่น ไฟล์สื่อ ไม่ได้

  • การดำเนินการโค้ดจะทำงานได้สูงสุด 30 วินาทีก่อนที่จะหมดเวลา

  • ในบางกรณี การเปิดใช้การดำเนินการโค้ดอาจทำให้เกิดการถดถอยในด้านอื่นๆ ของเอาต์พุตโมเดล (เช่น การเขียนเรื่องราว)

  • เครื่องมือเรียกใช้โค้ดไม่รองรับ URI ของไฟล์เป็นอินพุต/เอาต์พุต อย่างไรก็ตาม เครื่องมือเรียกใช้โค้ดรองรับอินพุตไฟล์และเอาต์พุตกราฟเป็นไบต์แบบอินไลน์ การใช้ความสามารถในการป้อนและส่งออกเหล่านี้จะช่วยให้คุณอัปโหลดไฟล์ CSV และไฟล์ข้อความ ถามคำถามเกี่ยวกับไฟล์ และสร้างกราฟ Matplotlib เป็นส่วนหนึ่งของผลการดำเนินการโค้ดได้ MIME ประเภทที่รองรับสำหรับ ไบต์แบบอินไลน์คือ .cpp, .csv, .java, .jpeg, .js, .png, .py, .ts และ .xml

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

สภาพแวดล้อมการเรียกใช้โค้ดมีไลบรารีต่อไปนี้ คุณติดตั้งไลบรารีของตัวเองไม่ได้


แสดงความคิดเห็น เกี่ยวกับประสบการณ์การใช้งาน Firebase AI Logic