สร้างการสนทนาแบบหลายรอบ (แชท) โดยใช้ Gemini API

คุณสามารถสร้างการสนทนาแบบอิสระได้หลายรอบโดยใช้ Gemini API SDK ของ Firebase AI Logic ช่วยลดความซับซ้อนของกระบวนการโดยการจัดการสถานะของการสนทนา ดังนั้นคุณจึงไม่ต้องจัดเก็บประวัติการสนทนาด้วยตนเองเหมือนกับ generateContent() (หรือ generateContentStream())

ข้ามไปยังโค้ดสำหรับการแชทแบบข้อความเท่านั้น ข้ามไปยังโค้ดสำหรับการแก้ไขรูปภาพแบบวนซ้ำ ข้ามไปยังโค้ดสำหรับการตอบกลับแบบสตรีม

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

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

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

สำหรับการทดสอบและปรับปรุงพรอมต์ซ้ำๆ เราขอแนะนำให้ใช้ Google AI Studio

ดูแหล่งข้อมูลที่เป็นประโยชน์

Swift

ลองใช้แอปเริ่มต้นด่วน

ใช้แอป Quickstart เพื่อลองใช้ SDK อย่างรวดเร็วและดูการใช้งานที่สมบูรณ์ของ Use Case ต่างๆ หรือใช้แอป Quickstart หากคุณไม่มีแอปแพลตฟอร์ม Apple ของตัวเอง หากต้องการใช้แอป Quickstart คุณจะต้องเชื่อมต่อแอปกับโปรเจ็กต์ Firebase

ไปที่แอป Quickstart

ดูวิดีโอแนะนำ

วิดีโอนี้สาธิตวิธีใช้แชทกับ Firebase AI Logic โดยการสร้างแอปวางแผนมื้ออาหารที่ทำงานด้วยระบบ AI ในชีวิตจริง ซึ่งช่วยให้ผู้ใช้แชทกับเชฟในครัวเกี่ยวกับสูตรอาหารที่ต้องการเตรียมได้

นอกจากนี้ คุณยังดาวน์โหลดและสำรวจฐานของโค้ดสำหรับแอปในวิดีโอได้ด้วย

ดูฐานของโค้ดสำหรับแอปวิดีโอ



Kotlin

ลองใช้แอปเริ่มต้นด่วน

ใช้แอป Quickstart เพื่อลองใช้ SDK อย่างรวดเร็วและดูการใช้งานที่สมบูรณ์ของ Use Case ต่างๆ หรือใช้แอป Quickstart หากคุณไม่มีแอป Android ของตัวเอง หากต้องการใช้แอป Quickstart คุณจะต้องเชื่อมต่อแอปกับโปรเจ็กต์ Firebase

ไปที่แอป Quickstart

Java

ลองใช้แอปเริ่มต้นด่วน

ใช้แอป Quickstart เพื่อลองใช้ SDK อย่างรวดเร็วและดูการใช้งานที่สมบูรณ์ของ Use Case ต่างๆ หรือใช้แอป Quickstart หากคุณไม่มีแอป Android ของตัวเอง หากต้องการใช้แอป Quickstart คุณจะต้องเชื่อมต่อแอปกับโปรเจ็กต์ Firebase

ไปที่แอป Quickstart

Web

ลองใช้แอปเริ่มต้นด่วน

ใช้แอป Quickstart เพื่อลองใช้ SDK อย่างรวดเร็วและดูการใช้งานที่สมบูรณ์ของ Use Case ต่างๆ หรือใช้แอป Quickstart หากคุณไม่มีเว็บแอปเป็นของตัวเอง หากต้องการใช้แอป Quickstart คุณจะต้องเชื่อมต่อแอปกับโปรเจ็กต์ Firebase

ไปที่แอป Quickstart

ดูวิดีโอแนะนำ

วิดีโอนี้สาธิตวิธีใช้แชทกับ Firebase AI Logic โดยการสร้างแอปวางแผนมื้ออาหารที่ทำงานด้วยระบบ AI ในชีวิตจริง ซึ่งช่วยให้ผู้ใช้แชทกับเชฟในครัวเกี่ยวกับสูตรอาหารที่ต้องการเตรียมได้

นอกจากนี้ คุณยังดาวน์โหลดและสำรวจฐานของโค้ดสำหรับแอปในวิดีโอได้ด้วย

ดูฐานของโค้ดสำหรับแอปของวิดีโอ



Dart

ลองใช้แอปเริ่มต้นด่วน

ใช้แอป Quickstart เพื่อลองใช้ SDK อย่างรวดเร็วและดูการใช้งานที่สมบูรณ์ของ Use Case ต่างๆ หรือใช้แอป Quickstart หากคุณไม่มีแอป Flutter ของตัวเอง หากต้องการใช้แอป Quickstart คุณจะต้องเชื่อมต่อแอปกับโปรเจ็กต์ Firebase

ไปที่แอป Quick Start

Unity

ลองใช้แอปเริ่มต้นด่วน

ใช้แอป Quickstart เพื่อลองใช้ SDK อย่างรวดเร็วและดูการใช้งานที่สมบูรณ์ของ Use Case ต่างๆ หรือใช้แอป Quickstart หากคุณไม่มีเกม Unity ของตัวเอง หากต้องการใช้แอปเริ่มต้นใช้งานด่วน คุณจะต้องเชื่อมต่อแอปกับโปรเจ็กต์ Firebase

ไปที่แอป Quick Start

สร้างประสบการณ์การแชทแบบข้อความเท่านั้น

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

หากต้องการสร้างการสนทนาแบบหลายรอบ (เช่น แชท) ให้เริ่มต้นด้วยการเริ่มต้นแชทโดยเรียกใช้ startChat() จากนั้นใช้ sendMessage() เพื่อส่งข้อความใหม่ของผู้ใช้ ซึ่งจะเพิ่มข้อความและคำตอบลงในประวัติการแชทด้วย

roleที่เชื่อมโยงกับเนื้อหาในการสนทนามี 2 ตัวเลือกที่เป็นไปได้ ดังนี้

  • user: บทบาทที่ให้พรอมต์ ค่านี้เป็นค่าเริ่มต้นสำหรับการเรียกใช้ sendMessage() และฟังก์ชันจะแสดงข้อยกเว้นหากมีการส่งบทบาทอื่น

  • model: บทบาทที่ให้คำตอบ บทบาทนี้ใช้ได้เมื่อเรียกใช้ startChat() ด้วย history ที่มีอยู่

    โปรดทราบว่าระบบไม่รองรับรอบการโต้ตอบของโมเดลที่กำหนดไว้ล่วงหน้าสำหรับ gemini-4-argon, โมเดล gemini-3.x-flash (ยกเว้น gemini-3.5-flash) และ gemini-3.5-flash-lite หากเทิร์นสุดท้ายที่ไม่ว่างเปล่าในคำขอเป็นเทิร์น model คำขอจะดำเนินการไม่สำเร็จพร้อมข้อผิดพลาด 400

Swift

คุณสามารถเรียกใช้ startChat() และ sendMessage() เพื่อส่งข้อความของผู้ใช้ใหม่ได้ดังนี้


import FirebaseAILogic

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


// Optionally specify existing chat history
let history = [
  ModelContent(role: "user", parts: "Hello, I have 2 dogs in my house."),
  ModelContent(role: "model", parts: "Great to meet you. What would you like to know?"),
]

// Initialize the chat with optional chat history
let chat = model.startChat(history: history)

// To generate text output, call sendMessage and pass in the message
let response = try await chat.sendMessage("How many paws are in my house?")
print(response.text ?? "No text in response.")

Kotlin

คุณสามารถเรียกใช้ startChat() และ sendMessage() เพื่อส่งข้อความของผู้ใช้ใหม่ได้ดังนี้

สำหรับ 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-3.8-flash")


// Initialize the chat
val chat = model.startChat(
  history = listOf(
    content(role = "user") { text("Hello, I have 2 dogs in my house.") },
    content(role = "model") { text("Great to meet you. What would you like to know?") }
  )
)

val response = chat.sendMessage("How many paws are in my house?")
print(response.text)

Java

คุณสามารถเรียกใช้ startChat() และ sendMessage() เพื่อส่งข้อความของผู้ใช้ใหม่ได้ดังนี้

สำหรับ 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-3.8-flash");

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


// (optional) Create previous chat history for context
Content.Builder userContentBuilder = new Content.Builder();
userContentBuilder.setRole("user");
userContentBuilder.addText("Hello, I have 2 dogs in my house.");
Content userContent = userContentBuilder.build();

Content.Builder modelContentBuilder = new Content.Builder();
modelContentBuilder.setRole("model");
modelContentBuilder.addText("Great to meet you. What would you like to know?");
Content modelContent = userContentBuilder.build();

List<Content> history = Arrays.asList(userContent, modelContent);

// Initialize the chat
ChatFutures chat = model.startChat(history);

// Create a new user message
Content.Builder messageBuilder = new Content.Builder();
messageBuilder.setRole("user");
messageBuilder.addText("How many paws are in my house?");

Content message = messageBuilder.build();

// Send the message
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(message);
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

คุณสามารถเรียกใช้ startChat() และ sendMessage() เพื่อส่งข้อความของผู้ใช้ใหม่ได้ดังนี้


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


async function run() {
  const chat = model.startChat({
    history: [
      {
        role: "user",
        parts: [{ type: "text", text: "Hello, I have 2 dogs in my house." }],
      },
      {
        role: "model",
        parts: [{ type: "text", text: "Great to meet you. What would you like to know?" }],
      },
    ],
    generationConfig: {
      maxOutputTokens: 100,
    },
  });

  const msg = "How many paws are in my house?";

  const result = await chat.sendMessage(msg);

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

run();

Dart

คุณสามารถเรียกใช้ startChat() และ sendMessage() เพื่อส่งข้อความถึงผู้ใช้ใหม่ได้ดังนี้


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-3.8-flash');


// Initialize the chat with history
final chat = model.startChat(
  history: [
    Content.text('Hello, I have 2 dogs in my house.'),
    Content.model([const TextPart('Great to meet you. What would you like to know?')]),
  ],
);
// Send a message to the chat
final response = await chat.sendMessage(Content.text('How many paws are in my house?'));
print(response.text);

Unity

คุณสามารถเรียกใช้ StartChat() และ SendMessageAsync() เพื่อส่งข้อความของผู้ใช้ใหม่ได้ดังนี้


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


// Optionally specify existing chat history
var history = new [] {
  ModelContent.Text("Hello, I have 2 dogs in my house."),
  new ModelContent("model", new ModelContent.TextPart("Great to meet you. What would you like to know?")),
};

// Initialize the chat with optional chat history
var chat = model.StartChat(history);

// To generate text output, call SendMessageAsync and pass in the message
var response = await chat.SendMessageAsync("How many paws are in my house?");
UnityEngine.Debug.Log(response.Text ?? "No text in response.");

ดูวิธีเลือกโมเดล ที่เหมาะกับ Use Case และแอปของคุณ

ปรับแต่งและแก้ไขรูปภาพโดยใช้แชทแบบหลายรอบ

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

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

สร้างอินสแตนซ์ GenerativeModel รวมรูปแบบการตอบกลับของ IMAGE ไว้ในการกำหนดค่าโมเดล และเรียกใช้ startChat() และ sendMessage() เพื่อส่งข้อความใหม่ของผู้ใช้

Swift


import FirebaseAILogic

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
  modelName: "gemini-nano-banana-2.1",
  // Configure the model to respond with images only.
  generationConfig: GenerationConfig(responseModalities: [.image])
)

// Initialize the chat
let chat = model.startChat()

guard let image = UIImage(named: "scones") else { fatalError("Image file not found.") }

// Provide an initial text prompt instructing the model to edit the image
let prompt = "Edit this image to make it look like a cartoon"

// To generate an initial response, send a user message with the image and text prompt
let response = try await chat.sendMessage(image, prompt)

// Inspect the generated image
guard let inlineDataPart = response.inlineDataParts.first else {
  fatalError("No image data in response.")
}
guard let uiImage = UIImage(data: inlineDataPart.data) else {
  fatalError("Failed to convert data to UIImage.")
}

// Follow up requests do not need to specify the image again
let followUpResponse = try await chat.sendMessage("But make it old-school line drawing style")

// Inspect the edited image after the follow up request
guard let followUpInlineDataPart = followUpResponse.inlineDataParts.first else {
  fatalError("No image data in response.")
}
guard let followUpUIImage = UIImage(data: followUpInlineDataPart.data) else {
  fatalError("Failed to convert data to UIImage.")
}

Kotlin


// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
    modelName = "gemini-nano-banana-2.1",
    // Configure the model to respond with images only.
    generationConfig = generationConfig {
responseModalities = listOf(ResponseModality.IMAGE) }
)

// Provide an image for the model to edit
val bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.scones)

// Create the initial prompt instructing the model to edit the image
val prompt = content {
    image(bitmap)
    text("Edit this image to make it look like a cartoon")
}

// Initialize the chat
val chat = model.startChat()

// To generate an initial response, send a user message with the image and text prompt
var response = chat.sendMessage(prompt)
// Inspect the returned image
var generatedImageAsBitmap = response
    .candidates.first().content.parts.filterIsInstance<ImagePart>().firstOrNull()?.image

// Follow up requests do not need to specify the image again
response = chat.sendMessage("But make it old-school line drawing style")
generatedImageAsBitmap = response
    .candidates.first().content.parts.filterIsInstance<ImagePart>().firstOrNull()?.image

Java


// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI()).generativeModel(
    "gemini-nano-banana-2.1",
    // Configure the model to respond with images only.
    new GenerationConfig.Builder()
        .setResponseModalities(Arrays.asList(ResponseModality.IMAGE))
        .build()
);

GenerativeModelFutures model = GenerativeModelFutures.from(ai);

// Provide an image for the model to edit
Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.scones);

// Initialize the chat
ChatFutures chat = model.startChat();

// Create the initial prompt instructing the model to edit the image
Content prompt = new Content.Builder()
        .setRole("user")
        .addImage(bitmap)
        .addText("Edit this image to make it look like a cartoon")
        .build();

// To generate an initial response, send a user message with the image and text prompt
ListenableFuture<GenerateContentResponse> response = chat.sendMessage(prompt);
// Extract the image from the initial response
ListenableFuture<@Nullable Bitmap> initialRequest = Futures.transform(response, result -> {
    for (Part part : result.getCandidates().get(0).getContent().getParts()) {
        if (part instanceof ImagePart) {
            ImagePart imagePart = (ImagePart) part;
            return imagePart.getImage();
        }
    }
    return null;
}, executor);

// Follow up requests do not need to specify the image again
ListenableFuture<GenerateContentResponse> modelResponseFuture = Futures.transformAsync(
        initialRequest,
        generatedImage -> {
            Content followUpPrompt = new Content.Builder()
                    .addText("But make it old-school line drawing style")
                    .build();
            return chat.sendMessage(followUpPrompt);
        },
        executor);

// Add a final callback to check the reworked image
Futures.addCallback(modelResponseFuture, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        for (Part part : result.getCandidates().get(0).getContent().getParts()) {
            if (part instanceof ImagePart) {
                ImagePart imagePart = (ImagePart) part;
                Bitmap generatedImageAsBitmap = imagePart.getImage();
                break;
            }
        }
    }

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

Web


import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend, ResponseModality } 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-nano-banana-2.1",
  // Configure the model to respond with images only.
  generationConfig: {
    responseModalities: [ResponseModality.IMAGE],
  },
});

// Prepare an image for the model to edit
async function fileToGenerativePart(file) {
  const base64EncodedDataPromise = new Promise((resolve) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result.split(',')[1]);
    reader.readAsDataURL(file);
  });
  return {
    type: "inlineData",
    inlineData: { data: await base64EncodedDataPromise, mimeType: file.type },
  };
}

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

// Provide an initial text prompt instructing the model to edit the image
const prompt = "Edit this image to make it look like a cartoon";

// Initialize the chat
const chat = model.startChat();

// To generate an initial response, send a user message with the image and text prompt
const result = await chat.sendMessage([prompt, imagePart]);

// Request and inspect the generated image
try {
  const inlineDataParts = result.response.inlineDataParts();
  if (inlineDataParts?.[0]) {
    // Inspect the generated image
    const image = inlineDataParts[0].inlineData;
    console.log(image.mimeType, image.data);
  }
} catch (err) {
  console.error('Prompt or candidate was blocked:', err);
}

// Follow up requests do not need to specify the image again
const followUpResult = await chat.sendMessage("But make it old-school line drawing style");

// Request and inspect the returned image
try {
  const followUpInlineDataParts = followUpResult.response.inlineDataParts();
  if (followUpInlineDataParts?.[0]) {
    // Inspect the generated image
    const followUpImage = followUpInlineDataParts[0].inlineData;
    console.log(followUpImage.mimeType, followUpImage.data);
  }
} catch (err) {
  console.error('Prompt or candidate was blocked:', err);
}

Dart


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

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

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
final model = FirebaseAI.googleAI().generativeModel(
  model: 'gemini-nano-banana-2.1',
  // Configure the model to respond with images only.
  generationConfig: GenerationConfig(responseModalities: [ResponseModalities.image]),
);

// Prepare an image for the model to edit
final image = await File('scones.jpg').readAsBytes();
final imagePart = InlineDataPart('image/jpeg', image);

// Provide an initial text prompt instructing the model to edit the image
final prompt = TextPart("Edit this image to make it look like a cartoon");

// Initialize the chat
final chat = model.startChat();

// To generate an initial response, send a user message with the image and text prompt
final response = await chat.sendMessage([
  Content.multi([prompt,imagePart])
]);

// Inspect the returned image
if (response.inlineDataParts.isNotEmpty) {
  final imageBytes = response.inlineDataParts[0].bytes;
  // Process the image
} else {
  // Handle the case where no images were generated
  print('Error: No images were generated.');
}

// Follow up requests do not need to specify the image again
final followUpResponse = await chat.sendMessage([
  Content.text("But make it old-school line drawing style")
]);

// Inspect the returned image
if (followUpResponse.inlineDataParts.isNotEmpty) {
  final followUpImageBytes = response.inlineDataParts[0].bytes;
  // Process the image
} else {
  // Handle the case where no images were generated
  print('Error: No images were generated.');
}

Unity


using Firebase;
using Firebase.AI;

// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a Gemini model that supports image output.
var model = FirebaseAI.GetInstance(FirebaseAI.Backend.GoogleAI()).GetGenerativeModel(
  modelName: "gemini-nano-banana-2.1",
  // Configure the model to respond with images only.
  generationConfig: new GenerationConfig(
    responseModalities: new[] { ResponseModality.Image })
);

// Prepare an image for the model to edit
var imageFile = System.IO.File.ReadAllBytes(System.IO.Path.Combine(
  UnityEngine.Application.streamingAssetsPath, "scones.jpg"));
var image = ModelContent.InlineData("image/jpeg", imageFile);

// Provide an initial text prompt instructing the model to edit the image
var prompt = ModelContent.Text("Edit this image to make it look like a cartoon.");

// Initialize the chat
var chat = model.StartChat();

// To generate an initial response, send a user message with the image and text prompt
var response = await chat.SendMessageAsync(new [] { prompt, image });

// Inspect the returned image
var imageParts = response.Candidates.First().Content.Parts
                         .OfType<ModelContent.InlineDataPart>()
                         .Where(part => part.MimeType == "image/png");
// Load the image into a Unity Texture2D object
UnityEngine.Texture2D texture2D = new(2, 2);
if (texture2D.LoadImage(imageParts.First().Data.ToArray())) {
  // Do something with the image
}

// Follow up requests do not need to specify the image again
var followUpResponse = await chat.SendMessageAsync("But make it old-school line drawing style");

// Inspect the returned image
var followUpImageParts = followUpResponse.Candidates.First().Content.Parts
                         .OfType<ModelContent.InlineDataPart>()
                         .Where(part => part.MimeType == "image/png");
// Load the image into a Unity Texture2D object
UnityEngine.Texture2D followUpTexture2D = new(2, 2);
if (followUpTexture2D.LoadImage(followUpImageParts.First().Data.ToArray())) {
  // Do something with the image
}

สตรีมคำตอบ

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

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



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

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

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

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

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

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

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


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