Gemini API 快速入門導覽課程

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

事前準備

使用 Gemini API 時需要 API 金鑰,您可以免費建立金鑰,然後開始使用。

建立 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

發出第一項要求

以下範例使用 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 的實際運作方式: