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 and Swagger 2.0 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, v3.1, and Swagger 2.0 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, prompt optimization options, and production-ready middleware.


Installation & Importing

Install the PyPI package:

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

Import in Python:

from langchain_openapi_tools import OpenAPIToolkit, OpenAPIToolkitConfig

Migration Note

# Old (deprecated, but still works for backward compatibility):
from langchain_openapi import OpenAPIToolkit

# New (recommended):
from langchain_openapi_tools import OpenAPIToolkit

Features

  • Zero-Code Tool Generation: Runtime conversion of OpenAPI specs (YAML/JSON) into LangChain StructuredTools.
  • 🚀 Swagger 2.0 & OpenAPI 3.x: Native normalization of legacy Swagger 2.0 and modern OpenAPI 3.0/3.1 specs.
  • 🗜️ Prompt Optimization & Filtering: Description modes (full, compact, minimal), description compression, overrides, callbacks, and operation/tag filtering to drastically reduce context window usage.
  • 🔒 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 via the built-in adapter layer)
  • OpenAPI 3.0.x (JSON and YAML)
  • OpenAPI 3.1.x (JSON and YAML, including union type arrays, oneOf / anyOf / allOf, and const)

Note: Swagger 2.0 is commonly referred to as OpenAPI 2.0.

Compatibility Matrix

Feature Swagger 2.0 OpenAPI 3.0 OpenAPI 3.1
Path / query / header / cookie params
$ref resolution (internal)
Base URL from host + basePath
Base URL from servers[]
Fallback base URL from spec source URL
application/json request bodies
application/x-www-form-urlencoded
multipart/form-data (incl. files)
text/* and application/xml
Vendor +json media types
oneOf / anyOf (as Python Union)
allOf merge into single model
nullable: true (3.0)
type: ["string", "null"] (3.1)
const
readOnly / writeOnly / deprecated
Security: Bearer / API key / Basic
Async execution (httpx.AsyncClient)

Not yet supported: discriminator-driven union routing, patternProperties, $dynamicRef / $dynamicAnchor, callbacks, links, webhooks, and XML request-body serialization from Python dicts.


Quick Start

from langchain_openapi_tools 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_tools import OpenAPIToolkit


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

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


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

Prompt Optimization & Tool Customization

Large OpenAPI specifications can generate extensive tool descriptions that exceed model context windows. langchain_openapi_tools provides full control over description generation and context footprint.

Configuration Object (OpenAPIToolkitConfig)

from langchain_openapi_tools import OpenAPIToolkit, OpenAPIToolkitConfig

config = OpenAPIToolkitConfig(
    description_mode="compact",
    compress_descriptions=True,
    include_tags=["Works"],
    tool_description_overrides={
        "get_works": "Search scholarly papers registered with Crossref."
    },
)

toolkit = OpenAPIToolkit.from_url(
    "https://api.crossref.org/swagger-docs", config=config
)

Description Modes (description_mode)

  • full (default): Complete summary, description, HTTP method, path, and schema parameter details.
  • compact: Summary and short parameter list without response schemas or redundant examples.
  • minimal: A single-sentence summary ideal for large specifications with dozens of tools.
toolkit = OpenAPIToolkit.from_url(url, description_mode="minimal")

Description Compression (compress_descriptions=True)

Removes duplicate text, redundant whitespace, and empty sections without altering tool semantics:

toolkit = OpenAPIToolkit.from_url(url, compress_descriptions=True)

Custom Overrides & Callbacks

Override descriptions for specific tools:

toolkit = OpenAPIToolkit.from_url(
    url, tool_description_overrides={"get_works": "Search scholarly papers."}
)

Or pass a custom builder callback:

def my_builder(operation):
    return f"Execute {operation.name} on path {operation.path}."


toolkit = OpenAPIToolkit.from_url(url, description_builder=my_builder)

Operation Filtering

Filter tools before they are created to reduce context window overhead:

# Filter by Tags
toolkit = OpenAPIToolkit.from_url(url, include_tags=["Works"], exclude_tags=["Admin"])

# Filter by Operations
toolkit = OpenAPIToolkit.from_url(
    url, include_operations=["get_works"], exclude_operations=["delete_work"]
)

Architecture Pipeline

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

Example:

from langchain_openapi_tools import OpenAPIToolkit
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model

toolkit = OpenAPIToolkit.from_url(
    "https://api.crossref.org/swagger-docs"
)

model = init_chat_model("openrouter:qwen/qwen3-32b:free")

agent = create_agent(
    model=model,
    tools=toolkit.get_tools(tags=["Works"]),
)

response = agent.invoke({
    "messages": "Find papers about Kashmir"
})

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-2.0.0.tar.gz (907.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-2.0.0-py3-none-any.whl (41.0 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: langchain_openapi_tools-2.0.0.tar.gz
  • Upload date:
  • Size: 907.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-2.0.0.tar.gz
Algorithm Hash digest
SHA256 1f109560184f6548e8502fab92a00332a40fe3f14e07685b89b654c8ef97741f
MD5 0d01690c8b87c7bdacab594d2a8f56d2
BLAKE2b-256 6451bfba00db79761a3a0e1d6088a6dc90737cc01ce04156b68f16d43bdbef3c

See more details on using hashes here.

Provenance

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

File metadata

File hashes

Hashes for langchain_openapi_tools-2.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8076ba7cd623c95a192c756a74e98b8cc64f2fb1256c396556559d26866994ef
MD5 67c8a17ec802094abdcab16d285e9fbb
BLAKE2b-256 e59fd3cffdafe52496ccfcfc90794181ad0685b49ee64c978a8f841f56912708

See more details on using hashes here.

Provenance

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