Tạo văn bản
Gemini API có thể tạo đầu ra là văn bản từ dữ liệu đầu vào là văn bản, hình ảnh, video và âm thanh.
Sau đây là một ví dụ cơ bản:
Python
from google import genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="How does AI work?"
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: "How does AI work?",
});
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-3.5-flash",
genai.Text("Explain how AI works in a few words"),
nil,
)
fmt.Println(result.Text())
}
Java
import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;
public class GenerateContentWithTextInput {
public static void main(String[] args) {
Client client = new Client();
GenerateContentResponse response =
client.models.generateContent("gemini-3.5-flash", "How does AI work?", null);
System.out.println(response.text());
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "How does AI work?"
}
]
}
]
}'
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: 'How AI does work?' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.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);
}
Suy nghĩ cùng Gemini
Các mô hình Gemini thường được bật tính năng "tư duy" theo mặc định. Tính năng này cho phép mô hình suy luận trước khi trả lời một yêu cầu.
Mỗi mô hình hỗ trợ các cấu hình tư duy khác nhau, giúp bạn kiểm soát chi phí, độ trễ và mức độ thông minh. Để biết thêm thông tin, hãy xem hướng dẫn tư duy.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="How does AI work?",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(thinking_level="low")
),
)
print(response.text)
JavaScript
import { GoogleGenAI, ThinkingLevel } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: "How does AI work?",
config: {
thinkingConfig: {
thinkingLevel: ThinkingLevel.LOW,
},
}
});
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)
}
thinkingLevelVal := "low"
result, _ := client.Models.GenerateContent(
ctx,
"gemini-3.5-flash",
genai.Text("How does AI work?"),
&genai.GenerateContentConfig{
ThinkingConfig: &genai.ThinkingConfig{
ThinkingLevel: &thinkingLevelVal,
},
}
)
fmt.Println(result.Text())
}
Java
import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.ThinkingConfig;
import com.google.genai.types.ThinkingLevel;
public class GenerateContentWithThinkingConfig {
public static void main(String[] args) {
Client client = new Client();
GenerateContentConfig config =
GenerateContentConfig.builder()
.thinkingConfig(ThinkingConfig.builder().thinkingLevel(new ThinkingLevel("low")))
.build();
GenerateContentResponse response =
client.models.generateContent("gemini-3.5-flash", "How does AI work?", config);
System.out.println(response.text());
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "How does AI work?"
}
]
}
],
"generationConfig": {
"thinkingConfig": {
"thinkingLevel": "low"
}
}
}'
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: 'How AI does work?' },
],
},
],
generationConfig: {
thinkingConfig: {
thinkingLevel: 'low'
}
}
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.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);
}
Hướng dẫn hệ thống và các cấu hình khác
Bạn có thể hướng dẫn hành vi của các mô hình Gemini bằng chỉ dẫn hệ thống. Để làm như vậy, hãy truyền một đối tượng GenerateContentConfig.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.5-flash",
config=types.GenerateContentConfig(
system_instruction="You are a cat. Your name is Neko."),
contents="Hello there"
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: "Hello there",
config: {
systemInstruction: "You are a cat. Your name is Neko.",
},
});
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)
}
config := &genai.GenerateContentConfig{
SystemInstruction: genai.NewContentFromText("You are a cat. Your name is Neko.", genai.RoleUser),
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-3.5-flash",
genai.Text("Hello there"),
config,
)
fmt.Println(result.Text())
}
Java
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
public class GenerateContentWithSystemInstruction {
public static void main(String[] args) {
Client client = new Client();
GenerateContentConfig config =
GenerateContentConfig.builder()
.systemInstruction(
Content.fromParts(Part.fromText("You are a cat. Your name is Neko.")))
.build();
GenerateContentResponse response =
client.models.generateContent("gemini-3.5-flash", "Hello there", config);
System.out.println(response.text());
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
-H "x-goog-api-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"
}
]
}
]
}'
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 systemInstruction = {
parts: [{
text: 'You are a cat. Your name is Neko.'
}]
};
const payload = {
systemInstruction,
contents: [
{
parts: [
{ text: 'Hello there' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.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);
}
Đối tượng GenerateContentConfig cũng cho phép bạn ghi đè các tham số tạo mặc định, chẳng hạn như max_output_tokens.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.5-flash",
contents=["Explain how AI works"],
config=types.GenerateContentConfig(
max_output_tokens=1000
)
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: "Explain how AI works",
config: {
maxOutputTokens: 1000,
},
});
console.log(response.text);
}
await main();
Go
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
config := &genai.GenerateContentConfig{
MaxOutputTokens: 1000,
ResponseMIMEType: "application/json",
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-3.5-flash",
genai.Text("What is the average size of a swallow?"),
config,
)
fmt.Println(result.Text())
}
Java
import com.google.genai.Client;
import com.google.genai.types.GenerateContentConfig;
import com.google.genai.types.GenerateContentResponse;
public class GenerateContentWithConfig {
public static void main(String[] args) {
Client client = new Client();
GenerateContentConfig config = GenerateContentConfig.builder().maxOutputTokens(1000).build();
GenerateContentResponse response =
client.models.generateContent("gemini-3.5-flash", "Explain how AI works", config);
System.out.println(response.text());
}
}
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.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"
}
]
}
],
"generationConfig": {
"stopSequences": [
"Title"
],
"maxOutputTokens": 1000
}
}'
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 generationConfig = {
maxOutputTokens: 1000,
responseFormat: { text: { mimeType: "text/plain" } },
};
const payload = {
generationConfig,
contents: [
{
parts: [
{ text: 'Explain how AI works in a few words' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.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);
}
Hãy tham khảo GenerateContentConfig trong tài liệu tham khảo API của chúng tôi để xem danh sách đầy đủ các tham số có thể định cấu hình và nội dung mô tả của các tham số đó.
Thông tin đầu vào đa phương thức
Gemini API hỗ trợ dữ liệu đầu vào đa phương thức, cho phép bạn kết hợp văn bản với các tệp nội dung nghe nhìn. Ví dụ sau đây minh hoạ cách cung cấp hình ảnh:
Python
from PIL import Image
from google import genai
client = genai.Client()
image = Image.open("/path/to/organ.png")
response = client.models.generate_content(
model="gemini-3.5-flash",
contents=[image, "Tell me about this instrument"]
)
print(response.text)
JavaScript
import {
GoogleGenAI,
createUserContent,
createPartFromUri,
} from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const image = await ai.files.upload({
file: "/path/to/organ.png",
});
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: [
createUserContent([
"Tell me about this instrument",
createPartFromUri(image.uri, image.mimeType),
]),
],
});
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)
}
imagePath := "/path/to/organ.jpg"
imgData, _ := os.ReadFile(imagePath)
parts := []*genai.Part{
genai.NewPartFromText("Tell me about this instrument"),
&genai.Part{
InlineData: &genai.Blob{
MIMEType: "image/jpeg",
Data: imgData,
},
},
}
contents := []*genai.Content{
genai.NewContentFromParts(parts, genai.RoleUser),
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-3.5-flash",
contents,
nil,
)
fmt.Println(result.Text())
}
Java
import com.google.genai.Client;
import com.google.genai.Content;
import com.google.genai.types.GenerateContentResponse;
import com.google.genai.types.Part;
public class GenerateContentWithMultiModalInputs {
public static void main(String[] args) {
Client client = new Client();
Content content =
Content.fromParts(
Part.fromText("Tell me about this instrument"),
Part.fromUri("/path/to/organ.jpg", "image/jpeg"));
GenerateContentResponse response =
client.models.generateContent("gemini-3.5-flash", content, null);
System.out.println(response.text());
}
}
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-3.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d "@$TEMP_JSON"
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 imageUrl = 'https://example.com/image.jpg';
const image = getImageData(imageUrl);
const payload = {
contents: [
{
parts: [
{ image },
{ text: 'Tell me about this instrument' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.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);
}
function getImageData(url) {
const blob = UrlFetchApp.fetch(url).getBlob();
return {
mimeType: blob.getContentType(),
data: Utilities.base64Encode(blob.getBytes())
};
}
Để biết các phương thức thay thế để cung cấp hình ảnh và quy trình xử lý hình ảnh nâng cao hơn, hãy xem hướng dẫn về việc hiểu hình ảnh. API này cũng hỗ trợ các đầu vào và thông tin văn bản, video và âm thanh.
Hiện câu trả lời theo thời gian thực
Theo mặc định, mô hình chỉ trả về phản hồi sau khi toàn bộ quá trình tạo hoàn tất.
Để có các hoạt động tương tác mượt mà hơn, hãy sử dụng tính năng truyền phát trực tiếp để nhận các thực thể GenerateContentResponse theo gia số khi chúng được tạo.
Python
from google import genai
client = genai.Client()
response = client.models.generate_content_stream(
model="gemini-3.5-flash",
contents=["Explain how AI works"]
)
for chunk in response:
print(chunk.text, end="")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContentStream({
model: "gemini-3.5-flash",
contents: "Explain how AI works",
});
for await (const chunk of response) {
console.log(chunk.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)
}
stream := client.Models.GenerateContentStream(
ctx,
"gemini-3.5-flash",
genai.Text("Write a story about a magic backpack."),
nil,
)
for chunk, _ := range stream {
part := chunk.Candidates[0].Content.Parts[0]
fmt.Print(part.Text)
}
}
Java
import com.google.genai.Client;
import com.google.genai.ResponseStream;
import com.google.genai.types.GenerateContentResponse;
public class GenerateContentStream {
public static void main(String[] args) {
Client client = new Client();
ResponseStream<GenerateContentResponse> responseStream =
client.models.generateContentStream(
"gemini-3.5-flash", "Write a story about a magic backpack.", null);
for (GenerateContentResponse res : responseStream) {
System.out.print(res.text());
}
// To save resources and avoid connection leaks, it is recommended to close the response
// stream after consumption (or using try block to get the response stream).
responseStream.close();
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:streamGenerateContent?alt=sse" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
--no-buffer \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works"
}
]
}
]
}'
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' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:streamGenerateContent';
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);
}
Cuộc trò chuyện nhiều lượt (chat)
Các SDK của chúng tôi cung cấp chức năng thu thập nhiều vòng lời nhắc và câu trả lời vào một cuộc trò chuyện, giúp bạn dễ dàng theo dõi nhật ký trò chuyện.
Python
from google import genai
client = genai.Client()
chat = client.chats.create(model="gemini-3.5-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 { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const chat = ai.chats.create({
model: "gemini-3.5-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();
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)
}
history := []*genai.Content{
genai.NewContentFromText("Hi nice to meet you! I have 2 dogs in my house.", genai.RoleUser),
genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),
}
chat, _ := client.Chats.Create(ctx, "gemini-3.5-flash", nil, history)
res, _ := chat.SendMessage(ctx, genai.Part{Text: "How many paws are in my house?"})
if len(res.Candidates) > 0 {
fmt.Println(res.Candidates[0].Content.Parts[0].Text)
}
}
Java
import com.google.genai.Chat;
import com.google.genai.Client;
import com.google.genai.types.Content;
import com.google.genai.types.GenerateContentResponse;
public class MultiTurnConversation {
public static void main(String[] args) {
Client client = new Client();
Chat chatSession = client.chats.create("gemini-3.5-flash");
GenerateContentResponse response =
chatSession.sendMessage("I have 2 dogs in my house.");
System.out.println("First response: " + response.text());
response = chatSession.sendMessage("How many paws are in my house?");
System.out.println("Second response: " + response.text());
// Get the history of the chat session.
// Passing 'true' to getHistory() returns the curated history, which excludes
// empty or invalid parts.
// Passing 'false' here would return the comprehensive history, including
// empty or invalid parts.
ImmutableList<Content> history = chatSession.getHistory(true);
System.out.println("History: " + history);
}
}
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent \
-H "x-goog-api-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?"
}
]
}
]
}'
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: [
{
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?' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.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);
}
Bạn cũng có thể dùng tính năng truyền trực tuyến cho các cuộc trò chuyện nhiều lượt.
Python
from google import genai
client = genai.Client()
chat = client.chats.create(model="gemini-3.5-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 { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const chat = ai.chats.create({
model: "gemini-3.5-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();
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)
}
history := []*genai.Content{
genai.NewContentFromText("Hi nice to meet you! I have 2 dogs in my house.", genai.RoleUser),
genai.NewContentFromText("Great to meet you. What would you like to know?", genai.RoleModel),
}
chat, _ := client.Chats.Create(ctx, "gemini-3.5-flash", nil, history)
stream := chat.SendMessageStream(ctx, genai.Part{Text: "How many paws are in my house?"})
for chunk, _ := range stream {
part := chunk.Candidates[0].Content.Parts[0]
fmt.Print(part.Text)
}
}
Java
import com.google.genai.Chat;
import com.google.genai.Client;
import com.google.genai.ResponseStream;
import com.google.genai.types.GenerateContentResponse;
public class MultiTurnConversationWithStreaming {
public static void main(String[] args) {
Client client = new Client();
Chat chatSession = client.chats.create("gemini-3.5-flash");
ResponseStream<GenerateContentResponse> responseStream =
chatSession.sendMessageStream("I have 2 dogs in my house.", null);
for (GenerateContentResponse response : responseStream) {
System.out.print(response.text());
}
responseStream = chatSession.sendMessageStream("How many paws are in my house?", null);
for (GenerateContentResponse response : responseStream) {
System.out.print(response.text());
}
// Get the history of the chat session. History is added after the stream
// is consumed and includes the aggregated response from the stream.
System.out.println("History: " + chatSession.getHistory(false));
}
}
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:streamGenerateContent?alt=sse \
-H "x-goog-api-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?"
}
]
}
]
}'
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: [
{
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?' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:streamGenerateContent';
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);
}
Mẹo tạo câu lệnh
Hãy tham khảo hướng dẫn về thiết kế câu lệnh của chúng tôi để biết các đề xuất về cách khai thác tối đa Gemini.
Bước tiếp theo
- Dùng thử Gemini trong Google AI Studio.
- Thử nghiệm với đầu ra có cấu trúc cho các phản hồi tương tự như JSON.
- Khám phá các khả năng hiểu hình ảnh, video, âm thanh và tài liệu của Gemini.
- Tìm hiểu về các chiến lược đưa ra câu lệnh bằng tệp đa phương thức.
Tạo nội dung
Đây là điểm cuối trung tâm để gửi câu lệnh đến mô hình. Có 2 điểm cuối để tạo nội dung, điểm khác biệt chính là cách bạn nhận phản hồi:
generateContent(REST): Nhận một yêu cầu và cung cấp một phản hồi duy nhất sau khi mô hình hoàn tất toàn bộ quá trình tạo.streamGenerateContent(SSE): Nhận chính xác cùng một yêu cầu, nhưng mô hình sẽ truyền trực tuyến các phần phản hồi khi chúng được tạo. Điều này giúp cải thiện trải nghiệm người dùng cho các ứng dụng tương tác vì cho phép bạn hiển thị ngay kết quả một phần.
Cấu trúc nội dung yêu cầu
Nội dung yêu cầu là một đối tượng JSON giống hệt nhau đối với cả chế độ tiêu chuẩn và chế độ truyền phát trực tiếp, đồng thời được tạo từ một số đối tượng cốt lõi:
- Đối tượng
Content: Đại diện cho một lượt trong cuộc trò chuyện. - Đối tượng
Part: Một phần dữ liệu trong lượtContent(chẳng hạn như văn bản hoặc hình ảnh). inline_data(Blob): Vùng chứa cho các byte nội dung nghe nhìn thô và loại MIME của chúng.
Ở cấp cao nhất, phần nội dung yêu cầu chứa một đối tượng contents, đây là danh sách các đối tượng Content, mỗi đối tượng đại diện cho lượt trong cuộc trò chuyện. Trong hầu hết các trường hợp, để tạo văn bản cơ bản, bạn sẽ có một đối tượng Content duy nhất, nhưng nếu muốn duy trì nhật ký trò chuyện, bạn có thể sử dụng nhiều đối tượng Content.
Sau đây là nội dung yêu cầu generateContent điển hình:
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
// A list of Part objects goes here
]
},
{
"role": "model",
"parts": [
// A list of Part objects goes here
]
}
]
}'
Cấu trúc nội dung phản hồi
Nội dung phản hồi tương tự cho cả chế độ phát trực tuyến và chế độ tiêu chuẩn, ngoại trừ những điểm sau:
- Chế độ chuẩn: Nội dung phản hồi chứa một phiên bản của
GenerateContentResponse. - Chế độ truyền phát trực tiếp: Nội dung phản hồi chứa một luồng các thực thể
GenerateContentResponse.
Nhìn chung, phần nội dung phản hồi chứa một đối tượng candidates, là danh sách các đối tượng Candidate. Đối tượng Candidate chứa một đối tượng Content có phản hồi được tạo do mô hình trả về.
Ví dụ về API REST
Câu lệnh đa phương thức (văn bản và hình ảnh)
Để cung cấp cả văn bản và hình ảnh trong một câu lệnh, mảng parts phải chứa hai đối tượng Part: một cho văn bản và một cho hình ảnh inline_data.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{
"inline_data": {
"mime_type":"image/jpeg",
"data": "/9j/4AAQSkZJRgABAQ... (base64-encoded image)"
}
},
{"text": "What is in this picture?"},
]
}]
}'
Cuộc trò chuyện nhiều lượt (chat)
Để tạo một cuộc trò chuyện có nhiều lượt, bạn hãy xác định mảng contents bằng nhiều đối tượng Content. API sẽ sử dụng toàn bộ nhật ký này làm bối cảnh cho phản hồi tiếp theo. role cho mỗi đối tượng Content phải thay đổi giữa user và model.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"role": "user",
"parts": [
{ "text": "Hello." }
]
},
{
"role": "model",
"parts": [
{ "text": "Hello! How can I help you today?" }
]
},
{
"role": "user",
"parts": [
{ "text": "Please write a four-line poem about the ocean." }
]
}
]
}'
Những điểm chính cần ghi nhớ
Contentlà phong bì: Đây là vùng chứa cấp cao nhất cho một lượt tương tác trong tin nhắn, cho dù đó là từ người dùng hay mô hình.Partcho phép đa phương thức: Sử dụng nhiều đối tượngParttrong một đối tượngContentđể kết hợp nhiều loại dữ liệu (văn bản, hình ảnh, URI video, v.v.).- Chọn phương thức dữ liệu:
- Đối với nội dung nghe nhìn nhỏ, được nhúng trực tiếp (như hầu hết hình ảnh), hãy sử dụng
Partvớiinline_data. - Đối với các tệp lớn hơn hoặc tệp mà bạn muốn sử dụng lại trên các yêu cầu, hãy sử dụng File API để tải tệp lên và tham chiếu tệp đó bằng một phần
file_data.
- Đối với nội dung nghe nhìn nhỏ, được nhúng trực tiếp (như hầu hết hình ảnh), hãy sử dụng
- Quản lý nhật ký trò chuyện: Đối với các ứng dụng trò chuyện sử dụng REST API, hãy tạo mảng
contentsbằng cách thêm các đối tượngContentcho mỗi lượt, luân phiên giữa các vai trò"user"và"model". Nếu bạn đang sử dụng một SDK, hãy tham khảo tài liệu SDK để biết cách quản lý nhật ký cuộc trò chuyện được đề xuất.
Ví dụ về phản hồi
Các ví dụ sau đây cho thấy cách các thành phần này kết hợp với nhau cho nhiều loại yêu cầu.
Câu trả lời chỉ có văn bản
Phản hồi văn bản mặc định bao gồm một mảng candidates có một hoặc nhiều đối tượng content chứa phản hồi của mô hình.
Sau đây là ví dụ về một phản hồi chuẩn:
{
"candidates": [
{
"content": {
"parts": [
{
"text": "At its core, Artificial Intelligence works by learning from vast amounts of data ..."
}
],
"role": "model"
},
"finishReason": "STOP",
"index": 1
}
],
}
Sau đây là chuỗi các phản hồi truyền trực tuyến. Mỗi phản hồi đều chứa một responseId liên kết toàn bộ phản hồi với nhau:
{
"candidates": [
{
"content": {
"parts": [
{
"text": "The image displays"
}
],
"role": "model"
},
"index": 0
}
],
"usageMetadata": {
"promptTokenCount": ...
},
"modelVersion": "gemini-3.5-flash",
"responseId": "mAitaLmkHPPlz7IPvtfUqQ4"
}
...
{
"candidates": [
{
"content": {
"parts": [
{
"text": " the following materials:\n\n* **Wood:** The accordion and the violin are primarily"
}
],
"role": "model"
},
"index": 0
}
],
"usageMetadata": {
"promptTokenCount": ...
}
"modelVersion": "gemini-3.5-flash",
"responseId": "mAitaLmkHPPlz7IPvtfUqQ4"
}
Live API (BidiGenerateContent) WebSockets API
Live API cung cấp một API dựa trên WebSocket có trạng thái để truyền trực tuyến hai chiều nhằm hỗ trợ các trường hợp sử dụng truyền trực tuyến theo thời gian thực. Bạn có thể xem hướng dẫn về Live API và tài liệu tham khảo API Live để biết thêm thông tin chi tiết.
Mô hình chuyên biệt
Ngoài nhóm mô hình của Gemini, Gemini API còn cung cấp các điểm cuối cho các mô hình chuyên biệt như Imagen, Lyria và các mô hình nhúng. Bạn có thể xem các hướng dẫn này trong phần Mô hình.
Platform API
Các điểm cuối còn lại cho phép bạn sử dụng các chức năng bổ sung với các điểm cuối chính đã mô tả cho đến nay. Hãy xem các chủ đề Chế độ hàng loạt và File API trong phần Hướng dẫn để tìm hiểu thêm.
Bước tiếp theo
Nếu bạn mới bắt đầu, hãy tham khảo các hướng dẫn sau đây để hiểu rõ mô hình lập trình Gemini API:
Bạn cũng có thể xem hướng dẫn về các chức năng. Hướng dẫn này giới thiệu các tính năng của Gemini API và cung cấp ví dụ về mã: