텍스트 생성

Gemini API는 Gemini 모델을 활용하여 텍스트, 이미지, 동영상, 오디오를 비롯한 다양한 입력에서 텍스트 출력을 생성할 수 있습니다.

다음은 단일 텍스트 입력을 사용하는 기본 예입니다.

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) 

자바스크립트

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(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, _ := genai.NewClient(ctx, &genai.ClientConfig{       APIKey:  os.Getenv("GEMINI_API_KEY"),       Backend: genai.BackendGeminiAPI,   })    result, _ := client.Models.GenerateContent(       ctx,       "gemini-2.0-flash",       genai.Text("Explain how AI works in a few words"),       nil,   )    fmt.Println(result.Text()) } 

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?"           }         ]       }     ]   }' 

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-2.0-flash:generateContent?key=${apiKey}`;   const options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(payload)   };    const response = UrlFetchApp.fetch(url, options);   const data = JSON.parse(response);   const content = data['candidates'][0]['content']['parts'][0]['text'];   console.log(content); } 

시스템 안내 및 구성

시스템 안내를 사용하여 Gemini 모델의 동작을 안내할 수 있습니다. 이렇게 하려면 GenerateContentConfig 객체를 전달합니다.

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) 

자바스크립트

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(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, _ := genai.NewClient(ctx, &genai.ClientConfig{       APIKey:  os.Getenv("GEMINI_API_KEY"),       Backend: genai.BackendGeminiAPI,   })    config := &genai.GenerateContentConfig{       SystemInstruction: genai.NewContentFromText("You are a cat. Your name is Neko.", genai.RoleUser),   }    result, _ := client.Models.GenerateContent(       ctx,       "gemini-2.0-flash",       genai.Text("Hello there"),       config,   )    fmt.Println(result.Text()) } 

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"           }         ]       }     ]   }' 

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-2.0-flash:generateContent?key=${apiKey}`;   const options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(payload)   };    const response = UrlFetchApp.fetch(url, options);   const data = JSON.parse(response);   const content = data['candidates'][0]['content']['parts'][0]['text'];   console.log(content); } 

GenerateContentConfig 객체를 사용하면 온도와 같은 기본 생성 매개변수를 재정의할 수도 있습니다.

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) 

자바스크립트

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(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, _ := genai.NewClient(ctx, &genai.ClientConfig{     APIKey:  os.Getenv("GEMINI_API_KEY"),     Backend: genai.BackendGeminiAPI,   })    temp := float32(0.9)   topP := float32(0.5)   topK := float32(20.0)   maxOutputTokens := int32(100)    config := &genai.GenerateContentConfig{     Temperature:       &temp,     TopP:              &topP,     TopK:              &topK,     MaxOutputTokens:   maxOutputTokens,     ResponseMIMEType:  "application/json",   }    result, _ := client.Models.GenerateContent(     ctx,     "gemini-2.0-flash",     genai.Text("What is the average size of a swallow?"),     config,   )    fmt.Println(result.Text()) } 

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     }   }' 

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 = {     temperature: 1,     topP: 0.95,     topK: 40,     maxOutputTokens: 8192,     responseMimeType: '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-2.0-flash:generateContent?key=${apiKey}`;   const options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(payload)   };    const response = UrlFetchApp.fetch(url, options);   const data = JSON.parse(response);   const content = data['candidates'][0]['content']['parts'][0]['text'];   console.log(content); } 

구성 가능한 매개변수와 설명의 전체 목록은 API 참조의 GenerateContentConfig를 참고하세요.

멀티모달 입력

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) 

자바스크립트

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(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, _ := genai.NewClient(ctx, &genai.ClientConfig{       APIKey:  os.Getenv("GEMINI_API_KEY"),       Backend: genai.BackendGeminiAPI,   })    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-2.0-flash",       contents,       nil,   )    fmt.Println(result.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-2.0-flash:generateContent?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 = 'http://image/url';   const image = getImageData(imageUrl);   const payload = {     contents: [       {         parts: [           { image },           { text: 'Tell me about this instrument' },         ],       },     ],   };    const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=${apiKey}`;   const options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(payload)   };    const response = UrlFetchApp.fetch(url, options);   const data = JSON.parse(response);   const content = data['candidates'][0]['content']['parts'][0]['text'];   console.log(content); }  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(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(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, _ := genai.NewClient(ctx, &genai.ClientConfig{       APIKey:  os.Getenv("GEMINI_API_KEY"),       Backend: genai.BackendGeminiAPI,   })    stream := client.Models.GenerateContentStream(       ctx,       "gemini-2.0-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)   } } 

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"           }         ]       }     ]   }' 

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-2.0-flash:streamGenerateContent?key=${apiKey}`;   const options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(payload)   };    const response = UrlFetchApp.fetch(url, options);   const data = JSON.parse(response);   const content = data['candidates'][0]['content']['parts'][0]['text'];   console.log(content); } 

멀티턴 대화 (채팅)

Google의 SDK는 여러 번의 프롬프트와 응답을 채팅으로 수집하는 기능을 제공하므로 대화 기록을 쉽게 추적할 수 있습니다.

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) 

자바스크립트

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(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, _ := genai.NewClient(ctx, &genai.ClientConfig{       APIKey:  os.Getenv("GEMINI_API_KEY"),       Backend: genai.BackendGeminiAPI,   })    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-2.0-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)   } } 

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?"           }         ]       }     ]   }' 

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-2.0-flash:generateContent?key=${apiKey}`;   const options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(payload)   };    const response = UrlFetchApp.fetch(url, options);   const data = JSON.parse(response);   const content = data['candidates'][0]['content']['parts'][0]['text'];   console.log(content); } 

스트리밍은 멀티턴 대화에도 사용할 수 있습니다.

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) 

자바스크립트

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(); 

Go

package main  import (   "context"   "fmt"   "os"   "google.golang.org/genai" )  func main() {    ctx := context.Background()   client, _ := genai.NewClient(ctx, &genai.ClientConfig{       APIKey:  os.Getenv("GEMINI_API_KEY"),       Backend: genai.BackendGeminiAPI,   })    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-2.0-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)   } } 

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?"           }         ]       }     ]   }' 

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-2.0-flash:streamGenerateContent?key=${apiKey}`;   const options = {     method: 'POST',     contentType: 'application/json',     payload: JSON.stringify(payload)   };    const response = UrlFetchApp.fetch(url, options);   const data = JSON.parse(response);   const content = data['candidates'][0]['content']['parts'][0]['text'];   console.log(content); } 

지원되는 모델

Gemini 계열의 모든 모델은 텍스트 생성을 지원합니다. 모델 및 기능에 대해 자세히 알아보려면 모델 페이지를 참고하세요.

권장사항

프롬프트 팁

기본 텍스트 생성의 경우 예시, 시스템 안내 또는 특정 형식이 필요하지 않은 제로샷 프롬프트로 충분합니다.

맞춤형 출력을 위해 다음을 실행합니다.

  • 시스템 안내를 사용하여 모델을 안내합니다.
  • 모델을 안내할 입력 및 출력 예시를 몇 개 제공합니다. 이를 퓨샷 프롬프트라고 합니다.
  • 고급 사용 사례의 경우 미세 조정을 고려하세요.

자세한 내용은 프롬프트 엔지니어링 가이드를 참고하세요.

구조화된 출력

경우에 따라 JSON과 같은 구조화된 출력이 필요할 수 있습니다. 방법을 알아보려면 구조화된 출력 가이드를 참고하세요.

다음 단계