首页 > web前端 > js教程 > 正文

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

聖光之護
发布: 2025-02-03 22:18:02
原创
305人浏览过

本文介绍如何使用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)的详细内容,更多请关注php中文网其它相关文章!

豆包AI编程
豆包AI编程

智能代码生成与优化,高效提升开发速度与质量!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号