Gemini API 快速入門導覽課程

本快速入門導覽課程說明如何安裝程式庫,以及如何使用 Interactions API 發出第一筆 Gemini API 要求。

事前準備

如要使用 Gemini API,您必須有 API 金鑰,才能驗證要求、強制執行安全限制,以及追蹤帳戶的使用情形。

在 AI Studio 上免費建立一個,即可開始使用:

建立 Gemini API 金鑰

安裝 Google GenAI SDK

Python

使用 Python 3.9 以上版本,透過下列 pip 指令安裝 google-genai 套件

pip install -q -U google-genai

JavaScript

使用 Node.js v18 以上版本,透過下列 npm 指令安裝 Google Gen AI SDK for TypeScript and JavaScript

npm install @google/genai

發出第一項要求

您可以透過下列 2 種方式傳送 Gemini API 要求:

  • (建議) Interactions API 是新的基本元素,可透過型別執行步驟,原生支援多步驟工具使用、自動化調度管理和複雜的推論流程。日後,除了核心主線系列之外的新模型,以及新的代理能力和工具,都只會在 Interactions API 上推出。
  • generateContent 可讓模型產生簡單的無狀態回覆。雖然我們建議使用 Interactions API,但 generateContent 也完全支援。

這個範例使用 Interactions API,透過 Gemini 3 Flash 模型將要求傳送至 Gemini API。

如果您將 API 金鑰設為環境變數 GEMINI_API_KEY,使用 Gemini API 程式庫時,用戶端會自動擷取該金鑰。否則,您需要在初始化用戶端時傳遞 API 金鑰做為引數。

請注意,Gemini API 文件中的所有程式碼範例,都假設您已設定環境變數 GEMINI_API_KEY

Python

from google import genai

# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-3-flash-preview", 
    input="Explain how AI works in a few words"
)

# Print the model's text response
for step in interaction.steps:
    if step.type == "model_output":
        for content_block in step.content:
            if content_block.type == "text":
                print(content_block.text)

JavaScript

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

// The client gets the API key from the environment variable `GEMINI_API_KEY`.
const ai = new GoogleGenAI({});

async function main() {
  const interaction = await ai.interactions.create({
    model: "gemini-3-flash-preview",
    input: "Explain how AI works in a few words",
  });

  const modelStep = interaction.steps.find(s => s.type === 'model_output');
  if (modelStep) {
    for (const contentBlock of modelStep.content) {
      if (contentBlock.type === 'text') console.log(contentBlock.text);
    }
  }
}

main();

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "gemini-3-flash-preview",
    "input": "Explain how AI works in a few words"
  }'

後續步驟

您已發出第一項 API 要求,現在不妨參考下列指南,瞭解 Gemini 的實際運作方式: