本文介绍如何使用google gemini api快速生成高质量的api文档,并演示如何灵活地输出json或yaml格式的结果。作者shrijith venkatrama,hexmos创始人,分享了liveapi的构建过程,这是一个通过代码生成api文档的强大工具。
步骤1:获取Gemini API密钥
首先,需要在Google AI Studio获取免费的API密钥,用于后续的API请求。
步骤2:安装SDK和配置
创建一个项目,安装@google/generative-ai依赖包:
<code class="bash">mkdir structured-gemini cd structured-gemini npm install @google/generative-ai</code>
导入genai库,并使用环境变量中的API密钥进行配置:
<code class="javascript">import { googlegenerativeai } from "@google/generative-ai";
const genai = new googlegenerativeai(process.env.api_key);</code>步骤3:使用Schema生成JSON
本例中,目标是获取历史上十大悬疑电影的列表,每部电影以JSON对象形式呈现。
3.1 定义Schema:
<code class="javascript">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"],
},
};</code>3.2 定义模型:
<code class="javascript">const model = genai.getgenerativemodel({
model: "gemini-1.5-pro",
generationconfig: {
responsemimetype: "application/json",
responseschema: schema,
},
});</code>3.3 生成JSON并格式化输出:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
<code class="javascript">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);</code>运行代码将得到格式化的JSON输出。
步骤4:生成YAML输出
由于直接生成YAML格式不可行,采用先获取JSON再转换为YAML的方案。
安装@catalystic/json-to-yaml:
<code class="bash">npm i @catalystic/json-to-yaml</code>
导入并使用转换器:
<code class="javascript">import { convert } from "@catalystic/json-to-yaml";
async function fetchmovies() {
// ... (previous code) ...
const yaml = convert(movies);
console.log("\n==============\n");
console.log(yaml);
}</code>运行后,将得到YAML格式的输出结果。

通过以上步骤,可以高效地利用Google Gemini API生成结构化的API文档,并根据需要灵活地选择JSON或YAML格式输出。
以上就是如何在双子座AI中生成结构化输出(JSON,YAML)的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号