调用OpenAI API遇类型错误:ChatCompletion无'data'属性如何解决?
解决ChatCompletion类型无data属性的解构错误
你遇到的错误是因为当前使用的OpenAI SDK(v4版本)中,chat.completions.create方法返回的response本身就是ChatCompletion类型实例,该类型不存在data属性,直接解构data会触发类型错误。
正确解决方案
直接从response的choices数组中提取模型生成的内容即可,由于你设置了n:1,数组只会包含一条结果。修改后的完整代码如下:
import openai from "@/openai"; import { NextResponse } from "next/server"; export async function POST(request: Request){ const {todos} = await request.json(); const response = await openai.chat.completions.create({ model: "gpt-3.5-turbo", temperature: 0.8, n: 1, stream: false, messages: [ { role: "system", content: `When responding, welcome the user always as Hello User and say Welcome to the Todo List App! Limit text to 200 characters.` }, { role: "user", content: `Hi there, provide a summary of the following todos. Count how many todos are in each category such as To do, in progress and done, then tell the user to have a productive day! Here's the data: ${JSON.stringify( todos )}` } ] }); // 提取模型生成的总结内容 const { choices: [{ message: { content: summary } }] } = response; // 返回JSON结果给前端 return NextResponse.json({ summary }); }
关键说明
ChatCompletion类型的核心结构中,choices字段存储模型的返回结果数组,每个元素包含message对象,message.content就是生成的文本内容。- 如果后续设置
n大于1,需要遍历choices数组处理每条返回结果。
内容的提问来源于stack exchange,提问作者user9187915
相关产品推荐
相关产品推荐

