我正在按照一个教程学习如何实现Google Gemini的API。教程中使用的是Next.js的API路由,但我使用的是NestJS作为独立的后端。我们使用相同的提示,并明确要求Gemini以JSON格式返回数据。
他的响应正确地以JSON格式返回,如下所示:
但我的响应是以文本/字符串形式返回的:
这是我的代码:
async generateVideo(prompt: string) { try { const model = this.genAI.getGenerativeModel({ model: 'gemini-1.5-flash', }); const generationConfig = { temperature: 1, topP: 0.95, topK: 64, maxOutputTokens: 8192, responseMimeType: 'application/json', }; const chatSession = model.startChat({ generationConfig, history: [ /*Removed because it was too long */ ], }); const result = await chatSession.sendMessage(prompt.toString()); console.log(result.response.text()); return { data: result.response.text(), // 我猜我在这里犯了一个错误? }; } catch (error) {}
回答:
此修改使用JSON.parse将文本响应转换为JSON对象后再返回。现在,data将持有解析后的JSON,而不是原始字符串。
const result = await chatSession.sendMessage(prompt.toString());console.log(result.response.text());
const parsedData = JSON.parse(result.response.text()); // 解析JSON响应 return { data: parsedData, };