Skip to main content

Convert OpenAPI specifications into native, production-grade LangChain tools.

Project description

langchain-openapi

langchain-openapi logo

Convert OpenAPI v3.0 & v3.1 specifications into native, production-grade LangChain tools.

CI Status PyPI Version Documentation Python 3.11+ Code Style: Ruff Checked with MyPy License: MIT


langchain_openapi is a modern Python library designed to seamlessly convert OpenAPI v3.0 and v3.1 specifications into native, type-safe LangChain tools for AI agents and LLM applications.

No python code generation is required—tools are generated dynamically at runtime with strict Pydantic input schemas and production-ready middleware.


Features

  • Zero-Code Tool Generation: Runtime conversion of OpenAPI specs (YAML/JSON) into LangChain StructuredTools.
  • 🔒 Pluggable Authentication: Built-in support for Bearer Tokens, API Key Headers, Query Parameters, Basic Auth, and custom request providers.
  • 🛡️ Production Middleware: Composable middleware architecture for Retries (exponential backoff), Rate Limiting (token-bucket), Caching (TTL), Pagination aggregation, and Sanitized Logging.
  • 🎯 Type-Safe Validation: Dynamically generated Pydantic input schemas ensure LLM arguments adhere strictly to specification types before network transport.
  • 🌐 Async Engine: Non-blocking asynchronous network transport powered by httpx.AsyncClient.

Supported Specifications

  • Swagger 2.0 (Automatically normalized to OpenAPI 3.0)
  • OpenAPI 3.0.x (JSON and YAML)
  • OpenAPI 3.1.x (JSON and YAML)

Architecture Pipeline

          Swagger 2.0 / OpenAPI 3.x
                     │
                     ▼
            Swagger Normalizer
                     │
                     ▼
          Normalized OpenAPI Model
                     │
                     ▼
              Existing Parser
                     │
                     ▼
           Internal Operation Models
                     │
                     ▼
            Schema Converter
                     │
                     ▼
              HTTP Executor
                     │
                     ▼
          LangChain StructuredTools

Quick Start

Installation

uv add langchain-openapi-tools
# or
pip install langchain-openapi-tools

Basic Usage

from langchain_openapi import OpenAPIToolkit

# Load spec from remote URL or local file
toolkit = OpenAPIToolkit.from_url("https://api.crossref.org/swagger-docs")

# Extract generated tools
tools = toolkit.get_tools()

print(f"Generated {len(tools)} tools:")
for tool in tools[:3]:
    print(f"- {tool.name}: {tool.description}")

Agent Integration

import asyncio
from langchain_openapi import OpenAPIToolkit


async def main():
    toolkit = OpenAPIToolkit.from_url("https://api.crossref.org/swagger-docs")
    search_tool = toolkit.get_tool("search_works")

    if search_tool:
        result = await search_tool.ainvoke({"query": "LangGraph"})
        print("Search Result:", result)


if __name__ == "__main__":
    asyncio.run(main())

Architecture

OpenAPI Specification (JSON / YAML)
             │
             ▼
      OpenAPILoader
             │
             ▼
       OpenAPIParser ───► ReferenceResolver ($ref)
             │
             ▼
     SchemaConverter ───► Dynamic Pydantic Input Models
             │
             ▼
   LangChainToolFactory ───► LangChain StructuredTool
             │
             ▼
     AsyncHTTPExecutor
             │
             ▼
    Middleware Pipeline (Retry, RateLimit, Cache, Pagination, Logging)
             │
             ▼
    Request Providers (Authentication & Custom Headers)
             │
             ▼
        httpx.AsyncClient (HTTP Target API)

Authentication Methods

langchain_openapi supports pluggable authentication via RequestProvider classes:

from langchain_openapi import (
    APIKeyHeaderProvider,
    BasicAuthProvider,
    BearerAuthProvider,
    CompositeProvider,
    OpenAPIToolkit,
)

# 1. Bearer Token Auth
toolkit_bearer = OpenAPIToolkit.from_url(
    "https://api.github.com/openapi",
    provider=BearerAuthProvider(token="secret_token"),
)

# 2. API Key Header Auth
toolkit_apikey = OpenAPIToolkit.from_url(
    "https://api.example.com/spec.json",
    provider=APIKeyHeaderProvider(key="secret_key", header="X-API-Key"),
)

# 3. Composite Provider (Multiple authentication schemes)
composite = CompositeProvider(
    [
        BearerAuthProvider(token="secret_jwt"),
        APIKeyHeaderProvider(key="secret_key", header="X-API-Key"),
    ]
)

toolkit_composite = OpenAPIToolkit.from_url(
    "https://api.example.com/spec.json",
    provider=composite,
)

Production Middleware & Resilience

Intercept requests and responses to apply cross-cutting resilience concerns:

from langchain_openapi import (
    CacheMiddleware,
    LoggingMiddleware,
    OpenAPIToolkit,
    PaginationMiddleware,
    RateLimitMiddleware,
    RetryMiddleware,
)

toolkit = OpenAPIToolkit.from_url(
    "https://api.example.com/openapi.json",
    middleware=[
        LoggingMiddleware(),
        RetryMiddleware(retries=3, backoff="exponential"),
        RateLimitMiddleware(requests_per_second=10.0),
        CacheMiddleware(ttl=300.0),
        PaginationMiddleware(max_pages=10),
    ],
)

Example Applications

Runnable example projects are located in examples/:


Roadmap

  • Milestone 1: Project Foundation & Tooling
  • Milestone 2: OpenAPI Specification Loader
  • Milestone 3: OpenAPI Parser & Data Models
  • Milestone 4: Dynamic Pydantic Schema Converter
  • Milestone 5: Async HTTP Executor Engine
  • Milestone 6: LangChain Tool Factory & Toolkit
  • Milestone 7: Authentication & Request Providers
  • Milestone 8: Production Middleware & Resilience Pipeline
  • Milestone 9: Open Source Readiness & Documentation
  • Milestone 10: v1.0 Release Candidate & PyPI Publish

Development & Contributing

Please read CONTRIBUTING.md for details on code style, testing, and pull request procedures.

# Sync virtual environment
uv sync --extra dev

# Run all checks (format, lint, mypy, pytest, docs build, benchmark)
make all

License

This project is licensed under the MIT License - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

langchain_openapi_tools-1.0.2.tar.gz (872.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

langchain_openapi_tools-1.0.2-py3-none-any.whl (32.0 kB view details)

Uploaded Python 3

File details

Details for the file langchain_openapi_tools-1.0.2.tar.gz.

File metadata

  • Download URL: langchain_openapi_tools-1.0.2.tar.gz
  • Upload date:
  • Size: 872.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/7.0.0 CPython/3.13.14

File hashes

Hashes for langchain_openapi_tools-1.0.2.tar.gz
Algorithm Hash digest
SHA256 8ffa6a2719d64cd6145ec149acd5bfaa369458e9c94e762aefa52433f0ef10fa
MD5 bd5816cde091e4eec611fc0bba85d966
BLAKE2b-256 062413586a1cea32eb2095b90505f522f2c0abc98ce565ef7cc7d957aafc107b

See more details on using hashes here.

Provenance

The following attestation bundles were made for langchain_openapi_tools-1.0.2.tar.gz:

Publisher: publish.yml on abhaywani114/langchain-openapi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file langchain_openapi_tools-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for langchain_openapi_tools-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 9c51c246637e3442fa2e9b0f34a493fa11b6035a382a422b27b7626e6468ea80
MD5 e2af57aece624dfb50d8956553d66f35
BLAKE2b-256 202547955425988054aec12300cc0981d4ea9292b82c653bb887d9a2648b91ff

See more details on using hashes here.

Provenance

The following attestation bundles were made for langchain_openapi_tools-1.0.2-py3-none-any.whl:

Publisher: publish.yml on abhaywani114/langchain-openapi

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page