API Gemini có thể tạo đầu ra văn bản để phản hồi nhiều loại dữ liệu đầu vào, bao gồm cả văn bản, hình ảnh, video và âm thanh. Hướng dẫn này cho bạn biết cách tạo văn bản bằng cách sử dụng dữ liệu đầu vào văn bản và hình ảnh. Hướng dẫn này cũng bao gồm các hướng dẫn về tính năng phát trực tuyến, trò chuyện và hệ thống.
Nhập văn bản
Cách đơn giản nhất để tạo văn bản bằng API Gemini là cung cấp cho mô hình một đầu vào chỉ văn bản, như trong ví dụ sau:
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)
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.0-flash",
contents: "How does AI work?",
});
console.log(response.text);
}
await main();
// 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
}
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?"
}
]
}
]
}'
Nhập hình ảnh
API Gemini hỗ trợ phương thức nhập đa phương thức kết hợp tệp văn bản và nội dung nghe nhìn. Ví dụ sau đây cho thấy cách tạo văn bản từ dữ liệu đầu vào văn bản và hình ảnh:
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)
import {
GoogleGenAI,
createUserContent,
createPartFromUri,
} from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const image = await ai.files.upload({
file: "/path/to/organ.png",
});
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: [
createUserContent([
"Tell me about this instrument",
createPartFromUri(image.uri, image.mimeType),
]),
],
});
console.log(response.text);
}
await main();
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)
# 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"
Đầu ra phát trực tuyến
Theo mặc định, mô hình sẽ trả về một phản hồi sau khi hoàn tất toàn bộ quá trình tạo văn bản. Bạn có thể đạt được khả năng tương tác nhanh hơn bằng cách sử dụng tính năng truyền trực tuyến để trả về các thực thể của GenerateContentResponse
khi chúng được tạo.
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="")
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const response = await ai.models.generateContentStream({
model: "gemini-2.0-flash",
contents: "Explain how AI works",
});
for await (const chunk of response) {
console.log(chunk.text);
}
}
await main();
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)
}
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"
}
]
}
]
}'
Cuộc trò chuyện nhiều lượt
SDK Gemini cho phép bạn thu thập nhiều vòng câu hỏi và câu trả lời vào một cuộc trò chuyện. Định dạng trò chuyện cho phép người dùng từng bước tìm ra câu trả lời và nhận trợ giúp về các vấn đề gồm nhiều phần. Việc triển khai SDK trò chuyện này cung cấp một giao diện để theo dõi nhật ký trò chuyện, nhưng ở chế độ nền, giao diện này sử dụng cùng một phương thức generateContent
để tạo phản hồi.
Ví dụ về mã sau đây cho thấy cách triển khai tính năng trò chuyện cơ bản:
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)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const chat = ai.chats.create({
model: "gemini-2.0-flash",
history: [
{
role: "user",
parts: [{ text: "Hello" }],
},
{
role: "model",
parts: [{ text: "Great to meet you. What would you like to know?" }],
},
],
});
const response1 = await chat.sendMessage({
message: "I have 2 dogs in my house.",
});
console.log("Chat response 1:", response1.text);
const response2 = await chat.sendMessage({
message: "How many paws are in my house?",
});
console.log("Chat response 2:", response2.text);
}
await main();
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)
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?"
}
]
}
]
}'
Bạn cũng có thể sử dụng tính năng phát trực tiếp kèm theo tính năng trò chuyện, như trong ví dụ sau:
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)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
async function main() {
const chat = ai.chats.create({
model: "gemini-2.0-flash",
history: [
{
role: "user",
parts: [{ text: "Hello" }],
},
{
role: "model",
parts: [{ text: "Great to meet you. What would you like to know?" }],
},
],
});
const stream1 = await chat.sendMessageStream({
message: "I have 2 dogs in my house.",
});
for await (const chunk of stream1) {
console.log(chunk.text);
console.log("_".repeat(80));
}
const stream2 = await chat.sendMessageStream({
message: "How many paws are in my house?",
});
for await (const chunk of stream2) {
console.log(chunk.text);
console.log("_".repeat(80));
}
}
await main();
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)
}
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?"
}
]
}
]
}'
Tham số cấu hình
Mọi câu lệnh bạn gửi đến mô hình đều bao gồm các tham số kiểm soát cách mô hình tạo phản hồi. Bạn có thể định cấu hình các tham số này hoặc cho phép mô hình sử dụng các tuỳ chọn mặc định.
Ví dụ sau đây cho thấy cách định cấu hình các tham số mô hình:
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)
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.0-flash",
contents: "Explain how AI works",
config: {
maxOutputTokens: 500,
temperature: 0.1,
},
});
console.log(response.text);
}
await main();
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)
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
}
}'
Sau đây là một số thông số mô hình mà bạn có thể định cấu hình. (Quy ước đặt tên thay đổi tuỳ theo ngôn ngữ lập trình.)
stopSequences
: Chỉ định tập hợp các trình tự ký tự (tối đa 5) sẽ ngừng tạo đầu ra. Nếu được chỉ định, API sẽ dừng tại lần xuất hiện đầu tiên củastop_sequence
. Trình tự dừng sẽ không được đưa vào phản hồi.temperature
: Kiểm soát tính ngẫu nhiên của kết quả. Sử dụng các giá trị cao hơn để có nhiều phản hồi sáng tạo hơn và các giá trị thấp hơn để có nhiều phản hồi có thể xác định hơn. Giá trị có thể nằm trong khoảng [0,0, 2,0].maxOutputTokens
: Đặt số lượng mã thông báo tối đa để đưa vào một đề xuất.topP
: Thay đổi cách mô hình chọn mã thông báo cho đầu ra. Các mã thông báo được chọn từ xác suất cao nhất đến thấp nhất cho đến khi tổng xác suất của các mã thông báo bằng giá trịtopP
. Giá trịtopP
mặc định là 0,95.topK
: Thay đổi cách mô hình chọn mã thông báo cho đầu ra.topK
bằng 1 có nghĩa là mã thông báo được chọn là mã thông báo có nhiều khả năng nhất trong số tất cả các mã thông báo trong từ vựng của mô hình, trong khitopK
bằng 3 có nghĩa là mã thông báo tiếp theo được chọn trong số 3 mã thông báo có nhiều khả năng nhất bằng cách sử dụng nhiệt độ. Các mã thông báo được lọc thêm dựa trêntopP
, trong đó mã thông báo cuối cùng được chọn bằng cách lấy mẫu nhiệt độ.
Hướng dẫn về hệ thống
Hướng dẫn hệ thống cho phép bạn điều hướng hành vi của một mô hình dựa trên trường hợp sử dụng cụ thể. Khi cung cấp hướng dẫn hệ thống, bạn sẽ cung cấp thêm ngữ cảnh cho mô hình để giúp mô hình hiểu được nhiệm vụ và tạo ra các câu trả lời được tuỳ chỉnh hơn. Mô hình phải tuân thủ hướng dẫn của hệ thống trong toàn bộ quá trình tương tác với người dùng, cho phép bạn chỉ định hành vi ở cấp sản phẩm riêng biệt với lời nhắc do người dùng cuối cung cấp.
Bạn có thể đặt hướng dẫn hệ thống khi khởi chạy mô hình:
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)
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.0-flash",
contents: "Hello there",
config: {
systemInstruction: "You are a cat. Your name is Neko.",
},
});
console.log(response.text);
}
await main();
// 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
}
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"
}
]
}
]
}'
Sau đó, bạn có thể gửi yêu cầu đến mô hình như bình thường.
Mô hình được hỗ trợ
Toàn bộ nhóm mô hình Gemini đều hỗ trợ tạo văn bản. Để tìm hiểu thêm về các mô hình và chức năng của chúng, hãy xem phần Mô hình.
Mẹo về câu lệnh
Đối với các trường hợp sử dụng tạo văn bản cơ bản, câu lệnh của bạn có thể không cần bao gồm bất kỳ ví dụ đầu ra, hướng dẫn hệ thống hoặc thông tin định dạng nào. Đây là phương pháp không có ví dụ. Đối với một số trường hợp sử dụng, lời nhắc một lần hoặc vài lần có thể tạo ra kết quả phù hợp hơn với kỳ vọng của người dùng. Trong một số trường hợp, bạn cũng nên cung cấp hướng dẫn hệ thống để giúp mô hình hiểu được nhiệm vụ hoặc tuân theo các nguyên tắc cụ thể.
Bước tiếp theo
- Dùng thử hướng dẫn bắt đầu sử dụng Gemini API trong Colab.
- Tìm hiểu cách sử dụng tính năng hiểu thị giác của Gemini để xử lý hình ảnh và video.
- Tìm hiểu cách sử dụng tính năng hiểu âm thanh của Gemini để xử lý tệp âm thanh.
- Tìm hiểu về chiến lược nhắc tệp đa phương thức.