将 REST API 与 OpenAPI 集成在一起¶
ADK 通过从源代码自动生成可调用的工具,简化了与外部 REST API 的交互过程。 OpenAPI 规范(v3.x)这样一来,就无需为每个 API 端点手动定义单独的功能工具了。
核心优势(Core Benefit)
使用 OpenAPIToolset 用于立即创建代理工具(agent tools)。RestApiTool)这些信息可以直接从您现有的 API 文档(OpenAPI 规范)中获取,从而让代理程序能够无缝地调用您的 Web 服务。
关键组件¶
OpenAPIToolset这是您将使用的主要类。您需要使用自己的 OpenAPI 规范来初始化该类,该类负责工具的解析和生成工作。RestApiTool这个类表示一个单独的、可调用的 API 操作(例如……)GET /pets/{petId}或者POST /pets).OpenAPIToolset创建一个RestApiTool对于你在规范中定义的每个操作,系统都会创建一个相应的实例。
它是如何工作的?¶
当你使用该流程时,主要步骤包括以下内容: OpenAPIToolset:
-
初始化与解析:
- 您提供了 OpenAPI 规范(即接口的定义和详细信息),以便其他开发人员能够根据这些规范来开发相应的应用程序或服务。
OpenAPIToolset可以以 Python 字典、JSON 字符串或 YAML 字符串的形式提供数据。 - 该工具集会在内部解析相关规范(spec),并解决其中出现的所有内部引用(internal references)。
$ref)以了解完整的 API 结构。
- 您提供了 OpenAPI 规范(即接口的定义和详细信息),以便其他开发人员能够根据这些规范来开发相应的应用程序或服务。
-
Operation Discovery:
- 该系统能够识别所有有效的 API 操作(例如:
GET,POST,PUT,DELETE)在……中定义的paths您规范中的对象(Object of your specification)。
- 该系统能够识别所有有效的 API 操作(例如:
-
工具生成(Tool Generation):
- 对于每个被发现的操作,
OpenAPIToolset会自动创建相应的内容。RestApiTool`instance.` - 工具名称:源自……
operationId在规格说明中(已转换为……)snake_case(最多 60 个字符)。如果……operationId如果某个名称缺失,系统会从该方法(method)和路径(path)中生成一个默认名称。 - 工具描述:使用
summary或者description从该操作中获取大型语言模型(LLM)的相关数据。 - API 详情:在内部存储所需的 HTTP 方法、路径、服务器基础 URL、参数(路径、查询参数、请求头信息、Cookie),以及请求体的结构(即请求体的数据格式)。
- 对于每个被发现的操作,
-
RestApiTool功能(即产品或服务能够实现的具体操作或功能):每个生成的……RestApiTool:- 模式生成(Schema Generation):动态创建一个
FunctionDeclaration该方案根据操作的参数和请求体来决定如何使用相应的工具。它告诉大型语言模型(LLM)应该使用哪些参数来调用该工具。 - 执行(过程)当大型语言模型(LLM)调用该工具时,该工具会根据大型语言模型的参数以及 OpenAPI 规范来构建 HTTP 请求。请求内容包括 URL、请求头、查询参数以及请求体。如果配置了相应的认证机制,该工具会处理认证流程;随后,它会使用异步方式执行 API 调用。
httpx这个库的读写操作超时时间为 600 秒(可以通过配置进行调整)。httpx_client_factory).
- 模式生成(Schema Generation):动态创建一个
-
身份验证(Authentication)您可以配置全局身份验证机制(例如 API 密钥或 OAuth 等)。详情请参阅…… 身份验证(Authentication) (详情请参阅……) 在初始化时……
OpenAPIToolset这种身份验证配置会自动应用于所有生成的(资源/账户等)。RestApiToolinstances.
使用流程(Usage Workflow)¶
请按照以下步骤将 OpenAPI 规范集成到您的代理程序中:
- 获取规格信息:获取您的 OpenAPI 规范文档(例如,从某个来源加载该文档)。
.json或者.yaml(从文件中读取数据,或从 URL 中获取数据。) -
实例化工具集(Instantiate Toolset):创建一个
OpenAPIToolset实例,传递规范内容及类型。)spec_str/spec_dict,spec_str_type请提供身份验证信息(Authentication details)。auth_scheme,auth_credential)如果 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”:将某个项目或功能添加到代理(agent)中。这里的“agent”可以指代各种系统组件或应用程序中的代理进程(例如:网络代理、数据采集代理等)。:将检索到的工具包含到您的……中。
LlmAgent'stoolslist. -
指示代理程序执行特定操作。:请更新您的代理程序的指令,以便让它了解新的 API 功能以及它可以使用的工具的名称(例如:
list_pets,create_pet根据规格生成的工具描述也将对大型语言模型(LLM)有所帮助。 - 运行代理程序。:使用以下方法来执行您的代理程序:
Runner当大型语言模型(LLM)确定需要调用某个 API 时,它会生成一个函数调用,该调用会指向相应的 API。RestApiTool然后,该系统会自动处理 HTTP 请求。
看看它的实际运行效果吧。¶
这个示例展示了如何根据一个简单的 Pet Store OpenAPI 规范(使用相关工具)生成相应的应用程序或服务。 httpbin.org (用于生成模拟响应),并通过代理程序与这些模拟响应进行交互。
代码:宠物店 API
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import asyncio
import uuid # For unique session IDs
from dotenv import load_dotenv
from google.adk.agents import LlmAgent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
# --- OpenAPI Tool Imports ---
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset
# --- Load Environment Variables (If ADK tools need them, e.g., API keys) ---
load_dotenv() # Create a .env file in the same directory if needed
# --- Constants ---
APP_NAME_OPENAPI = "openapi_petstore_app"
USER_ID_OPENAPI = "user_openapi_1"
SESSION_ID_OPENAPI = f"session_openapi_{uuid.uuid4()}" # Unique session ID
AGENT_NAME_OPENAPI = "petstore_manager_agent"
GEMINI_MODEL = "gemini-2.0-flash"
# --- Sample OpenAPI Specification (JSON String) ---
# A basic Pet Store API example using httpbin.org as a mock server
openapi_spec_string = """
{
"openapi": "3.0.0",
"info": {
"title": "Simple Pet Store API (Mock)",
"version": "1.0.1",
"description": "An API to manage pets in a store, using httpbin for responses."
},
"servers": [
{
"url": "https://httpbin.org",
"description": "Mock server (httpbin.org)"
}
],
"paths": {
"/get": {
"get": {
"summary": "List all pets (Simulated)",
"operationId": "listPets",
"description": "Simulates returning a list of pets. Uses httpbin's /get endpoint which echoes query parameters.",
"parameters": [
{
"name": "limit",
"in": "query",
"description": "Maximum number of pets to return",
"required": false,
"schema": { "type": "integer", "format": "int32" }
},
{
"name": "status",
"in": "query",
"description": "Filter pets by status",
"required": false,
"schema": { "type": "string", "enum": ["available", "pending", "sold"] }
}
],
"responses": {
"200": {
"description": "A list of pets (echoed query params).",
"content": { "application/json": { "schema": { "type": "object" } } }
}
}
}
},
"/post": {
"post": {
"summary": "Create a pet (Simulated)",
"operationId": "createPet",
"description": "Simulates adding a new pet. Uses httpbin's /post endpoint which echoes the request body.",
"requestBody": {
"description": "Pet object to add",
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"required": ["name"],
"properties": {
"name": {"type": "string", "description": "Name of the pet"},
"tag": {"type": "string", "description": "Optional tag for the pet"}
}
}
}
}
},
"responses": {
"201": {
"description": "Pet created successfully (echoed request body).",
"content": { "application/json": { "schema": { "type": "object" } } }
}
}
}
},
"/get?petId={petId}": {
"get": {
"summary": "Info for a specific pet (Simulated)",
"operationId": "showPetById",
"description": "Simulates returning info for a pet ID. Uses httpbin's /get endpoint.",
"parameters": [
{
"name": "petId",
"in": "path",
"description": "This is actually passed as a query param to httpbin /get",
"required": true,
"schema": { "type": "integer", "format": "int64" }
}
],
"responses": {
"200": {
"description": "Information about the pet (echoed query params)",
"content": { "application/json": { "schema": { "type": "object" } } }
},
"404": { "description": "Pet not found (simulated)" }
}
}
}
}
}
"""
# --- Create OpenAPIToolset ---
petstore_toolset = OpenAPIToolset(
spec_str=openapi_spec_string,
spec_str_type='json',
# No authentication needed for httpbin.org
)
# --- Agent Definition ---
root_agent = LlmAgent(
name=AGENT_NAME_OPENAPI,
model=GEMINI_MODEL,
tools=[petstore_toolset], # Pass the list of RestApiTool objects
instruction="""You are a Pet Store assistant managing pets via an API.
Use the available tools to fulfill user requests.
When creating a pet, confirm the details echoed back by the API.
When listing pets, mention any filters used (like limit or status).
When showing a pet by ID, state the ID you requested.
""",
description="Manages a Pet Store using tools generated from an OpenAPI spec."
)
# --- Session and Runner Setup ---
async def setup_session_and_runner():
session_service_openapi = InMemorySessionService()
runner_openapi = Runner(
agent=root_agent,
app_name=APP_NAME_OPENAPI,
session_service=session_service_openapi,
)
await session_service_openapi.create_session(
app_name=APP_NAME_OPENAPI,
user_id=USER_ID_OPENAPI,
session_id=SESSION_ID_OPENAPI,
)
return runner_openapi
# --- Agent Interaction Function ---
async def call_openapi_agent_async(query, runner_openapi):
print("\n--- Running OpenAPI Pet Store Agent ---")
print(f"Query: {query}")
content = types.Content(role='user', parts=[types.Part(text=query)])
final_response_text = "Agent did not provide a final text response."
try:
async for event in runner_openapi.run_async(
user_id=USER_ID_OPENAPI, session_id=SESSION_ID_OPENAPI, new_message=content
):
# Optional: Detailed event logging for debugging
# print(f" DEBUG Event: Author={event.author}, Type={'Final' if event.is_final_response() else 'Intermediate'}, Content={str(event.content)[:100]}...")
if event.get_function_calls():
call = event.get_function_calls()[0]
print(f" Agent Action: Called function '{call.name}' with args {call.args}")
elif event.get_function_responses():
response = event.get_function_responses()[0]
print(f" Agent Action: Received response for '{response.name}'")
# print(f" Tool Response Snippet: {str(response.response)[:200]}...") # Uncomment for response details
elif event.is_final_response() and event.content and event.content.parts:
# Capture the last final text response
final_response_text = event.content.parts[0].text.strip()
print(f"Agent Final Response: {final_response_text}")
except Exception as e:
print(f"An error occurred during agent run: {e}")
import traceback
traceback.print_exc() # Print full traceback for errors
print("-" * 30)
# --- Run Examples ---
async def run_openapi_example():
runner_openapi = await setup_session_and_runner()
# Trigger listPets
await call_openapi_agent_async("Show me the pets available.", runner_openapi)
# Trigger createPet
await call_openapi_agent_async("Please add a new dog named 'Dukey'.", runner_openapi)
# Trigger showPetById
await call_openapi_agent_async("Get info for pet with ID 123.", runner_openapi)
# --- Execute ---
if __name__ == "__main__":
print("Executing OpenAPI example...")
# Use asyncio.run() for top-level execution
try:
asyncio.run(run_openapi_example())
except RuntimeError as e:
if "cannot be called from a running event loop" in str(e):
print("Info: Cannot run asyncio.run from a running event loop (e.g., Jupyter/Colab).")
# If in Jupyter/Colab, you might need to run like this:
# await run_openapi_example()
else:
raise e
print("OpenAPI example finished.")
高级配置¶
注意:
本节中提到的参数需要使用 ADK Python v2.0.0 或更高版本才能正常使用。
带有自定义头的请求(Custom headers with…) header_provider¶
要动态地为每个 API 请求添加自定义头部(custom headers),请提供一个可执行的函数(callable)。
header_provider该可调用对象(callable)会接收到……(具体内容在原文中被省略了)。 ReadonlyContext 并返回一个包含所有请求头信息的字典(dictionary of headers),如下例所示:
from google.adk.agents.readonly_context import ReadonlyContext
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset
openapi_spec = {...} # Loaded from your OpenAPI file.
def my_header_provider(context: ReadonlyContext) -> dict[str, str]:
return {"X-Request-ID": context.invocation_id}
toolset = OpenAPIToolset(
spec_dict=openapi_spec,
header_provider=my_header_provider,
)
使用……进行 SSL 证书验证 ssl_verify¶
要为工具集中的所有工具配置 SSL 证书验证功能,请使用以下方法:
ssl_verify 以下示例展示了如何为使用自定义 CA 证书的环境配置 SSL 验证功能:
from google.adk.tools.openapi_tool.openapi_spec_parser.openapi_toolset import OpenAPIToolset
openapi_spec = {...} # Loaded from your OpenAPI file.
toolset = OpenAPIToolset(
spec_dict=openapi_spec,
ssl_verify="/path/to/ca.pem",
)
请勿禁用验证功能。
ssl_verify 也接受(其他形式或内容) True, False,或者一个 ssl.SSLContext. 设置
ssl_verify=False 该设置会完全禁用证书验证功能,从而使所有请求都容易被拦截。请使用根证书(CA)的路径或自定义的证书配置文件来替代默认设置。 SSLContext
相反。
工具名称前缀: tool_name_prefix¶
要为工具集生成的所有工具名称添加前缀,请使用以下方法:
tool_name_prefix 参数。以下示例展示了如何在使用多个 OpenAPI 规范时避免名称冲突: