การเริ่มต้นใช้งานฉบับย่อนี้แสดงวิธีติดตั้งไลบรารีและส่งคำขอ 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
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" } ] } ] }'
"กำลังคิด" จะเปิดอยู่โดยค่าเริ่มต้นในตัวอย่างโค้ดหลายรายการ
ตัวอย่างโค้ดจำนวนมากในเว็บไซต์นี้ใช้โมเดล Gemini 2.5 Flash ซึ่งเปิดใช้ฟีเจอร์ "การคิด" โดยค่าเริ่มต้นเพื่อปรับปรุงคุณภาพของคำตอบ โปรดทราบว่าการดำเนินการนี้อาจทำให้เวลาในการตอบสนองและการใช้โทเค็นเพิ่มขึ้น หากให้ความสําคัญกับความเร็วหรือต้องการลดต้นทุนให้น้อยที่สุด คุณสามารถปิดใช้ฟีเจอร์นี้ได้โดยการตั้งงบประมาณการคิดเป็น 0 ดังที่แสดงในตัวอย่างด้านล่าง ดูรายละเอียดเพิ่มเติมได้ที่คู่มือการคิด
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