OpenAPI Tool Usage Guide¶
Changelog
- API updates in version: 0.4.12
- New in version: 0.4.0
Introduction¶
This guide explains how to integrate OpenAPI with ToolRegistry, allowing you to register and call tools based on an OpenAPI specification. The guide provides examples for both synchronous and asynchronous registration methods, using a math service as a demonstration.
API Changes in version 0.4.12¶
The register() method with source="openapi" now accepts the following keyword arguments:
client_config: atoolregistry.integrations.openapi.HttpClientConfigobject that configures the HTTP client used to interact with the API. You can configure the headers, authorization, timeout, and other settings. Allowing greater flexibility than the previous version.openapi_spec: The OpenAPI specification asDict[str, Any], loaded with a function likeload_openapi_specorload_openapi_spec_async. These functions accept a file path or a URL to the OpenAPI specification or a URL to the base api and return the parsed OpenAPI specification as a dictionary.
You must now explicitly pass both the client_config (as the first positional argument) and openapi_spec (as a keyword argument).
OpenAPI Tool Registration¶
Synchronous Registration¶
You can register OpenAPI tools synchronously using the register() method with source="openapi". For example:
import os
from toolregistry.integrations.openapi import HttpClientConfig, load_openapi_spec
from toolregistry import ToolRegistry
PORT = os.getenv("PORT", 8000) # Default port is 8000; can be overridden by an environment variable
registry = ToolRegistry()
client_config = HttpClientConfig(base_url=f"http://localhost:{PORT}", allow_private_hosts=True)
openapi_spec = load_openapi_spec(f"http://localhost:{PORT}", allow_private_hosts=True) # Auto-discovery of OpenAPI spec
# Synchronously register OpenAPI tools
registry.register(client_config, source="openapi", openapi_spec=openapi_spec)
print(registry) # Output: A ToolRegistry object with the registered OpenAPI tools
You should see a schema printed as follow. Here, we only display the first entry for clarity.
[
{
"type": "function",
"function": {
"name": "add_get",
"description": "Calculate a + b and return the result.\n\nArgs:\n a (float): The first operand.\n b (float): The second operand.\n\nReturns:\n dict: A dictionary containing the key \"result\" with the sum of a and b.",
"parameters": {
"type": "object",
"properties": {
"a": {
"type": "number",
"description": ""
},
"b": {
"type": "number",
"description": ""
}
},
"required": ["a", "b"]
},
"is_async": false
}
}
]
Asynchronous Registration¶
In an asynchronous environment, use the register_async() method with source="openapi" to register tools:
import asyncio
import os
from toolregistry.integrations.openapi import HttpClientConfig, load_openapi_spec_async
from toolregistry import ToolRegistry
PORT = os.getenv("PORT", 8000)
registry = ToolRegistry()
client_config = HttpClientConfig(base_url=f"http://localhost:{PORT}", allow_private_hosts=True)
async def async_register():
openapi_spec = await load_openapi_spec_async(f"http://localhost:{PORT}", allow_private_hosts=True) # Auto-discovery of OpenAPI spec
await registry.register_async(client_config, source="openapi", openapi_spec=openapi_spec)
print(registry) # Optionally, inspect the registry for registered tools
asyncio.run(async_register())
HTTP Client Configuration¶
In some cases, OpenAPI services may require specific configurations such as custom headers, timeouts, or SSL certificates. You can tune these settings with the HttpClientConfig class. Here's an example of authorization bearer tokens in header.
from toolregistry.integrations.openapi import HttpClientConfig
OPENAPI_SERVER_URL = os.getenv("OPENAPI_SERVER_URL", "http://localhost:8000")
OPENAPI_BEARER_TOKENS = os.getenv("OPENAPI_BEARER_TOKENS", "your-api-token")
client_config = HttpClientConfig(
base_url=OPENAPI_SERVER_URL,
headers={"Authorization": f"Bearer {OPENAPI_BEARER_TOKENS}"}, # this sets the Bearer token
allow_private_hosts=True, # the example default is a loopback address (#370)
)
If nothing special is needed, you can create HttpClientConfig with just the base_url:
from toolregistry.integrations.openapi import HttpClientConfig
client_config = HttpClientConfig(
base_url=OPENAPI_SERVER_URL,
allow_private_hosts=True, # the example default is a loopback address (#370)
)
Load OpenAPI Specification¶
When using the functions load_openapi_spec or load_openapi_spec_async, the following behaviors apply:
- Base URL provided: If you specify only a base URL (e.g.,
http://localhost:8000), the loader will attempt "best effort" auto-discovery to locate the OpenAPI specification file. It checks endpoints such ashttp://<base_url>/openapi.json,http://<base_url>/swagger.json, etc. If auto-discovery fails, ensure the base URL is accurate and the specification is accessible. - File path provided: If you provide a file path (e.g.,
./openapi_spec.json), the function will load the OpenAPI specification directly from the file. A local path or afile://URI is refused unless you passallow_local_files=True; the default isFalse, because a location supplied by someone else could otherwise read an arbitrary local file. Enable the flag only when the path comes from a trusted local source. Unlike simple direct load, the functionality includes unwinding$refblocks commonly found in OpenAPI specifications. This ensures that any schema references are fully resolved within the returned dictionary. - Size and nesting budgets: the loader streams the document and reads at most 10 MiB by default (
DEFAULT_MAX_SPEC_BYTES), and rejects a document nested deeper than 100 containers (DEFAULT_MAX_SPEC_DEPTH). Passmax_bytes=ormax_depth=to change either budget. A document over the byte budget raisesSpecTooLargeError; one over the depth budget raisesSpecTooDeepError; both are subclasses ofValueError. A declaredContent-Lengthover the budget is refused before the body is read, an unbounded stream is cut off at the limit, and auto-discovery probes read headers only. - Address policy: before any request, the host is resolved and refused when it is loopback, link-local, private, multicast or reserved, or when it does not resolve. Pass
allow_private_hosts=Truefor an API on the same machine or a private network. Redirects are refused by default (follow_redirects=False): the next hop cannot be checked against the policy, so a 3xx raisesValueErrorand the final URL must be used instead. The same rule covers spec loading and refresh; a tool call still follows redirects, because the vendored client cannot expose each hop for validation β see #399. - Tool response size: a tool call buffers its response, so
HttpClientConfigcaps it at 10 MiB by default (DEFAULT_MAX_TOOL_RESPONSE_BYTES, importable fromtoolregistry.utils). Passmax_response_size=to raise the cap, ormax_response_size=Noneto disable it; exceeding the cap raisesResponseTooLargeError, re-exported fromtoolregistry.errors.
from toolregistry.integrations.openapi import load_openapi_spec
openapi_spec = load_openapi_spec("./openapi_spec.json", allow_local_files=True) # Load from file
openapi_spec = load_openapi_spec("http://localhost:8000", allow_private_hosts=True) # auto-discovery with URL to service root
openapi_spec = load_openapi_spec("http://localhost:8000/openapi.json", allow_private_hosts=True) # load from specification URL
Persistent Connections¶
Changelog
New in version: 0.7.0
By default, OpenAPI integrations now use persistent HTTP connections β the HTTP client is reused across multiple tool calls, enabling connection pooling and reducing latency.
Context Manager Usage¶
Use ToolRegistry as a context manager to ensure HTTP clients are properly closed:
from toolregistry import ToolRegistry
from toolregistry.integrations.openapi import HttpClientConfig, load_openapi_spec
with ToolRegistry() as registry:
client_config = HttpClientConfig(base_url="http://localhost:8000", allow_private_hosts=True)
openapi_spec = load_openapi_spec("http://localhost:8000", allow_private_hosts=True)
registry.register(client_config, source="openapi", openapi_spec=openapi_spec)
result = registry["add_get"](1, 2)
# HTTP connections are automatically closed on exit
Explicit Cleanup¶
registry = ToolRegistry()
registry.register(client_config, source="openapi", openapi_spec=openapi_spec)
# ... use tools ...
registry.close() # Close all persistent HTTP connections
# Or in async code:
await registry.close_async()
Opting Out¶
To create a fresh HTTP connection per call (the old behavior), pass persistent=False:
Calling OpenAPI Tools¶
Once the OpenAPI tools are registered, they support both synchronous and asynchronous invocation methods.
Synchronous Calls¶
Tools can be invoked directly as Python callables, or you can retrieve them using the get_callable or get_tool methods:
# Direct access using subscript notation
add_func = registry["add_get"]
result = add_func(1, 2)
print(result) # Expected output: 3.0
# Retrieve the callable with get_callable and call it
add_func = registry.get_callable("add_get")
result = add_func(3, 4)
print(result) # Expected output: 7.0
# Retrieve the tool object with get_tool and invoke its run method
add_tool = registry.get_tool("add_get")
result = add_tool.run({"a": 5, "b": 6})
print(result) # Expected output: 11.0
Asynchronous Calls¶
For asynchronous calls, you can use the callable's __call__ or the tool object's arun methods:
import asyncio
async def call_async_add_func():
# Direct subscript access for asynchronous invocation
add_func = registry["add_get"]
result = await add_func(7, 7)
print(result) # Expected output: 14.0
asyncio.run(call_async_add_func())
async def call_async_add_tool():
# Retrieve the tool object for asynchronous invocation
add_tool = registry.get_tool("add_get")
result = await add_tool.arun({"a": 9, "b": 10})
print(result) # Expected output: 19.0
asyncio.run(call_async_add_tool())
Integrating OpenAPI with the OpenAI Client¶
You can integrate OpenAPI tool registration into an OpenAI-compatible API workflow. The updated example incorporates the new APIs:
from dotenv import load_dotenv
from toolregistry.integrations.openapi import HttpClientConfig, load_openapi_spec
from toolregistry import ToolRegistry
from openai import OpenAI
import os
# Load environment variables from .env file
load_dotenv()
PORT = os.getenv("PORT", 8000) # default port 8000, change via environment variable
registry = ToolRegistry()
client_config = HttpClientConfig(base_url=f"http://localhost:{PORT}", allow_private_hosts=True)
openapi_spec = load_openapi_spec(f"http://localhost:{PORT}", allow_private_hosts=True)
registry.register(client_config, source="openapi", openapi_spec=openapi_spec)
# Set up OpenAI client
client = OpenAI(
api_key=os.getenv("API_KEY", "your-api-key"),
base_url=os.getenv("BASE_URL", "https://api.deepseek.com/"),
)
messages = [
{
"role": "user",
"content": "I have 15 chestnuts. Joe ate 3. How many chestnuts do I have left?",
}
]
# Make the chat completion request
response = client.chat.completions.create(
model="deepseek-v3",
messages=messages,
tools=registry.get_schemas(),
tool_choice="auto",
)
# Handle tool calls using ToolRegistry
if response.choices[0].message.tool_calls:
tool_calls = response.choices[0].message.tool_calls
print(tool_calls)
# Execute tool calls
tool_responses = registry.execute_tool_calls(tool_calls)
print(tool_responses)
# Construct assistant messages with results
assistant_tool_messages = registry.build_tool_call_messages(
tool_calls, tool_responses
)
print(assistant_tool_messages)
# Send the results back to the model
messages.extend(assistant_tool_messages)
second_response = client.chat.completions.create(
model="deepseek-v3", messages=messages
)
# Print final response
print(second_response.choices[0].message.content)
Notes¶
- OpenAPI tool registration supports both synchronous and asynchronous methods. Once tools are registered, they can be invoked as simple Python functions or as tool objects.
- During invocation, parameters are automatically converted based on the tool definition. For example, the
add_gettool expects numeric inputs and returns a numeric result. - The integration with the OpenAI client allows you to seamlessly incorporate tool execution into your chat workflows.
Follow the examples above to efficiently integrate and utilize OpenAPI tools with ToolRegistry.