本文介绍如何使用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-geminicd structured-gemininpm 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并格式化输出:
Ideogram
Ideogram是一个全新的文本转图像AI绘画生成平台,擅长于生成带有文本的图像,如LOGO上的字母、数字等。
512 查看详情
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格式的输出结果。

通过以上步骤,可以高效地利用Google Gemini API生成结构化的API文档,并根据需要灵活地选择JSON或YAML格式输出。
以上就是如何在双子座AI中生成结构化输出(JSON,YAML)的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/779201.html
微信扫一扫
支付宝扫一扫