Gemini API 개요

Gemini API를 사용하면 Google의 최신 생성 모델에 액세스할 수 있습니다. API를 통해 사용할 수 있는 일반 기능에 익숙해졌다면 선택한 언어에 대한 튜토리얼을 통해 개발을 시작해 보세요.

모델

Gemini는 Google에서 개발한 일련의 멀티모달 생성형 AI 모델입니다. Gemini 모델은 선택한 모델 변형에 따라 프롬프트에서 텍스트 및 이미지를 허용하고 텍스트 응답을 출력할 수 있습니다.

자세한 모델 정보를 확인하려면 Gemini 모델 페이지를 참고하세요. list_models 메서드를 사용하여 사용 가능한 모든 모델을 나열한 후 get_model 메서드를 사용하여 특정 모델의 메타데이터를 가져올 수도 있습니다.

프롬프트 데이터 및 설계

특정 Gemini 모델은 텍스트 데이터와 미디어 파일을 모두 입력으로 허용합니다. 이 기능은 콘텐츠 생성, 데이터 분석, 문제 해결에 필요한 많은 가능성을 제공합니다. 사용 중인 모델의 일반적인 입력 토큰 한도를 포함하여 고려해야 할 몇 가지 제한사항과 요구사항이 있습니다. 특정 모델의 토큰 한도에 관한 자세한 내용은 Gemini 모델을 참고하세요.

Gemini API를 사용하는 프롬프트의 크기는 20MB를 초과할 수 없습니다. Gemini API는 프롬프트에 사용할 미디어 파일을 임시로 저장하는 File API를 제공하므로 20MB 한도를 초과하는 프롬프트 데이터를 제공할 수 있습니다. Files API 사용 및 메시지 표시에 지원되는 파일 형식에 관한 자세한 내용은 미디어 파일로 메시지 표시를 참고하세요.

프롬프트 설계 및 텍스트 입력

효과적인 프롬프트 또는 프롬프트 엔지니어링을 만드는 것은 예술과 과학의 조합입니다. 프롬프팅에 접근하는 방법에 대한 안내는 프롬프팅 소개를, 프롬프팅에 대한 다양한 접근 방식을 알아보려면 프롬프트 101 가이드를 참조하세요.

콘텐츠 생성

Gemini API를 사용하면 사용하는 모델 변형에 따라 프롬프트에 텍스트 데이터와 이미지 데이터를 모두 사용할 수 있습니다. 예를 들어 텍스트 전용 프롬프트 또는 Gemini 1.5 모델을 사용한 멀티모달 프롬프트에서 텍스트를 생성할 수 있습니다 이 섹션에서는 각각의 기본 코드 예를 제공합니다. 모든 매개변수를 다루는 더 자세한 예는 generateContent API 참조를 확인하세요.

텍스트 및 이미지 입력

이미지가 포함된 텍스트 프롬프트를 Gemini 1.5 모델로 전송하여 비전 관련 작업을 수행할 수 있습니다. 예를 들어 이미지에 자막을 추가하거나 이미지 속 이미지를 식별하는 작업이 여기에 해당합니다.

다음 코드 예에서는 지원되는 각 언어에 대한 텍스트 및 이미지 프롬프트의 기본 구현을 보여줍니다.

Python

model = genai.GenerativeModel('gemini-1.5-flash')

cookie_picture = {
    'mime_type': 'image/png',
    'data': pathlib.Path('cookie.png').read_bytes()
}
prompt = "Do these look store-bought or homemade?"

response = model.generate_content(
    model="gemini-1.5-flash",
    content=[prompt, cookie_picture]
)
print(response.text)

전체 코드 스니펫은 Python 가이드를 참조하세요.

Go

vmodel := client.GenerativeModel("gemini-1.5-flash")

data, err := os.ReadFile(filepath.Join("path-to-image", imageFile))
if err != nil {
  log.Fatal(err)
}
resp, err := vmodel.GenerateContent(ctx, genai.Text("Do these look store-bought or homemade?"), genai.ImageData("jpeg", data))
if err != nil {
  log.Fatal(err)
}

전체 예는 Go 가이드를 참조하세요.

Node.js

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const prompt = "Do these look store-bought or homemade?";
const image = {
  inlineData: {
    data: Buffer.from(fs.readFileSync("cookie.png")).toString("base64"),
    mimeType: "image/png",
  },
};

const result = await model.generateContent([prompt, image]);
console.log(result.response.text());

전체 예는 Node.js 튜토리얼을 참조하세요.

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });

const prompt = "Do these look store-bought or homemade?";
const image = {
  inlineData: {
    data: base64EncodedImage /* see JavaScript quickstart for details */,
    mimeType: "image/png",
  },
};

const result = await model.generateContent([prompt, image]);
console.log(result.response.text());

전체 예는 웹 가이드를 참조하세요.

Dart (Flutter)

final model = GenerativeModel(model: 'gemini-1.5-flash', apiKey: apiKey);
final prompt = 'Do these look store-bought or homemade?';
final imageBytes = await File('cookie.png').readAsBytes();
final content = [
  Content.multi([
    TextPart(prompt),
    DataPart('image/png', imageBytes),
  ])
];

final response = await model.generateContent(content);
print(response.text);

전체 예는 Dart (Flutter) 튜토리얼을 참고하세요.

Swift

let model = GenerativeModel(name: "gemini-1.5-flash", apiKey: "API_KEY")
let cookieImage = UIImage(...)
let prompt = "Do these look store-bought or homemade?"

let response = try await model.generateContent(prompt, cookieImage)

전체 예는 Swift 튜토리얼을 참고하세요.

Android

val generativeModel = GenerativeModel(
    modelName = "gemini-1.5-flash",
    apiKey = BuildConfig.apiKey
)

val cookieImage: Bitmap = // ...
val inputContent = content() {
  image(cookieImage)
  text("Do these look store-bought or homemade?")
}

val response = generativeModel.generateContent(inputContent)
print(response.text)

전체 예는 Android 튜토리얼을 참고하세요.

cURL

curl https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key=${API_KEY} \
    -H 'Content-Type: application/json' \
    -X POST \
    -d @<(echo'{
          "contents":[
            { "parts":[
                {"text": "Do these look store-bought or homemade?"},
                { "inlineData": {
                    "mimeType": "image/png",
                    "data": "'$(base64 -w0 cookie.png)'"
                  }
                }
              ]
            }
          ]
         }')

자세한 내용은 REST API 가이드를 참조하세요.

텍스트 전용 입력

Gemini API는 텍스트 전용 입력도 처리할 수 있습니다. 이 기능을 사용하면 텍스트 완성 및 요약과 같은 자연어 처리 (NLP) 태스크를 수행할 수 있습니다.

다음 코드 예에서는 지원되는 각 언어에 대한 텍스트 전용 프롬프트의 기본 구현을 보여줍니다.

Python

model = genai.GenerativeModel('gemini-1.5-flash')

prompt = "Write a story about a magic backpack."

response = model.generate_content(prompt)

전체 예는 Python 가이드를 참조하세요.

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

model := client.GenerativeModel("gemini-1.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text("Write a story about a magic backpack."))
if err != nil {
  log.Fatal(err)
}

전체 예는 Go 가이드를 참조하세요.

Node.js

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const prompt = "Write a story about a magic backpack.";

const result = await model.generateContent(prompt);
console.log(result.response.text());

전체 예는 Node.js 튜토리얼을 참조하세요.

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const prompt = "Write a story about a magic backpack.";

const result = await model.generateContent(prompt);
console.log(result.response.text());

전체 예는 웹 가이드를 참조하세요.

Dart (Flutter)

final model = GenerativeModel(model: 'gemini-1.5-flash', apiKey: apiKey);
final prompt = 'Write a story about a magic backpack.';
final content = [Content.text(prompt)];
final response = await model.generateContent(content);
print(response.text);

전체 예는 Dart (Flutter) 튜토리얼을 참고하세요.

Swift

let model = GenerativeModel(name: "gemini-1.5-flash", apiKey: "API_KEY")
let prompt = "Write a story about a magic backpack."

let response = try await model.generateContent(prompt)

전체 예는 Swift 튜토리얼을 참고하세요.

Android

val generativeModel = GenerativeModel(
    modelName = "gemini-1.5-flash",
    apiKey = BuildConfig.apiKey
)

val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)

전체 예는 Android 튜토리얼을 참고하세요.

cURL

curl https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{ "contents":[
      { "parts":[{"text": "Write a story about a magic backpack"}]}
    ]
}'

자세한 내용은 REST API 가이드를 참조하세요.

멀티턴 대화 (채팅)

Gemini API를 사용하여 사용자를 위한 대화형 채팅 환경을 빌드할 수 있습니다. API의 채팅 기능을 사용하면 여러 라운드의 질문과 응답을 수집할 수 있으므로 사용자가 점차 답을 얻거나 여러 부분으로 구성된 문제에 대한 도움을 받을 수 있습니다. 이 기능은 챗봇, 대화형 강사 또는 고객 지원 도우미와 같이 지속적인 커뮤니케이션이 필요한 애플리케이션에 적합합니다.

다음 코드 예에서는 지원되는 각 언어의 채팅 상호작용의 기본 구현을 보여줍니다.

Python

  model = genai.GenerativeModel('gemini-1.5-flash')
  chat = model.start_chat(history=[])

  response = chat.send_message(
      "Pretend you\'re a snowman and stay in character for each response.")
  print(response.text)

  response = chat.send_message(
      "What\'s your favorite season of the year?")
  print(response.text)

전체 예는 Python 가이드의 채팅 데모를 참조하세요.

Go

model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()
cs.History = []*genai.Content{
  &genai.Content{
    Parts: []genai.Part{
      genai.Text("Pretend you're a snowman and stay in character for each response."),
    },
    Role: "user",
  },
  &genai.Content{
    Parts: []genai.Part{
      genai.Text("Hello! It's cold! Isn't that great?"),
    },
    Role: "model",
  },
}

resp, err := cs.SendMessage(ctx, genai.Text("What's your favorite season of the year?"))
if err != nil {
  log.Fatal(err)
}

전체 예는 Go 가이드의 채팅 데모를 참조하세요.

Node.js

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"});

const chat = model.startChat({
  history: [
    {
      role: "user",
      parts: "Pretend you're a snowman and stay in character for each response.",
    },
    {
      role: "model",
      parts: "Hello! It's cold! Isn't that great?",
    },
  ],
  generationConfig: {
    maxOutputTokens: 100,
  },
});

const msg = "What's your favorite season of the year?";
const result = await chat.sendMessage(msg);
console.log(result.response.text());

전체 예는 Node.js 튜토리얼의 채팅 데모를 참조하세요.

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash"});

const chat = model.startChat({
  history: [
    {
      role: "user",
      parts: "Pretend you're a snowman and stay in character for each response.",
    },
    {
      role: "model",
      parts: "Hello! It's so cold! Isn't that great?",
    },
  ],
  generationConfig: {
    maxOutputTokens: 100,
  },
});

const msg = "What's your favorite season of the year?";
const result = await chat.sendMessage(msg);
console.log(result.response.text());

전체 예는 웹 가이드의 채팅 데모를 참조하세요.

Dart (Flutter)

final model = GenerativeModel(model: 'gemini-1.5-flash', apiKey: apiKey);
final chat = model.startChat(history: [
  Content.text(
      "Pretend you're a snowman and stay in character for each response."),
  Content.model([TextPart("Hello! It's cold! Isn't that great?")]),
]);
final content = Content.text("What's your favorite season of the year?");
final response = await chat.sendMessage(content);
print(response.text);

전체 예는 Dart (Flutter) 튜토리얼의 채팅 데모를 참고하세요.

Swift

let model = GenerativeModel(name: "gemini-1.5-flash", apiKey: "API_KEY")
let chat = model.startChat()

var message = "Pretend you're a snowman and stay in character for each response."
var response = try await chat.sendMessage(message)

message = "What\'s your favorite season of the year?"
response = try await chat.sendMessage(message)

전체 예는 Swift 튜토리얼의 채팅 데모를 참조하세요.

Android

val generativeModel = GenerativeModel(
    modelName = "gemini-1.5-flash",
    apiKey = BuildConfig.apiKey
)

val chat = generativeModel.startChat()
val response = chat.sendMessage("Pretend you're a snowman and stay in
        character for each response.")
print(response.text)

전체 예는 Android 튜토리얼을 참고하세요.

cURL

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {"role":"user",
         "parts":[{
           "text": "Pretend you're a snowman and stay in character for each
        {"role": "model",
            response."}]},
         "parts":[{
           "text": "Hello! It's so cold! Isn't that great?"}]},
        {"role": "user",
         "parts":[{
           "text": "What\'s your favorite season of the year?"}]},
       ]
    }' 2> /dev/null | grep "text"
# response example:
"text": "Winter, of course!"

자세한 내용은 REST API 가이드를 참조하세요.

스트리밍 응답

Gemini API는 생성형 AI 모델에서 데이터 스트림으로 응답을 받는 추가적인 방법을 제공합니다 스트리밍 응답은 모델에 의해 생성될 때 증분 데이터 조각을 애플리케이션으로 다시 전송합니다. 이 기능을 사용하면 사용자 요청에 빠르게 응답하여 진행 상황을 표시하고 보다 대화형 환경을 만들 수 있습니다.

스트리밍 대답은 자유 형식의 프롬프팅 및 Gemini 모델과의 채팅을 위한 옵션입니다. 다음 코드 예에서는 지원되는 각 언어의 프롬프트에 대한 스트리밍 응답을 요청하는 방법을 보여줍니다.

Python

prompt = "Write a story about a magic backpack."

response = genai.stream_generate_content(
    model="models/gemini-1.5-flash",
    prompt=prompt
)

전체 코드 스니펫은 Python 가이드를 참조하세요.

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("API_KEY")))
if err != nil {
  log.Fatal(err)
}
defer client.Close()

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

  // print resp
}

전체 예는 Go 가이드를 참조하세요.

Node.js

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const prompt = "Write a story about a magic backpack.";

const result = await model.generateContentStream([prompt]);
// print text as it comes in
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  console.log(chunkText);
}

전체 예는 Node.js 튜토리얼을 참조하세요.

const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const prompt = "Write a story about a magic backpack.";

const result = await model.generateContentStream([prompt]);
// print text as it comes in
for await (const chunk of result.stream) {
  const chunkText = chunk.text();
  console.log(chunkText);
}

전체 예는 웹 가이드를 참조하세요.

Dart (Flutter)

final model = GenerativeModel(model: 'gemini-1.5-flash', apiKey: apiKey);
final prompt = 'Write a story about a magic backpack.';
final content = [Content.text(prompt)];
final response = model.generateContentStream(content);
await for (final chunk in response) {
  print(chunk.text);
}

전체 예는 Dart (Flutter) 튜토리얼을 참고하세요.

Swift

let model = GenerativeModel(name: "gemini-1.5-flash", apiKey: "API_KEY")
let prompt = "Write a story about a magic backpack."

let stream = model.generateContentStream(prompt)
for try await chunk in stream {
  print(chunk.text ?? "No content")
}

전체 예는 Swift 튜토리얼을 참고하세요.

Android

val generativeModel = GenerativeModel(
    modelName = "gemini-1.5-flash",
    apiKey = BuildConfig.apiKey
)

val inputContent = content {
  text("Write a story about a magic backpack.")
}

var fullResponse = ""
generativeModel.generateContentStream(inputContent).collect { chunk ->
  print(chunk.text)
  fullResponse += chunk.text
}

전체 예는 Android 튜토리얼을 참고하세요.

cURL

curl https://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:streamGenerateContent?key=${API_KEY} \
    -H 'Content-Type: application/json' \
    --no-buffer \
    -d '{ "contents":[
            {"role": "user",
              "parts":[{"text": "Write a story about a magic backpack."}]
            }
          ]
        }' > response.json

자세한 내용은 REST API 가이드를 참조하세요.

JSON 형식 응답

애플리케이션에 따라 프롬프트에 대한 응답이 구조화된 데이터 형식으로 반환되도록 할 수 있습니다. 특히 응답을 사용하여 프로그래밍 인터페이스를 채우는 경우 더욱 그렇습니다. Gemini API는 JSON 형식의 응답을 요청하는 구성 매개변수를 제공합니다.

response_mime_type 구성 옵션을 application/json로 설정하여 모델이 JSON을 출력하도록 할 수 있습니다. 그러면 프롬프트에서 응답으로 원하는 JSON 형식을 설명합니다.

Python

model = genai.GenerativeModel('gemini-1.5-flash',
                              generation_config={"response_mime_type": "application/json"})

prompt = """
  List 5 popular cookie recipes.

  Using this JSON schema:

    Recipe = {"recipe_name": str}

  Return a `list[Recipe]`
  """

response = model.generate_content(prompt)
print(response.text)

cURL

curl https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=$API_KEY \
    -H 'Content-Type: application/json' \
    -X POST \
    -d '{
      "contents": [
        {
          "parts": [
            {
              "text": "\nList 5 popular cookie recipes.\n\nUsing this JSON schema:\n\n  Recipe = {\"recipe_name\": str}\n\nReturn a `list[Recipe]`\n      "
            }
          ]
        }
      ]
      "generationConfig": {
            "response_mime_type": "application/json",
      }
    }'

Gemini 1.5 플래시 모델은 반환되기를 원하는 JSON 스키마의 텍스트 설명만 허용하지만, Gemini 1.5 Pro 모델에서는 스키마 객체 (또는 Python 유형에 상응하는 항목)를 전달할 수 있으며, 모델 출력은 해당 스키마를 엄격하게 따릅니다. 이를 제어된 생성 또는 제한적인 디코딩이라고도 합니다.

예를 들어 Recipe 객체의 목록을 가져오려면 list[Recipe]generation_config 인수의 response_schema 필드에 전달합니다.

Python

import typing_extensions as typing

class Recipe(typing.TypedDict):
  recipe_name: str

model = genai.GenerativeModel(model_name="models/gemini-1.5-pro")

result = model.generate_content(
  "List 5 popular cookie recipes",
  generation_config=genai.GenerationConfig(response_mime_type="application/json",
                                           response_schema = list[Recipe]))

print(result.text)

cURL

  curl https://generativelanguage.googleapis.com/v1beta/models/models/gemini-1.5-pro:generateContent?
      -H 'Content-Type: application/json'
      -X POST \
      -d '{
        "contents": [
          {
            "parts": [
              {
                "text": "List 5 popular cookie recipes"
              }
            ]
          }
        ],
        "generationConfig": {
          "responseMimeType": "application/json",
          "responseSchema": {
            "type": "ARRAY",
            "items": {
              "type": "OBJECT",
              "properties": {
                "recipe_name": {
                  "type": "STRING"
                }
              }
            }
          }
        }
      }'
  ```

자세한 내용은 Gemini API 설명서JSON 모드 빠른 시작을 참고하세요.

임베딩

Gemini API의 임베딩 서비스는 단어, 구문, 문장에 대한 최첨단 임베딩을 생성합니다. 그 결과로 생성된 임베딩은 특히 시맨틱 검색, 텍스트 분류, 클러스터링과 같은 NLP 작업에 사용할 수 있습니다. 임베딩 가이드에서 임베딩의 정의와 임베딩 서비스의 주요 사용 사례를 참고하여 시작해 보세요.

다음 단계