规划和执行查询计划¶
本示例演示了如何在问答系统中使用 OpenAI 函数调用 ChatCompletion 模型来规划和执行查询计划。通过将复杂问题分解为带有明确依赖关系的小子问题,系统可以系统地收集必要的信息来回答主要问题。
动机
本示例的目标是展示查询规划如何用于处理复杂问题、促进迭代信息收集、自动化工作流程和优化流程。通过利用 OpenAI 函数调用模型,您可以设计和执行结构化计划以有效地找到答案。
用例
- 复杂问题回答
- 迭代信息收集
- 工作流程自动化
- 流程优化
使用 OpenAI 函数调用模型,您可以自定义规划过程并将其集成到您的特定应用程序中,以满足您的独特需求。
定义结构¶
让我们定义表示查询计划和查询所需的模型。
import Instructor from "@/instructor"
import OpenAI from "openai"
import { z } from "zod"
const QueryTypeSchema = z.enum(["SINGLE", "MERGE_MULTIPLE_RESPONSES"]);
const QuerySchema = z.object({
id: z.number(),
question: z.string(),
dependencies: z.array(z.number()).optional(),
node_type: QueryTypeSchema.default("SINGLE")
})
const QueryPlanSchema = z.object({
query_graph: z.array(QuerySchema)
})
规划查询计划¶
现在,让我们演示如何使用定义的模型和 OpenAI API 来规划和执行查询计划。
const oai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY ?? undefined,
organization: process.env.OPENAI_ORG_ID ?? undefined
})
const client = Instructor({
client: oai,
mode: "FUNCTIONS",
})
const createQueryPlan = async (question: string): Promise<QueryPlan | undefined> => {
const queryPlan: QueryPlan = await client.chat.completions.create({
messages: [
{
"role": "system",
"content": "You are a world class query planning algorithm capable of breaking apart questions into its dependency queries such that the answers can be used to inform the parent question. Do not answer the questions, simply provide a correct compute graph with good specific questions to ask and relevant dependencies. Before you call the function, think step-by-step to get a better understanding of the problem.",
},
{
"role": "user",
"content": `Consider: ${question}\nGenerate the correct query plan.`,
},
],
model: "gpt-4o",
response_model: { schema: QueryPlanSchema },
max_tokens: 1000,
temperature: 0.0,
max_retries: 2,
})
return queryPlan || undefined
}
const queryPlan = await createQueryPlan(
"What is the difference in populations of Canada and the Jason's home country?"
)
console.log({ queryPlan: JSON.stringify(queryPlan) })
无 RAG
虽然本示例构建了查询计划,但我们并未提出实际回答问题的方法。您可以实现自己的回答函数,该函数可能会进行检索并调用 OpenAI 进行检索增强生成。该步骤也会用到函数调用,但这超出了本示例的范围。
{
"query_graph": [
{
"id": 1,
"question": "What is the population of Canada?",
"dependencies": [],
"node_type": "SINGLE"
},
{
"id": 2,
"question": "What is the name of Jason's home country?",
"dependencies": [],
"node_type": "SINGLE"
},
{
"id": 3,
"question": "What is the population of {country}?",
"dependencies": [2],
"node_type": "SINGLE"
},
{
"id": 4,
"question": "What is the difference in population between Canada and {country}?",
"dependencies": [1, 3],
"node_type": "MERGE_MULTIPLE_RESPONSES"
}
]
}
在上面的代码中,我们定义了一个 createQueryPlan
函数,该函数接受一个问题作为输入,并使用 OpenAI API 生成查询计划。
结论¶
在本示例中,我们演示了如何在问答系统中使用 OpenAI 函数调用 ChatCompletion
模型来规划和执行查询计划。我们使用 Zod 定义了所需的结构并创建了查询规划器函数。