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

  • OpenAPI 3.0.x (JSON and YAML)
  • OpenAPI 3.1.x (JSON and YAML)
  • Swagger 2.0 (Explicitly rejected with descriptive error)

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.0.tar.gz (867.5 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.0-py3-none-any.whl (28.7 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: langchain_openapi_tools-1.0.0.tar.gz
  • Upload date:
  • Size: 867.5 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.0.tar.gz
Algorithm Hash digest
SHA256 faaf4ab8f1ff6e122c4cc8b4a0f22b7c9e5e4f075dbf927ff2f614e17c615707
MD5 17e4cd5a9248e697b75af393a3293387
BLAKE2b-256 cff5082a77dbf72a917533bcfce7a68a1ce66d0ebd879354370c4181cbe24928

See more details on using hashes here.

Provenance

The following attestation bundles were made for langchain_openapi_tools-1.0.0.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.0-py3-none-any.whl.

File metadata

File hashes

Hashes for langchain_openapi_tools-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 a9ba3cf7e9df91f194f2e0ec53bef0d99d9f6b86cf72291a140fd031fcad5acc
MD5 fea2e0feaced3bb6ce783a379b31dbe0
BLAKE2b-256 e078b516dfb4a58263e719c924917e4d9c066dbe448a4a45562fb0344ded6876

See more details on using hashes here.

Provenance

The following attestation bundles were made for langchain_openapi_tools-1.0.0-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