本快速入門說明如何安裝程式庫,並發出第一個 Gemini API 要求。
事前準備
您需要 Gemini API 金鑰。如果還沒有金鑰,可以在 Google AI Studio 免費取得。
安裝 Google GenAI SDK
使用 Python 3.9 以上版本,請使用以下 pip 指令安裝 google-genai
套件:
pip install -q -U google-genai
使用 Node.js 18 以上版本,請使用下列 npm 指令安裝 Google Gen AI SDK for TypeScript and JavaScript:
npm install @google/genai
使用 go get 指令在模組目錄中安裝 google.golang.org/genai:
go get google.golang.org/genai
- 如要建立新的 Apps Script 專案,請前往 script.new。
- 按一下「Untitled project」。
- 重新命名 Apps Script 專案「AI Studio」,然後按一下「Rename」。
- 設定 API 金鑰
- 按一下左側的「專案設定」圖示
。
- 在「指令碼屬性」下方,按一下「新增指令碼屬性」。
- 在「Property」 中輸入鍵名:
GEMINI_API_KEY
。 - 在「Value」 中輸入 API 金鑰的值。
- 按一下「儲存指令碼屬性」。
- 按一下左側的「專案設定」圖示
- 使用下列程式碼取代
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 的運作方式: