从旧版迁移到 generative-ai-js:Google Gemini API 开发者必备指南
从旧版迁移到 generative-ai-js:Google Gemini API 开发者必备指南
generative-ai-js 是 Google Gemini API 官方的 Node.js/TypeScript 库,为开发者提供了简单清晰的路径来构建基于 Gemini 模型的应用。随着版本迭代,旧版 SDK 已不再适用于最新功能,本指南将帮助你快速完成从旧版到 generative-ai-js 的无缝迁移,确保你的项目持续获得最新能力与支持。
为什么选择 generative-ai-js?
Google Generative AI SDK(generative-ai-js)经过全新设计,专注于提供极致简洁的开发体验。相比旧版 SDK,它带来了多项关键改进:
- 更直观的 API 设计:简化了模型初始化、内容生成和工具调用流程
- 完整的 TypeScript 支持:提供精确的类型定义,减少开发错误
- 增强的错误处理:引入专用错误类型如
GoogleGenerativeAIError和GoogleGenerativeAIFetchError - 扩展的功能集:支持文件管理、内容缓存、函数调用等高级特性
图:使用 generative-ai-js 就像为你的开发流程装备了高效喷气背包,显著提升开发效率
准备工作:环境与安装
在开始迁移前,请确保你的开发环境满足以下要求:
- Node.js 14.0.0 或更高版本
- npm 6.0.0 或更高版本
迁移的第一步是安装最新版 generative-ai-js:
# 克隆仓库
git clone https://gitcode.com/gh_mirrors/ge/generative-ai-js
cd generative-ai-js
# 安装依赖
npm install @google/generative-ai
核心迁移步骤
1. 模型初始化方式变更
旧版 SDK 的模型初始化代码:
// 旧版方式
const { GoogleAI } = require('@google-cloud/aiplatform');
const ai = new GoogleAI({ projectId: 'your-project-id' });
const model = ai.getGenerativeModel({ model: 'gemini-pro' });
新版 generative-ai-js 的初始化方式:
// 新版方式
import { GoogleGenerativeAI } from '@google/generative-ai';
const genAI = new GoogleGenerativeAI('YOUR_API_KEY');
const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
主要变化:
- 不再需要项目 ID,改为直接使用 API 密钥
- 类名从
GoogleAI变更为GoogleGenerativeAI - 简化了模型获取流程
2. 文件管理功能迁移
在 0.13.0 版本中,GoogleAIFileManager 类的导入路径发生了变化:
// 旧版导入方式
import { GoogleAIFileManager } from '@google/generative-ai/files';
// 新版导入方式
import { GoogleAIFileManager } from '@google/generative-ai/server';
文件上传示例:
const fileManager = new GoogleAIFileManager(apiKey);
const file = await fileManager.uploadFile('path/to/file.jpg', {
mimeType: 'image/jpeg',
displayName: 'My Image'
});
3. 处理重大变更与修复
generative-ai-js 引入了多项重要的 API 变更,需要特别注意:
3.1 命名修复
版本 0.22.0 修复了两个重要的命名问题:
groundingChunks:修复了拼写错误groundingSupports:从groundingSupport重命名(增加了 's')
3.2 响应结构优化
响应对象的结构也有调整,例如使用 response.text() 简化文本提取:
// 旧版方式
const response = await model.generateContent('Hello');
const text = response.candidates[0].content.parts[0].text;
// 新版方式
const result = await model.generateContent('Hello');
const response = await result.response;
const text = response.text();
图:迁移过程中可能遇到的挑战就像跨越有食人鱼的河流,本指南将帮助你安全抵达对岸
高级功能迁移指南
缓存管理
generative-ai-js 新增了 GoogleAICacheManager 类,用于缓存大型内容:
import { GoogleAICacheManager } from '@google/generative-ai/server';
const cacheManager = new GoogleAICacheManager(apiKey);
const cachedContent = await cacheManager.create({
displayName: 'My cached content',
contents: [{ role: 'user', parts: [{ text: 'Hello world' }] }],
ttlSeconds: 3600
});
函数调用
函数调用功能也有改进,使用 functionCalls() 替代了旧版的 functionCall():
// 旧版方式
const response = await model.generateContent({
contents: [{ role: 'user', parts: [{ text: 'What is the weather?' }] }],
tools: [{ functionDeclarations: [weatherFunction] }],
toolConfig: { functionCall: { name: 'get_weather' } }
});
// 新版方式
const response = await model.generateContent({
contents: [{ role: 'user', parts: [{ text: 'What is the weather?' }] }],
tools: [{ functionDeclarations: [weatherFunction] }],
toolConfig: { functionCallingConfig: { mode: 'FUNCTION_CALL', allowedFunctionNames: ['get_weather'] } }
});
迁移后的验证与测试
完成代码迁移后,建议进行全面测试以确保功能正常:
- 运行项目测试套件:
npm test
-
检查示例代码:项目提供了丰富的示例可参考 samples/ 目录,包括:
- samples/chat.js:聊天功能示例
- samples/function_calling.js:函数调用示例
- samples/files.js:文件管理示例
-
验证 API 响应:使用新的响应处理方式确保正确获取和解析模型输出
常见问题与解决方案
Q: 迁移后出现 "GoogleAIFileManager not found" 错误?
A: 这是因为文件管理器类已移动到 server 子路径,请更新导入为 from '@google/generative-ai/server'
Q: 如何处理 groundingChunks 相关的类型错误?
A: 版本 0.22.0 修复了此拼写错误,请将代码中的 groundingChunk 改为 groundingChunks
Q: 响应对象的 text() 方法返回 undefined?
A: 确保使用 await result.response 获取完整响应后再调用 text() 方法
图:成功迁移后,你将像消防员救援小猫一样轻松应对各种开发挑战
总结与下一步
迁移到 generative-ai-js 不仅能让你使用最新的 Gemini API 功能,还能获得更简洁、更强大的开发体验。完整的迁移指南可参考 Gemini API 文档。
建议下一步:
- 查看 CHANGELOG.md 了解所有版本变更
- 探索 src/ 目录下的源代码,深入理解库的实现细节
- 尝试使用新功能如代码执行、搜索基础和内容缓存
通过本指南,你已经掌握了从旧版 SDK 迁移到 generative-ai-js 的核心步骤。如有其他问题,可查阅项目的 docs/ 目录或提交 issue 获取支持。
更多推荐
所有评论(0)