Skip to content

Instantly share code, notes, and snippets.

@TiagoGouvea
Created July 16, 2024 12:04
Show Gist options
  • Save TiagoGouvea/66bafedf3fda398b3c28ba971e7b0a52 to your computer and use it in GitHub Desktop.
Save TiagoGouvea/66bafedf3fda398b3c28ba971e7b0a52 to your computer and use it in GitHub Desktop.
Convert openAi functions to gemini function calling
import { ChatCompletionTool } from 'openai/src/resources/chat/completions';
import {
FunctionDeclarationSchemaType,
FunctionDeclarationsTool,
} from '@google/generative-ai';
const openAiTools: ChatCompletionTool[] = [
{
type: 'function',
function: {
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'],
},
},
},
{
type: 'function',
function: {
name: 'escalateToHumanAgent',
description: 'Escalate to human agent',
parameters: {
type: 'object',
properties: {
reason: {
type: 'string',
description: 'Reason for escalating to human agent',
},
},
required: ['reason'],
},
},
},
];
const convertToolsToGemini = (
tools: ChatCompletionTool[],
): FunctionDeclarationsTool[] => {
return tools.map((tool) => {
const { type, properties, required } = tool.function.parameters;
return {
functionDeclarations: [
{
name: tool.function.name,
description: tool.function.description,
parameters: {
type: type.toUpperCase() as FunctionDeclarationSchemaType,
properties: Object.fromEntries(
Object.entries(properties).map(([key, value]) => {
const prop = value as { type: string; description?: string };
return [
key,
{
type: prop.type.toUpperCase() as FunctionDeclarationSchemaType,
description: prop.description,
},
];
}),
),
required: required as string[],
},
},
],
};
});
};
const geminiTools = convertToolsToGemini(openAiTools);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment