本文介绍如何使用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格式的输出结果。
通过以上步骤,可以高效地利用Google Gemini API生成结构化的API文档,并根据需要灵活地选择JSON或YAML格式输出。
以上就是如何在双子座AI中生成结构化输出(JSON,YAML)的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号