Do you have an OpenAPI file or URL and want to use it in your Assistants API or OpenAI Function Calling? Look no further.
This is a quick and dirty parser for OpenAPI spec to OpenAI Functions. It currently does not resolve $ref
pointers.
pnpm add openapi-to-functions
import { convertRawOpenAPISpecToOpenAIFunctions } from 'openapi-to-functions';
const functionsFromUrl = convertRawOpenAPISpecToOpenAIFunctions('https://url.com/openapi.yml');
// or
const functionsFromSpec = convertRawOpenAPISpecToOpenAIFunctions(openApiSpecString);
Input:
openapi: 3.1.0
info:
title: Shop API
version: 1.0.0
servers:
- url: 'https://shop.com/api/v1'
paths:
/order:
get:
summary: Retrieve an order by the provided order name
parameters:
- in: query
name: orderName
required: true
schema:
type: string
description: Order name
outputs:
[
{
name: 'get_order',
description: 'Retrieve an order by the provided order name',
parameters: {
type: 'object',
properties: {
orderName: {
type: 'string',
description: 'Order name',
location: 'query',
},
},
required: ['orderName'],
},
},
];
Then you can manipulate it further to get to a list of tools:
const tools = functionsFromSpec.map((func) => ({
type: 'function',
function: func,
}));
and use in OpenAI call:
const response = await openai.chat.completions.create({
model: 'gpt-4o',
messages: messages,
tools: [
{
type: 'function',
function: {
name: 'get_order',
description: 'Retrieve an order by the provided order name',
parameters: {
type: 'object',
properties: {
orderName: {
type: 'string',
description: 'Order name',
location: 'query',
},
},
required: ['orderName'],
},
},
},
],
tool_choice: 'auto',
});