Skip to main content
This example demonstrates how to create custom tools in Python using Composio’s decorator-based API with Pydantic models for type safety.

Overview

In this example, you’ll learn how to:
  • Create custom tools using the @composio.tools.custom_tool decorator
  • Define input schemas with Pydantic models
  • Create standalone tools and toolkit-integrated tools
  • Access authentication credentials in tools
  • Make authenticated API requests

Prerequisites

1

Install dependencies

2

Set up environment variables

Create a .env file with your API key:

Complete Example

How It Works

1

Define Input Schema

Create a Pydantic BaseModel class that defines the input parameters. Use Field to add descriptions and validation.
2

Decorate Tool Function

Use @composio.tools.custom_tool to register your function as a tool. Optionally specify a toolkit for authentication.
3

Implement Tool Logic

Write the tool’s logic. For toolkit-integrated tools, you can access execute_request and auth_credentials.
4

Execute the Tool

Call composio.tools.execute() with the tool’s slug and arguments to run it.

Tool Function Signatures

Function Parameters

BaseModel
required
The validated input parameters matching your Pydantic model
ExecuteRequestFn
Helper function to make authenticated HTTP requests to the toolkit’s API
dict
Authentication credentials for the toolkit

Pydantic Field Options

Use Pydantic’s Field for rich parameter definitions:

Expected Output

Advanced Examples

Handle nested data with Pydantic models:
Accept lists of items:
Use enums for restricted choices:
Handle errors gracefully:

Tool Attributes

After decoration, your function has additional attributes:

Best Practices

Descriptive Docstrings: Use clear docstrings - they become the tool description for AI models
Field Descriptions: Always add descriptions to Pydantic fields for better AI understanding
Type Safety: Use Pydantic’s validation features to ensure type safety
Error Handling: Return structured error responses instead of raising exceptions
Toolkit Integration: Use toolkit parameter when you need authentication for external APIs

Next Steps

OpenAI Example

Use custom tools with OpenAI Agents

CrewAI Example

Use custom tools in CrewAI crews