如何将OpenAI函数调用工具转换为Gemini函数调用工具?
将OpenAI工具转换为Gemini工具的方法
要把OpenAI格式的工具适配到Gemini,核心是对齐两者的结构差异——它们的参数JSON Schema完全通用,只需调整外层包裹逻辑即可。以下是具体实现:
1. 格式差异说明
OpenAI的工具外层用type: 'function'包裹函数定义,而Gemini直接使用FunctionDeclaration类型(来自Google AI SDK),每个工具对象直接包含name、description和parameters字段,无需额外外层标记。
2. 批量转换函数
可以写一个极简的转换函数,批量处理OpenAI工具数组:
import { FunctionDeclaration } from '@google/generative-ai'; import { ChatCompletionTool } from 'openai/src/resources/chat/completions'; // 转换OpenAI工具到Gemini格式 function convertOpenAIToGeminiTools(openAiTools: ChatCompletionTool[]): FunctionDeclaration[] { return openAiTools.map(tool => tool.function as FunctionDeclaration); }
3. 转换后的示例结果
用你提供的OpenAI工具数组转换后,得到的Gemini工具如下:
import { FunctionDeclaration } from '@google/generative-ai'; const geminiTools: FunctionDeclaration[] = [ { name: 'saveLead', description: 'Save lead information', parameters: { type: 'object', properties: { name: { type: 'string', description: 'Lead name', }, phone: { type: 'string', }, email: { type: 'string', description: 'Valid email RFC 5322', }, }, required: ['name', 'phone', 'email'], }, }, { name: 'escalateToHumanAgent', description: 'Escalate to human agent', parameters: { type: 'object', properties: { reason: { type: 'string', description: 'Reason for escalating to human agent', }, }, required: ['reason'], }, }, ];
关键提示
- 参数部分完全无需修改,两者的JSON Schema标准一致
- JavaScript环境下可直接去掉类型声明,仅保留
return openAiTools.map(tool => tool.function) - 该逻辑支持任意数量的工具批量转换,适配多提供商项目的快速切换需求
内容的提问来源于stack exchange,提问作者Tiago Gouvêa
相关产品推荐
相关产品推荐

