Gemini API 快速入門導覽課程

本快速入門導覽課程說明如何安裝程式庫,並發出第一個 Gemini API 要求。

事前準備

您需要 Gemini API 金鑰。如果還沒有金鑰,可以在 Google AI Studio 免費取得

安裝 Google GenAI SDK

Python

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

pip install -q -U google-genai 

JavaScript

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

npm install @google/genai 

Go

在模組目錄中,使用 go get 指令安裝 google.golang.org/genai

go get google.golang.org/genai 

Java

如果您使用 Maven,可以將下列項目新增至依附元件,安裝 google-genai

<dependencies>   <dependency>     <groupId>com.google.genai</groupId>     <artifactId>google-genai</artifactId>     <version>1.0.0</version>   </dependency> </dependencies> 

Apps Script

  1. 如要建立新的 Apps Script 專案,請前往 script.new
  2. 按一下「未命名專案」
  3. 將 Apps Script 專案重新命名為「AI Studio」,然後點選「重新命名」
  4. 設定 API 金鑰
    1. 按一下左側的「專案設定」圖示 專案設定圖示
    2. 在「指令碼屬性」下方,按一下「新增指令碼屬性」
    3. 在「Property」(屬性) 中輸入鍵名:GEMINI_API_KEY
    4. 在「Value」(值) 部分輸入 API 金鑰的值。
    5. 按一下「儲存指令碼屬性」
  5. Code.gs 檔案內容替換成下列程式碼:

發出第一項要求

以下範例使用 generateContent 方法,透過 Gemini 2.5 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()  response = client.models.generate_content(     model="gemini-2.5-flash", contents="Explain how AI works in a few words" ) print(response.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 response = await ai.models.generateContent({     model: "gemini-2.5-flash",     contents: "Explain how AI works in a few words",   });   console.log(response.text); }  main(); 

Go

package main  import (     "context"     "fmt"     "log"     "google.golang.org/genai" )  func main() {     ctx := context.Background()     // The client gets the API key from the environment variable `GEMINI_API_KEY`.     client, err := genai.NewClient(ctx, nil)     if err != nil {         log.Fatal(err)     }      result, err := client.Models.GenerateContent(         ctx,         "gemini-2.5-flash",         genai.Text("Explain how AI works in a few words"),         nil,     )     if err != nil {         log.Fatal(err)     }     fmt.Println(result.Text()) } 

Java

package com.example;  import com.google.genai.Client; import com.google.genai.types.GenerateContentResponse;  public class GenerateTextFromTextInput {   public static void main(String[] args) {     // The client gets the API key from the environment variable `GEMINI_API_KEY`.     Client client = new Client();      GenerateContentResponse response =         client.models.generateContent(             "gemini-2.5-flash",             "Explain how AI works in a few words",             null);      System.out.println(response.text());   } } 

Apps Script

// 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.5-flash:generateContent';   const options = {     method: 'POST',     contentType: 'application/json',     headers: {       'x-goog-api-key': apiKey,     },     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); } 

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \   -H "x-goog-api-key: $GEMINI_API_KEY" \   -H 'Content-Type: application/json' \   -X POST \   -d '{     "contents": [       {         "parts": [           {             "text": "Explain how AI works in a few words"           }         ]       }     ]   }' 

許多程式碼範例預設會開啟「思考」功能

本網站上的許多程式碼範例都使用 Gemini 2.5 Flash 模型,這個模型預設啟用「思考」功能,可提升回覆品質。請注意,這可能會增加回應時間和權杖用量。如果您優先考量速度或希望盡量降低成本,可以將思考預算設為零,停用這項功能,如下列範例所示。詳情請參閱思考指南

Python

from google import genai from google.genai import types  client = genai.Client()  response = client.models.generate_content(     model="gemini-2.5-flash",     contents="Explain how AI works in a few words",     config=types.GenerateContentConfig(         thinking_config=types.ThinkingConfig(thinking_budget=0) # Disables thinking     ), ) print(response.text) 

JavaScript

import { GoogleGenAI } from "@google/genai";  const ai = new GoogleGenAI({});  async function main() {   const response = await ai.models.generateContent({     model: "gemini-2.5-flash",     contents: "Explain how AI works in a few words",     config: {       thinkingConfig: {         thinkingBudget: 0, // Disables thinking       },     }   });   console.log(response.text); }  await main(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, err := genai.NewClient(ctx, nil)   if err != nil {       log.Fatal(err)   }    result, _ := client.Models.GenerateContent(       ctx,       "gemini-2.5-flash",       genai.Text("Explain how AI works in a few words"),       &genai.GenerateContentConfig{         ThinkingConfig: &genai.ThinkingConfig{             ThinkingBudget: int32(0), // Disables thinking         },       }   )    fmt.Println(result.Text()) } 

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \   -H "x-goog-api-key: $GEMINI_API_KEY" \   -H 'Content-Type: application/json' \   -X POST \   -d '{     "contents": [       {         "parts": [           {             "text": "Explain how AI works in a few words"           }         ]       }     ]     "generationConfig": {       "thinkingConfig": {         "thinkingBudget": 0       }     }   }' 

Apps Script

// 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.5-flash:generateContent';   const options = {     method: 'POST',     contentType: 'application/json',     headers: {       'x-goog-api-key': apiKey,     },     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); } 

後續步驟

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