Gemini API สร้างเอาต์พุตข้อความเพื่อตอบสนองต่ออินพุตที่หลากหลายได้ ซึ่งรวมถึงข้อความ รูปภาพ วิดีโอ และเสียง คู่มือนี้จะแสดงวิธีสร้างข้อความโดยใช้การป้อนข้อความและรูปภาพ รวมถึงสตรีมมิง แชท และวิธีการของระบบ
การป้อนข้อความ
วิธีที่ง่ายที่สุดในการสร้างข้อความโดยใช้ Gemini API คือการให้อินพุตแบบข้อความเท่านั้นรายการเดียวแก่โมเดล ดังที่แสดงในตัวอย่างต่อไปนี้
Python
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=["How does AI work?"]
)
print(response.text)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
async function main() {
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
const prompt = "How does AI work?";
const result = await model.generateContent(prompt);
console.log(result.response.text());
}
main();
Go
// import packages here
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-2.0-flash")
resp, err := model.GenerateContent(ctx, genai.Text("How does AI work?"))
if err != nil {
log.Fatal(err)
}
printResponse(resp) // helper function for printing content parts
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "How does AI work?"
}
]
}
]
}'
อินพุตรูปภาพ
Gemini API รองรับอินพุตแบบหลายรูปแบบที่รวมไฟล์ข้อความและสื่อ ตัวอย่างต่อไปนี้แสดงวิธีสร้างข้อความจากอินพุตข้อความและรูปภาพ
Python
from PIL import Image
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
image = Image.open("/path/to/organ.png")
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=[image, "Tell me about this instrument"]
)
print(response.text)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
import * as fs from 'node:fs';
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-2.0-flash" });
function fileToGenerativePart(path, mimeType) {
return {
inlineData: {
data: Buffer.from(fs.readFileSync(path)).toString("base64"),
mimeType,
},
};
}
const prompt = "Describe how this product might be manufactured.";
const imagePart = fileToGenerativePart("/path/to/image.png", "image/png");
const result = await model.generateContent([prompt, imagePart]);
console.log(result.response.text());
Go
model := client.GenerativeModel("gemini-2.0-flash")
imgData, err := os.ReadFile(filepath.Join(testDataDir, "organ.jpg"))
if err != nil {
log.Fatal(err)
}
resp, err := model.GenerateContent(ctx,
genai.Text("Tell me about this instrument"),
genai.ImageData("jpeg", imgData))
if err != nil {
log.Fatal(err)
}
printResponse(resp)
REST
# Use a temporary file to hold the base64 encoded image data
TEMP_B64=$(mktemp)
trap 'rm -f "$TEMP_B64"' EXIT
base64 $B64FLAGS $IMG_PATH > "$TEMP_B64"
# Use a temporary file to hold the JSON payload
TEMP_JSON=$(mktemp)
trap 'rm -f "$TEMP_JSON"' EXIT
cat > "$TEMP_JSON" << EOF
{
"contents": [
{
"parts": [
{
"text": "Tell me about this instrument"
},
{
"inline_data": {
"mime_type": "image/jpeg",
"data": "$(cat "$TEMP_B64")"
}
}
]
}
]
}
EOF
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d "@$TEMP_JSON"
เอาต์พุตสตรีมมิง
โดยค่าเริ่มต้น โมเดลจะแสดงคำตอบหลังจากดำเนินการสร้างข้อความทั้งหมดเสร็จสมบูรณ์ คุณทําให้การโต้ตอบเร็วขึ้นได้โดยใช้การสตรีมเพื่อแสดงผลอินสแตนซ์ของ GenerateContentResponse
ขณะสร้างขึ้น
Python
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
response = client.models.generate_content_stream(
model="gemini-2.0-flash",
contents=["Explain how AI works"]
)
for chunk in response:
print(chunk.text, end="")
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const prompt = "Explain how AI works";
const result = await model.generateContentStream(prompt);
for await (const chunk of result.stream) {
const chunkText = chunk.text();
process.stdout.write(chunkText);
}
Go
model := client.GenerativeModel("gemini-1.5-flash")
iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))
for {
resp, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
printResponse(resp)
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=${GEMINI_API_KEY}" \
-H 'Content-Type: application/json' \
--no-buffer \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works"
}
]
}
]
}'
การสนทนาแบบหลายรอบ
Gemini SDK ช่วยให้คุณรวบรวมคำถามและคำตอบหลายรอบไว้ในแชทได้ รูปแบบแชทช่วยให้ผู้ใช้สามารถค้นหาคำตอบและรับความช่วยเหลือเกี่ยวกับปัญหาแบบหลายส่วนได้ การใช้ SDK ของแชทนี้จะมีอินเทอร์เฟซสำหรับติดตามประวัติการสนทนา แต่เบื้องหลังจะใช้เมธอด generateContent
เดียวกันเพื่อสร้างคำตอบ
ตัวอย่างโค้ดต่อไปนี้แสดงการใช้งานแชทพื้นฐาน
Python
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
chat = client.chats.create(model="gemini-2.0-flash")
response = chat.send_message("I have 2 dogs in my house.")
print(response.text)
response = chat.send_message("How many paws are in my house?")
print(response.text)
for message in chat.get_history():
print(f'role - {message.role}',end=": ")
print(message.parts[0].text)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const chat = model.startChat({
history: [
{
role: "user",
parts: [{ text: "Hello" }],
},
{
role: "model",
parts: [{ text: "Great to meet you. What would you like to know?" }],
},
],
});
let result = await chat.sendMessage("I have 2 dogs in my house.");
console.log(result.response.text());
let result2 = await chat.sendMessage("How many paws are in my house?");
console.log(result2.response.text());
Go
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()
cs.History = []*genai.Content{
{
Parts: []genai.Part{
genai.Text("Hello, I have 2 dogs in my house."),
},
Role: "user",
},
{
Parts: []genai.Part{
genai.Text("Great to meet you. What would you like to know?"),
},
Role: "model",
},
}
res, err := cs.SendMessage(ctx, genai.Text("How many paws are in my house?"))
if err != nil {
log.Fatal(err)
}
printResponse(res)
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "Hello"
}
]
},
{
"role": "model",
"parts": [
{
"text": "Great to meet you. What would you like to know?"
}
]
},
{
"role": "user",
"parts": [
{
"text": "I have two dogs in my house. How many paws are in my house?"
}
]
}
]
}'
นอกจากนี้ คุณยังใช้การสตรีมร่วมกับแชทได้ด้วย ดังที่แสดงในตัวอย่างต่อไปนี้
Python
from google import genai
client = genai.Client(api_key="GEMINI_API_KEY")
chat = client.chats.create(model="gemini-2.0-flash")
response = chat.send_message_stream("I have 2 dogs in my house.")
for chunk in response:
print(chunk.text, end="")
response = chat.send_message_stream("How many paws are in my house?")
for chunk in response:
print(chunk.text, end="")
for message in chat.get_history():
print(f'role - {message.role}', end=": ")
print(message.parts[0].text)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const chat = model.startChat({
history: [
{
role: "user",
parts: [{ text: "Hello" }],
},
{
role: "model",
parts: [{ text: "Great to meet you. What would you like to know?" }],
},
],
});
let result = await chat.sendMessageStream("I have 2 dogs in my house.");
for await (const chunk of result.stream) {
const chunkText = chunk.text();
process.stdout.write(chunkText);
}
let result2 = await chat.sendMessageStream("How many paws are in my house?");
for await (const chunk of result2.stream) {
const chunkText = chunk.text();
process.stdout.write(chunkText);
}
Go
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()
cs.History = []*genai.Content{
{
Parts: []genai.Part{
genai.Text("Hello, I have 2 dogs in my house."),
},
Role: "user",
},
{
Parts: []genai.Part{
genai.Text("Great to meet you. What would you like to know?"),
},
Role: "model",
},
}
iter := cs.SendMessageStream(ctx, genai.Text("How many paws are in my house?"))
for {
resp, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
printResponse(resp)
}
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{
"text": "Hello"
}
]
},
{
"role": "model",
"parts": [
{
"text": "Great to meet you. What would you like to know?"
}
]
},
{
"role": "user",
"parts": [
{
"text": "I have two dogs in my house. How many paws are in my house?"
}
]
}
]
}'
พารามิเตอร์การกําหนดค่า
พรอมต์ทุกรายการที่คุณส่งไปยังโมเดลจะมีพารามิเตอร์ที่ควบคุมวิธีที่โมเดลสร้างคำตอบ คุณสามารถกําหนดค่าพารามิเตอร์เหล่านี้ หรือให้โมเดลใช้ตัวเลือกเริ่มต้นก็ได้
ตัวอย่างต่อไปนี้แสดงวิธีกําหนดค่าพารามิเตอร์ของโมเดล
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.0-flash",
contents=["Explain how AI works"],
config=types.GenerateContentConfig(
max_output_tokens=500,
temperature=0.1
)
)
print(response.text)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent({
contents: [
{
role: 'user',
parts: [
{
text: "Explain how AI works",
}
],
}
],
generationConfig: {
maxOutputTokens: 1000,
temperature: 0.1,
}
});
console.log(result.response.text());
Go
model := client.GenerativeModel("gemini-1.5-pro-latest")
model.SetTemperature(0.9)
model.SetTopP(0.5)
model.SetTopK(20)
model.SetMaxOutputTokens(100)
model.SystemInstruction = genai.NewUserContent(genai.Text("You are Yoda from Star Wars."))
model.ResponseMIMEType = "application/json"
resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
if err != nil {
log.Fatal(err)
}
printResponse(resp)
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works"
}
]
}
],
"generationConfig": {
"stopSequences": [
"Title"
],
"temperature": 1.0,
"maxOutputTokens": 800,
"topP": 0.8,
"topK": 10
}
}'
ต่อไปนี้คือพารามิเตอร์โมเดลบางส่วนที่คุณกําหนดค่าได้ (รูปแบบการตั้งชื่อจะแตกต่างกันไปตามภาษาโปรแกรม)
stopSequences
: ระบุชุดลำดับอักขระ (สูงสุด 5 ชุด) ที่จะหยุดการสร้างเอาต์พุต หากระบุไว้ API จะหยุดที่stop_sequence
ที่ปรากฏขึ้นครั้งแรก ระบบจะไม่รวมลําดับการหยุดไว้เป็นส่วนหนึ่งของคําตอบtemperature
: ควบคุมความสุ่มของเอาต์พุต ใช้ค่าที่สูงขึ้นสําหรับคําตอบที่สร้างสรรค์มากขึ้น และใช้ค่าที่ต่ำลงสําหรับคําตอบที่แน่นอนมากขึ้น ค่าที่ใช้ได้อยู่ในช่วง [0.0, 2.0]maxOutputTokens
: กําหนดจํานวนโทเค็นสูงสุดที่จะรวมไว้ในตัวเลือกtopP
: เปลี่ยนวิธีที่โมเดลเลือกโทเค็นสําหรับเอาต์พุต ระบบจะเลือกโทเค็นจากความน่าจะเป็นสูงสุดไปจนถึงต่ำสุดจนกว่าผลรวมของความน่าจะเป็นจะเท่ากับค่าtopP
ค่าเริ่มต้นของtopP
คือ 0.95topK
: เปลี่ยนวิธีที่โมเดลเลือกโทเค็นสําหรับเอาต์พุตtopK
เท่ากับ 1 หมายความว่าโทเค็นที่เลือกมีแนวโน้มมากที่สุดในบรรดาโทเค็นทั้งหมดในคลังคำของโมเดล ส่วนtopK
เท่ากับ 3 หมายความว่าระบบจะเลือกโทเค็นถัดไปจากโทเค็นที่มีแนวโน้มมากที่สุด 3 รายการโดยใช้อุณหภูมิ ระบบจะกรองโทเค็นเพิ่มเติมตามtopP
โดยเลือกโทเค็นสุดท้ายโดยใช้การสุ่มตัวอย่างอุณหภูมิ
วิธีการของระบบ
คำสั่งของระบบช่วยให้คุณควบคุมลักษณะการทํางานของรูปแบบตาม Use Case ที่เฉพาะเจาะจง เมื่อระบุคำสั่งของระบบ คุณจะให้บริบทเพิ่มเติมแก่โมเดลเพื่อช่วยในการทําความเข้าใจงานและสร้างคำตอบที่ปรับแต่งมากขึ้น โดยโมเดลควรเป็นไปตามวิธีการของระบบตลอดการโต้ตอบกับผู้ใช้ ซึ่งจะช่วยให้คุณระบุลักษณะการทำงานระดับผลิตภัณฑ์แยกจากพรอมต์ที่ผู้ใช้ปลายทางระบุได้
คุณตั้งค่าคำสั่งของระบบได้เมื่อเริ่มต้นโมเดล ดังนี้
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.0-flash",
config=types.GenerateContentConfig(
system_instruction="You are a cat. Your name is Neko."),
contents="Hello there"
)
print(response.text)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
async function main() {
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({
model: "gemini-2.0-flash",
systemInstruction: "You are a cat. Your name is Neko.",
});
const prompt = "Hello there";
const result = await model.generateContent(prompt);
console.log(result.response.text());
}
main();
Go
// import packages here
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-2.0-flash")
model.SystemInstruction = &genai.Content{
Parts: []genai.Part{genai.Text(`
You are a cat. Your name is Neko.
`)},
}
resp, err := model.GenerateContent(ctx, genai.Text("Hello there"))
if err != nil {
log.Fatal(err)
}
printResponse(resp) // helper function for printing content parts
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"system_instruction": {
"parts": [
{
"text": "You are a cat. Your name is Neko."
}
]
},
"contents": [
{
"parts": [
{
"text": "Hello there"
}
]
}
]
}'
จากนั้นคุณจะส่งคำขอไปยังโมเดลได้ตามปกติ
โมเดลที่รองรับ
โมเดลทั้งหมดในตระกูล Gemini รองรับการสร้างข้อความ ดูข้อมูลเพิ่มเติมเกี่ยวกับรูปแบบและความสามารถของรูปแบบได้ที่รูปแบบ
เคล็ดลับเกี่ยวกับพรอมต์
สำหรับกรณีการใช้งานพื้นฐานในการสร้างข้อความ พรอมต์อาจไม่จําเป็นต้องใส่ตัวอย่างเอาต์พุต วิธีการของระบบ หรือข้อมูลการจัดรูปแบบ นี่เป็นแนวทางแบบไม่ใช้ข้อมูลตัวอย่าง สําหรับ Use Case บางรายการ พรอมต์แบบคำเดียวหรือแบบไม่กี่คำอาจให้ผลลัพธ์ที่สอดคล้องกับความคาดหวังของผู้ใช้มากกว่า ในบางกรณี คุณอาจต้องระบุคำสั่งของระบบด้วยเพื่อช่วยโมเดลทำความเข้าใจงานหรือทำตามหลักเกณฑ์ที่เฉพาะเจาะจง
ขั้นตอนถัดไป
- ลองใช้การเริ่มต้นใช้งาน Gemini API ใน Colab
- ดูวิธีใช้การทําความเข้าใจภาพของ Gemini เพื่อประมวลผลรูปภาพและวิดีโอ
- ดูวิธีใช้การทําความเข้าใจเสียงของ Gemini เพื่อประมวลผลไฟล์เสียง
- ดูข้อมูลเกี่ยวกับกลยุทธ์การแจ้งให้ส่งไฟล์แบบหลายรูปแบบ