文本生成

当以文本、图片、视频和音频作为输入时,Gemini API 可以生成文本输出。

本指南介绍了如何使用 generateContentstreamGenerateContent 方法生成文本。如需了解如何使用 Gemini 的视觉和音频功能,请参阅Vision音频指南。

根据纯文本输入生成文本

使用 Gemini API 生成文本的最简单方法是向模型提供单个纯文本输入,如以下示例所示:

import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const prompt = "Explain how AI works";

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

在本例中,问题(“解释 AI 的工作原理”)不包含任何输出示例、系统说明或格式设置信息。这是一种零样本方法。对于某些用例,一次性多次性提示可能会生成更符合用户预期的输出。在某些情况下,您可能还需要提供系统说明,以帮助模型理解任务或遵循特定准则。

根据文本和图片输入生成文本

Gemini API 支持将文本与媒体文件相结合的多模态输入。以下示例展示了如何根据文本和图片输入生成文本:

import { GoogleGenerativeAI } from "@google/generative-ai";
import * as fs from 'node:fs';

const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

function fileToGenerativePart(path, mimeType) {
  return {
    inlineData: {
      data: Buffer.from(fs.readFileSync(path)).toString("base64"),
      mimeType,
    },
  };
}

const prompt = "Describe how this product might be manufactured.";
const imagePart = fileToGenerativePart("/path/to/image.png", "image/png");

const result = await model.generateContent([prompt, imagePart]);
console.log(result.response.text());

生成文本串流

默认情况下,模型会在完成整个文本生成流程后返回回答。您可以通过不等待完整结果,而是使用流式传输来处理部分结果,从而实现更快的互动。

以下示例展示了如何使用 streamGenerateContent 方法实现流式传输,以便根据纯文本输入提示生成文本。

import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const prompt = "Explain how AI works";

const result = await model.generateContentStream(prompt);

for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}

创建聊天对话

借助 Gemini SDK,您可以收集多轮问题和回答,让用户逐步获得答案,或在遇到多部分问题时获得帮助。此 SDK 功能提供了一个用于跟踪对话历史记录的接口,但在后台使用相同的 generateContent 方法来创建响应。

以下代码示例展示了基本聊天功能的实现:

import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const chat = model.startChat({
  history: [
    {
      role: "user",
      parts: [{ text: "Hello" }],
    },
    {
      role: "model",
      parts: [{ text: "Great to meet you. What would you like to know?" }],
    },
  ],
});

let result = await chat.sendMessage("I have 2 dogs in my house.");
console.log(result.response.text());
let result2 = await chat.sendMessage("How many paws are in my house?");
console.log(result2.response.text());

您还可以将流式传输与聊天功能搭配使用,如以下示例所示:

import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const chat = model.startChat({
  history: [
    {
      role: "user",
      parts: [{ text: "Hello" }],
    },
    {
      role: "model",
      parts: [{ text: "Great to meet you. What would you like to know?" }],
    },
  ],
});

let result = await chat.sendMessageStream("I have 2 dogs in my house.");
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}
let result2 = await chat.sendMessageStream("How many paws are in my house?");
for await (const chunk of result2.stream) {
  const chunkText = chunk.text();
  process.stdout.write(chunkText);
}

配置文本生成

您向模型发送的每个提示都包含控制模型如何生成回答的参数。您可以使用 GenerationConfig 配置这些参数。如果您未配置参数,则模型会使用默认选项,这些选项可能会因模型而异。

以下示例展示了如何配置几个可用选项。

import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const result = await model.generateContent({
    contents: [
        {
          role: 'user',
          parts: [
            {
              text: "Explain how AI works",
            }
          ],
        }
    ],
    generationConfig: {
      maxOutputTokens: 1000,
      temperature: 0.1,
    }
});

console.log(result.response.text());

添加系统说明

借助系统说明,您可以根据自己的特定需求和使用情形来控制模型的行为。

通过向模型提供系统指令,您可以为模型提供额外的上下文来了解任务、生成自定义程度更高的回答,并在用户与模型的整个交互过程中遵循特定的准则。您还可以通过设置系统说明来指定产品级行为,与最终用户提供的提示分开。

您可以在初始化模型时设置系统说明:

// Set the system instruction during model initialization
const model = genAI.getGenerativeModel({
  model: "gemini-1.5-flash",
  systemInstruction: "You are a cat. Your name is Neko.",
});

然后,您可以像往常一样向模型发送请求。

后续步骤

现在,您已经探索了 Gemini API 的基础知识,不妨尝试:

  • 视觉理解:了解如何使用 Gemini 的原生视觉理解功能处理图片和视频。
  • 音频理解:了解如何使用 Gemini 的原生音频理解功能处理音频文件。