在 NestJS 应用程序中以 JSON 形式返回 Google Gemini 响应

问题描述 投票:0回答:1

我正在跟随一位导师学习如何实现 Google Gemini 的 API。他使用 Next.js API 路由,但我使用 NestJS 作为单独的后端。我们使用相同的提示,向 Gemini 指定数据必须以 JSON 格式返回。

他的响应以 JSON 格式正确,如下所示:

enter image description here

但我的是文本/字符串:

enter image description here

这是我的代码:

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(), // I guess I made an error here?
      };
    } catch (error) {}

node.js nestjs backend google-gemini
1个回答
0
投票

此修改使用 JSON.parse 在返回之前将文本响应转换为 JSON 对象。现在,数据将保存解析后的 JSON,而不是原始字符串。

const result =等待chatSession.sendMessage(prompt.toString()); console.log(结果.response.text());

  const parsedData = JSON.parse(result.response.text()); // Parse the JSON response

  return {
    data: parsedData,
  };
© www.soinside.com 2019 - 2024. All rights reserved.