登录
首页 >  文章 >  前端

如何在双子座AI中生成结构化输出(JSON,YAML)

时间:2025-02-03 08:33:58 446浏览 收藏

你在学习文章相关的知识吗?本文《如何在双子座AI中生成结构化输出(JSON,YAML)》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

本文介绍如何使用Google Gemini API快速生成高质量的API文档,并演示如何灵活地输出JSON或YAML格式的结果。作者Shrijith Venkatrama,Hexmos创始人,分享了LiveAPI的构建过程,这是一个通过代码生成API文档的强大工具。

步骤1:获取Gemini API密钥

首先,需要在Google AI Studio获取免费的API密钥,用于后续的API请求。

步骤2:安装SDK和配置

创建一个项目,安装@google/generative-ai依赖包:

mkdir structured-gemini
cd structured-gemini
npm install @google/generative-ai

导入genai库,并使用环境变量中的API密钥进行配置:

import { googlegenerativeai } from "@google/generative-ai";

const genai = new googlegenerativeai(process.env.api_key);

步骤3:使用Schema生成JSON

本例中,目标是获取历史上十大悬疑电影的列表,每部电影以JSON对象形式呈现。

3.1 定义Schema:

import { googlegenerativeai, schematype } from "@google/generative-ai";

const schema = {
  description: "top 10 mystery movies of all time",
  type: schematype.array,
  items: {
    type: schematype.object,
    properties: {
      title: { type: schematype.string, description: "title of the movie", nullable: false },
      director: { type: schematype.string, description: "director of the movie", nullable: false },
      year: { type: schematype.integer, description: "year of release", nullable: false },
      imdbrating: { type: schematype.number, description: "imdb rating of the movie", nullable: false },
    },
    required: ["title", "director", "year", "imdbrating"],
  },
};

3.2 定义模型:

const model = genai.getgenerativemodel({
  model: "gemini-1.5-pro",
  generationconfig: {
    responsemimetype: "application/json",
    responseschema: schema,
  },
});

3.3 生成JSON并格式化输出:

async function fetchmovies() {
  const result = await model.generatecontent(
    "list the top 10 mystery movies of all time with their title, director, year of release, and imdb rating."
  );
  let movies = JSON.parse(result.response.text());
  console.log(JSON.stringify(movies, null, 2));
}

fetchmovies().catch(console.error);

运行代码将得到格式化的JSON输出。

步骤4:生成YAML输出

由于直接生成YAML格式不可行,采用先获取JSON再转换为YAML的方案。

安装@catalystic/json-to-yaml

npm i @catalystic/json-to-yaml

导入并使用转换器:

import { convert } from "@catalystic/json-to-yaml";

async function fetchmovies() {
  // ... (previous code) ...
  const yaml = convert(movies);
  console.log("\n==============\n");
  console.log(yaml);
}

运行后,将得到YAML格式的输出结果。

如何在双子座AI中生成结构化输出(JSON,YAML)

通过以上步骤,可以高效地利用Google Gemini API生成结构化的API文档,并根据需要灵活地选择JSON或YAML格式输出。

今天关于《如何在双子座AI中生成结构化输出(JSON,YAML)》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>