* OpenAPI tool execution section per Issue #1227 - 11 Rendered view PRs> #1245 #1246 Original Issue> #1227 --- - Updated the execution section of the OpenAPI tool and improved language. - Did minor edits to format and headers * Update openapi-tools.md
5.1 KiB
Integrate REST APIs with OpenAPI
ADK simplifies interacting with external REST APIs by automatically generating callable tools directly from an OpenAPI Specification (v3.x). This eliminates the need to manually define individual function tools for each API endpoint.
!!! tip "Core Benefit"
Use OpenAPIToolset to instantly create agent tools (RestApiTool) from your existing API documentation (OpenAPI spec), enabling agents to seamlessly call your web services.
Key components
OpenAPIToolset: This is the primary class you'll use. You initialize it with your OpenAPI specification, and it handles the parsing and generation of tools.RestApiTool: This class represents a single, callable API operation (likeGET /pets/{petId}orPOST /pets).OpenAPIToolsetcreates oneRestApiToolinstance for each operation defined in your spec.
How it works
The process involves these main steps when you use OpenAPIToolset:
-
Initialization & Parsing:
- You provide the OpenAPI specification to
OpenAPIToolseteither as a Python dictionary, a JSON string, or a YAML string. - The toolset internally parses the spec, resolving any internal references (
$ref) to understand the complete API structure.
- You provide the OpenAPI specification to
-
Operation Discovery:
- It identifies all valid API operations (e.g.,
GET,POST,PUT,DELETE) defined within thepathsobject of your specification.
- It identifies all valid API operations (e.g.,
-
Tool Generation:
- For each discovered operation,
OpenAPIToolsetautomatically creates a correspondingRestApiToolinstance. - Tool Name: Derived from the
operationIdin the spec (converted tosnake_case, max 60 chars). IfoperationIdis missing, a name is generated from the method and path. - Tool Description: Uses the
summaryordescriptionfrom the operation for the LLM. - API Details: Stores the required HTTP method, path, server base URL, parameters (path, query, header, cookie), and request body schema internally.
- For each discovered operation,
-
RestApiToolFunctionality: Each generatedRestApiTool:- Schema Generation: Dynamically creates a
FunctionDeclarationbased on the operation's parameters and request body. This schema tells the LLM how to call the tool (what arguments are expected). - Execution: When the LLM calls the tool, the tool constructs the HTTP
request, including the URL, headers, query parameters, and body, using the
LLM's arguments and the OpenAPI specification. The tool handles
authentication if configured, and executes the API call asynchronously using the
httpxlibrary. - Response Handling: Returns the API response (typically JSON) back to the agent flow.
- Schema Generation: Dynamically creates a
-
Authentication: You can configure global authentication (like API keys or OAuth - see Authentication for details) when initializing
OpenAPIToolset. This authentication configuration is automatically applied to all generatedRestApiToolinstances.
Usage workflow
Follow these steps to integrate an OpenAPI spec into your agent:
-
Obtain Spec: Get your OpenAPI specification document (e.g., load from a
.jsonor.yamlfile, fetch from a URL). -
Instantiate Toolset: Create an
OpenAPIToolsetinstance, passing the spec content and type (spec_str/spec_dict,spec_str_type). Provide authentication details (auth_scheme,auth_credential) if required by the API.from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset # Example with a JSON string openapi_spec_json = '...' # Your OpenAPI JSON string toolset = OpenAPIToolset(spec_str=openapi_spec_json, spec_str_type="json") # Example with a dictionary # openapi_spec_dict = {...} # Your OpenAPI spec as a dict # toolset = OpenAPIToolset(spec_dict=openapi_spec_dict) -
Add to Agent: Include the retrieved tools in your
LlmAgent'stoolslist.from google.adk.agents import LlmAgent my_agent = LlmAgent( name="api_interacting_agent", model="gemini-flash-latest", # Or your preferred model tools=[toolset], # Pass the toolset # ... other agent config ... ) -
Instruct agent: Update your agent's instructions to inform it about the new API capabilities and the names of the tools it can use (e.g.,
list_pets,create_pet). The tool descriptions generated from the spec will also help the LLM. -
Run agent: Execute your agent using the
Runner. When the LLM determines it needs to call one of the APIs, it will generate a function call targeting the appropriateRestApiTool, which will then handle the HTTP request automatically.
See it in action
This example demonstrates generating tools from a simple Pet Store OpenAPI spec (using httpbin.org for mock responses) and interacting with them via an agent.
???+ "Code: Pet Store API"
```python title="openapi_example.py"
--8<-- "examples/python/snippets/tools/openapi_tool.py"
```