npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

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

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.

npm version License: MIT

🎯 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:

  1. Load any OpenAPI spec
  2. Call two functions
  3. 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_here

You 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_secret

These 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 spec
    • endpoint (string, required): API endpoint path
    • method (enum, required): HTTP method (GET, POST, PUT, DELETE, PATCH)
    • queryParams (object, optional): Query parameters
    • body (object, optional): Request body for POST/PUT/PATCH
    • headers (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

  1. 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.

  2. Dynamic API Calls: The AI agent analyzes user requests, extracts relevant information from the OpenAPI spec, and calls the openapi tool with the correct parameters.

  3. 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:

  • servers section (global or per-endpoint) with base URLs
  • paths with endpoints and HTTP methods
  • parameters for each endpoint (with required/optional flags)
  • components.securitySchemes for 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.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. 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