Gemini API 快速入門導覽課程

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

事前準備

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

安裝 Google Gen AI SDK

Python

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

pip install -q -U google-genai 

JavaScript

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

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. 按一下「Untitled project」
  3. 重新命名 Apps Script 專案「AI Studio」,然後按一下「Rename」
  4. 設定 API 金鑰
    1. 按一下左側的「專案設定」圖示 專案設定圖示
    2. 在「指令碼屬性」下方,按一下「新增指令碼屬性」
    3. 在「Property」中輸入鍵名:GEMINI_API_KEY
    4. 在「Value」 中輸入 API 金鑰的值。
    5. 按一下「儲存指令碼屬性」
  5. 使用下列程式碼取代 Code.gs 檔案內容:

提出第一個要求

以下範例使用 generateContent 方法,透過 Gemini 2.5 Flash 模型傳送要求至 Gemini API。

Python

from google import genai  client = genai.Client(api_key="YOUR_API_KEY")  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";  const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });  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()     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.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 `GOOGLE_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?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); } 

REST

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-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"           }         ]       }     ]   }' 

許多程式碼範例預設為啟用「Thinking」

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

Python

from google import genai from google.genai import types  client = genai.Client(api_key="GEMINI_API_KEY")  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({ apiKey: "GEMINI_API_KEY" });  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, _ := genai.NewClient(ctx, &genai.ClientConfig{       APIKey:  os.Getenv("GEMINI_API_KEY"),       Backend: genai.BackendGeminiAPI,   })    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?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?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); } 

後續步驟

您已完成第一個 API 要求,建議您參閱下列指南,瞭解 Gemini 的運作方式: