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

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

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

몇 가지 사용 사례는 다음과 같습니다.

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

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

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

JSON 출력으로 이동 enum 출력으로 이동

구조화된 출력 구성

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

  • 하이브리드 추론 모드: 추론이 클라우드에서 실행되는지 기기에서 실행되는지와 관계없이 모델이 구조화된 출력으로 응답하도록 inCloudParamsonDeviceParams를 모두 구성합니다.

    • 온디바이스 모델의 경우: Schema 도우미 메서드로 만든 스키마 또는 일반 JSON 스키마를 사용하여 onDeviceParams에서 responseConstraint를 지정합니다.

    • 클라우드 호스팅 모델의 경우: inCloudParams에서 responseMimeType(JSON의 경우 application/json, enum의 경우 text/x.enum) 및 responseSchema를 지정합니다.

  • 비하이브리드 추론 모드: 위에 설명된 해당 구성만 사용합니다.

시작하기 전에

Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다.

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


JSON 출력으로 이동 enum 출력으로 이동

JSON 출력

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

이 예시의 시나리오에서 모델은 이름, 나이, 종, 선택적 액세서리와 같은 구조화된 속성을 사용하여 판타지 이야기의 캐릭터 프로필 목록을 생성합니다.

다음 방법 중 하나를 사용하여 응답 스키마를 정의할 수 있습니다.

  • Firebase Schema 도우미 메서드 (권장): 도우미 메서드 (예: Schema.object()Schema.enumString())를 사용하여 추가 상용구 없이 코드에 간결하고 압축된 스키마를 직접 작성합니다.

  • 일반 JSON 스키마: 기존 스키마 정의가 있거나, 플랫폼 또는 백엔드 서비스 간에 스키마를 공유하거나, JSON 파일에서 스키마를 가져오는 경우 표준 JSON 스키마 객체를 사용합니다.

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

이 예에서는 Firebase AI Logic SDK에서 제공하는 Schema 도우미 메서드 (예: Schema.object, Schema.array, Schema.string, Schema.number)를 사용하여 객체 스키마를 정의합니다.

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.
이 섹션에서는 선택한 Gemini API 제공업체의 버튼을 클릭하여 이 페이지에 제공업체별 콘텐츠가 표시되도록 합니다.

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode,
  Schema
} from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp.
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Define a schema using the `Schema` helper methods.
// Optional properties are specified in optionalProperties.
const jsonSchema = Schema.object({
  properties: {
    characters: Schema.array({
      items: Schema.object({
        properties: {
          name: Schema.string(),
          age: Schema.number(),
          species: Schema.string(),
          accessory: Schema.string()
        },
        optionalProperties: ["accessory"]
      })
    })
  }
});

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    }
  },
  // For on-device models, pass the schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const prompt = "Create profiles for some characters for a fantasy story.";

// Generate the structured output.
const result = await model.generateContent(prompt);

// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());

// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));

예 2: 일반 JSON 스키마 사용

이 예에서는 JSON만 사용하여 스키마를 정의합니다.

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.
이 섹션에서는 선택한 Gemini API 제공업체의 버튼을 클릭하여 이 페이지에 제공업체별 콘텐츠가 표시되도록 합니다.

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode
} from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp.
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Define the schema as a plain JSON object.
// Properties are required by default unless omitted from the required array.
const jsonSchema = {
  type: "object",
  properties: {
    characters: {
      type: "array",
      items: {
        type: "object",
        properties: {
          name: {
            type: "string",
            nullable: false
          },
          age: {
            type: "number",
            nullable: false
          },
          species: {
            type: "string",
            nullable: false
          },
          accessory: {
            type: "string",
            nullable: true
          }
        },
        nullable: false,
        required: [
          "name",
          "age",
          "species"
        ]
      },
      nullable: false
    }
  },
  nullable: false,
  required: [
    "characters"
  ]
};

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "application/json",
      responseSchema: jsonSchema
    }
  },
  // For on-device models, pass the schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: jsonSchema
    }
  }
});

const prompt = "Create profiles for some characters for a fantasy story.";

// Generate the structured output.
const result = await model.generateContent(prompt);

// Access the generated JSON string conforming to the schema from response.text().
console.log(result.response.text());

// Parse the JSON string into a JavaScript object.
console.log(JSON.parse(result.response.text()));

열거형 출력

다음 예에서는 하이브리드 추론 (예: PREFER_ON_DEVICE)을 수용하도록 일반 열거형 출력 예를 조정합니다.

이 예시의 시나리오에서 모델은 허용된 옵션의 사전 정의된 목록(drama, comedy 또는 documentary)에서 단일 장르를 선택하여 영화 설명을 분류합니다.

다음 방법 중 하나를 사용하여 응답 스키마를 정의할 수 있습니다.

  • Firebase Schema 도우미 메서드 (권장): 도우미 메서드 (예: Schema.object()Schema.enumString())를 사용하여 추가 상용구 없이 코드에 간결하고 압축된 스키마를 직접 작성합니다.

  • 일반 JSON 스키마: 기존 스키마 정의가 있거나, 플랫폼 또는 백엔드 서비스 간에 스키마를 공유하거나, JSON 파일에서 스키마를 가져오는 경우 표준 JSON 스키마 객체를 사용합니다.

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

이 예시에서는 Firebase AI Logic SDK에서 제공하는 Schema.enumString 도우미 메서드를 사용하여 허용된 enum 값을 정의합니다.

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.
이 섹션에서는 선택한 Gemini API 제공업체의 버튼을 클릭하여 이 페이지에 제공업체별 콘텐츠가 표시되도록 합니다.

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode,
  Schema
} from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp.
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Define an enum schema using the `Schema` helper method with allowed string values.
const enumSchema = Schema.enumString({
  enum: ["drama", "comedy", "documentary"]
});

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    }
  },
  // For on-device models, pass the enum schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

const prompt = `The film aims to educate and inform viewers about real-life
subjects, events, or people. It offers a factual record of a particular topic
by combining interviews, historical footage, and narration. The primary purpose
of a film is to present information and provide insights into various aspects
of reality.`;

// Generate the structured enum output.
const result = await model.generateContent(prompt);

// Access the selected enum value string from response.text().
console.log(result.response.text());

예 2: 일반 JSON 스키마 사용

이 예에서는 JSON만 사용하여 enum 스키마를 정의합니다.

이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요.
이 섹션에서는 선택한 Gemini API 제공업체의 버튼을 클릭하여 이 페이지에 제공업체별 콘텐츠가 표시되도록 합니다.

import { initializeApp } from "firebase/app";
import {
  getAI,
  getGenerativeModel,
  GoogleAIBackend,
  InferenceMode
} from "firebase/ai";

// TODO(developer): Replace the following with your app's Firebase configuration.
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize FirebaseApp.
const firebaseApp = initializeApp(firebaseConfig);

// Initialize the Gemini Developer API backend service.
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });

// Define the enum schema as a plain JSON object.
const enumSchema = {
  type: "string",
  enum: ["drama", "comedy", "documentary"]
};

// Create a GenerativeModel instance configured to use a hybrid inference mode (like PREFER_ON_DEVICE).
const model = getGenerativeModel(ai, {
  mode: InferenceMode.INFERENCE_MODE,
  // For cloud-hosted models, specify MIME type and response schema.
  inCloudParams: {
    model: "CLOUD_MODEL_NAME",
    generationConfig: {
      responseMimeType: "text/x.enum",
      responseSchema: enumSchema
    }
  },
  // For on-device models, pass the enum schema as the response constraint.
  onDeviceParams: {
    promptOptions: {
      responseConstraint: enumSchema
    }
  }
});

const prompt = `The film aims to educate and inform viewers about real-life
subjects, events, or people. It offers a factual record of a particular topic
by combining interviews, historical footage, and narration. The primary purpose
of a film is to present information and provide insights into various aspects
of reality.`;

// Generate the structured enum output.
const result = await model.generateContent(prompt);

// Access the selected enum value string from response.text().
console.log(result.response.text());


Firebase AI Logic 사용 경험에 관한 의견 보내기