Gemini API 快速入门

本快速入门将向您介绍如何安装所选 SDK,然后发出您的第一个 Gemini API 请求。

安装 Gemini API 库

使用 Node.js v18 及更高版本,使用以下 npm 命令安装 Google Gen AI SDK for TypeScript and JavaScript

npm install @google/genai

提交第一个请求

在 Google AI Studio 中获取 Gemini API 密钥

使用 generateContent 方法向 Gemini API 发送请求。

import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });

async function main() {
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: "Explain how AI works in a few words",
  });
  console.log(response.text);
}

await main();

后续步骤

现在,您已发出第一个 API 请求,不妨探索以下指南,了解 Gemini 的运作方式: