使用 Gemini API 生成文本

您可以让 Gemini 模型根据纯文本提示或多模态提示生成文本。使用 Firebase AI Logic 时,您可以直接从应用中发出此请求。

多模态提示可以包含多种类型的输入(例如文本以及图片、PDF、纯文本文件、音频和视频)。

本指南介绍了如何根据纯文本提示和包含文件的基本多模态提示生成文本。

跳转到仅限文本输入的代码 跳转到多模态输入的代码 跳转到流式响应的代码


如需了解其他文本处理选项,请参阅其他指南
生成结构化输出 多轮对话 双向流式传输 在设备上生成文本 根据文本生成图片

准备工作

点击您的 Gemini API 提供商,以查看此页面上特定于提供商的内容和代码。

如果您尚未完成入门指南,请先完成该指南。该指南介绍了如何设置 Firebase 项目、将应用连接到 Firebase、添加 SDK、为所选的 Gemini API 提供程序初始化后端服务,以及创建 GenerativeModel 实例。

如需测试和迭代提示,我们建议使用 Google AI Studio

根据纯文本输入生成文本

在试用此示例之前,请完成本指南的准备工作部分,以设置您的项目和应用。
在该部分中,您还需要点击所选Gemini API提供商对应的按钮,以便在此页面上看到特定于提供商的内容

您可以仅使用文本输入来提示 Gemini 模型生成文本。

Swift

您可以调用 generateContent() 从纯文本输入生成文本。

 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-2.5-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 中的方法是挂起函数,需要从协程范围调用。
 // 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.5-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 = model.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.5-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.5-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.5-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.5-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 也支持提供 YouTube 网址

Swift

您可以调用 generateContent(),根据文本和视频文件的多模态输入生成文本。

 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-2.5-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 中的方法是挂起函数,需要从协程范围调用。
 // 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.5-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 = model.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.5-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.5-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.5-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.5-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 的要求

  • 在请求中提供文件的不同选项(内嵌或使用文件的网址/URI)
  • 支持的文件类型
  • 支持的 MIME 类型以及如何指定这些类型
  • 文件和多模态请求的要求和最佳实践



您还可以做些什么?

试用其他功能

了解如何控制内容生成

  • 了解提示设计,包括最佳实践、策略和示例提示。
  • 配置模型参数,例如温度和输出 token 数上限(对于 Gemini)或宽高比和人物生成(对于 Imagen)。
  • 使用安全设置来调整获得可能被视为有害的回答的可能性。
您还可以尝试使用提示和模型配置,甚至可以使用 Google AI Studio 获取生成的代码段。

详细了解支持的型号

了解适用于各种应用场景的模型及其配额价格


就您使用 Firebase AI Logic 的体验提供反馈