from google.cloud import dialogflowcx_v3beta1
def create_api_tool(project_id: str, location_id: str, agent_id: str,
tool_display_name: str, tool_description: str, openapi_yaml_string: str):
"""
Creates an API tool in the specified Dialogflow CX agent.
Args:
project_id: Google Cloud project ID.
location_id: Region ID (e.g., "global", "us-central1").
agent_id: Dialogflow CX agent ID.
tool_display_name: Display name for the new tool.
tool_description: Description of the tool's purpose.
openapi_yaml_string: OpenAPI 3.0 specification as a YAML string.
"""
client = dialogflowcx_v3beta1.ToolsClient()
parent = f"projects/{project_id}/locations/{location_id}/agents/{agent_id}"
tool_config = dialogflowcx_v3beta1.types.Tool(
display_name=tool_display_name,
description=tool_description,
tool_type=dialogflowcx_v3beta1.types.Tool.ToolType.OPEN_API,
open_api_spec=dialogflowcx_v3beta1.types.Tool.OpenApiSpec(
text_schema=openapi_yaml_string
)
)
try:
created_tool = client.create_tool(parent=parent, tool=tool_config)
print(f"Tool created successfully: {created_tool.name}")
print(f"Display Name: {created_tool.display_name}")
print(f"Tool Type: {dialogflowcx_v3beta1.types.Tool.ToolType(created_tool.tool_type).name}")
print(f"Tool ID: {created_tool.name.split('/')[-1]}")
return created_tool
except Exception as e:
print(f"Error creating tool: {e}")
return None
if __name__ == "__main__":
# Set your own values here or load from environment/config
PROJECT_ID = "your-project-id"
LOCATION_ID = "your-region" # e.g., "global"
AGENT_ID = "your-agent-id"
TOOL_DISPLAY_NAME = "Sample TODO API Tool"
TOOL_DESCRIPTION = "Fetches a specific TODO item from jsonplaceholder. Created via Python."
OPENAPI_SCHEMA = """
openapi: 3.0.0
info:
title: JSONPlaceholder TODO API
version: v1.0.0
description: A simple API to get a TODO item.
servers:
- url: https://jsonplaceholder.typicode.com
paths:
/todos/{todoId}:
get:
summary: Get a single TODO item by ID
operationId: getTodoById
parameters:
- name: todoId
in: path
required: true
description: ID of the todo to retrieve
schema:
type: integer
default: 1
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
userId:
type: integer
id:
type: integer
title:
type: string
completed:
type: boolean
default:
description: Error response
"""
new_tool = create_api_tool(PROJECT_ID, LOCATION_ID, AGENT_ID,
TOOL_DISPLAY_NAME, TOOL_DESCRIPTION, OPENAPI_SCHEMA)
if new_tool:
print(f"Tool '{new_tool.display_name}' details: {new_tool}")