การเริ่มต้นใช้งานฉบับย่อนี้แสดงวิธีติดตั้งไลบรารีและส่งคำขอ Gemini API รายการแรก
ก่อนเริ่มต้น
คุณต้องมีคีย์ Gemini API หากยังไม่มี คุณสามารถรับได้ฟรีใน Google AI Studio
ติดตั้ง Google GenAI SDK
Python
หากใช้ Python 3.9 ขึ้นไป ให้ติดตั้งแพ็กเกจ google-genai
โดยใช้คำสั่ง pip ต่อไปนี้
pip install -q -U google-genai
JavaScript
เมื่อใช้ Node.js v18 ขึ้นไป ให้ติดตั้ง Google Gen AI SDK สําหรับ TypeScript และ JavaScript โดยใช้คําสั่ง npm ต่อไปนี้
npm install @google/genai
Go
ติดตั้ง google.golang.org/genai ในไดเรกทอรีโมดูลโดยใช้คำสั่ง go get
go get google.golang.org/genai
Java
หากใช้ Maven คุณสามารถติดตั้ง google-genai ได้โดยเพิ่มรายการต่อไปนี้ลงใน Dependency
<dependencies>
<dependency>
<groupId>com.google.genai</groupId>
<artifactId>google-genai</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
Apps Script
- หากต้องการสร้างโปรเจ็กต์ Apps Script ใหม่ ให้ไปที่ script.new
- คลิกโปรเจ็กต์ที่ไม่มีชื่อ
- เปลี่ยนชื่อโปรเจ็กต์ Apps Script เป็น AI Studio แล้วคลิกเปลี่ยนชื่อ
- ตั้งค่าคีย์ API
- คลิกการตั้งค่าโปรเจ็กต์
ทางด้านซ้าย
- ในส่วนพร็อพเพอร์ตี้สคริปต์ ให้คลิกเพิ่มพร็อพเพอร์ตี้สคริปต์
- ในส่วน Property ให้ป้อนชื่อคีย์:
GEMINI_API_KEY
- สําหรับค่า ให้ป้อนค่าสําหรับคีย์ API
- คลิกบันทึกพร็อพเพอร์ตี้ของสคริปต์
- คลิกการตั้งค่าโปรเจ็กต์
- แทนที่เนื้อหาไฟล์
Code.gs
ด้วยโค้ดต่อไปนี้
ส่งคำขอแรก
ต่อไปนี้คือตัวอย่างที่ใช้เมธอด generateContent
เพื่อส่งคําขอไปยัง Gemini API โดยใช้โมเดล Gemini 2.5 Flash
หากคุณตั้งค่าคีย์ 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 ซึ่งเปิดใช้ฟีเจอร์ "การคิด" โดยค่าเริ่มต้นเพื่อปรับปรุงคุณภาพของคำตอบ โปรดทราบว่าการดำเนินการนี้อาจทำให้เวลาในการตอบสนองและการใช้โทเค็นเพิ่มขึ้น หากให้ความสําคัญกับความเร็วหรือต้องการลดต้นทุนให้น้อยที่สุด คุณสามารถปิดใช้ฟีเจอร์นี้ได้โดยการตั้งงบประมาณการคิดเป็น 0 ดังที่แสดงในตัวอย่างด้านล่าง ดูรายละเอียดเพิ่มเติมได้ที่คู่มือการคิด
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