Inference API

Inference API를 사용하여 Gemini 프롬프트를 생성합니다.

Gemini 모델 계열에는 멀티모달 프롬프트 요청에 사용할 수 있는 모델이 포함됩니다. 멀티모달이란 프롬프트에서 두 개 이상의 형식 또는 입력 유형을 사용할 수 있는 것을 말합니다. 멀티모달이 아닌 모델은 텍스트 프롬프트만 허용합니다. 형식에는 텍스트, 오디오, 동영상 등이 포함될 수 있습니다.

개요에 대해 더 많은 정보는 다음을 참고하세요.

지원되는 모델:

모델 버전
Gemini 1.5 Flash gemini-1.5-flash-001
Gemini 1.5 Pro도 gemini-1.5-pro-001
Gemini 1.0 Pro Vision gemini-1.0-pro-001
gemini-1.0-pro-vision-001
Gemini 1.0 Pro gemini-1.0-pro
gemini-1.0-pro-001
gemini-1.0-pro-002

제한사항:

많은 이미지를 제공하는 경우 지연 시간이 길어질 수 있습니다.

예시 문법

모델 응답을 생성하는 문법입니다.

비스트리밍

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \

https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
-d '{
  "contents": [{
    ...
  }],
  "generation_config": {
    ...
  },
  "safety_settings": {
    ...
  }
  ...
}'

Python

gemini_model = GenerativeModel(MODEL_ID)
generation_config = GenerationConfig(...)

model_response = gemini_model.generate_content([...], generation_config, safety_settings={...})

스트리밍

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:streamGenerateContent \
  -d '{
    "contents": [{
      ...
    }],
    "generation_config": {
      ...
    },
    "safety_settings": {
      ...
    }
    ...
  }'

Python

gemini_model = GenerativeModel(MODEL_ID)
model_response = gemini_model.generate_content([...], generation_config, safety_settings={...}, stream=True)

매개변수 목록

구현 세부정보는 예시를 참조하세요.

요청 본문

요청 본문에는 다음 매개변수가 있는 데이터가 포함됩니다.

매개변수

contents

필수: Content

모델과의 현재 대화 콘텐츠입니다.

싱글턴 쿼리의 경우 이는 단일 인스턴스입니다. 멀티턴 쿼리의 경우 이는 대화 기록과 최근 요청이 포함된 반복 필드입니다.

system_instruction

(선택사항) Content

사용자가 모델의 시스템 지침을 제공했습니다.

참고: parts에는 text만 사용해야 하며 각 part의 콘텐츠는 별도의 단락에 있어야 합니다.

tools

(선택사항) Functions Calling API를 참조하세요.

tool_config

(선택사항) Functions Calling API를 참조하세요.

safety_settings

(선택사항) SafetySetting

안전하지 않은 콘텐츠를 차단하는 요청별 설정입니다.

GenerateContentResponse.candidates에 적용되었습니다.

generation_config

(선택사항) GenerationConfig

생성 구성 설정

내용

메시지의 여러 부분으로 구성된 콘텐츠를 포함하는 기본 구조화된 데이터 유형입니다.

이 클래스는 roleparts라는 두 가지 기본 속성으로 구성됩니다. role 속성은 콘텐츠를 생성하는 개별 사용자를 나타내고 parts 속성에는 여러 요소가 포함되며 각 요소는 메시지 내 데이터 세그먼트를 나타냅니다.

매개변수

role

(선택사항) string

메시지를 생성하는 항목의 ID입니다. 다음과 같은 값이 지원됩니다.

  • user: 실제 사람이 메시지(일반적으로 사용자가 만든 메시지)를 보냈음을 나타냅니다.
  • model: 메시지가 모델에서 생성되었음을 나타냅니다.

model 값은 멀티턴 대화 중에 모델의 메시지를 대화에 삽입하는 데 사용됩니다.

멀티턴이 아닌 대화의 경우 이 필드를 비워 두거나 설정하지 않을 수 있습니다.

parts

Part

단일 메시지를 구성하는 순서가 지정된 부분의 목록입니다. 부분마다 IANA MIME 유형이 다를 수 있습니다.

일부

여러 부분으로 구성된 Content 메시지의 일부인 미디어를 포함하는 데이터 유형입니다.

매개변수

text

(선택사항) string

텍스트 프롬프트 또는 코드 스니펫입니다.

inline_data

(선택사항) Blob

원시 바이트의 인라인 데이터입니다.

file_data

(선택사항) FileData

파일에 저장된 데이터입니다.

function_call

(선택사항) FunctionCall.

FunctionDeclaration.name 필드를 나타내는 문자열과 모델에서 예측한 함수 호출의 매개변수가 포함된 구조화된 JSON 객체가 포함됩니다.

Functions Calling API를 참조하세요.

function_response

(선택사항) FunctionResponse.

FunctionDeclaration.name 필드를 나타내는 문자열과 함수 호출의 출력이 포함된 구조화된 JSON 객체가 포함된 FunctionCall의 결과 출력입니다. 모델에 대한 컨텍스트로 사용됩니다.

Functions Calling API를 참조하세요.

video_metadata

(선택사항) VideoMetadata

동영상 메타데이터입니다. 메타데이터는 동영상 데이터가 inline_data 또는 file_data에 표시되는 동안에만 지정되어야 합니다.

Blob

콘텐츠 blob입니다. 가능하다면 원시 바이트가 아닌 텍스트로 보내세요.

매개변수

mime_type

string

데이터의 IANA MIME 유형입니다.

data

bytes

원시 바이트입니다.

FileData

URI 기반 데이터

매개변수

mime_type

string

데이터의 IANA MIME 유형입니다.

file_uri

문자열

데이터를 저장하는 파일에 대한 Cloud Storage URI입니다.

FunctionCall

FunctionDeclaration.name을 나타내는 문자열과 매개변수와 해당 값이 포함된 구조화된 JSON 객체를 포함하는 모델에서 반환된 예측된 FunctionCall입니다.

매개변수

name

string

호출하려는 함수의 이름입니다.

args

Struct

JSON 객체 형식의 함수 매개변수와 값입니다.

매개변수 세부정보는 Function Calling API를 참조하세요.

FunctionResponse

FunctionDeclaration.name을 나타내는 문자열이 포함된 FunctionCall의 결과 출력입니다. 또한 함수의 출력이 포함된 구조화된 JSON 객체를 포함하고 이를 모델의 컨텍스트로 사용합니다. 여기에는 모델 예측을 기반으로 생성된 FunctionCall의 결과가 포함되어야 합니다.

매개변수

name

string

호출하려는 함수의 이름입니다.

response

Struct

JSON 객체 형식의 함수 응답입니다.

VideoMetadata

입력 동영상 콘텐츠를 설명하는 메타데이터입니다.

매개변수

start_offset

(선택사항) google.protobuf.Duration

동영상의 시작 오프셋입니다.

end_offset

(선택사항) google.protobuf.Duration

동영상의 종료 오프셋입니다.

SafetySetting

안전 설정입니다.

매개변수

category

(선택사항) HarmCategory

피해 카테고리입니다.

threshold

(선택사항) HarmBlockThreshold

피해 차단 기준점입니다.

max_influential_terms

(선택사항) int

안전 점수에 가장 많이 기여하는 영향력 있는 용어의 최대 개수로, 차단될 가능성이 있습니다.

method

(선택사항) HarmBlockMethod

확률 또는 심각도 점수에 기준점이 사용되는지 지정합니다. 지정하지 않으면 기준점이 확률 점수에 사용됩니다.

HarmCategory

콘텐츠를 차단하는 HTML 카테고리입니다.

매개변수

HARM_CATEGORY_UNSPECIFIED

피해 카테고리가 지정되지 않았습니다.

HARM_CATEGORY_HATE_SPEECH

피해 카테고리는 증오심 표현입니다.

HARM_CATEGORY_DANGEROUS_CONTENT

피해 카테고리는 위험한 콘텐츠입니다.

HARM_CATEGORY_HARASSMENT

피해 카테고리는 괴롭힘입니다.

HARM_CATEGORY_SEXUALLY_EXPLICIT

피해 카테고리는 음란물입니다.

HarmBlockThreshold

응답을 차단하는 데 사용되는 확률 기준점 수준입니다.

매개변수

HARM_BLOCK_THRESHOLD_UNSPECIFIED

지정되지 않은 피해 차단 기준점입니다.

BLOCK_LOW_AND_ABOVE

낮은 기준점 이상을 차단합니다(즉, 더 차단).

BLOCK_MEDIUM_AND_ABOVE

중간 기준점 이상을 차단합니다.

BLOCK_ONLY_HIGH

높은 기준점만 차단합니다(즉, 덜 차단).

BLOCK_NONE

차단하지 않습니다.

HarmBlockMethod

확률과 심각도의 조합에 따라 응답을 차단하는 가능성 기준점입니다.

매개변수

HARM_BLOCK_METHOD_UNSPECIFIED

피해 차단 메서드가 지정되지 않았습니다.

SEVERITY

피해 차단 메서드에서 확률 점수와 심각도 점수를 모두 사용합니다.

PROBABILITY

피해 차단 메서드에서 확률 점수를 사용합니다.

GenerationConfig

프롬프트를 생성할 때 사용되는 구성 설정입니다.

매개변수

temperature

(선택사항) float

예측 무작위성을 제어합니다.

top_p

(선택사항) float

지정하면 Nucleus 샘플링이 사용됩니다.

top_k

(선택사항) 지정된 경우 Top-K 샘플링이 사용됩니다.

candidate_count

(선택사항) int

생성할 후보의 수입니다.

max_output_tokens

(선택사항) int

메시지당 생성할 수 있는 최대 출력 토큰 수입니다.

stop_sequences

(선택사항) List[string]

시퀀스를 중지합니다.

presence_penalty

(선택사항) float

긍정적 페널티입니다.

frequency_penalty

(선택사항) float

빈도 페널티입니다.

response_mime_type

(선택사항) string (enum)

생성된 후보 텍스트의 출력 응답 mimetype입니다.

지원되는 mimetype은 다음과 같습니다.

  • text/plain: (기본값) 텍스트 출력입니다.
  • application/json: 후보의 JSON 응답입니다.
  • 모델에 적절한 응답 유형을 출력하라는 메시지가 표시되어야 합니다. 그렇지 않으면 동작이 정의되지 않습니다.

이 기능은 미리보기 기능입니다.

예시

비스트리밍 텍스트 응답

텍스트 입력에서 비스트리밍 모델 응답을 생성합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: 프로젝트 ID
  • LOCATION: 요청을 처리하는 리전
  • TEXT: 프롬프트에 포함할 텍스트 지침

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

JSON 요청 본문:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }]
}'

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent" | Select-Object -Expand Content

Python

import vertexai

from vertexai.generative_models import GenerativeModel

vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel(MODEL_ID)
response = model.generate_content("Write a story about a magic backpack.")

print(response)

NodeJS

const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function generateContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const request = {
    contents: [
      {
        role: 'user',
        parts: [
          {
            text: 'Write a story about a magic backpack.',
          },
        ],
      },
    ],
  };

  console.log(JSON.stringify(request));

  const result = await generativeModel.generateContent(request);

  console.log(result.response.candidates[0].content.parts[0].text);
}

비스트리밍 멀티모달 응답

텍스트와 이미지 같은 멀티모달 입력으로부터 비스트리밍 모델 응답을 생성합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: 프로젝트 ID
  • LOCATION: 요청을 처리하는 리전
  • TEXT: 프롬프트에 포함할 텍스트 지침
  • FILE_URI: 데이터를 저장하는 파일에 대한 Cloud Storage URI
  • MIME_TYPE: 데이터의 TIANA MIME 유형

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

JSON 요청 본문:

{
"contents": [{
  "role": "user",
  "parts": [
    {
      "text": "TEXT"
    },
    {
      "file_data": {"file_uri": "FILE_URI", "MIME_TYPE"}
    },
    {
      "file_data": {"file_uri": "FILE_URI", "MIME_TYPE"}
    }
  ]
}]
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent" | Select-Object -Expand Content

Python

import vertexai

from vertexai.generative_models import GenerativeModel, Part

vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel(MODEL_ID)
response = model.generate_content(
    [
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/video/animals.mp4", "video/mp4"
        ),
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/image/character.jpg",
            "image/jpeg",
        ),
        "Are these video and image correlated?",
    ]
)

print(response)

NodeJS

const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function generateContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex AI
  const vertexAI = new VertexAI({project: projectId, location: location});
  const generativeModel = vertexAI.getGenerativeModel({model: model});

  const request = {
    contents: [
      {
        role: 'user',
        parts: [
          {
            file_data: {
              file_uri: 'gs://cloud-samples-data/video/animals.mp4',
              mime_type: 'video/mp4',
            },
          },
          {
            file_data: {
              file_uri:
                'gs://cloud-samples-data/generative-ai/image/character.jpg',
              mime_type: 'image/jpeg',
            },
          },
          {text: 'Are this video and image correlated?'},
        ],
      },
    ],
  };

  const result = await generativeModel.generateContent(request);

  console.log(result.response.candidates[0].content.parts[0].text);
}

스트리밍 텍스트 응답

텍스트 입력에서 스트리밍 모델 응답을 생성합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: 프로젝트 ID
  • LOCATION: 요청을 처리하는 리전
  • TEXT: 프롬프트에 포함할 텍스트 지침

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent

JSON 요청 본문:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }]
}'

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent" | Select-Object -Expand Content

Python

import vertexai

from vertexai.generative_models import GenerativeModel

vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel(MODEL_ID)
responses = model.generate_content(
    "Write a story about a magic backpack.", stream=True
)

for response in responses:
    print(response)

NodeJS

const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function generateContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.getGenerativeModel({
    model: model,
  });

  const request = {
    contents: [
      {
        role: 'user',
        parts: [
          {
            text: 'Write a story about a magic backpack.',
          },
        ],
      },
    ],
  };

  console.log(JSON.stringify(request));

  const result = await generativeModel.generateContentStream(request);
  for await (const item of result.stream) {
    console.log(item.candidates[0].content.parts[0].text);
  }
}

스트리밍 멀티모달 응답

텍스트 및 이미지와 같은 멀티모달 입력에서 스트리밍 모델 응답을 생성합니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: 프로젝트 ID
  • LOCATION: 요청을 처리하는 리전
  • TEXT: 프롬프트에 포함할 텍스트 지침

HTTP 메서드 및 URL:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent

JSON 요청 본문:

{
  "contents": [{
    "role": "user",
    "parts": [{
      "text": "TEXT"
    }]
  }]
}'

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

curl

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent"

PowerShell

요청 본문을 request.json 파일에 저장하고 다음 명령어를 실행합니다.

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:streamGenerateContent" | Select-Object -Expand Content

Python

import vertexai

from vertexai.generative_models import GenerativeModel, Part

vertexai.init(project=PROJECT_ID, location="us-central1")

model = GenerativeModel(MODEL_ID)
responses = model.generate_content(
    [
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/video/animals.mp4", "video/mp4"
        ),
        Part.from_uri(
            "gs://cloud-samples-data/generative-ai/image/character.jpg",
            "image/jpeg",
        ),
        "Are these video and image correlated?",
    ],
    stream=True,
)

for response in responses:
    print(response)

NodeJS

const {VertexAI} = require('@google-cloud/vertexai');

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function generateContent(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex AI
  const vertexAI = new VertexAI({project: projectId, location: location});
  const generativeModel = vertexAI.getGenerativeModel({model: model});

  const request = {
    contents: [
      {
        role: 'user',
        parts: [
          {
            file_data: {
              file_uri: 'gs://cloud-samples-data/video/animals.mp4',
              mime_type: 'video/mp4',
            },
          },
          {
            file_data: {
              file_uri:
                'gs://cloud-samples-data/generative-ai/image/character.jpg',
              mime_type: 'image/jpeg',
            },
          },
          {text: 'Are this video and image correlated?'},
        ],
      },
    ],
  };

  const result = await generativeModel.generateContentStream(request);

  for await (const item of result.stream) {
    console.log(item.candidates[0].content.parts[0].text);
  }
}

다음 단계