Google GenAI Gemini API返回包代码而非Prompt响应的问题求助
在Plasmo Chrome扩展中调用Google Gemini API时,
response.text返回内部代码而非预期响应的问题分析与解决 问题概述
基于Plasmo开发Chrome扩展时,调用Google Gemini GenAI API,按照官方文档使用result.response.text获取响应,却得到了SDK内部的处理代码(而非Prompt对应的文本结果)。临时通过直接访问result.response.candidates[0].content.parts[0].text拿到了正确响应,但不清楚为何与官方文档的推荐用法相悖。
异常响应内容
收到的非预期响应代码:
()=>{ if (response.candidates && response.candidates.length > 0) { if (response.candidates.length > 1) console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning text from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`); if (hadBadFinishReason(response.candidates[0])) throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); return getText(response); } else if (response.promptFeedback) throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response); return ""; }
核心调用代码
原API调用方法:
async QueryAI(question){ const genAI = new GoogleGenerativeAI(process.env.PLASMO_PUBLIC_GEMINI_API_KEY.toString()); const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); const result = await model.generateContent(question); console.log("result"+result.response.text); return result.response.text; }
问题原因分析
- SDK兼容性问题:Plasmo的Chrome扩展运行环境(隔离的content/background脚本上下文)与部分版本的Google Generative AI SDK存在兼容性冲突,导致
response.text这个getter方法未被正确执行,反而返回了方法本身的源代码。 - 环境特性限制:Chrome扩展的执行环境对JS getter函数的绑定逻辑有特殊限制,使得访问
response.text时未触发预期的取值逻辑,直接返回了函数定义。
解决方案
1. 临时有效方案(已验证)
直接访问响应结构中的原始文本节点,替换原有的result.response.text逻辑,并添加空值校验避免报错:
async QueryAI(question){ const genAI = new GoogleGenerativeAI(process.env.PLASMO_PUBLIC_GEMINI_API_KEY.toString()); const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); const result = await model.generateContent(question); const response = result.response; // 空值校验:无候选结果时的处理 if (!response.candidates || response.candidates.length === 0) { if (response.promptFeedback) { throw new Error(`Prompt校验错误: ${JSON.stringify(response.promptFeedback)}`); } return ""; } // 多候选结果提示 if (response.candidates.length > 1) { console.warn(`当前响应包含${response.candidates.length}个候选结果,仅返回第一个`); } const candidate = response.candidates[0]; // 校验候选结果的内容结构 if (!candidate.content || !candidate.content.parts || candidate.content.parts.length === 0) { return ""; } return candidate.content.parts[0].text; }
2. 长期优化方案
- 升级Google Generative AI SDK到最新稳定版本,查看官方更新日志确认是否修复了类似环境下的兼容性问题。
- 检查Plasmo项目的构建配置,确保SDK被正确打包,避免函数被错误序列化。
内容的提问来源于stack exchange,提问作者envydos
相关产品推荐
相关产品推荐

