웹 앱에서 하이브리드 환경을 위한 구조화된 출력 생성

Gemini 모델은 기본적으로 응답을 비구조화된 텍스트로 반환합니다. 하지만 일부 사용 사례에서는 JSON과 같은 구조화된 텍스트가 필요합니다. 예를 들어 설정된 데이터 스키마가 필요한 다른 다운스트림 작업에 응답을 사용할 수 있습니다.

모델에서 생성된 출력이 항상 특정 스키마를 준수하도록 하려면, 모델 응답의 청사진처럼 작동하는 스키마를 정의하면 됩니다. 그러면 후처리를 줄여 모델 출력에서 데이터를 직접 추출할 수 있습니다.

예를 들면 다음과 같습니다.

  • 모델의 응답이 유효한 JSON을 생성하고 제공된 스키마를 준수하도록 합니다.
    예를 들어 모델은 항상 레시피 이름, 재료 목록, 단계를 포함하는 레시피의 구조화된 항목을 생성할 수 있습니다. 그러면 앱의 UI에서 이 정보를 더 쉽게 파싱하고 표시할 수 있습니다.

  • 분류 작업 중에 모델이 응답할 수 있는 방식을 제한합니다.
    예를 들어 모델이 생성하는 라벨 (예: good, positive, negative, bad와 같이 어느 정도 가변성이 있을 수 있음) 대신 특정 라벨 세트 (예: positive, negative와 같은 특정 enum 세트)로 텍스트에 주석을 달도록 할 수 있습니다.

이 페이지에서는 웹 앱의 하이브리드 환경에서 JSON 및 enum과 같은 구조화된 출력을 생성하는 방법을 설명합니다.

시작하기 전에

하이브리드 환경 빌드 시작 가이드를 완료했는지 확인하세요.

구조화된 출력 구성 설정

구조화된 출력 (예: JSON 및 enum) 생성은 클라우드 호스팅 모델과 온디바이스 모델을 모두 사용하는 추론에서 지원됩니다.

하이브리드 추론의 경우 inCloudParamsonDeviceParams 를 모두 사용하여 구조화된 출력으로 응답하도록 모델을 구성합니다. 다른 모드의 경우 적용 가능한 구성만 사용합니다.

  • inCloudParams의 경우: 적절한 responseMimeType (예: application/json)과 모델에서 사용할 responseSchema를 지정합니다.

  • onDeviceParams의 경우: 모델에서 사용할 responseConstraint를 지정합니다.

JSON 출력

다음 예에서는 일반 JSON 출력 예시 를 조정하여 하이브리드 추론 (이 예에서는 PREFER_ON_DEVICE)을 수용합니다.

예시 1: Firebase Schema 도우미 메서드 사용

이 예에서는 Firebase AI Logic SDK에서 제공하는 도우미 메서드를 사용하여 스키마 정의를 더 간결하게 만듭니다.

import {
  getAI,
  getGenerativeModel,
  Schema
} from "firebase/ai";

// This schema can also be defined as a plain JSON object.
// See next snippet for an example of a plain JSON schema.
const jsonSchema = Schema.object({
 properties: {
    characters: Schema.array({
      items: Schema.object({
        properties: {
          name: Schema.string(),
          accessory: Schema.string(),
          age: Schema.number(),
          species: Schema.string(),
        },
        optionalProperties: ["accessory"],
      }),
    }),
  }
});

const model = getGenerativeModel(ai, {
  mode: InferenceMode.PREFER_ON_DEVICE,
  inCloudParams: {
    generationConfig: {
      model: "gemini-3.1-flash-lite",
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    },
  }
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const result = await model
  .generateContent(
    "Create profiles for some characters for a fantasy story.");

console.log(result.response.text());
console.log(JSON.parse(result.response.text()));

// ...

예시 2: 일반 JSON 스키마 사용

이 예에서는 JSON만 사용하여 스키마를 정의하고 동일한 결과를 반환합니다.

import {
  getAI,
  getGenerativeModel,
  Schema
} from "firebase/ai";

// The JSON schema defined as a plain JSON object.
const jsonSchema = {
    "type": "object",
    "properties": {
        "characters": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "nullable": false
                    },
                    "accessory": {
                        "type": "string",
                        "nullable": false
                    },
                    "age": {
                        "type": "number",
                        "nullable": false
                    },
                    "species": {
                        "type": "string",
                        "nullable": false
                    }
                },
                "nullable": false,
                "required": [
                    "name",
                    "age",
                    "species"
                ]
            },
            "nullable": false
        }
    },
    "nullable": false,
    "required": [
        "characters"
    ]
};

const model = getGenerativeModel(ai, {
  mode: InferenceMode.PREFER_ON_DEVICE,
  inCloudParams: {
    generationConfig: {
      model: "gemini-3.1-flash-lite",
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    },
  }
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const result = await model
  .generateContent(
    "Create profiles for some characters for a fantasy story.");

console.log(result.response.text());
console.log(JSON.parse(result.response.text()));

Enum 출력

다음 예에서는 일반 enum 출력 예시 를 조정하여 하이브리드 추론 (이 예에서는 PREFER_ON_DEVICE)을 수용합니다.

import {
  getAI,
  getGenerativeModel,
  Schema
} from "firebase/ai";

// enumSchema can also be defined as a plain JSON schema instead of
// using the `Schema` helper methods, just as in the JSON output example.
const enumSchema = Schema.enumString({
  enum: ["drama", "comedy", "documentary"],
});

const model = getGenerativeModel(ai, {
  mode: InferenceMode.PREFER_ON_DEVICE,
  inCloudParams: {
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    },
  }
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

// ...