在NestJS应用中以JSON格式返回Google Gemini响应

我正在按照一个教程学习如何实现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(), // 我猜我在这里犯了一个错误?      };    } 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,  };

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注