Composio Tutorial: Tool Integration Platform for AI Agents
Composio is an open-source platform that enables AI agents to connect with 250+ external tools and applications such as GitHub, Slack, Gmail, Google Sheets, Jira, and many more. With Composio, you can build AI agents that don't just think but also take real-world actions through secure, managed API integrations.
In this tutorial, we'll learn how to use Composio from installation and authentication to building AI agents that can interact with various tools automatically.
Why Composio?
Building AI agents that interact with external tools typically requires significant boilerplate code: managing OAuth tokens, writing API wrappers, handling rate limiting, and ensuring security. Composio solves all these problems by providing:
- Managed Authentication: OAuth2, API Key, and Basic Auth handled automatically
- 250+ Pre-built Integrations: GitHub, Slack, Gmail, Notion, Jira, Linear, Google Drive, and more
- Framework Agnostic: Supports LangChain, CrewAI, AutoGen, LlamaIndex, OpenAI, and other frameworks
- Type-safe Actions: Every tool action has a clear schema for input and output
- Execution Environment: Supports local, Docker, and cloud execution
Installation
Python SDK Installation
pip install composio-core
For integration with specific frameworks, install additional packages:
# For OpenAI
pip install composio-openai
For LangChain
pip install composio-langchain
For CrewAI
pip install composio-crewai
For Autogen
pip install composio-autogen
For LlamaIndex
pip install composio-llamaindex
CLI Installation
Composio provides a CLI for managing connections and tools:
pip install composio-core
Login to Composio
composio login
Check status
composio whoami
API Key Setup
After logging in, you can obtain your API key from the Composio dashboard:
export COMPOSIOAPIKEY="your-api-key-here"
Or save it in a .env file:
COMPOSIOAPIKEY=your-api-key-here
Basic Usage
Connecting an App
The first step is connecting the application you want your agent to use. Composio handles the OAuth process automatically:
from composio import ComposioToolSet, App, Action
Initialize toolset
toolset = ComposioToolSet()
Start connection to GitHub
This will open a browser for OAuth authorization
entity = toolset.getentity(id="default")
connectionrequest = entity.initiateconnection(
appname=App.GITHUB
)
print(f"Open this URL to authorize: {connectionrequest.redirectUrl}")
print(f"Connection status: {connectionrequest.connectionStatus}")
For CLI, the connection process is simpler:
# Add GitHub connection
composio add github
Add Slack connection
composio add slack
View active connections
composio connections
Using Tools with OpenAI
Here's a simple example using Composio with OpenAI to create an agent that can interact with GitHub:
from composioopenai import ComposioToolSet, Action
from openai import OpenAI
Initialize
client = OpenAI()
toolset = ComposioToolSet()
Get GitHub tools
tools = toolset.get
tools(actions=[
Action.GITHUBCREATEISSUE,
Action.GITHUBLISTREPOS,
Action.GITHUBSTARREPO,
])
Make request to OpenAI with tools
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "system",
"content": "You are an assistant that helps manage GitHub repositories."
},
{
"role": "user",
"content": "Create a new issue in 'myorg/myproject' repo with title 'Fix login bug' and description 'Login page returns 500 error when using SSO'"
}
],
tools=tools,
toolchoice="auto"
)
Execute tool calls
result = toolset.handletoolcalls(response)
print(result)
Using Tools with LangChain
from composiolangchain import ComposioToolSet, Action
from langchainopenai import ChatOpenAI
from langchain.agents import createopenaifunctionsagent, AgentExecutor
from langchaincore.prompts import ChatPromptTemplate
Setup
llm = ChatOpenAI(model="gpt-4o")
toolset = ComposioToolSet()
Get tools
tools = toolset.gettools(actions=[
Action.GMAILSENDEMAIL,
Action.GMAILLISTEMAILS,
Action.GMAILREADEMAIL,
])
Create prompt
prompt = ChatPromptTemplate.frommessages([
("system", "You are an email assistant that helps manage the inbox."),
("human", "{input}"),
("placeholder", "{agentscratchpad}"),
])
Create agent
agent = createopenaifunctionsagent(llm, tools, prompt)
agentexecutor = AgentExecutor(agent=agent, tools=tools, verbose=True)
Run
result = agentexecutor.invoke({
"input": "Show me the 5 most recent emails in my inbox"
})
print(result["output"])
Advanced Usage
Custom Actions
Besides using built-in actions, you can create your own custom actions:
from composio import action
@action(toolname="customtool")
def calculateprojectcost(
hours: float,
hourlyrate: float,
taxpercentage: float = 10.0
) -> dict:
"""
Calculate total project cost based on work hours and rate.
:param hours: Number of work hours
:param hourlyrate: Rate per hour in USD
:param taxpercentage: Tax percentage (default 10%)
:return: Dictionary containing subtotal, tax, and total
"""
subtotal = hours hourlyrate
tax = subtotal (taxpercentage / 100)
total = subtotal + tax
return {
"subtotal": subtotal,
"tax": tax,
"total": total,
"currency": "USD"
}
Triggers (Event-Driven Agents)
Composio supports triggers that allow agents to respond to events in real-time:
from composio import ComposioToolSet, Action
toolset = ComposioToolSet()
Create listener for GitHub events
listener = toolset.createtriggerlistener()
@listener.callback(filters={"triggername": "GITHUBPULLREQUESTEVENT"})
def onpullrequest(event):
"""Called whenever there's a new PR in the repository"""
prdata = event.payload
print(f"New PR: {prdata['title']}")
print(f"Author: {prdata['user']['login']}")
print(f"Repository: {prdata['repository']['fullname']}")
# Agent can automatically perform code review
# or send notification to Slack
return {"status": "processed"}
Start listening for events
print("Listening for GitHub events...")
listener.listen()
Entity Management (Multi-User)
For applications serving multiple users, Composio provides entity management:
from composio import ComposioToolSet
toolset = ComposioToolSet()
Each user has their own entity
userentity = toolset.getentity(id="user-123")
Check if user is connected to GitHub
connections = userentity.getconnections()
githubconnected = any(
conn.appName == "github" for conn in connections
)
if not githubconnected:
# Initiate connection for this user
request = userentity.initiateconnection(appname="github")
print(f"User needs to authorize: {request.redirectUrl}")
else:
# User already connected, use tools directly
tools = toolset.gettools(
actions=["GITHUBLISTREPOS"],
entityid="user-123"
)
Filtering Tools
When working with many tools, you can filter based on use case:
from composio import ComposioToolSet, App
toolset = ComposioToolSet()
Filter tools by app
githubtools = toolset.gettools(apps=[App.GITHUB])
Filter by tags/use case
tools = toolset.gettools(
apps=[App.GITHUB],
tags=["issues", "pullrequests"]
)
Filter specific actions
tools = toolset.gettools(actions=[
"GITHUBCREATEISSUE",
"GITHUBLISTPULLREQUESTS",
"GITHUBMERGEPULLREQUEST",
])
Integration with CrewAI
Composio becomes exceptionally powerful when combined with multi-agent frameworks like CrewAI:
from composiocrewai import ComposioToolSet, Action
from crewai import Agent, Task, Crew
toolset = ComposioToolSet()
Tools for project manager agent
pmtools = toolset.gettools(actions=[
Action.GITHUBCREATEISSUE,
Action.GITHUBLISTISSUES,
Action.SLACKSENDMESSAGE,
])
Tools for developer agent
devtools = toolset.gettools(actions=[
Action.GITHUBCREATEPULLREQUEST,
Action.GITHUBLISTPULLREQUESTS,
Action.GITHUBGETFILECONTENT,
])
Define agents
projectmanager = Agent(
role="Project Manager",
goal="Manage tasks and coordinate the team",
backstory="Experienced PM who efficiently manages software projects",
tools=pmtools,
verbose=True
)
developer = Agent(
role="Software Developer",
goal="Implement features and fix bugs",
backstory="Senior developer who writes high-quality code",
tools=devtools,
verbose=True
)
Define tasks
reviewtask = Task(
description="Review all open issues in 'myorg/myproject' repo and create a priority summary",
agent=projectmanager,
expectedoutput="List of issues sorted by priority"
)
Run crew
crew = Crew(
agents=[projectmanager, developer],
tasks=[reviewtask],
verbose=True
)
result = crew.kickoff()
print(result)
Full Project Example: Automated PR Review Agent
Here's a complete example of building an agent that automatically performs code review on every new Pull Request:
from composioopenai import ComposioToolSet, Action
from openai import OpenAI
client = OpenAI()
toolset = ComposioToolSet()
def reviewpullrequest(repo: str, prnumber: int):
"""Automatically review a Pull Request"""
# Get required tools
tools = toolset.gettools(actions=[
Action.GITHUBGETPULLREQUEST,
Action.GITHUBLISTPULLREQUESTFILES,
Action.GITHUBCREATEREVIEWCOMMENT,
])
messages = [
{
"role": "system",
"content": """You are a senior code reviewer. Your job is to:
Read the Pull Request diff
Identify potential bugs, security issues, and code quality problems
Provide constructive review comments
Focus on important issues, not formatting"""
},
{
"role": "user",
"content": f"Review PR #{prnumber} in repository {repo}. "
f"Get the list of changed files, analyze the changes, "
f"and provide review comments."
}
]
# Loop to handle multiple tool calls
while True:
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tools,
toolchoice="auto"
)
message = response.choices[0].message
if message.toolcalls:
# Execute tool calls
results = toolset.handletoolcalls(response)
messages.append(message)
for result in results:
messages.append({
"role": "tool",
"toolcallid": result["toolcallid"],
"content": str(result["result"])
})
else:
# Agent finished review
print("Review complete:")
print(message.content)
break
Example usage
reviewpullrequest("myorg/myproject", 42)
Supported Apps
Here are some categories of apps supported by Composio:
| Category | Apps |
|----------|------|
| Version Control | GitHub, GitLab, Bitbucket |
| Communication | Slack, Discord, Microsoft Teams |
| Email | Gmail, Outlook |
| Project Management | Jira, Linear, Asana, Trello, Notion |
| Cloud Storage | Google Drive, Dropbox, OneDrive |
| CRM | Salesforce, HubSpot |
| Database | Supabase, Airtable |
| Monitoring | Datadog, PagerDuty |
| CI/CD | GitHub Actions, CircleCI |
| Social | Twitter/X, LinkedIn |
Best Practices
1. Use Specific Actions
Don't load all tools from an app. Select specific actions matching your agent's needs to reduce token usage and improve accuracy:
# Less optimal - too many tools
tools = toolset.gettools(apps=[App.GITHUB]) # 50+ actions
More optimal - only what's needed
tools = toolset.gettools(actions=[
Action.GITHUBCREATEISSUE,
Action.GITHUBLISTISSUES,
])
2. Manage Connections Securely
Always use entity management for multi-user scenarios and never hardcode credentials:
# Don't do this
toolset = ComposioToolSet(apikey="hardcoded-key")
Use environment variables
toolset = ComposioToolSet() # Automatically reads COMPOSIOAPIKEY
3. Handle Errors Gracefully
from composio.exceptions import ComposioSDKError
try:
result = toolset.executeaction(
action=Action.GITHUBCREATEISSUE,
params={
"owner": "myorg",
"repo": "myproject",
"title": "Bug report",
"body": "Description of the bug"
}
)
except ComposioSDKError as e:
print(f"Composio error: {e}")
# Handle gracefully
4. Use Triggers for Event-Driven Architecture
Instead of polling, use triggers to respond to events in real-time. This is more efficient and responsive.
5. Test with Sandbox
During development, use the Composio sandbox environment for testing without modifying production data:
# Use sandbox environment for testing
toolset = ComposioToolSet(
workspaceconfig={
"type": "docker",
"image": "composio/sandbox:latest"
}
)
6. Monitoring and Logging
Enable logging to monitor tool usage by agents:
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("composio")
Composio SDK will log every action executed
Conclusion
Composio simplifies the process of building AI agents that can interact with the real world through managed tool integrations. With support for 250+ applications, managed authentication, and compatibility with various AI frameworks, Composio eliminates boilerplate complexity so you can focus on your agent's business logic.
Key takeaways to remember:
- Start simple: Choose one or two tools most relevant to your use case
- Use specific actions: Avoid loading all tools at once for token efficiency
- Leverage triggers: For responsive, efficient event-driven agents
- Entity management: Essential for multi-user production applications
- Security: Always use environment variables for API keys and leverage Composio's managed OAuth
With this foundation, you can start building AI agents that are truly productive and can accomplish real tasks automatically.