OpenAI助手上传JSON文件提示格式无效问题求助
JSON文件上传OpenAI助手提示「无效文件格式」的解决方法
问题
上传appointments.json到OpenAI新助手时提示「无效文件格式」,但JSON属于官方支持的格式。
相关代码
调用上传方法的代码
const file = await AssistantHandler.UploadFiles({ file: [ { "start": "2023-11-14T15:30:00+01:00", "summary": "skdkasd", }, { "start": "2023-11-14T19:00:00+01:00", "summary": "jadslk", }, ], user_id: "ouG890XHkqh79nvlHQzftGkjKvEE", date: "2021-10-17", type: "prescription", });
文件创建与上传的核心代码
static CreateLocalFile = async ({ file, user_id, date, type }) => { try { const filePath = path.join("/tmp", `${user_id}-${type}-${date}.json`); file.forEach((obj) => { const jsonString = JSON.stringify(obj); fs.appendFileSync(filePath, jsonString + "\n"); }); return filePath; } catch (error) { console.error("Error creating local file:", error.message); throw error; } }; static async UploadFiles(params) { try { const filePath = await this.CreateLocalFile(params); const fileStream = fs.createReadStream(filePath, { encoding: "binary" }); const response = await this.openai.files.create({ file: fileStream, purpose: "assistants", }); fs.unlinkSync(filePath); return response; } catch (error) { console.error("Error uploading file:", error.message); throw error; } }
问题原因
当前CreateLocalFile方法生成的是JSON Lines格式文件(每行一个独立JSON对象),但OpenAI Files API要求上传的是标准JSON格式(整个文件是单个JSON数组或对象),所以会被判定为无效格式。
解决方法
修改CreateLocalFile方法,直接将整个数组序列化为单个JSON字符串写入文件,而不是逐个对象追加:
static CreateLocalFile = async ({ file, user_id, date, type }) => { try { const filePath = path.join("/tmp", `${user_id}-${type}-${date}.json`); // 将整个数组转为标准JSON字符串 const jsonString = JSON.stringify(file); fs.writeFileSync(filePath, jsonString); return filePath; } catch (error) { console.error("Error creating local file:", error.message); throw error; } };
另外,读取文件时无需指定encoding: "binary",OpenAI的SDK会自动处理正确格式,可改为:
const fileStream = fs.createReadStream(filePath);
内容的提问来源于stack exchange,提问作者Ehz uiq
相关产品推荐
相关产品推荐

