ผลผลิตที่มีโครงสร้าง
แก้ปัญหาอะไร?
บังคับให้ LLM เอาต์พุตในรูปแบบ JSON และเป็นรูปแบบที่ระบุ
โซลูชันเก่า
ขอให้ LLM เอาต์พุตในรูปแบบ JSON และชื่อและประเภทของแต่ละฟิลด์ในตัวอย่างเช่น
output in JSON object with follow fileds:
- name: string
- age: number
- isFemale: boolean
LangChain มี Parser ที่จะช่วยคุณสร้างคําเตือน
คําถามที่ 1
อย่างไรก็ตาม LLM ยังคงมีความน่าจะเป็นที่จะส่งผลลัพธ์ในรูปแบบที่ไม่ใช่ JSON หรือฟิลด์ที่ไม่คาดหวัง
โซลูชันในภายหลัง
API ของ OpenAI แนะนําโหมด 'json object' ซึ่งสามารถบังคับให้ LLM กลับไปที่รูปแบบ JSON
คําถามที่ 2
ฟิลด์ที่ส่งกลับโดย LLM อาจไม่คาดหวัง
โซลูชั่นล่าสุด
โครงการผลลัพธ์ที่มีโครงสร้างของ OpenAI สามารถใส่รูปแบบ JSON ที่ชัดเจนในฟิลด์ของ API เพื่อให้ 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);
}