Gemini API 快速入门

本快速入门将向您介绍如何安装我们的并发出您的第一个 Gemini API 请求。

准备工作

您需要一个 Gemini API 密钥。如果您还没有 API 密钥,可以在 Google AI Studio 中免费获取

安装 Google GenAI SDK

使用 Python 3.9 及更高版本时,请使用以下 pip 命令安装 google-genai 软件包

pip install -q -U google-genai

使用 Node.js v18 及更高版本,使用以下 npm 命令安装 适用于 TypeScript 和 JavaScript 的 Google 生成式 AI SDK

npm install @google/genai

使用 go get 命令在模块目录中安装 google.golang.org/genai

go get google.golang.org/genai
  1. 如需创建新的 Apps 脚本项目,请前往 script.new
  2. 点击 Untitled project
  3. 将 Apps 脚本项目重命名为 AI Studio,然后点击重命名
  4. 设置 API 密钥
    1. 点击左侧的项目设置 项目设置的图标
    2. 脚本属性下,点击添加脚本属性
    3. 对于媒体资源,输入键名称:GEMINI_API_KEY
    4. Value(值)中,输入 API 密钥的值。
    5. 点击保存脚本属性
  5. Code.gs 文件内容替换为以下代码:

提交第一个请求

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

from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Explain how AI works in a few words"
)
print(response.text)
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);
}

main();
package main

import (
    "context"
    "fmt"
    "log"

    "google.golang.org/genai"
)

func main() {
    ctx := context.Background()
    client, err := genai.NewClient(ctx, &genai.ClientConfig{
        APIKey:  "YOUR_API_KEY",
        Backend: genai.BackendGeminiAPI,
    })
    if err != nil {
        log.Fatal(err)
    }

    result, err := client.Models.GenerateContent(
        ctx,
        "gemini-2.0-flash",
        genai.Text("Explain how AI works in a few words"),
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result.Text())
}
// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
function main() {
  const payload = {
    contents: [
      {
        parts: [
          { text: 'Explain how AI works in a few words' },
        ],
      },
    ],
  };

  const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;
  const options = {
    method: 'POST',
    contentType: 'application/json',
    payload: JSON.stringify(payload)
  };

  const response = UrlFetchApp.fetch(url, options);
  const data = JSON.parse(response);
  const content = data['candidates'][0]['content']['parts'][0]['text'];
  console.log(content);
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$YOUR_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works in a few words"
          }
        ]
      }
    ]
  }'

后续步骤

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