텍스트 생성
텍스트 생성 (Text generation)
Gemini API는 텍스트, 이미지, 비디오, 오디오 입력에서 텍스트 출력을 생성할 수 있어요. 이 가이드에서 기본 예시부터 thinking, 시스템 지침, 멀티모달 입력, 스트리밍, 다중 턴 대화까지 살펴볼게요.
출처: 원문
본문
Gemini API는 텍스트, 이미지, 비디오, 오디오 입력에서 텍스트 출력을 생성할 수 있어요.
기본 예시는 이렇게 생겼어요:
Python
from google import genai
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.8-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.8-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.8-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.8-flash", "How does AI work?", null);
System.out.println(response.text());
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-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.8-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);
}
Gemini와 함께 하는 Thinking
Gemini 모델은 종종 기본적으로 "thinking"이 활성화되어 있으며, 요청에 응답하기 전에 추론할 수 있어요.
각 모델은 서로 다른 thinking 구성을 지원해서 비용, 지연 시간, 지능을 제어할 수 있어요. 자세한 내용은 thinking 가이드를 참고하세요.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.8-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.8-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.8-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.8-flash", "How does AI work?", config);
System.out.println(response.text());
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-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.8-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);
}
시스템 지침과 기타 구성
시스템 지침으로 Gemini 모델의 동작을 안내할 수 있어요. 이렇게 하려면 GenerateContentConfig 객체를 전달하세요.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.8-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.8-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.8-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.8-flash", "Hello there", config);
System.out.println(response.text());
}
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-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.8-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);
}
GenerateContentConfig 객체로 max_output_tokens 같은 기본 생성 파라미터도 덮어쓸 수 있어요.
temperature, top_p, top_k 파라미터는 모델이 응답을 생성하는 방식을 제어해요. 이 파라미터를 수정할 수는 있지만, Gemini 3.x 모델에서는 기본값을 유지하는 것을 강력히 권장해요. 이 파라미터를 변경하면(예: temperature를 1.0 미만으로 설정) 특히 복잡한 수학·추론 작업에서 루핑이나 성능 저하 같은 예상치 못한 동작이 발생할 수 있어요.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-3.8-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.8-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.8-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.8-flash", "Explain how AI works", config);
System.out.println(response.text());
}
}
REST
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-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.8-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 레퍼런스의 GenerateContentConfig를 참고하세요.
멀티모달 입력
Gemini API는 멀티모달 입력을 지원해서 텍스트를 미디어 파일과 결합할 수 있어요. 다음 예시는 이미지를 제공하는 방법을 보여줘요:
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.8-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.8-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.8-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.8-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.8-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.8-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())
};
}
이미지를 제공하는 다른 방법과 더 고급 이미지 처리는 이미지 이해 가이드를 참고하세요. API는 문서, 비디오, 오디오 입력과 이해도 지원해요.
스트리밍 응답
기본적으로 모델은 전체 생성 프로세스가 완료된 후에만 응답을 반환해요.
좀 더 유연한 상호작용을 위해 스트리밍을 사용해 생성되는 대로 GenerateContentResponse 인스턴스를 점진적으로 받을 수 있어요.
Python
from google import genai
client = genai.Client()
response = client.models.generate_content_stream(
model="gemini-3.8-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.8-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.8-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.8-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.8-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.8-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);
}
다중 턴 대화 (채팅)
SDK는 여러 라운드의 프롬프트와 응답을 채팅으로 모아주는 기능을 제공해서, 대화 기록을 쉽게 추적하게 해줘요.
참고: 채팅 기능은 SDK의 일부로만 구현돼요. 내부적으로는 여전히 generateContent API를 사용해요. 다중 턴 대화에서는 각 후속 턴마다 전체 대화 기록이 모델로 전송돼요.
Python
from google import genai
client = genai.Client()
chat = client.chats.create(model="gemini-3.8-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.8-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.8-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.8-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.8-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.8-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);
}
다중 턴 대화에도 스트리밍을 사용할 수 있어요.
Python
from google import genai
client = genai.Client()
chat = client.chats.create(model="gemini-3.8-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.8-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.8-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.8-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.8-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.8-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);
}
프롬프팅 팁
Gemini를 최대한 활용하는 방법은 프롬프트 엔지니어링 가이드를 참고하세요.
다음으로
- Google AI Studio에서 Gemini 사용해 보기.
- JSON 같은 응답을 위한 구조화 출력 실험해 보기.
- Gemini의 이미지, 비디오, 오디오, 문서 이해 기능 살펴보기.
- 멀티모달 파일 프롬프팅 전략 알아보기.
콘텐츠 생성
이것은 모델에 프롬프트를 보내는 핵심 엔드포인트예요. 콘텐츠를 생성하는 엔드포인트는 두 개이며, 핵심 차이는 응답을 받는 방식이에요:
generateContent(REST): 요청을 받고 모델이 전체 생성을 완료한 후 단일 응답을 제공해요.streamGenerateContent(SSE): 동일한 요청을 받지만, 생성되는 대로 응답의 청크를 스트리밍해요. 부분 결과를 즉시 표시할 수 있어 대화형 애플리케이션에 더 나은 사용자 경험을 제공해요.
요청 본문 구조
요청 본문은 표준·스트리밍 모드 모두에서 동일한 JSON 객체이며, 몇 가지 핵심 객체로 구성돼요:
Content객체: 대화에서 단일 턴을 나타내요.Part객체:Content턴 안의 데이터 조각 (텍스트나 이미지 같은).inline_data(Blob): 원시 미디어 바이트와 MIME 타입을 담는 컨테이너.
최상위에서 요청 본문은 대화의 턴을 각각 나타내는 Content 객체 목록인 contents 객체를 포함해요. 대부분의 경우 기본 텍스트 생성에는 단일 Content 객체가 있지만, 대화 기록을 유지하려면 여러 Content 객체를 사용할 수 있어요.
다음은 전형적인 generateContent 요청 본문이에요:
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-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
]
}
]
}'
응답 본문 구조
응답 본문은 스트리밍과 표준 모드에서 다음을 제외하고 유사해요:
- 표준 모드: 응답 본문에
GenerateContentResponse인스턴스가 포함돼요. - 스트리밍 모드: 응답 본문에
GenerateContentResponse인스턴스의 스트림이 포함돼요.
높은 수준에서 응답 본문은 Candidate 객체 목록인 candidates 객체를 포함해요. Candidate 객체는 모델이 반환한 생성 응답이 있는 Content 객체를 포함해요.
REST API 예시
멀티모달 프롬프트 (텍스트와 이미지)
프롬프트에 텍스트와 이미지를 모두 제공하려면 parts 배열에 두 개의 Part 객체(텍스트용, 이미지 inline_data용)가 있어야 해요.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-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?"},
]
}]
}'
다중 턴 대화 (채팅)
여러 턴으로 대화를 만들려면 여러 Content 객체로 contents 배열을 정의해요. API는 이 전체 기록을 다음 응답의 컨텍스트로 사용해요. 각 Content 객체의 role은 user와 model을 번갈아 가야 해요.
참고: 클라이언트 SDK는 이 목록을 자동으로 관리하는 채팅 인터페이스를 제공해요. REST API를 사용할 때는 대화 기록을 유지하는 책임이 여러분에게 있어요.
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-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." }
]
}
]
}'
핵심 요약
Content는 봉투예요: 사용자든 모델이든 메시지 턴의 최상위 컨테이너예요.Part는 멀티모달을 가능하게 해요: 단일Content객체 안에서 여러Part객체를 사용해 텍스트, 이미지, 비디오 URI 등 다양한 유형의 데이터를 결합하세요.- 데이터 방식을 선택하세요:
- 대부분의 이미지처럼 작고 직접 포함되는 미디어에는
inline_data가 있는Part를 사용하세요. - 더 큰 파일이나 여러 요청에서 재사용할 파일은 File API로 업로드하고
file_data파트로 참조하세요.
- 대부분의 이미지처럼 작고 직접 포함되는 미디어에는
- 대화 기록 관리: REST API를 사용하는 채팅 애플리케이션에서는 각 턴에
Content객체를 추가하고"user"와"model"역할을 번갈아 가며contents배열을 구성하세요. SDK를 사용한다면 대화 기록 관리에 권장되는 방법은 SDK 문서를 참고하세요.
응답 예시
다음 예시는 다양한 유형의 요청에서 이 구성 요소들이 어떻게 결합되는지 보여줘요.
텍스트 전용 응답
기본 텍스트 응답은 모델의 응답을 포함하는 하나 이상의 content 객체가 있는 candidates 배열로 구성돼요.
다음은 표준 응답의 예시예요:
{
"candidates": [
{
"content": {
"parts": [
{
"text": "At its core, Artificial Intelligence works by learning from vast amounts of data ..."
}
],
"role": "model"
},
"finishReason": "STOP",
"index": 1
}
],
}
다음은 스트리밍 응답의 연속이에요. 각 응답에는 전체 응답을 묶는 responseId가 포함돼요:
{
"candidates": [
{
"content": {
"parts": [
{
"text": "The image displays"
}
],
"role": "model"
},
"index": 0
}
],
"usageMetadata": {
"promptTokenCount": ...
},
"modelVersion": "gemini-3.8-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.8-flash",
"responseId": "mAitaLmkHPPlz7IPvtfUqQ4"
}
Live API (BidiGenerateContent) WebSockets API
Live API는 실시간 스트리밍 사용 사례를 위해 양방향 스트리밍을 가능하게 하는 상태 저장 WebSocket 기반 API를 제공해요. 자세한 내용은 Live API 가이드와 Live API 레퍼런스를 확인할 수 있어요.
특수 모델
Gemini 모델 계열 외에도 Gemini API는 Nano Banana, Lyria, embedding 모델 같은 특수 모델의 엔드포인트를 제공해요. Models 섹션 아래 가이드에서 확인할 수 있어요.
플랫폼 API
나머지 엔드포인트는 지금까지 설명한 메인 엔드포인트와 함께 사용할 추가 기능을 지원해요. 자세한 내용은 Guides 섹션의 Batch mode와 File API 주제를 확인하세요.
다음으로
막 시작했다면 Gemini API 프로그래밍 모델을 이해하는 데 도움이 되는 다음 가이드를 확인하세요:
또한 서로 다른 Gemini API 기능을 소개하고 코드 예시를 제공하는 기능 가이드도 확인할 수 있어요: