구조화 된 출력
어떤 문제를 해결하다
LLM 은 JSON 형식을 출력하도록 강요하고 지정된 스키마입니다.
오래된 해결책
프롬프트에서 LLM 에 JSON 형식과 각 필드의 이름 및 유형을 출력하도록 요청합니다.
output in JSON object with follow fileds:
- name: string
- age: number
- isFemale: boolean
LangChain 에는 프롬프트를 생성하는 데 도움이되는 파서가 있습니다.
질문 1
그러나 LLM 은 여전히 JSON 이 아닌 형식을 출력하거나 필드가 예상되지 않을 가능성이 있습니다.
이후의 솔루션
OpenAI 의 API 는 LLM 을 JSON 형식으로 반환하도록 강요하는 'json _ object' 모드를 도입했습니다.
질문 2
LLM 에서 반환되는 필드는 예상되지 않을 수 있습니다.
최신 솔루션
OpenAI 의 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);
}