Vertex AI Gemini API

หากคุณเพิ่งเริ่มใช้ Gemini API Gemini Developer API คือ ผู้ให้บริการ API ที่แนะนำสำหรับนักพัฒนาแอป Android แต่หากมีข้อกำหนดด้านตำแหน่งของข้อมูลที่เฉพาะเจาะจง หรือคุณอยู่ในสภาพแวดล้อม Vertex AI หรือ Google Cloud อยู่แล้ว คุณสามารถใช้ Vertex AI Gemini API ได้

การย้ายข้อมูลจาก Vertex AI ใน Firebase

หากเดิมคุณผสานรวมโมเดล Gemini Flash และ Pro โดยใช้ Vertex AI ใน Firebase คุณสามารถย้ายข้อมูลและใช้ Vertex AI ต่อไปในฐานะผู้ให้บริการ API ได้ อ่านเอกสารประกอบของ Firebase เพื่อดูคำแนะนำในการย้ายข้อมูลโดยละเอียด

เริ่มต้นใช้งาน

ก่อนที่จะโต้ตอบกับ Vertex AI Gemini API โดยตรงจากแอป คุณสามารถทดลองใช้พรอมต์ใน Vertex AI Studio ได้

ตั้งค่าโปรเจ็กต์ Firebase และเชื่อมต่อแอปกับ Firebase

เมื่อพร้อมที่จะเรียกใช้ Vertex AI Gemini API จากแอปแล้ว ให้ทําตาม วิธีการในคู่มือเริ่มต้นใช้งาน "ขั้นตอนที่ 1" ของ Firebase AI Logic เพื่อตั้งค่า Firebase และ SDK ในแอป

เพิ่มการอ้างอิง Gradle

เพิ่มทรัพยากร Dependency ของ Gradle ต่อไปนี้ลงในโมดูลแอป

dependencies {
  // ... other androidx dependencies

  // Import the BoM for the Firebase platform
  implementation(platform("com.google.firebase:firebase-bom:33.13.0"))

  // Add the dependency for the Firebase AI Logic library. When using the BoM,
  // you don't specify versions in Firebase library dependencies
  implementation("com.google.firebase:firebase-ai")
}

เริ่มต้นโมเดล Generative

เริ่มต้นด้วยการสร้างอินสแตนซ์ของ GenerativeModel และระบุชื่อโมเดล

Kotlin

val model = Firebase.ai(backend = GenerativeBackend.vertexAI())
                        .generativeModel("gemini-2.0-flash")

Java

GenerativeModel firebaseAI = FirebaseAI.getInstance(GenerativeBackend.vertexAI())
        .generativeModel("gemini-2.0-flash");

GenerativeModelFutures model = GenerativeModelFutures.from(firebaseAI);

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

สร้างข้อความ

หากต้องการสร้างคำตอบเป็นข้อความ ให้เรียกใช้ generateContent() พร้อมพรอมต์ของคุณ

Kotlin

// Note: generateContent() is a suspend function, which integrates well
// with existing Kotlin code.
scope.launch {
  val response = model.generateContent("Write a story about a magic backpack.")
}

Java

Content prompt = new Content.Builder()
    .addText("Write a story about a magic backpack.")
    .build();

ListenableFuture<GenerateContentResponse> response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
    @Override
    public void onSuccess(GenerateContentResponse result) {
        String resultText = result.getText();
        [...]
    }

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

คุณยังส่งรูปภาพ เสียง วิดีโอ และ ไฟล์พร้อมพรอมต์ข้อความได้เช่นเดียวกับ Gemini Developer API (ดู "โต้ตอบกับ Gemini Developer API จาก แอปของคุณ")

ดูข้อมูลเพิ่มเติมเกี่ยวกับ Firebase AI Logic SDK ได้ที่เอกสารประกอบของ Firebase