構造化出力(Structured Outputs)
「Structured Outputs」という用語は多義的で、次の 2 つを指すことがあります。
- LLM が構造化フォーマットで出力を生成する一般的な能力(本ページで扱う内容)
- OpenAI の Structured Outputs 機能。 これはレスポンス形式とツール(関数呼び出し)の両方に適用されます。
多くの LLM および LLM プロバイダーは、構造化フォーマット(通常は JSON)での出力生成をサポートしています。 これらの出力は Java オブジェクトに容易にマッピングでき、アプリケーションの他の部分で利用できます。
たとえば、次のような Person クラスがあるとします。
record Person(String name, int age, double height, boolean married) {
}
架空のキャラクターを記述した非構造化テキストから Person オブジェクトを抽出することを目指します。
Eldwin Brightblade is 412 years old and serves as court wizard in the kingdom of Aelyria.
He stands 1.65 meters tall and is known for his flowing white beard.
Currently unmarried, he devotes his time to studying ancient runes.
現在、LLM と LLM プロバイダーに応じて、これを実現する方法は次の 3 通りあります (信頼性の高い順):
JSON Schema
一部の LLM プロバイダー(現在は Amazon Bedrock、Azure OpenAI、Google AI Gemini、Mistral、Ollama、OpenAI)では、 望ましい出力に対して JSON schema を指定できます。 サポートされているすべての LLM プロバイダーは、こちら の 「JSON Schema」列で確認できます。
リクエストで JSON schema が指定されると、LLM はその schema に沿った出力を生成することが期待されます。
JSON schema は LLM プロバイダー API へのリクエスト内の専用属性で指定される点に注意してください。 プロンプト(システムメッセージやユーザーメッセージなど)に自由形式の指示を含める必要はありません。
LangChain4j は、低レベル ChatModel API
と高レベル AI Service API の両方で JSON Schema 機能をサポートしています。
ChatModel で JSON Schema を使う
低レベル ChatModel API では、ChatRequest を作成する際に
LLM プロバイダー非依存の ResponseFormat と JsonSchema を使って JSON schema を指定できます。
ResponseFormat responseFormat = ResponseFormat.builder()
.type(JSON) // type can be either TEXT (default) or JSON
.jsonSchema(JsonSchema.builder()
.name("Person") // OpenAI requires specifying the name for the schema
.rootElement(JsonObjectSchema.builder() // see [1] below
.addStringProperty("name")
.addIntegerProperty("age")
.addNumberProperty("height")
.addBooleanProperty("married")
.required("name", "age", "height", "married") // see [2] below
.build())
.build())
.build();
UserMessage userMessage = UserMessage.from("""
Eldwin Brightblade is 412 years old and serves as court wizard in the kingdom of Aelyria.
He stands 1.65 meters tall and is known for his flowing white beard.
Currently unmarried, he devotes his time to studying ancient runes.
""");
ChatRequest chatRequest = ChatRequest.builder()
.responseFormat(responseFormat)
.messages(userMessage)
.build();
ChatModel chatModel = OpenAiChatModel.builder()
.apiKey(System.getenv("OPENAI_API_KEY"))
.modelName("gpt-4o-mini")
.logRequests(true)
.logResponses(true)
.build();
// OR
ChatModel chatModel = AzureOpenAiChatModel.builder()
.endpoint(System.getenv("AZURE_OPENAI_URL"))
.apiKey(System.getenv("AZURE_OPENAI_API_KEY"))
.deploymentName("gpt-4o-mini")
.logRequestsAndResponses(true)
.build();
// OR
ChatModel chatModel = GoogleAiGeminiChatModel.builder()
.apiKey(System.getenv("GOOGLE_AI_GEMINI_API_KEY"))
.modelName("gemini-1.5-flash")
.logRequestsAndResponses(true)
.build();
// OR
ChatModel chatModel = OllamaChatModel.builder()
.baseUrl("http://localhost:11434")
.modelName("llama3.1")
.logRequests(true)
.logResponses(true)
.build();
// OR
ChatModel chatModel = MistralAiChatModel.builder()
.apiKey(System.getenv("MISTRAL_AI_API_KEY"))
.modelName("mistral-small-latest")
.logRequests(true)
.logResponses(true)
.build();
// OR
ChatModel chatModel = WatsonxChatModel.builder()
.baseUrl(System.getenv("WATSONX_URL"))
.projectId(System.getenv("WATSONX_PROJECT_ID"))
.apiKey(System.getenv("WATSONX_API_KEY"))
.modelName("ibm/granite-4-h-small")
.logRequests(true)
.logResponses(true)
.build();
// OR
ChatModel chatModel = BedrockChatModel.builder()
.modelId("us.anthropic.claude-haiku-4-5-20251001-v1:0")
.logRequests(true)
.logResponses(true)
.build();
ChatResponse chatResponse = chatModel.chat(chatRequest);
String output = chatResponse.aiMessage().text();
System.out.println(output); // {"name":"Eldwin Brightblade","age":412,"height":1.65,"married":false}
Person person = new ObjectMapper().readValue(output, Person.class);
System.out.println(person); // Person[name=Eldwin Brightblade, age=412, height=1.65, married=false]
注意点:
- [1] - ほとんどの場合、ルート要素は
JsonObjectSchema型である必要があります。 ただし:- Amazon Bedrock、Azure OpenAI、Mistral、Ollama、OpenAI、OpenAI Official はルート要素として
JsonRawSchemaも許可します - Gemini はルート要素として
JsonEnumSchemaとJsonArraySchemaも許可します
- Amazon Bedrock、Azure OpenAI、Mistral、Ollama、OpenAI、OpenAI Official はルート要素として
- [2] - 必須プロパティは明示的に指定する必要があります。そうでない場合はオプションと見なされます。
JSON schema の構造は JsonSchemaElement インターフェースで定義され、
次のサブタイプがあります。
JsonObjectSchema- オブジェクト型用。JsonStringSchema-String、char/Character型用。JsonIntegerSchema-int/Integer、long/Long、BigInteger型用。JsonNumberSchema-float/Float、double/Double、BigDecimal型用。JsonBooleanSchema-boolean/Boolean型用。JsonEnumSchema-enum型用。JsonArraySchema- 配列とコレクション(例:List、Set)用。JsonReferenceSchema- 再帰のサポート用(例:PersonがSet<Person> childrenフィールドを持つ場合)。JsonAnyOfSchema- ポリモーフィズムのサポート用(例:ShapeがCircleまたはRectangle)。JsonNullSchema- nullable 型のサポート用。JsonRawSchema- 独自に完全定義した JSON schema を使う場合。
JsonObjectSchema
JsonObjectSchema はネストされたプロパティを持つオブジェクトを表します。
通常は JsonSchema のルート要素です。
JsonObjectSchema にプロパティを追加する方法はいくつかあります。
properties(Map<String, JsonSchemaElement> properties)メソッドで一度にすべてのプロパティを追加できます。
JsonSchemaElement citySchema = JsonStringSchema.builder()
.description("The city for which the weather forecast should be returned")
.build();
JsonSchemaElement temperatureUnitSchema = JsonEnumSchema.builder()
.enumValues("CELSIUS", "FAHRENHEIT")
.build();
Map<String, JsonSchemaElement> properties = Map.of(
"city", citySchema,
"temperatureUnit", temperatureUnitSchema
);
JsonSchemaElement rootElement = JsonObjectSchema.builder()
.addProperties(properties)
.required("city") // required properties should be specified explicitly
.build();
addProperty(String name, JsonSchemaElement jsonSchemaElement)メソッドで個別にプロパティを追加できます。
JsonSchemaElement rootElement = JsonObjectSchema.builder()
.addProperty("city", citySchema)
.addProperty("temperatureUnit", temperatureUnitSchema)
.required("city")
.build();
add{Type}Property(String name)またはadd{Type}Property(String name, String description)メソッドのいずれかで個別にプロパティを追加できます。
JsonSchemaElement rootElement = JsonObjectSchema.builder()
.addStringProperty("city", "The city for which the weather forecast should be returned")
.addEnumProperty("temperatureUnit", List.of("CELSIUS", "FAHRENHEIT"))
.required("city")
.build();
詳細は JsonObjectSchema の Javadoc を参照してください。
JsonStringSchema
JsonStringSchema を作成する例:
JsonSchemaElement stringSchema = JsonStringSchema.builder()
.description("The name of the person")
.build();
JsonIntegerSchema
JsonIntegerSchema を作成する例:
JsonSchemaElement integerSchema = JsonIntegerSchema.builder()
.description("The age of the person")
.build();
JsonNumberSchema
JsonNumberSchema を作成する例:
JsonSchemaElement numberSchema = JsonNumberSchema.builder()
.description("The height of the person")
.build();
JsonBooleanSchema
JsonBooleanSchema を作成する例:
JsonSchemaElement booleanSchema = JsonBooleanSchema.builder()
.description("Is the person married?")
.build();