สร้างข้อความโดยใช้ Gemini API

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

พรอมต์แบบมัลติมีเดียอาจมีอินพุตหลายประเภท (เช่น ข้อความพร้อมกับรูปภาพ, PDF, ไฟล์ข้อความธรรมดา, เสียง และวิดีโอ)

คู่มือนี้จะแสดงวิธีสร้างข้อความจากพรอมต์แบบข้อความเท่านั้น และจากพรอมต์แบบมัลติโมดัลพื้นฐานที่มีไฟล์

ข้ามไปยังตัวอย่างโค้ดสําหรับอินพุตที่เป็นข้อความเท่านั้น ข้ามไปยังตัวอย่างโค้ดสําหรับอินพุตแบบหลายรูปแบบ


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

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

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

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

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

สร้างข้อความจากอินพุตที่เป็นข้อความเท่านั้น

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

คุณสามารถขอให้โมเดล Gemini สร้างข้อความได้โดยป้อนพรอมต์เป็นข้อความเท่านั้น

Swift

คุณสามารถเรียกใช้ generateContent() เพื่อสร้างข้อความจากอินพุตที่เป็นข้อความเท่านั้น


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-2.0-flash")


// Provide a prompt that contains text
let prompt = "Write a story about a magic backpack."

// To generate text output, call generateContent with the text input
let response = try await model.generateContent(prompt)
print(response.text ?? "No text in response.")

Kotlin

คุณสามารถเรียกใช้ generateContent() เพื่อสร้างข้อความจากอินพุตที่เป็นข้อความเท่านั้น

สำหรับ Kotlin เมธอดใน SDK นี้เป็นฟังก์ชันที่ระงับและต้องมีการเรียกใช้จากขอบเขต Coroutine

// 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("gemini-2.0-flash")


// Provide a prompt that contains text
val prompt = "Write a story about a magic backpack."

// To generate text output, call generateContent with the text input
val response = generativeModel.generateContent(prompt)
print(response.text)

Java

คุณสามารถเรียกใช้ generateContent() เพื่อสร้างข้อความจากอินพุตที่เป็นข้อความเท่านั้น

สําหรับ Java เมธอดใน SDK นี้จะแสดงผลเป็น ListenableFuture

// 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-2.0-flash");

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


// Provide a prompt that contains text
Content prompt = new Content.Builder()
    .addText("Write a story about a magic backpack.")
    .build();

// To generate text output, call generateContent with the text input
ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        System.out.println(resultText);
    }

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

Web

คุณสามารถเรียกใช้ generateContent() เพื่อสร้างข้อความจากอินพุตที่เป็นข้อความเท่านั้น


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-2.0-flash" });


// Wrap in an async function so you can use await
async function run() {
  // Provide a prompt that contains text
  const prompt = "Write a story about a magic backpack."

  // To generate text output, call generateContent with the text input
  const result = await model.generateContent(prompt);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

Dart

คุณสามารถเรียกใช้ generateContent() เพื่อสร้างข้อความจากอินพุตที่เป็นข้อความเท่านั้น


import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');


// Provide a prompt that contains text
final prompt = [Content.text('Write a story about a magic backpack.')];

// To generate text output, call generateContent with the text input
final response = await model.generateContent(prompt);
print(response.text);

Unity

คุณสามารถเรียกใช้ GenerateContentAsync() เพื่อสร้างข้อความจากอินพุตที่เป็นข้อความเท่านั้น


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");


// Provide a prompt that contains text
var prompt = "Write a story about a magic backpack.";

// To generate text output, call GenerateContentAsync with the text input
var response = await model.GenerateContentAsync(prompt);
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

สร้างข้อความจากอินพุตข้อความและไฟล์ (มัลติโมดัล)

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

คุณสามารถขอให้โมเดล Gemini สร้างข้อความโดยป้อนข้อความและไฟล์ โดยระบุ mimeType ของไฟล์อินพุตแต่ละไฟล์และไฟล์นั้นๆ ดูข้อกำหนดและคำแนะนำสำหรับไฟล์อินพุตได้ในส่วนถัดไปของหน้านี้

ตัวอย่างต่อไปนี้แสดงพื้นฐานเกี่ยวกับวิธีสร้างข้อความจากอินพุตไฟล์โดยการวิเคราะห์ไฟล์วิดีโอไฟล์เดียวที่ระบุเป็นข้อมูลในบรรทัด (ไฟล์ที่เข้ารหัส Base64)

โปรดทราบว่าตัวอย่างนี้แสดงการระบุไฟล์ในบรรทัด แต่ SDK ยังรองรับการระบุ URL ของ YouTube ด้วย

Swift

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


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-2.0-flash")


// Provide the video as `Data` with the appropriate MIME type.
let video = InlineDataPart(data: try Data(contentsOf: videoURL), mimeType: "video/mp4")

// Provide a text prompt to include with the video
let prompt = "What is in the video?"

// To generate text output, call generateContent with the text and video
let response = try await model.generateContent(video, prompt)
print(response.text ?? "No text in response.")

Kotlin

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

สำหรับ Kotlin เมธอดใน SDK นี้เป็นฟังก์ชันที่ระงับและต้องมีการเรียกใช้จากขอบเขต Coroutine

// 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("gemini-2.0-flash")


val contentResolver = applicationContext.contentResolver
contentResolver.openInputStream(videoUri).use { stream ->
  stream?.let {
    val bytes = stream.readBytes()

    // Provide a prompt that includes the video specified above and text
    val prompt = content {
        inlineData(bytes, "video/mp4")
        text("What is in the video?")
    }

    // To generate text output, call generateContent with the prompt
    val response = generativeModel.generateContent(prompt)
    Log.d(TAG, response.text ?: "")
  }
}

Java

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

สําหรับ Java เมธอดใน SDK นี้จะแสดงผลเป็น ListenableFuture

// 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-2.0-flash");

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


ContentResolver resolver = getApplicationContext().getContentResolver();
try (InputStream stream = resolver.openInputStream(videoUri)) {
    File videoFile = new File(new URI(videoUri.toString()));
    int videoSize = (int) videoFile.length();
    byte[] videoBytes = new byte[videoSize];
    if (stream != null) {
        stream.read(videoBytes, 0, videoBytes.length);
        stream.close();

        // Provide a prompt that includes the video specified above and text
        Content prompt = new Content.Builder()
                .addInlineData(videoBytes, "video/mp4")
                .addText("What is in the video?")
                .build();

        // To generate text output, call generateContent with the prompt
        ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
        Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
            @Override
            public void onSuccess(GenerateContentResponse result) {
                String resultText = result.getText();
                System.out.println(resultText);
            }

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

Web

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


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-2.0-flash" });


// Converts a File object to a Part object.
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(file);
  });
  return {
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

async function run() {
  // Provide a text prompt to include with the video
  const prompt = "What do you see?";

  const fileInputEl = document.querySelector("input[type=file]");
  const videoPart = await fileToGenerativePart(fileInputEl.files[0]);

  // To generate text output, call generateContent with the text and video
  const result = await model.generateContent([prompt, videoPart]);

  const response = result.response;
  const text = response.text();
  console.log(text);
}

run();

Dart

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


import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';

// Initialize FirebaseApp
await Firebase.initializeApp(
  options: DefaultFirebaseOptions.currentPlatform,
);

// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
final model =
      FirebaseAI.googleAI().generativeModel(model: 'gemini-2.0-flash');


// Provide a text prompt to include with the video
final prompt = TextPart("What's in the video?");

// Prepare video for input
final video = await File('video0.mp4').readAsBytes();

// Provide the video as `Data` with the appropriate mimetype
final videoPart = InlineDataPart('video/mp4', video);

// To generate text output, call generateContent with the text and images
final response = await model.generateContent([
  Content.multi([prompt, ...videoPart])
]);
print(response.text);

Unity

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


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service
var ai = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI());

// Create a `GenerativeModel` instance with a model that supports your use case
var model = ai.GetGenerativeModel(modelName: "gemini-2.0-flash");


// Provide the video as `data` with the appropriate MIME type.
var video = ModelContent.InlineData("video/mp4",
      System.IO.File.ReadAllBytes(System.IO.Path.Combine(
          UnityEngine.Application.streamingAssetsPath, "yourVideo.mp4")));

// Provide a text prompt to include with the video
var prompt = ModelContent.Text("What is in the video?");

// To generate text output, call GenerateContentAsync with the text and video
var response = await model.GenerateContentAsync(new [] { video, prompt });
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

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

สตรีมคำตอบ

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

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



ข้อกำหนดและคำแนะนำสำหรับไฟล์รูปภาพอินพุต

โปรดทราบว่าไฟล์ที่ระบุเป็นข้อมูลในบรรทัดจะได้รับการเข้ารหัสเป็น Base64 ระหว่างการรับส่ง ซึ่งจะเพิ่มขนาดของคำขอ คุณจะได้รับข้อผิดพลาด HTTP 413 หากคําขอมีขนาดใหญ่เกินไป

ดูรายละเอียดเกี่ยวกับหัวข้อต่อไปนี้ได้ในส่วนไฟล์อินพุตที่รองรับและข้อกำหนดสำหรับ Vertex AI Gemini API

  • ตัวเลือกต่างๆ ในการส่งไฟล์ในคำขอ (ในบรรทัดหรือใช้ URL หรือ URI ของไฟล์)
  • ประเภทไฟล์ที่รองรับ
  • ประเภท MIME ที่รองรับและวิธีระบุ
  • ข้อกำหนดและแนวทางปฏิบัติแนะนำสำหรับไฟล์และคําขอแบบหลายสื่อ



คุณทำอะไรได้อีกบ้าง

  • ดูวิธีนับโทเค็นก่อนส่งพรอมต์แบบยาวไปยังโมเดล
  • ตั้งค่า Cloud Storage for Firebase เพื่อให้คุณรวมไฟล์ขนาดใหญ่ในคำขอแบบหลายรูปแบบได้ และมีโซลูชันที่มีการจัดการมากขึ้นสำหรับส่งไฟล์ในพรอมต์ ไฟล์อาจรวมถึงรูปภาพ, PDF, วิดีโอ และเสียง
  • เริ่มคิดเกี่ยวกับการเตรียมพร้อมสำหรับเวอร์ชันที่ใช้งานจริง (ดูรายการตรวจสอบเวอร์ชันที่ใช้งานจริง) ซึ่งรวมถึงการดำเนินการต่อไปนี้

ลองใช้ความสามารถอื่นๆ

ดูวิธีควบคุมการสร้างเนื้อหา

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

ดูข้อมูลเพิ่มเติมเกี่ยวกับรูปแบบที่รองรับ

ดูข้อมูลเกี่ยวกับรูปแบบที่ใช้ได้กับกรณีการใช้งานต่างๆ รวมถึงโควต้าและราคา


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