플렉스 추론

Gemini Flex API는 가변 지연 시간과 최선을 다하는 가용성을 제공하는 대신 표준 요금에 비해 비용이 50% 절감되는 추론 등급입니다. 동기 처리가 필요하지만 표준 API의 실시간 성능은 필요하지 않은 지연 시간 허용 워크로드용으로 설계되었습니다.

Flex 사용 방법

Flex 등급을 사용하려면 요청에서 service_tierflex로 지정합니다. 기본적으로 이 필드를 생략하면 요청에서 표준 등급을 사용합니다.

Python

from google import genai

client = genai.Client()

try:
    interaction = client.interactions.create(
        model="gemini-3-flash-preview",
        input="Analyze this dataset for trends...",
        service_tier='flex'
    )
    print(interaction.steps[-1].content[0].text)
except Exception as e:
    print(f"Flex request failed: {e}")

자바스크립트

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

async function main() {
    try {
        const interaction = await client.interactions.create({
            model: 'gemini-3-flash-preview',
            input: 'Analyze this dataset for trends...',
            serviceTier: 'flex'
        });
        console.log(interaction.steps.at(-1).content[0].text);
    } catch (e) {
        console.log(`Flex request failed: ${e}`);
    }
}
await main();

REST

curl -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
  -H "Content-Type: application/json" \
  -H "x-goog-api-key: $GEMINI_API_KEY" \
  -d '{
      "model": "gemini-3-flash-preview",
      "input": "Analyze this dataset for trends...",
      "service_tier": "flex"
  }'

Flex 추론 작동 방식

Gemini Flex 추론은 표준 API와 Batch API의 24시간 처리 시간 간의 격차를 해소합니다. 유휴 상태의 '제어 가능한' 컴퓨팅 용량을 활용하여 백그라운드 작업과 순차적 워크플로를 위한 비용 효율적인 솔루션을 제공합니다.

기능 Flex 우선순위 표준 일괄
가격 책정 50% 할인 Standard보다 75~100% 더 많음 정상가 50% 할인
지연 시간 분 (목표 1~15분) 낮음 (초) 수 초에서 수 분 최대 24시간
안정성 최선의 노력 (삭제 가능) 높음 (삭제 불가) 높음 / 중간~높음 높음 (처리량)
인터페이스 동기식 동기식 동기식 비동기식

주요 이점

  • 비용 효율성: 비프로덕션 평가, 백그라운드 에이전트, 데이터 보강에 상당한 절감 효과가 있습니다.
  • 마찰 감소: 기존 요청에 단일 매개변수만 추가하면 됩니다.
  • 동기 워크플로: 다음 요청이 이전 요청의 출력에 종속되는 순차적 API 체인에 적합하며, 에이전트형 워크플로의 일괄 처리보다 유연합니다.

사용 사례

  • 오프라인 평가: 'LLM-as-a-judge' 회귀 테스트 또는 리더보드를 실행합니다.
  • 백그라운드 에이전트: CRM 업데이트, 프로필 빌드, 콘텐츠 검토와 같이 지연이 허용되는 순차적 작업
  • 예산 제약이 있는 연구: 제한된 예산으로 많은 토큰이 필요한 학술 실험

비율 제한

유연한 추론 트래픽은 일반 비율 제한에 포함되며 Batch API와 같은 확장된 비율 제한은 제공하지 않습니다.

조절 가능한 용량

플렉스 트래픽은 우선순위가 낮게 처리됩니다. 표준 트래픽이 급증하면 우선순위가 높은 사용자의 용량을 확보하기 위해 Flex 요청이 선점되거나 삭제될 수 있습니다. 우선순위가 높은 추론을 찾고 있다면 우선순위 추론을 확인하세요.

오류 코드

유연한 용량을 사용할 수 없거나 시스템이 혼잡한 경우 API는 표준 오류 코드를 반환합니다.

  • 503 서비스를 사용할 수 없음: 현재 시스템이 한도에 도달했습니다.
  • 429 Too Many Requests: 비율 제한 또는 리소스 소진.

고객 책임

  • 서버 측 대체 없음: 예상치 못한 요금이 청구되지 않도록 Flex 용량이 가득 차면 시스템에서 Flex 요청을 Standard 등급으로 자동 업그레이드하지 않습니다.
  • 재시도: 지수 백오프를 사용하여 자체 클라이언트 측 재시도 로직을 구현해야 합니다.
  • 제한 시간: Flex 요청이 대기열에 있을 수 있으므로 연결이 조기에 종료되지 않도록 클라이언트 측 제한 시간을 10분 이상으로 늘리는 것이 좋습니다.

제한 시간 창 조정

REST API 및 클라이언트 라이브러리의 요청별 제한 시간을 구성할 수 있습니다. 클라이언트 측 시간 제한이 의도한 서버 대기 시간 (예: Flex 대기열의 경우 600초 이상)을 포함하는지 항상 확인하세요. SDK는 제한 시간 값을 밀리초 단위로 예상합니다.

요청별 제한 시간

Python

from google import genai

client = genai.Client()

try:
    interaction = client.interactions.create(
        model="gemini-3-flash-preview",
        input="why is the sky blue?",
        service_tier="flex",
        http_options={"timeout": 900000}
    )
except Exception as e:
    print(f"Flex request failed: {e}")

자바스크립트

import { GoogleGenAI } from '@google/genai';

const client = new GoogleGenAI({});

async function main() {
    try {
        const interaction = await client.interactions.create({
            model: "gemini-3-flash-preview",
            input: "why is the sky blue?",
            serviceTier: "flex",
            httpOptions: {timeout: 900000}
        });
    } catch (e) {
        console.log(`Flex request failed: ${e}`);
    }
}

await main();

재시도 구현

Flex는 삭제 가능하고 503 오류로 실패하므로 실패한 요청을 계속하기 위해 재시도 로직을 선택적으로 구현하는 예는 다음과 같습니다.

Python

import time
from google import genai

client = genai.Client()

def call_with_retry(max_retries=3, base_delay=5):
    for attempt in range(max_retries):
        try:
            return client.interactions.create(
                model="gemini-3-flash-preview",
                input="Analyze this batch statement.",
                service_tier="flex",
            )
        except Exception as e:
            if attempt < max_retries - 1:
                delay = base_delay * (2 ** attempt) # Exponential Backoff
                print(f"Flex busy, retrying in {delay}s...")
                time.sleep(delay)
            else:
                # Fallback to standard on last strike (Optional)
                print("Flex exhausted, falling back to Standard...")
                return client.interactions.create(
                    model="gemini-3-flash-preview",
                    input="Analyze this batch statement."
                )

# Usage
interaction = call_with_retry()
print(interaction.steps[-1].content[0].text)

자바스크립트

import { GoogleGenAI } from '@google/genai';

const ai = new GoogleGenAI({});

async function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function callWithRetry(maxRetries = 3, baseDelay = 5) {
  for (let attempt = 0; attempt < maxRetries; attempt++) {
    try {
      console.log(`Attempt ${attempt + 1}: Calling Flex tier...`);
      const interaction = await ai.interactions.create({
        model: "gemini-3-flash-preview",
        input: "Analyze this batch statement.",
        serviceTier: 'flex',
      });
      return interaction;
    } catch (e) {
      if (attempt < maxRetries - 1) {
        const delay = baseDelay * (2 ** attempt);
        console.log(`Flex busy, retrying in ${delay}s...`);
        await sleep(delay * 1000);
      } else {
        console.log("Flex exhausted, falling back to Standard...");
        return await ai.interactions.create({
          model: "gemini-3-flash-preview",
          input: "Analyze this batch statement.",
        });
      }
    }
  }
}

async function main() {
    const interaction = await callWithRetry();
    console.log(interaction.steps.at(-1).content[0].text);
}

await main();

가격 책정

유연한 추론은 표준 API의 50% 로 가격이 책정되며 토큰당 청구됩니다.

지원되는 모델

다음 모델은 유연한 추론을 지원합니다.

모델 플렉스 추론
Gemini 3.1 Flash-Lite ✔️
Gemini 3.1 Flash-Lite 프리뷰 ✔️
Gemini 3.1 Pro 프리뷰 ✔️
Gemini 3 Flash 프리뷰 ✔️
Gemini 2.5 Pro ✔️
Gemini 2.5 Flash ✔️
Gemini 2.5 Flash-Lite ✔️

다음 단계