メインコンテンツまでスキップ

Structured Outputs

どんな問題を解決

LLMがJSON形式で指定されたスキーマを出力するよう強制する

古い解決策。

LLMがJSON形式と各フィールドの名前とタイプをプロンプトで出力するように要求します。

output in JSON object with follow fileds:
- name: string
- age: number
- isFemale: boolean

LangChainには、キューを生成するParserがあります。

質問1。

しかし、LLMはJSON以外の形式を出力するか、フィールドが期待されていない可能性があります。

後の解決策

Open AIのAPIはjson_objectパターンを導入し、LLMにJSON形式を強制的に返すことができる。

質問2の質問

LLMが返すフィールドは期待通りではない場合がある。

最新のソリューション。

Open AIのStructured Outputsスキームでは、APIフィールドに明示的なJSONスキーマを渡すことができ、LLMが指定されたフォーマットを出力できるようになります。

response_format: { "type": "json_schema", "json_schema": … , "strict": true }

json_schemaでフォーマットを指定できます。例えば、

{
type: "json_schema",
json_schema: {
name: "math_response",
schema: {
type: "object",
properties: {
steps: {
type: "array",
items: {
type: "object",
properties: {
explanation: { type: "string" },
output: { type: "string" }
},
required: ["explanation", "output"],
additionalProperties: false
}
},
final_answer: { type: "string" }
},
required: ["steps", "final_answer"],
additionalProperties: false
},
strict: true
}
}

Node.jsでは、もっと簡単にできます:

JSONスキーマを定義する

import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";

const Step = z.object({
explanation: z.string(),
output: z.string(),
});

const MathResponse = z.object({
steps: z.array(Step),
final_answer: z.string(),
});

response_formatフィールドに追加

const completion = await openai.beta.chat.completions.parse({
model: "gpt-4o-mini",
messages: [
{ role: "system", content: "You are a helpful math tutor. Guide the user through the solution step by step." },
{ role: "user", content: "how can I solve 8x + 7 = -23" },
],
response_format: zodResponseFormat(MathResponse, "math_response"),
});

非常に便利です。

** LangChainでの使い方 **

import { ChatOpenAI } from "@langchain/openai";
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { z } from "zod";
import { zodResponseFormat } from "openai/helpers/zod";

export async function main() {
const CalendarEvent = z.object({
name: z.string(),
date: z.string(),
participants: z.array(z.string()),
});

const model = new ChatOpenAI({
model: "gpt-4o-mini",
// 在这里添加
modelKwargs: {
response_format: zodResponseFormat(CalendarEvent, "event"),
},
});
const messages = [
new SystemMessage("Extract the event information."),
new HumanMessage("我和小明参加婚礼"),
];
const parser = new StringOutputParser();

const chain = model.pipe(parser);
const resp = await chain.invoke(messages);
console.log(resp);
}

参考までに

官网