Google Generative AI API调用报错:Invalid JSON payload问题求助
集成Google Generative AI API时400 Bad Request错误修复
问题概述
调用Gemini-1.5-flash API进行函数调用时,收到400 Bad Request错误,具体错误信息:
Invalid JSON payload received. Unknown name "response" at 'contents[2].parts[0].function_response': Proto field is not repeating, cannot start list.
错误原因
错误源于函数响应的格式不符合API要求:
- API要求函数响应需使用
content字段传递返回值,而非代码中使用的response字段。 - 直接传递数组或字符串作为响应值时,API无法解析(因为Proto字段不支持直接列表形式),必须将返回值包装为对象结构。
修复方案
1. 调整函数响应结构
将原代码中response字段替换为content,并将返回值包装为对象:
// 原错误代码 const functionResponse = { name: callingFunction.name, response: apiResponse, }; // 修改后代码 const functionResponse = { name: callingFunction.name, content: { result: apiResponse // 用统一键名包装所有类型的返回值 }, };
2. 确保返回值为可序列化对象
若函数返回的是Mongoose查询结果(如餐厅列表),需转换为普通JSON对象,避免序列化问题:
// 在查询时添加.lean() const restaurants = await Restaurant.find(find).select("name address").lean();
完整修改后的核心代码片段
if (callingFunctions && callingFunctions.length > 0) { const callingFunction = callingFunctions[0]; const apiResponse = await functions[callingFunction.name](callingFunction.args); // 修复后的函数响应结构 const functionResponse = { name: callingFunction.name, content: { result: apiResponse }, }; const result2 = await chat.sendMessage([ { functionResponse: functionResponse, }, ]); answer = result2.response.text(); }
验证说明
修改后,函数响应的格式完全符合Google Generative AI API的规范:
- 使用API要求的
content字段传递结构化数据 - 返回值统一包装为对象,避免直接传递数组/字符串导致的解析错误
内容的提问来源于stack exchange,提问作者Duy Phạm
相关产品推荐
相关产品推荐

