openapi-tool-aisdk
v1.0.0
Published
A generic OpenAPI tool for Vercel AI SDK that can execute API requests based on any OpenAPI 3.0 specification
Maintainers
Readme
openapi-tool-aisdk
A generic OpenAPI tool for Vercel AI SDK that enables AI agents to execute real API requests based on any OpenAPI 3.0 specification.
🎯 What This Package Does
This package provides two simple functions and one React view component that transform any OpenAPI specification into a fully functional AI agent tool. Instead of manually writing custom tools for each API, you can:
- Load any OpenAPI spec
- Call two functions
- Have a fully functional API-aware AI agent
Before this package:
- ❌ Write custom tools for each API endpoint
- ❌ Manually maintain API documentation in prompts
- ❌ Update code every time the API changes
With this package:
- ✅ Drop in any OpenAPI spec
- ✅ Get instant AI-powered API integration
- ✅ Auto-update when specs change
🚀 Features
- ✅ Generic & Reusable - Works with any OpenAPI 3.0 specification
- ✅ Vercel AI SDK Compatible - Built specifically for the Vercel AI SDK
- ✅ Automatic Base URL Extraction - Extracts base URLs from OpenAPI specs
- ✅ Authentication Support - Handles API keys and custom headers
- ✅ Type-Safe - Full TypeScript support with Zod validation
- ✅ Easy Integration - Two simple functions to get started
- ✅ Zero Runtime Dependencies - Peer dependencies only (ai, zod)
📦 Installation
npm install openapi-tool-aisdk ai zod🔑 Environment Variables
Before running your application, set up the required environment variables:
Required: OpenAI API Key
# .env.local or .env
OPENAI_API_KEY=your_openai_api_key_hereYou can get your OpenAI API key from platform.openai.com/api-keys.
Optional: API Keys for Your OpenAPI Endpoints
If the APIs defined in your OpenAPI specification require authentication, you may need additional environment variables:
# Example: Weather API
WEATHER_API_KEY=your_weather_api_key
# Example: Custom API
CUSTOM_API_KEY=your_custom_api_key
X_API_SECRET=your_api_secretThese keys will be passed through the headers parameter when the AI agent calls the OpenAPI tool. Make sure to configure your system prompt or agent to use these environment variables when making authenticated requests.
🎯 Quick Start
import { createOpenAPITool, generateSystemPrompt } from 'openapi-tool-aisdk';
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
import fs from 'fs';
// 1. Load your OpenAPI specification
const openapiSpec = fs.readFileSync('./openapi.yml', 'utf-8');
// 2. Generate system prompt with the spec
const systemPrompt = generateSystemPrompt(openapiSpec);
// 3. Create the OpenAPI tool
const openapiTool = createOpenAPITool();
// 4. Use with Vercel AI SDK
const result = await generateText({
model: openai('gpt-5-mini'),
system: systemPrompt,
prompt: 'Get weather data for Tokyo',
tools: {
openapi: openapiTool,
},
});Tailwind v4 note (for OpenAPIView)
If you use the React view component from this package, add a Tailwind v4 @source so Tailwind scans the package files (since node_modules is excluded by default):
/* app/globals.css */
@import "tailwindcss";
@source "../node_modules/openapi-tool-aisdk/dist/**/*.{js,jsx,ts,tsx}";After adding this, restart your dev server so Tailwind regenerates styles.
📖 API Reference
generateSystemPrompt(openapiSpec: string): string
Generates a comprehensive system prompt that includes:
- The OpenAPI specification in a structured format
- Detailed instructions on how to use the OpenAPI tool
- Step-by-step guide for extracting base URLs, endpoints, and parameters
- Authentication handling guidelines
- Best practices for API interactions
Parameters:
openapiSpec(string): Your OpenAPI specification as a string (YAML or JSON format)
Returns:
- (string): A formatted system prompt ready to be used with your AI agent
Example:
import fs from 'fs';
const openapiSpec = fs.readFileSync('./my-api-spec.yml', 'utf-8');
const systemPrompt = generateSystemPrompt(openapiSpec);
// Use in your agent's system context
const agent = new Agent({
model: openai('gpt-5-mini'),
system: `You are a helpful assistant. ${systemPrompt}`,
tools: { openapi: createOpenAPITool() }
});createOpenAPITool()
Creates a generic OpenAPI execution tool compatible with Vercel AI SDK.
Returns:
- A Vercel AI SDK tool that accepts:
baseUrl(string, required): Base URL from OpenAPI specendpoint(string, required): API endpoint pathmethod(enum, required): HTTP method (GET, POST, PUT, DELETE, PATCH)queryParams(object, optional): Query parametersbody(object, optional): Request body for POST/PUT/PATCHheaders(object, optional): Custom headers for authentication
Example:
const openapiTool = createOpenAPITool();
// The AI agent will call this tool like:
// {
// baseUrl: "https://api.example.com",
// endpoint: "/v1/users",
// method: "GET",
// queryParams: { limit: 10 },
// headers: { "Authorization": "Bearer token" }
// }OpenAPIView
OpenAPIView is a small React component that renders the UI for the tool-openapi parts emitted by Vercel AI SDK agents. Use it to quickly visualize input, loading states, errors, and success responses without writing your own component.
import { OpenAPIView } from 'openapi-tool-aisdk';
// Inside your message renderer
message.parts.map((part, index) => {
switch (part.type) {
case 'tool-openapi': {
return <OpenAPIView invocation={part} key={index} />;
}
}
});States handled:
- input-streaming
- input-available
- output-available (loading | error | success)
- output-error
💡 Complete Examples
Example 1: Simple API Call
import { createOpenAPITool, generateSystemPrompt } from 'openapi-tool-aisdk';
import { openai } from '@ai-sdk/openai';
import { generateText } from 'ai';
import fs from 'fs';
const spec = fs.readFileSync('./weather-api.yml', 'utf-8');
const result = await generateText({
model: openai('gpt-5-mini'),
system: generateSystemPrompt(spec),
prompt: 'What is the weather in London?',
tools: { openapi: createOpenAPITool() },
});
console.log(result.text);Example 2: With Next.js API Route
// app/api/chat/route.ts
import { createOpenAPITool, generateSystemPrompt } from 'openapi-tool-aisdk';
import { openai } from '@ai-sdk/openai';
import { streamText } from 'ai';
import fs from 'fs';
import path from 'path';
const openapiSpec = fs.readFileSync(
path.join(process.cwd(), 'public', 'openapi.yml'),
'utf-8'
);
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({
model: openai('gpt-5-mini'),
system: generateSystemPrompt(openapiSpec),
messages,
tools: {
openapi: createOpenAPITool(),
},
});
return result.toDataStreamResponse();
}Example 3: With Vercel AI SDK Agents
import { Agent } from 'ai';
import { createOpenAPITool, generateSystemPrompt } from 'openapi-tool-aisdk';
const openapiSpec = fs.readFileSync('./openapi.yml', 'utf-8');
const agent = new Agent({
model: openai('gpt-5-mini'),
system: generateSystemPrompt(openapiSpec),
tools: {
openapi: createOpenAPITool(),
},
});
const response = await agent.respond({
messages: [{ role: 'user', content: 'Get user data' }],
});Example 4: Multiple APIs
const weatherSpec = fs.readFileSync('./weather-api.yml', 'utf-8');
const paymentSpec = fs.readFileSync('./payment-api.yml', 'utf-8');
const systemPrompt = `
${generateSystemPrompt(weatherSpec)}
Additionally, you also have access to a payment API:
${generateSystemPrompt(paymentSpec)}
`;
const result = await generateText({
model: openai('gpt-5-mini'),
system: systemPrompt,
prompt: 'Get weather and process payment',
tools: { openapi: createOpenAPITool() },
});🔧 How It Works
System Prompt Generation: The
generateSystemPrompt()function embeds your OpenAPI spec into a structured prompt that teaches the AI how to read and use the specification.Dynamic API Calls: The AI agent analyzes user requests, extracts relevant information from the OpenAPI spec, and calls the
openapitool with the correct parameters.Tool Execution: The
createOpenAPITool()constructs the full URL, handles authentication, executes the fetch request, and returns structured results.
📋 OpenAPI Spec Requirements
Your OpenAPI specification should include:
serverssection (global or per-endpoint) with base URLspathswith endpoints and HTTP methodsparametersfor each endpoint (with required/optional flags)components.securitySchemesfor authentication (if needed)
Example:
openapi: 3.0.0
info:
title: My API
servers:
- url: https://api.example.com
paths:
/users:
get:
parameters:
- name: limit
in: query
schema:
type: integer🎨 Authentication Support
The tool supports authentication via headers. The AI agent will extract auth requirements from your OpenAPI spec and include the necessary headers:
// The AI agent calls the tool with appropriate headers:
{
baseUrl: "https://api.example.com",
endpoint: "/protected",
method: "GET",
headers: {
"Authorization": "Bearer user-token",
"X-API-Key": "api-key"
}
}Passing Environment Variables to Headers
You can instruct the AI agent to use environment variables for authentication by including this in your system prompt:
const systemPrompt = `
${generateSystemPrompt(openapiSpec)}
When making API requests that require authentication, use the following credentials:
- Weather API: Use the API key from environment variable WEATHER_API_KEY in the headers as {"X-API-Key": "WEATHER_API_KEY"}
- Protected endpoints: Use {"Authorization": "Bearer YOUR_TOKEN"}
`;Or handle it programmatically by accessing environment variables in your route handler:
// app/api/chat/route.ts
export async function POST(req: Request) {
const result = streamText({
model: openai('gpt-5-mini'),
system: generateSystemPrompt(openapiSpec) + `
Available API Keys:
- WEATHER_API_KEY: ${process.env.WEATHER_API_KEY}
`,
messages,
tools: { openapi: createOpenAPITool() },
});
return result.toDataStreamResponse();
}🛠️ Development
# Clone the repository
git clone https://github.com/yourusername/openapi-tool-aisdk.git
cd openapi-tool-aisdk
# Install dependencies
npm install
# Build the package
npm run build
# Run tests
node test-example.js📝 TypeScript Support
This package is written in TypeScript and includes full type definitions.
import type { Tool } from 'ai';
const openapiTool: Tool = createOpenAPITool();📦 Package Details
- Size: ~15KB (minified)
- Dependencies: None (peer dependencies: ai, zod)
- TypeScript: Full support with type definitions
- Node: 18+ required
- License: MIT
🚀 Publishing to NPM
To publish this package to npm:
# 1. Login to NPM
npm login
# 2. Verify package contents
npm pack --dry-run
# 3. Publish
npm publish
# For subsequent updates
npm version patch # 1.0.0 -> 1.0.1
npm publish🤝 Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
MIT
🙏 Acknowledgments
- Built for Vercel AI SDK
- Inspired by the need for generic, reusable AI tools
📬 Support
For issues and questions, please open an issue on GitHub.
🔗 Links
Built with ❤️ for the Vercel AI SDK community
