Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Migrate Examples section from fern

Sushmithamallesh2c8cb942122e
diff --git a/fumadocs/content/examples/fast-api.mdx b/fumadocs/content/examples/fast-api.mdx
new file mode 100644
index 000000000..14353d9ae
--- /dev/null
+++ b/fumadocs/content/examples/fast-api.mdx
@@ -0,0 +1,398 @@
+---
+title: Basic FastAPI Server
+description: Build a simple Gmail agent with Composio and FastAPI
+---
+
+This cookbook will guide you through building agents equipped with tools using `Composio`, `OpenAI`, and `FastAPI`.
+
+## Prerequisites
+
+* Python 3.10+
+* [UV](https://docs.astral.sh/uv/getting-started/installation/)
+* Composio API key
+* OpenAI API key
+
+## Building an AI agent that can interact with `gmail` service
+
+First, let's start with building a simple AI agent with Composio tools that lets the agent interact with `gmail`.
+
+```python
+from openai import OpenAI
+from composio import Composio
+from composio_openai import OpenAIProvider
+import os
+
+def run_gmail_agent(
+ composio_client: Composio[OpenAIProvider],
+ openai_client: OpenAI,
+ user_id: str, # Composio uses the User ID to store and access user-level authentication tokens.
+ prompt: str,
+):
+ """
+ Run the Gmail agent using composio and openai clients.
+ """
+ # Step 1: Fetch the necessary Gmail tools list with Composio
+ tools = composio_client.tools.get(
+ user_id=user_id,
+ tools=[
+ "GMAIL_FETCH_EMAILS",
+ "GMAIL_SEND_EMAIL",
+ "GMAIL_CREATE_EMAIL_DRAFT"
+ ]
+ )
+
+ # Step 2: Use OpenAI to generate a response based on the prompt and available tools
+ response = openai_client.chat.completions.create(
+ model="gpt-4.1",
+ tools=tools,
+ messages=[{"role": "user", "content": prompt}],
+ )
+
+ # Step 3: Handle tool calls with Composio and return the result
+ result = composio_client.provider.handle_tool_calls(response=response, user_id=user_id)
+ return result
+```
+
+<Callout>
+This example demonstrates a basic agent without state management or agentic loops,
+suitable for simple one-step tasks. For complex multi-step workflows requiring
+memory and iterative reasoning, see our cookbooks with frameworks like LangChain,
+CrewAI, or AutoGen.
+</Callout>
+
+To invoke this agent, authenticate your users with Composio's managed authentication service.
+
+## Authenticating users
+
+
+To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
+
+To create an authentication config for `gmail` you need `client_id` and `client_secret` from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2). Once you have the credentials, use the following piece of code to set up authentication for `gmail`.
+
+```python
+from composio import Composio
+from composio_openai import OpenAIProvider
+
+def create_auth_config(composio_client: Composio[OpenAIProvider]):
+ """
+ Create a auth config for the gmail toolkit.
+ """
+ client_id = os.getenv("GMAIL_CLIENT_ID")
+ client_secret = os.getenv("GMAIL_CLIENT_SECRET")
+ if not client_id or not client_secret:
+ raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")
+
+ return composio_client.auth_configs.create(
+ toolkit="GMAIL",
+ options={
+ "name": "default_gmail_auth_config",
+ "type": "use_custom_auth",
+ "auth_scheme": "OAUTH2",
+ "credentials": {
+ "client_id": client_id,
+ "client_secret": client_secret,
+ },
+ },
+ )
+```
+
+This will create a Gmail authentication config to authenticate your app’s users. Ideally, create one authentication object per project, so check for an existing auth config before creating a new one.
+
+```python
+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
+ """
+ Fetch the auth config for a given user id.
+ """
+ auth_configs = composio_client.auth_configs.list()
+ for auth_config in auth_configs.items:
+ if auth_config.toolkit == "GMAIL":
+ return auth_config
+
+ return None
+```
+
+<Callout>
+Composio platform provides composio managed authentication for some apps to
+fast-track your development, `gmail` being one of them. You can use these
+default auth configs for development, but for production, always use your
+own oauth app configuration.
+</Callout>
+
+Once you have authentication management in place, we can start with connecting your users to your `gmail` app. Let's implement a function to connect users to your `gmail` app via composio.
+
+```python
+from fastapi import FastAPI
+
+# Function to initiate a connected account
+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
+ """
+ Create a connection for a given user id and auth config id.
+ """
+ # Fetch or create the auth config for the gmail toolkit
+ auth_config = fetch_auth_config(composio_client=composio_client)
+ if not auth_config:
+ auth_config = create_auth_config(composio_client=composio_client)
+
+ # Create a connection for the user
+ return composio_client.connected_accounts.initiate(
+ user_id=user_id,
+ auth_config_id=auth_config.id,
+ )
+
+# Setup FastAPI
+app = FastAPI()
+
+# Connection initiation endpoint
[email protected]("/connection/create")
+def _create_connection(
+ request: CreateConnectionRequest,
+ composio_client: ComposioClient,
+) -> dict:
+ """
+ Create a connection for a given user id.
+ """
+ # For demonstration, using a default user_id. Replace with real user logic in production.
+ user_id = "default"
+
+ # Create a new connection for the user
+ connection_request = create_connection(composio_client=composio_client, user_id=user_id)
+ return {
+ "connection_id": connection_request.id,
+ "redirect_url": connection_request.redirect_url,
+ }
+```
+
+Now, you can make a request to this endpoint on your client app, and your user will get a URL which they can use to authenticate.
+
+## Set Up FastAPI service
+
+We will use [`FastApi`](https://fastapi.tiangolo.com/) to build an HTTP service that authenticates your users and lets them interact with your agent. This guide will provide best practices for using composio client in production environments.
+
+### Setup dependencies
+
+FastAPI allows [dependency injection](https://fastapi.tiangolo.com/reference/dependencies/) to simplify the usage of SDK clients that must be singletons. We recommend using composio SDK client as singleton.
+
+```python
+import os
+import typing_extensions as te
+
+from composio import Composio
+from composio_openai import OpenAIProvider
+
+from fastapi import Depends
+
+_composio_client: Composio[OpenAIProvider] | None = None
+
+def provide_composio_client():
+ """
+ Provide a Composio client.
+ """
+ global _composio_client
+ if _composio_client is None:
+ _composio_client = Composio(provider=OpenAIProvider())
+ return _composio_client
+
+
+ComposioClient = te.Annotated[Composio, Depends(provide_composio_client)]
+"""
+A Composio client dependency.
+"""
+```
+
+Check [dependencies](./simple_gmail_agent/server/dependencies.py) module for more details.
+
+### Invoke agent via FastAPI
+
+When invoking an agent, make sure you validate the `user_id`.
+
+```python
+def check_connected_account_exists(
+ composio_client: Composio[OpenAIProvider],
+ user_id: str,
+):
+ """
+ Check if a connected account exists for a given user id.
+ """
+ # Fetch all connected accounts for the user
+ connected_accounts = composio_client.connected_accounts.list(
+ user_ids=[user_id],
+ toolkit_slugs=["GMAIL"],
+ )
+
+ # Check if there's an active connected account
+ for account in connected_accounts.items:
+ if account.status == "ACTIVE":
+ return True
+
+ # Ideally you should not have inactive accounts, but if you do, delete them.
+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")
+ return False
+
+def validate_user_id(user_id: str, composio_client: ComposioClient):
+ """
+ Validate the user id, if no connected account is found, create a new connection.
+ """
+ if check_connected_account_exists(composio_client=composio_client, user_id=user_id):
+ return user_id
+
+ raise HTTPException(
+ status_code=404, detail={"error": "No connected account found for the user id"}
+ )
+
+# Endpoint: Run the Gmail agent for a given user id and prompt
+def _run_gmail_agent(
+ request: RunGmailAgentRequest,
+ composio_client: ComposioClient,
+ openai_client: OpenAIClient, # OpenAI client will be injected as dependency
+) -> List[ToolExecutionResponse]:
+ """
+ Run the Gmail agent for a given user id and prompt.
+ """
+ # For demonstration, using a default user_id. Replace with real user logic in production.
+ user_id = "default"
+
+ # Validate the user id before proceeding
+ user_id = validate_user_id(user_id=user_id, composio_client=composio_client)
+
+ # Run the Gmail agent using Composio and OpenAI
+ result = run_gmail_agent(
+ composio_client=composio_client,
+ openai_client=openai_client,
+ user_id=user_id,
+ prompt=request.prompt,
+ )
+ return result
+```
+
+<Callout>
+Check [server](./simple_gmail_agent/server/) module for service implementation
+</Callout>
+
+## Putting everything together
+
+So far, we have created an agent with ability to interact with `gmail` using the `composio` SDK, functions to manage connected accounts for users and a FastAPI service. Now let's run the service.
+
+<Callout>
+Before proceeding, check the [code](./simple_gmail_agent/server/api.py) for utility endpoints not discussed in the cookbook
+</Callout>
+
+
+1. Clone the repository
+ ```bash
+ git clone [email protected]:composiohq/composio-fastapi
+ cd composio-fastapi/
+ ```
+2. Setup environment
+ ```bash
+ cp .env.example .env
+ ```
+
+ Fill the api keys
+ ```dotenv
+ COMPOSIO_API_KEY=
+ OPENAI_API_KEY=
+ ```
+
+ Create the virtual env
+ ```bash
+ make env
+ source .venv/bin/activate
+ ```
+3. Run the HTTP server
+ ```bash
+ uvicorn simple_gmail_agent.server.api:create_app --factory
+ ```
+## Testing the API with curl
+
+Assuming the server is running locally on `http://localhost:8000`.
+
+### Check if a connection exists
+```bash
+curl -X POST http://localhost:8000/connection/exists
+```
+
+### Create a connection
+Note: The body fields are required by the API schema, but are ignored internally in this example service.
+```bash
+curl -X POST http://localhost:8000/connection/create \
+ -H "Content-Type: application/json" \
+ -d '{
+ "user_id": "default",
+ "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
+ }'
+```
+Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.
+
+### Check connection status
+Use the `connection_id` returned from the create step.
+```bash
+curl -X POST http://localhost:8000/connection/status \
+ -H "Content-Type: application/json" \
+ -d '{
+ "user_id": "default",
+ "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
+ }'
+```
+
+### Run the Gmail agent
+Requires an active connected account for the `default` user.
+```bash
+curl -X POST http://localhost:8000/agent \
+ -H "Content-Type: application/json" \
+ -d '{
+ "user_id": "default",
+ "prompt": "Summarize my latest unread emails from the last 24 hours."
+ }'
+```
+
+### Fetch emails (direct action)
+```bash
+curl -X POST http://localhost:8000/actions/fetch_emails \
+ -H "Content-Type: application/json" \
+ -d '{
+ "user_id": "default",
+ "limit": 5
+ }'
+```
+
+These examples are intended solely for testing purposes.
+
+## Using Composio for managed auth and tools
+
+Composio reduces boilerplate for building AI agents that access and use various apps. In this cookbook, to build Gmail integration without Composio, you would have to write code to
+
+- manage Gmail OAuth app
+- manage user connections
+- tools for your agents to interact with Gmail
+
+Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.
+
+## Best practices
+
+**🎯 Effective Prompts**:
+- Be specific: "Send email to [email protected] about tomorrow's 2pm meeting" works better than "send email"
+- Include context: "Reply to Sarah's email about the budget with our approval"
+- Use natural language: The agent understands conversational requests
+
+**🔒 User Management**:
+- Use unique, consistent `user_id` values for each person
+- Each user maintains their own Gmail connection
+- User IDs can be email addresses, usernames, or any unique identifier
+
+
+## Troubleshooting
+
+**Connection Issues**:
+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
+- Check if the user has completed Gmail authorization.
+- Verify the user_id matches exactly between requests
+
+**API Errors**:
+- Check the server logs for detailed error messages
+- Ensure request payloads match the expected format
+- Visit `/docs` endpoint for API schema validation
+
+**Gmail API Limits**:
+- Gmail has rate limits; the agent will handle these gracefully
+- For high-volume usage, consider implementing request queuing
diff --git a/fumadocs/content/examples/gmail-labeler.mdx b/fumadocs/content/examples/gmail-labeler.mdx
new file mode 100644
index 000000000..61d8e3360
--- /dev/null
+++ b/fumadocs/content/examples/gmail-labeler.mdx
@@ -0,0 +1,381 @@
+---
+title: Gmail Labeler
+description: Build an agent that automatically labels incoming Gmail messages using triggers
+---
+
+With Composio's managed authentication, tool calling and triggers, it's easy to
+build the AI agents that can interact and react the real world events reducing
+the boilerplate required to setup and manage the authentication. This cookbook
+will walk you through the process of building agents using `Composio`, `LangChain`.
+
+## Prerequisites
+
+* Python3.x
+* [UV](https://docs.astral.sh/uv/getting-started/installation/)
+* Composio API key
+* OpenAI API key
+* Understanding of building AI agents (Preferably with LangChain)
+
+## Build gmail agent to label your messages
+
+```python
+from composio import Composio
+from composio_langchain import LangchainProvider
+
+from langchain import hub
+from langchain.agents import AgentExecutor, create_openai_functions_agent
+from langchain_openai import ChatOpenAI
+
+
+def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):
+ """
+ Create an agent for a given user id.
+ """
+ # Step 1: Get all the tools
+ tools = composio_client.tools.get(
+ user_id=user_id,
+ tools=[
+ "GMAIL_LIST_LABELS",
+ "GMAIL_ADD_LABEL_TO_EMAIL",
+ "GMAIL_CREATE_LABEL",
+ ],
+ )
+
+ # Step 2: Pull relevant agent prompt.
+ prompt = hub.pull("hwchase17/openai-functions-agent")
+
+ # Step 3: Initialize chat model.
+ openai_client = ChatOpenAI(model="gpt-5")
+
+ # Step 4: Define agent
+ return AgentExecutor(
+ agent=create_openai_functions_agent(
+ openai_client,
+ tools,
+ prompt,
+ ),
+ tools=tools,
+ verbose=False,
+ )
+```
+
+## Authenticating users
+
+To authenticate your users with Composio you need an auth config for the given
+app, In this case you need one for gmail. You can create and manage auth configs
+from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=gmail).
+Composio platform provides composio managed authentication for some apps to help
+you fast-track your development, `gmail` being one of them. You can use these
+default auth configs for development, but for production you should always use
+your own oauth app configuration.
+
+Using dashboard is the preferred way of managing authentication configs, but if
+you want to do it manually you can follow the guide below
+
+<details>
+
+<summary>Click to expand</summary>
+
+To create an authentication config for `gmail` you need `client_id` and `client_secret`
+from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).
+Once you have the required credentials you can use the following piece of
+code to set up authentication for `gmail`.
+
+```python
+from composio import Composio
+from composio_langchain import LangchainProvider
+
+def create_auth_config(composio_client: Composio[OpenAIProvider]):
+ """
+ Create a auth config for the gmail toolkit.
+ """
+ client_id = os.getenv("GMAIL_CLIENT_ID")
+ client_secret = os.getenv("GMAIL_CLIENT_SECRET")
+ if not client_id or not client_secret:
+ raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")
+
+ return composio_client.auth_configs.create(
+ toolkit="gmail",
+ options={
+ "name": "default_gmail_auth_config",
+ "type": "use_custom_auth",
+ "auth_scheme": "OAUTH2",
+ "credentials": {
+ "client_id": client_id,
+ "client_secret": client_secret,
+ },
+ },
+ )
+```
+
+This will create an authentication config for `gmail` which you can use to
+authenticate your users for your app. Ideally you should just create one
+authentication object per project, so check for an existing auth config
+before you create a new one.
+
+```python
+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
+ """
+ Fetch the auth config for a given user id.
+ """
+ auth_configs = composio_client.auth_configs.list()
+ for auth_config in auth_configs.items:
+ if auth_config.toolkit == "gmail":
+ return auth_config
+
+ return None
+```
+</details>
+
+Once you have authentication management in place, we can start with connecting
+your users to your `gmail` app. Let's implement a function to connect the users
+to your `gmail` app via composio.
+
+```python
+# Function to initiate a connected account
+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
+ """
+ Create a connection for a given user id and auth config id.
+ """
+ # Fetch or create the auth config for the gmail toolkit
+ auth_config = fetch_auth_config(composio_client=composio_client)
+ if not auth_config:
+ auth_config = create_auth_config(composio_client=composio_client)
+
+ # Create a connection for the user
+ return composio_client.connected_accounts.initiate(
+ user_id=user_id,
+ auth_config_id=auth_config.id,
+ )
+```
+
+Now, when creating tools for your agent always check if the user already has a
+connected account before creating a new one.
+
+```python
+def check_connected_account_exists(
+ composio_client: Composio[LangchainProvider],
+ user_id: str,
+):
+ """
+ Check if a connected account exists for a given user id.
+ """
+ # Fetch all connected accounts for the user
+ connected_accounts = composio_client.connected_accounts.list(
+ user_ids=[user_id],
+ toolkit_slugs=["GMAIL"],
+ )
+
+ # Check if there's an active connected account
+ for account in connected_accounts.items:
+ if account.status == "ACTIVE":
+ return True
+
+ # Ideally you should not have inactive accounts, but if you do, you should delete them
+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")
+ return False
+```
+
+
+## Creating Triggers
+
+You can use triggers to make your agents react to real world events. In this example,
+we will use triggers to invoke your agent everytime there's a new message in your
+gmail inbox.
+
+```python
+# Create a new trigger
+def create_trigger(
+ composio_client: Composio[LangchainProvider],
+ connected_account_id: str,
+) -> str:
+ """
+ Create a trigger.
+ """
+ response = composio_client.triggers.create(
+ slug="GMAIL_NEW_GMAIL_MESSAGE",
+ connected_account_id=connected_account_id,
+ trigger_config={},
+ )
+ return response.trigger_id
+```
+
+When creating triggers, make sure there are no duplicate triggers. Use following
+code as reference for checking if trigger for given connected account exists or not.
+
+```python
+def check_trigger_exists(
+ composio_client: Composio[LangchainProvider],
+ connected_account_id: str,
+) -> t.Optional[str]:
+ """
+ Check if a trigger exists.
+ """
+ triggers = composio_client.triggers.list_active(
+ trigger_names=["GMAIL_NEW_GMAIL_MESSAGE"],
+ connected_account_ids=[connected_account_id],
+ )
+ for trigger in triggers.items:
+ return trigger.id
+ return None
+```
+
+
+Once trigger is created, you can listen to events using a trigger subscription.
+
+```python
+# Create subscription object
+trigger_subscription = composio_client.triggers.subscribe()
+
+# Register event handler
+@trigger_subscription.handle(
+ trigger_id="<TRIGGER_ID>", # Filter out events that does not belong this trigger id
+ trigger_slug="GMAIL_NEW_GMAIL_MESSAGE",
+)
+def handle_event(event: TriggerEvent):
+ print("> Received email with subject: ", event["payload"]["subject"])
+
+# Wait for events
+trigger_subscription.wait_forever()
+```
+
+## Putting everything together
+
+Let's put together everything by making the agent react to new messages in your
+inbox.
+
+```python
+# Create a trigger subscription factory
+
+def create_trigger_subscription(
+ composio_client: Composio[LangchainProvider],
+ trigger_slug: str,
+ trigger_id: str,
+ agent: AgentExecutor,
+):
+ """
+ Create a trigger subscription for the given agent.
+ """
+ trigger_subscription = composio_client.triggers.subscribe()
+
+ @trigger_subscription.handle(
+ trigger_slug=trigger_slug,
+ trigger_id=trigger_id,
+ )
+ def handle_event(event: TriggerEvent):
+ print("> Received email with subject: ", event["payload"]["subject"])
+ result = agent.invoke(
+ input={
+ "input": APPLY_NEW_LABEL.format( # Check `gmail_labeler/prompt.py`
+ message_id=event["payload"]["id"],
+ message_subject=event["payload"]["subject"],
+ message_text=event["payload"]["message_text"],
+ )
+ }
+ )
+ print("> Result: ", result["output"])
+
+ return trigger_subscription
+```
+
+Package everything as a single entry point.
+
+```python
+def run_agent(user_id: str):
+ # Create composio client
+ composio_client = Composio(provider=LangchainProvider())
+
+ # Validate conected account
+ connected_account_id = check_connected_account_exists(composio_client, user_id)
+ if connected_account_id is None:
+ connection_request = create_connection(composio_client, user_id)
+ print(
+ f"Authenticate with the following link: {connection_request.redirect_url}"
+ )
+ connection_request.wait_for_connection()
+ connected_account_id = connection_request.id
+
+ # Check if trigger exists, create if not
+ trigger_id = check_trigger_exists(
+ composio_client=composio_client,
+ connected_account_id=connected_account_id,
+ )
+ if trigger_id is None:
+ trigger_id = create_trigger(
+ composio_client=composio_client,
+ connected_account_id=connected_account_id,
+ )
+
+ # Create agent
+ agent = create_agent(user_id=user_id, composio_client=composio_client)
+
+ # Create trigger subscription
+ trigger_subscription = create_trigger_subscription(
+ composio_client=composio_client,
+ trigger_slug=GMAIL_NEW_GMAIL_MESSAGE_TRIGGER,
+ trigger_id=trigger_id,
+ agent=agent,
+ )
+
+ # Wait forever
+ print("Waiting for events...")
+ trigger_subscription.wait_forever()
+```
+
+To test the above function as CLI, follow the steps below
+
+1. Clone the repository
+ ```bash
+ git clone [email protected]:composiohq/gmail-labeler
+ cd gmail-labeler/
+ ```
+2. Setup environment
+ ```bash
+ cp .env.example .env
+ ```
+
+ Fill the api keys
+ ```dotenv
+ COMPOSIO_API_KEY=
+ OPENAI_API_KEY=
+ ```
+
+ Create the virtual env
+ ```bash
+ make env
+ source .venv/bin/activate
+ ```
+3. Run the agent
+ ```bash
+ python gmail_labeler --user-id "default"
+ ```
+
+## Using Composio for managed auth and tools
+
+Composio reduces a lot of boilerplate for building AI agents with ability access and use a wide variety of apps. For example in this cookbook, to build `gmail` integration without composio you would have to write code to
+- manage `gmail` oauth app
+- manage user connections
+- tools for your agents to interact with `gmail`
+- Infra for listening to changes in your gmail inbox
+
+Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
+
+## Best practices
+
+**🔒 User Management**:
+
+- Use unique, consistent `user_id` values for each person
+- Each user maintains their own gmail connection
+- User IDs can be email addresses, usernames, or any unique identifier
+
+## Troubleshooting
+
+**Connection Issues**:
+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
+- Check that the user has completed `gmail` authorization
+- Verify the user_id matches exactly between requests
+
+**API Errors**:
+- Check the server logs for detailed error messages
+- Ensure request payloads match the expected format
+- Visit `/docs` endpoint for API schema validation
diff --git a/fumadocs/content/examples/hono.mdx b/fumadocs/content/examples/hono.mdx
new file mode 100644
index 000000000..c327ff2b3
--- /dev/null
+++ b/fumadocs/content/examples/hono.mdx
@@ -0,0 +1,419 @@
+---
+title: Basic Hono Server
+description: Build a simple Gmail agent with Composio and Hono.js
+---
+
+With Composio's managed authentication and tool calling, it's easy to build
+AI agents that interact with the real world while reducing boilerplate for
+setup and authentication management. This cookbook will guide you through
+building and serving agents using `Composio`, `OpenAI`, and `Hono.js`.
+
+## Prerequisites
+
+* Node.js 18.x or higher
+* npm or yarn package manager
+* Composio API key
+* OpenAI API key
+* Basic knowledge of OAuth
+* Understanding of building HTTP services (preferably using Hono.js)
+
+## Building an AI agent that can interact with `gmail` service
+
+First, let's start with building a simple AI agent embedded with tools from
+Composio that lets the agent interact with the `gmail` service.
+
+```typescript
+import { OpenAI } from 'openai';
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
+
+export async function runGmailAgent(
+ composioClient: Composio<OpenAIProvider>,
+ openaiClient: OpenAI,
+ userId: string, // Composio uses the User ID to store and access user-level authentication tokens.
+ prompt: string,
+): Promise<any[]> {
+ // Step 1: Fetch the necessary Gmail tools list with Composio
+ const tools = await composioClient.tools.get(
+ userId,
+ {
+ tools: [
+ "GMAIL_FETCH_EMAILS",
+ "GMAIL_SEND_EMAIL",
+ "GMAIL_CREATE_EMAIL_DRAFT"
+ ]
+ }
+ );
+
+ // Step 2: Use OpenAI to generate a response based on the prompt and available tools
+ const response = await openaiClient.chat.completions.create({
+ model: "gpt-4.1",
+ tools,
+ messages: [{ role: "user", content: prompt }],
+ });
+
+ // Step 3: Handle tool calls with Composio and return the result
+ const result = await composioClient.provider.handleToolCalls(
+ userId,
+ response
+ );
+ return result;
+}
+```
+
+<Callout>
+ This is a simple agent without state management and agentic loop implementation,
+ so the agent can't perform complicated tasks. If you want to understand how
+ composio can be used with agentic loops, check other cookbooks with more
+ agentic frameworks.
+</Callout>
+
+To invoke this agent, authenticate your users with Composio's managed authentication service.
+
+## Authenticating users
+
+To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
+
+To create an authentication config for `gmail` you need `client_id` and `client_secret` from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2). Once you have the credentials, use the following piece of code to set up authentication for `gmail`.
+
+```typescript
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
+
+export async function createAuthConfig(composioClient: Composio<OpenAIProvider>) {
+ /**
+ * Create a auth config for the gmail toolkit.
+ */
+ const clientId = process.env.GMAIL_CLIENT_ID;
+ const clientSecret = process.env.GMAIL_CLIENT_SECRET;
+ if (!clientId || !clientSecret) {
+ throw new Error("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set");
+ }
+
+ return composioClient.authConfigs.create(
+ "GMAIL",
+ {
+ "name": "default_gmail_auth_config",
+ "type": "use_custom_auth",
+ "authScheme": "OAUTH2",
+ "credentials": {
+ "clientId": clientId,
+ "clientSecret": clientSecret,
+ },
+ },
+ );
+}
+```
+
+This will create a Gmail authentication config to authenticate your app's users. Ideally, create one authentication object per project, so check for an existing auth config before creating a new one.
+
+```typescript
+export async function fetchAuthConfig(composioClient: Composio<OpenAIProvider>) {
+ /**
+ * Fetch the auth config for a given user id.
+ */
+ const authConfigs = await composioClient.authConfigs.list();
+ for (const authConfig of authConfigs.items) {
+ if (authConfig.toolkit.slug === "gmail") {
+ return authConfig;
+ }
+ }
+
+ return null;
+}
+```
+
+<Callout>
+ Composio platform provides composio managed authentication for some apps to
+ fast-track your development, `gmail` being one of them. You can use these
+ default auth configs for development, but for production, always use your
+ own oauth app configuration.
+</Callout>
+
+Once you have authentication management in place, we can start with connecting your users to your `gmail` app. Let's implement a function to connect users to your `gmail` app via composio.
+
+```typescript
+import { Hono } from 'hono';
+
+// Function to initiate a connected account
+export async function createConnection(composioClient: Composio<OpenAIProvider>, userId: string) {
+ /**
+ * Create a connection for a given user id and auth config id.
+ */
+ // Fetch or create the auth config for the gmail toolkit
+ let authConfig = await fetchAuthConfig(composioClient);
+ if (!authConfig) {
+ authConfig = await createAuthConfig(composioClient);
+ }
+
+ // Create a connection for the user
+ return composioClient.connectedAccounts.initiate(
+ userId,
+ authConfig.id,
+ );
+}
+
+// Setup Hono
+const app = new Hono();
+
+// Connection initiation endpoint
+app.post("/connection/create", async (c) => {
+ /**
+ * Create a connection for a given user id.
+ */
+ // For demonstration, using a default user_id. Replace with real user logic in production.
+ const userId = "default";
+
+ // Create a new connection for the user
+ const connectionRequest = await createConnection(composioClient, userId);
+ return c.json({
+ "connection_id": connectionRequest.id,
+ "redirect_url": connectionRequest.redirectUrl,
+ });
+});
+```
+
+Now, you can make a request to this endpoint on your client app, and your user will get a URL which they can use to authenticate.
+
+## Set Up Hono service
+
+We will use [`Hono.js`](https://hono.dev/) to build an HTTP service that authenticates your users and lets them interact with your agent. This guide will provide best practices for using composio client in production environments.
+
+### Setup dependencies
+
+Hono allows dependency injection patterns to simplify the usage of SDK clients that must be singletons. We recommend using composio SDK client as singleton.
+
+```typescript
+import { Composio } from '@composio/core';
+import { OpenAIProvider } from '@composio/openai';
+import { OpenAI } from 'openai';
+
+let _composioClient: Composio<OpenAIProvider> | null = null;
+
+export function provideComposioClient(): Composio<OpenAIProvider> {
+ /**
+ * Provide a Composio client.
+ */
+ if (_composioClient === null) {
+ _composioClient = new Composio({
+ provider: new OpenAIProvider()
+ });
+ }
+ return _composioClient;
+}
+
+// A Composio client dependency.
+export type ComposioClient = Composio<OpenAIProvider>;
+```
+
+Check [config/composio.ts](./src/config/composio.ts) module for more details.
+
+### Invoke agent via Hono
+
+When invoking an agent, make sure you validate the `user_id`.
+
+```typescript
+export function checkConnectedAccountExists(
+ composioClient: Composio<OpenAIProvider>,
+ userId: string,
+): Promise<boolean> {
+ /**
+ * Check if a connected account exists for a given user id.
+ */
+ // Fetch all connected accounts for the user
+ return composioClient.connectedAccounts.list({ userIds: [userId], toolkitSlugs: ["GMAIL"] }).then(connectedAccounts => {
+
+ // Check if there's an active connected account
+ for (const account of connectedAccounts.items) {
+ if (account.status === "ACTIVE") {
+ return true;
+ }
+
+ // Ideally you should not have inactive accounts, but if you do, delete them.
+ console.log(`[warning] inactive account ${account.id} found for user id: ${userId}`);
+ }
+ return false;
+ });
+}
+
+export async function validateUserId(userId: string, composioClient: ComposioClient): Promise<string> {
+ /**
+ * Validate the user id, if no connected account is found, create a new connection.
+ */
+ if (await checkConnectedAccountExists(composioClient, userId)) {
+ return userId;
+ }
+
+ throw new Error("No connected account found for the user id");
+}
+
+// Endpoint: Run the Gmail agent for a given user id and prompt
+app.post("/agent", async (c) => {
+ /**
+ * Run the Gmail agent for a given user id and prompt.
+ */
+ const request = await c.req.json();
+
+ // For demonstration, using a default user_id. Replace with real user logic in production.
+ const userId = "default";
+
+ // Validate the user id before proceeding
+ await validateUserId(userId, composioClient);
+
+ // Run the Gmail agent using Composio and OpenAI
+ const result = await runGmailAgent(
+ composioClient,
+ openaiClient,
+ userId,
+ request.prompt,
+ );
+ return c.json(result);
+});
+```
+
+<Callout>
+ Check [src/api.ts](./src/api.ts) module for service implementation
+</Callout>
+
+## Putting everything together
+
+So far, we have created an agent with ability to interact with `gmail` using the `composio` SDK, functions to manage connected accounts for users and a Hono service. Now let's run the service.
+
+<Callout>
+ Before proceeding, check the [code](./src/api.ts) for utility endpoints not discussed in the cookbook
+</Callout>
+
+1. Clone the repository
+ ```bash
+ git clone [email protected]:composiohq/composio-hono
+ cd composio-hono/
+ ```
+2. Setup environment
+
+ ```bash
+ cp .env.example .env
+ ```
+
+ Fill the api keys
+
+ ```dotenv
+ COMPOSIO_API_KEY=
+ OPENAI_API_KEY=
+ ```
+
+ Install dependencies
+
+ ```bash
+ npm install
+ ```
+3. Run the HTTP server
+ ```bash
+ npm run dev
+ ```
+
+## Testing the API with curl
+
+Assuming the server is running locally on `http://localhost:8000`.
+
+### Check if a connection exists
+
+```bash
+curl -X POST http://localhost:8000/connection/exists
+```
+
+### Create a connection
+
+Note: The body fields are required by the API schema, but are ignored internally in this example service.
+
+```bash
+curl -X POST http://localhost:8000/connection/create \
+ -H "Content-Type: application/json" \
+ -d '{
+ "user_id": "default",
+ "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
+ }'
+```
+
+Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.
+
+### Check connection status
+
+Use the `connection_id` returned from the create step.
+
+```bash
+curl -X POST http://localhost:8000/connection/status \
+ -H "Content-Type: application/json" \
+ -d '{
+ "user_id": "default",
+ "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
+ }'
+```
+
+### Run the Gmail agent
+
+Requires an active connected account for the `default` user.
+
+```bash
+curl -X POST http://localhost:8000/agent \
+ -H "Content-Type: application/json" \
+ -d '{
+ "user_id": "default",
+ "prompt": "Summarize my latest unread emails from the last 24 hours."
+ }'
+```
+
+### Fetch emails (direct action)
+
+```bash
+curl -X POST http://localhost:8000/actions/fetch_emails \
+ -H "Content-Type: application/json" \
+ -d '{
+ "user_id": "default",
+ "limit": 5
+ }'
+```
+
+These examples are intended solely for testing purposes.
+
+## Using Composio for managed auth and tools
+
+Composio reduces boilerplate for building AI agents that access and use various apps. In this cookbook, to build Gmail integration without Composio, you would have to write code to
+
+* manage Gmail OAuth app
+* manage user connections
+* tools for your agents to interact with Gmail
+
+Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.
+
+## Best practices
+
+**🎯 Effective Prompts**:
+
+* Be specific: "Send email to [[email protected]](mailto:[email protected]) about tomorrow's 2pm meeting" works better than "send email"
+* Include context: "Reply to Sarah's email about the budget with our approval"
+* Use natural language: The agent understands conversational requests
+
+**🔑 User Management**:
+
+* Use unique, consistent `user_id` values for each person
+* Each user maintains their own Gmail connection
+* User IDs can be email addresses, usernames, or any unique identifier
+
+## Troubleshooting
+
+**Connection Issues**:
+
+* Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
+* Check if the user has completed Gmail authorization.
+* Verify the user\_id matches exactly between requests
+
+**API Errors**:
+
+* Check the server logs for detailed error messages
+* Ensure request payloads match the expected format
+* Visit `/docs` endpoint for API schema validation
+
+**Gmail API Limits**:
+
+* Gmail has rate limits; the agent will handle these gracefully
+* For high-volume usage, consider implementing request queuing
\ No newline at end of file
diff --git a/fumadocs/content/examples/index.mdx b/fumadocs/content/examples/index.mdx
index e30fc862b..31bea4b1d 100644
--- a/fumadocs/content/examples/index.mdx
+++ b/fumadocs/content/examples/index.mdx
@@ -7,15 +7,19 @@ Explore practical examples of building AI agents with Composio.
## Getting Started
-- [Basic FastAPI Server](/examples/fast-api) - Build a simple API server with Composio
-- [Basic Hono Server](/examples/hono) - Build a Hono server with Composio
+- [Basic FastAPI Server](/examples/fast-api) - Build a Gmail agent with FastAPI
+- [Basic Hono Server](/examples/hono) - Build a Gmail agent with Hono.js
## Productivity & Automation
-- [Gmail Labeller](/examples/gmail-labeler) - Automatically label emails
-- [Slack Summariser](/examples/slack-summariser) - Summarize Slack conversations
-- [Supabase SQL Agent](/examples/supabase-sql-agent) - Query databases with AI
+- [Gmail Labeler](/examples/gmail-labeler) - Automatically label incoming emails using triggers
+- [Slack Summarizer](/examples/slack-summariser) - Summarize Slack channel messages
+- [Supabase SQL Agent](/examples/supabase-sql-agent) - Execute SQL queries using natural language
## Full Stack Applications
-- [Full Stack Chat App](/examples/vercel-chat) - Complete chat application example
+- [Full Stack Chat App](/examples/vercel-chat) - Build a chat interface with user connections
+
+## Behind the Curtain
+
+- [Tool Type Generator](/examples/tool-generator) - Build platforms using raw tool definitions
diff --git a/fumadocs/content/examples/meta.json b/fumadocs/content/examples/meta.json
index ca164f6da..78c2f9a5b 100644
--- a/fumadocs/content/examples/meta.json
+++ b/fumadocs/content/examples/meta.json
@@ -1,7 +1,17 @@
{
"title": "Examples",
+ "root": true,
"pages": [
"---Getting Started---",
- "index"
+ "fast-api",
+ "hono",
+ "---Productivity & Automation---",
+ "gmail-labeler",
+ "slack-summariser",
+ "supabase-sql-agent",
+ "---Full Stack Applications---",
+ "vercel-chat",
+ "---Behind the Curtain---",
+ "tool-generator"
]
}
diff --git a/fumadocs/content/examples/slack-summariser.mdx b/fumadocs/content/examples/slack-summariser.mdx
new file mode 100644
index 000000000..6480f4020
--- /dev/null
+++ b/fumadocs/content/examples/slack-summariser.mdx
@@ -0,0 +1,303 @@
+---
+title: Slack Summarizer
+description: Build an agent that summarizes Slack channel messages
+---
+
+With Composio's managed authentication and tool calling, it's easy to build the
+AI agents that can interact with the real world while reducing the boilerplate
+required to setup and manage the authentication. This cookbook will walk you through
+the process of building agents using `Composio`, `LangChain`.
+
+## Prerequisites
+
+* Python3.x
+* [UV](https://docs.astral.sh/uv/getting-started/installation/)
+* Composio API key
+* OpenAI API key
+* Understanding of building AI agents (Preferably with LangChain)
+
+## Build slack agent
+
+Let's start by building an agent that can interact with your slack workspace using Composio.
+
+```python
+from composio import Composio
+from composio_langchain import LangchainProvider
+
+from langchain import hub
+from langchain.agents import AgentExecutor, create_openai_functions_agent
+from langchain_openai import ChatOpenAI
+
+
+def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):
+ """
+ Create an agent for a given user id.
+ """
+ # Step 1: Get all the tools
+ tools = composio_client.tools.get(
+ user_id=user_id,
+ toolkits=["SLACK"],
+ )
+
+ # Step 2: Pull relevant agent prompt.
+ prompt = hub.pull("hwchase17/openai-functions-agent")
+
+ # Step 3: Initialize chat model.
+ openai_client = ChatOpenAI(model="gpt-5")
+
+ # Step 4: Define agent
+ return AgentExecutor(
+ agent=create_openai_functions_agent(
+ openai_client,
+ tools,
+ prompt,
+ ),
+ tools=tools,
+ verbose=True,
+ )
+```
+
+
+## Authenticating users
+
+To authenticate your users with Composio you need an auth config for the given
+app, In this case you need one for slack. You can create and manage auth configs
+from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=slack).
+
+Composio platform provides composio managed authentication for some apps to help
+you fast-track your development, `slack` being one of them. You can use these
+default auth configs for development, but for production you should always use
+your own oauth app configuration.
+
+Using dashboard is the preferred way of managing authentication configs, but if
+you want to do it manually you can follow the guide below
+
+<details>
+
+<summary>Click to expand</summary>
+
+---
+
+To create an authentication config for `slack` you need `client_id` and `client_secret`
+from your Slack [App](https://api.slack.com/apps). Once you have the required credentials
+you can use the following piece of code to set up authentication for `slack`.
+
+```python
+from composio import Composio
+from composio_langchain import LangchainProvider
+
+def create_auth_config(composio_client: Composio[OpenAIProvider]):
+ """
+ Create a auth config for the slack toolkit.
+ """
+ client_id = os.getenv("SLACK_CLIENT_ID")
+ client_secret = os.getenv("SLACK_CLIENT_SECRET")
+ if not client_id or not client_secret:
+ raise ValueError("SLACK_CLIENT_ID and SLACK_CLIENT_SECRET must be set")
+
+ return composio_client.auth_configs.create(
+ toolkit="SLACK",
+ options={
+ "name": "default_slack_auth_config",
+ "type": "use_custom_auth",
+ "auth_scheme": "OAUTH2",
+ "credentials": {
+ "client_id": client_id,
+ "client_secret": client_secret,
+ },
+ },
+ )
+```
+
+This will create an authentication config for `slack` which you can use to
+authenticate your users for your app. Ideally you should just create one
+authentication object per project, so check for an existing auth config
+before you create a new one.
+
+```python
+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
+ """
+ Fetch the auth config for a given user id.
+ """
+ auth_configs = composio_client.auth_configs.list()
+ for auth_config in auth_configs.items:
+ if auth_config.toolkit == "SLACK":
+ return auth_config
+
+ return None
+```
+</details>
+
+Once you have authentication management in place, we can start with connecting
+your users to your `slack` app. Let's implement a function to connect the users
+to your `slack` app via composio.
+
+```python
+
+# Function to initiate a connected account
+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
+ """
+ Create a connection for a given user id and auth config id.
+ """
+ # Fetch or create the auth config for the slack toolkit
+ auth_config = fetch_auth_config(composio_client=composio_client)
+ if not auth_config:
+ auth_config = create_auth_config(composio_client=composio_client)
+
+ # Create a connection for the user
+ return composio_client.connected_accounts.initiate(
+ user_id=user_id,
+ auth_config_id=auth_config.id,
+ )
+```
+
+Now, when creating tools for your agent always check if the user already has a
+connected account before creating a new one.
+
+```python
+def check_connected_account_exists(
+ composio_client: Composio[LangchainProvider],
+ user_id: str,
+):
+ """
+ Check if a connected account exists for a given user id.
+ """
+ # Fetch all connected accounts for the user
+ connected_accounts = composio_client.connected_accounts.list(
+ user_ids=[user_id],
+ toolkit_slugs=["SLACK"],
+ )
+
+ # Check if there's an active connected account
+ for account in connected_accounts.items:
+ if account.status == "ACTIVE":
+ return True
+
+ # Ideally you should not have inactive accounts, but if you do, you should delete them
+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")
+ return False
+```
+
+## Modifiers
+
+In the current setup, we are expanding too much unnecessary tokens because response
+from `SLACK_FETCH_CONVERSATION_HISTORY` tool call contains too much unnecessary
+information. This can be fixed using `after_execute` modifier. An after execute
+modifier is called after a tool execution is complete, here you can process
+and modify the response object to make it more easy to consume for your agent.
+
+```python
+from composio import after_execute
+from composio.types import ToolExecutionResponse
+
+
+@after_execute(tools=["SLACK_FETCH_CONVERSATION_HISTORY"])
+def clean_conversation_history(
+ tool: str,
+ toolkit: str,
+ response: ToolExecutionResponse,
+) -> ToolExecutionResponse:
+ """
+ Clean the conversation history.
+ """
+ if not response["data"]["ok"]:
+ return response
+
+ try:
+ response["data"]["messages"] = [
+ {"user": message["user"], "text": message["text"]}
+ for message in response["data"]["messages"]
+ if message["type"] == "message"
+ ]
+ except KeyError:
+ pass
+
+ return response
+```
+
+To register modifiers, include them in the `composio.tools.get` call.
+
+```python
+tools = composio_client.tools.get(
+ user_id=user_id,
+ toolkits=[SLACK_TOOLKIT],
+ modifiers=[clean_conversation_history],
+)
+```
+
+## Putting everything together
+
+So far, we have created an agent with ability to interact with your `slack`
+workspace using the `composio` SDK, functions to manage connected accounts
+for users and a simple agent runner. Let's package this as a CLI tool.
+
+```python
+def run_agent(user_id: str, prompt: str):
+ composio_client = Composio(provider=LangchainProvider())
+ if not check_connected_account_exists(composio_client, user_id):
+ connection_request = create_connection(composio_client, user_id)
+ print(
+ f"Authenticate with the following link: {connection_request.redirect_url}"
+ )
+ connection_request.wait_for_connection()
+
+ agent = create_agent(user_id, composio_client)
+ agent.invoke({"input": prompt})
+```
+
+To test the above function as CLI, follow the steps below
+
+1. Clone the repository
+ ```bash
+ git clone [email protected]:composiohq/slack-summarizer
+ cd slack-summarizer/
+ ```
+2. Setup environment
+ ```bash
+ cp .env.example .env
+ ```
+
+ Fill the api keys
+ ```dotenv
+ COMPOSIO_API_KEY=
+ OPENAI_API_KEY=
+ ```
+
+ Create the virtual env
+ ```bash
+ make env
+ source .venv/bin/activate
+ ```
+3. Run the agent
+ ```bash
+ python slack_summariser --user-id "default" --prompt "summarise last 5 messages from #general channel"
+ ```
+
+## Using Composio for managed auth and tools
+
+Composio reduces a lot of boilerplate for building AI agents with ability access and use a wide variety of apps. For example in this cookbook, to build `slack` integration without composio you would have to write code to
+- manage `slack` oauth app
+- manage user connections
+- tools for your agents to interact with `slack`
+
+Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
+
+## Best practices
+
+**🔒 User Management**:
+
+- Use unique, consistent `user_id` values for each person
+- Each user maintains their own slack connection
+- User IDs can be email addresses, usernames, or any unique identifier
+
+## Troubleshooting
+
+**Connection Issues**:
+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
+- Check that the user has completed `slack` authorization
+- Verify the user_id matches exactly between requests
+
+**API Errors**:
+- Check the server logs for detailed error messages
+- Ensure request payloads match the expected format
+- Visit `/docs` endpoint for API schema validation
diff --git a/fumadocs/content/examples/supabase-sql-agent.mdx b/fumadocs/content/examples/supabase-sql-agent.mdx
new file mode 100644
index 000000000..1da4ad390
--- /dev/null
+++ b/fumadocs/content/examples/supabase-sql-agent.mdx
@@ -0,0 +1,254 @@
+---
+title: Supabase SQL Agent
+description: Build an agent that executes SQL queries on Supabase using natural language
+---
+
+With Composio's managed authentication and tool calling, it's easy to build
+AI agents that interact with the real world while reducing boilerplate for
+setup and authentication management. This guide will walk you through using
+the Supabase CLI agent built with `Composio` and `LlamaIndex`.
+
+
+## Requirements
+
+* Python 3.10+
+* [UV](https://docs.astral.sh/uv/getting-started/installation/) (recommended) or pip
+* Composio API key
+* OpenAI API key
+* Understanding of building AI agents (Preferably with LlamaIndex)
+
+## Build an agent to perform Supabase tasks
+
+```python
+from composio import Composio
+from composio_llamaindex import LlamaIndexProvider
+
+from llama_index.llms.openai import OpenAI
+from llama_index.core.agent.workflow import FunctionAgent
+from llama_index.core.workflow import Context
+
+
+def create_agent(user_id: str, composio_client: Composio[LlamaIndexProvider]):
+ """
+ Create a function agent that can perform Supabase tasks.
+ """
+
+ # Setup client
+ llm = OpenAI(model="gpt-5")
+
+ # Get All the tools
+ tools = composio_client.tools.get(
+ user_id=user_id,
+ tools=[
+ "SUPABASE_LIST_ALL_PROJECTS",
+ "SUPABASE_BETA_RUN_SQL_QUERY",
+ ],
+ )
+
+ agent = FunctionAgent(
+ tools=tools,
+ llm=llm,
+ system_prompt=(
+ "You are a helpful assistant that can help with supabase queries."
+ ),
+ )
+
+ # Since this is a continuosly running agent, we need to maintain state across
+ # different user messages
+ ctx = Context(workflow=agent)
+ return agent, ctx
+```
+
+This agent can convert your natural language queries to SQL queries and execute
+them on supabase for you. For you agent to be able to execute queries, you need
+to authenticate the agent for supabase.
+
+
+## Authenticating users
+
+To authenticate your users with Composio you need an auth config for the given
+app, In this case you need one for supabase. You can create and manage auth configs
+from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=supabase).
+Composio platform provides composio managed authentication for some apps to help
+you fast-track your development, `supabase` being one of them. You can use these
+default auth configs for development, but for production you should always use
+your own oauth app configuration.
+
+Using dashboard is the preferred way of managing authentication configs, but if
+you want to do it manually you can follow the guide below
+
+<details>
+
+<summary>Click to expand</summary>
+
+---
+
+To create an authentication config for `supabase` you need `client_id` and `client_secret`
+from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).
+Once you have the required credentials you can use the following piece of
+code to set up authentication for `supabase`.
+
+```python
+from composio import Composio
+from composio_langchain import LangchainProvider
+
+def create_auth_config(composio_client: Composio[OpenAIProvider]):
+ """
+ Create a auth config for the supabase toolkit.
+ """
+ client_id = os.getenv("SUPABASE_CLIENT_ID")
+ client_secret = os.getenv("SUPABASE_CLIENT_SECRET")
+ if not client_id or not client_secret:
+ raise ValueError("SUPABASE_CLIENT_ID and SUPABASE_CLIENT_SECRET must be set")
+
+ return composio_client.auth_configs.create(
+ toolkit="supabase",
+ options={
+ "name": "default_supabase_auth_config",
+ "type": "use_custom_auth",
+ "auth_scheme": "OAUTH2",
+ "credentials": {
+ "client_id": client_id,
+ "client_secret": client_secret,
+ },
+ },
+ )
+```
+
+This will create an authentication config for `supabase` which you can use to
+authenticate your users for your app. Ideally you should just create one
+authentication object per project, so check for an existing auth config
+before you create a new one.
+
+```python
+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
+ """
+ Fetch the auth config for a given user id.
+ """
+ auth_configs = composio_client.auth_configs.list()
+ for auth_config in auth_configs.items:
+ if auth_config.toolkit == "supabase":
+ return auth_config
+
+ return None
+```
+</details>
+
+Once you have authentication management in place, we can start with connecting
+your users to your `supabase` app. Let's implement a function to connect the users
+to your `supabase` app via composio.
+
+```python
+# Function to initiate a connected account
+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
+ """
+ Create a connection for a given user id and auth config id.
+ """
+ # Fetch or create the auth config for the supabase toolkit
+ auth_config = fetch_auth_config(composio_client=composio_client)
+ if not auth_config:
+ auth_config = create_auth_config(composio_client=composio_client)
+
+ # Create a connection for the user
+ return composio_client.connected_accounts.initiate(
+ user_id=user_id,
+ auth_config_id=auth_config.id,
+ )
+```
+
+Now, when creating tools for your agent always check if the user already has a
+connected account before creating a new one.
+
+```python
+def check_connected_account_exists(
+ composio_client: Composio[LangchainProvider],
+ user_id: str,
+):
+ """
+ Check if a connected account exists for a given user id.
+ """
+ # Fetch all connected accounts for the user
+ connected_accounts = composio_client.connected_accounts.list(
+ user_ids=[user_id],
+ toolkit_slugs=["SUPABASE"],
+ )
+
+ # Check if there's an active connected account
+ for account in connected_accounts.items:
+ if account.status == "ACTIVE":
+ return True
+
+ # Ideally you should not have inactive accounts, but if you do, you should delete them
+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")
+ return False
+```
+
+
+## Create a chat loop
+
+```python
+async def run_loop(user_id: str):
+ # Initialize composio client.
+ composio_client = Composio(provider=LlamaIndexProvider())
+
+ # Setup connection if required
+ if not check_connected_account_exists(
+ composio_client=composio_client,
+ user_id=user_id,
+ ):
+ connection_request = create_connection(
+ composio_client=composio_client,
+ user_id=user_id,
+ )
+ print(
+ f"Authenticate with the following link: {connection_request.redirect_url}"
+ )
+
+ # Create agent
+ agent, ctx = create_agent(
+ user_id=user_id,
+ composio_client=composio_client,
+ )
+
+ # Run a simple REPL loop
+ while True:
+ user_input = input("user > ")
+ if user_input.lower() == "exit":
+ break
+
+ result = await agent.run(user_msg=user_input, ctx=ctx)
+ print("agent > ", result)
+ print("Exiting...")
+```
+
+## Using Composio for managed auth and tools
+
+Composio reduces a lot of boilerplate for building AI agents with ability access
+and use a wide variety of apps. For example in this cookbook, to build `supabase`
+integration without composio you would have to write code to
+
+- manage `supabase` oauth app
+- manage user connections
+- tools for your agents to interact with `supabase`
+
+Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
+
+## Best practices
+
+**🔒 User Management**:
+
+- Use unique, consistent `user_id` values for each person
+- Each user maintains their own supabase connection
+- User IDs can be email addresses, usernames, or any unique identifier
+
+## Troubleshooting
+
+**Connection Issues**:
+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
+- Check that the user has completed `supabase` authorization
+- Verify the user_id matches exactly between requests
+
+**API Errors**:
+- Check the server logs for detailed error messages
+- Ensure request payloads match the expected format
+- Visit `/docs` endpoint for API schema validation
diff --git a/fumadocs/content/examples/tool-generator.mdx b/fumadocs/content/examples/tool-generator.mdx
new file mode 100644
index 000000000..fee1feb0e
--- /dev/null
+++ b/fumadocs/content/examples/tool-generator.mdx
@@ -0,0 +1,273 @@
+---
+title: Tool Type Generator
+description: Build your own platform using raw tool definitions
+---
+
+This is a bit of a checky tutorial as it is dogfooding the `docs` tool generation process.
+
+To motivate this example clearly, in our tools section — we have details about let's say [`Github`](/tools/github) tool, that shows its auth scheme, actions and their params.
+
+Now why would anyone outside of Composio want to do this? Well if you are building a platform on top of Composio, perchance a Workflow builder like langflow. You would want to show some or all of this information to your users.
+
+This is a non standard use case, that we support and love users building on top of us but if this is uninteresting to you, you can skip this tutorial.
+
+## How does one build a tool type generator?
+
+In composio, we have two internal states for tools
+
+1. Raw tool definition
+2. Provider tool definition
+
+The raw tool definition is an generic input output schema definition that we internally for tools, we expose it for customers if they want to build on top of it but it is not the primary way tools are normally used.
+
+The provider tool definition, translates this raw tool definition to the specific schema of a provider (by default `openai`).
+
+For building something like this, we need to use the raw tool definition.
+
+
+## Getting the raw tool definition
+
+Of course, you need to initiate the `Composio` sdk first and use a `COMPOSIO_API_KEY` environment variable.
+
+
+```python Python {2} title="tool_doc_generator/main.py" maxLines=40 wordWrap
+
+ def __init__(self, include_local: bool = False):
+ """
+```
+
+
+Let us see an example output for a raw `GMAIL` toolkit, with all of its tools.
+
+this is just a taste but you can see the full output [here](https://github.com/composio-dev/composio/blob/next/fern/pages/src/examples/tool-generator/output.json).
+
+```json JSON title="output.json" maxLines=40
+[
+ {
+ "deprecated": {
+ "available_versions": [
+ "0_1",
+ "latest",
+ "latest:base"
+ ],
+ "display_name": "Modify email labels",
+ "is_deprecated": false,
+ "toolkit": {
+ "logo": "https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/gmail.svg"
+ },
+ "version": "0_1",
+ "displayName": "Modify email labels"
+ },
+ "description": "Adds and/or removes specified gmail labels for a message; ensure `message id` and all `label ids` are valid (use 'listlabels' for custom label ids).",
+ "input_parameters": {
+ "properties": {
+ "add_label_ids": {
+ "default": [],
+ "description": "Label IDs to add. For custom labels, obtain IDs via 'listLabels'. System labels (e.g., 'INBOX', 'SPAM') can also be used.",
+ "examples": [
+ "STARRED",
+ "IMPORTANT",
+ "Label_123"
+ ],
+ "items": {
+ "type": "string"
+ },
+ "title": "Add Label Ids",
+ "type": "array"
+ },
+ "message_id": {
+ "description": "Immutable ID of the message to modify (e.g., from 'fetchEmails' or 'fetchMessagesByThreadId').",
+ "examples": [
+ "17f1b2b9c1b2a3d4"
+ ],
+ "title": "Message Id",
+ "type": "string"
+ },
+ "remove_label_ids": {
+ "default": [],
+ "description": "Label IDs to remove. For custom labels, obtain IDs via 'listLabels'. System labels can also be used.",
+ "examples": [
+ "UNREAD",
+ "Label_456"
+ ],
+ "items": {
+ "type": "string"
+ },
+ "title": "Remove Label Ids",
+ "type": "array"
+ },
+ "user_id": {
+ "default": "me",
+ "description": "User's email address or 'me' for the authenticated user.",
+ "examples": [
+ "me",
+ ],
+ "title": "User Id",
+ "type": "string"
+ }
+ },
+ "required": [
+ "message_id"
+ ],
+ "title": "AddLabelToEmailRequest",
+ "type": "object"
+ },
+ "name": "Modify email labels",
+ "no_auth": false,
+ "output_parameters": {
+ "properties": {
+ "data": {
+ "description": "Data from the action execution",
+ "properties": {
+ "response_data": {
+ "description": "Full `Message` resource with updated labels.",
+ "title": "Response Data",
+ "type": "object"
+ }
+ },
+ "required": [
+ "response_data"
+ ],
+ "title": "Data",
+ "type": "object"
+ },
+ "error": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "default": null,
+```
+
+```sh
+jq '.[0] | keys' pages/src/examples/tool-generator/output.json
+[
+ "available_versions",
+ "deprecated",
+ "description",
+ "input_parameters",
+ "name",
+ "no_auth",
+ "output_parameters",
+ "scopes",
+ "slug",
+ "tags",
+ "toolkit",
+ "version"
+]
+```
+
+There is a bunch of useful information here, around the `input_parameters` and `output_parameters` for this example but `scopes` is very valuable to know what permissions are required for this tool.
+
+Now from these `input_parameters` and `output_parameters` you can showcase the tool definitions.
+
+
+```python Python title="tool_doc_generator/main.py" maxLines=40
+ fields = []
+ _, field_config = field
+
+ for field_list, required in [
+ (getattr(field_config, "required", []), True),
+ (getattr(field_config, "optional", []), False),
+ ]:
+ for f in field_list:
+ if hasattr(f, "name"):
+ fields.append(self._create_param_from_field(f, required))
+```
+
+There is a bunch of other processing things happening here that are super generally relevant, so not going to call them out here that said there is another thing i want to showcase
+
+## Toolkit Information
+
+Toolkis are what we call apps or integrations, for us they are a collection of tools. `GMAIL` has `GMAIL_SEND_EMAIL` as a tool.
+
+Now for building something out like this, you might also want information about the toolkit itself.
+
+A toolkit has information like `categories` or `auth_schemes`
+
+```python Python title="tool_doc_generator/main.py" maxLines=40
+ """
+ Initialize the tool documentation generator.
+
+ Args:
+```
+
+`auth_schemes` here are `OAUTH2`, `API_KEY` or `BASIC_AUTH`, etc — essentially the types of how one could authenticate with the toolkit.
+
+```python Python title="tool_doc_generator/main.py" maxLines=40
+ # Initialize composio client
+ self.composio = Composio()
+ self.include_local = include_local
+
+ # For tracking generated tools
+ self.generated_tools = []
+ self.problematic_actions = []
+
+ def generate_docs(
+ self, output_path: Path, max_workers: int | None = None, limit: int | None = None
+```
+
+Here is a way to parse the `auth_scheme` data
+
+
+these are `tuple` objects as they have different schema for specific conditions like `auth_config_creation` or `connected_account_initiation`
+
+they also have `required` and `optional` fields.
+
+the context here is there are some fields you need while creating an auth config and some you need while connecting an account. this separation is done by the `tuple` here
+
+```python Python title="tool_doc_generator/main.py" maxLines=40
+ auth_schemes: t.Optional[t.List[toolkit_retrieve_response.AuthConfigDetail]] = None,
+ ) -> None:
+ schemes = ", ".join(
+ self._get_auth_type(s) for s in (auth_schemes or []) if self._extract_auth_fields(s)
+ )
+ self._blocks.extend(
+ [
+ f"""## Connecting to {app_name}
+### Create an auth config
+Use the dashboard to create an auth config for the {app_name} toolkit. This allows you to connect multiple {app_name} accounts to Composio for agents to use.
+
+<Steps>
+ <Step title="Select App">
+ Navigate to **[{app_name}](https://platform.composio.dev?next_page=/marketplace/{app_name})**.
+ </Step>
+ <Step title="Configure Auth Config Settings">
+ Select among the supported auth schemes of and configure them here.
+ </Step>
+ <Step title="Create and Get auth config ID">
+ Click **"Create {app_name} Auth Config"**. After creation, **copy the displayed ID starting with `ac_`**. This is your auth config ID. This is _not_ a sensitive ID -- you can save it in environment variables or a database.
+ **This ID will be used to create connections to the toolkit for a given user.**
+ </Step>
+</Steps>
+"""
+ ],
+ )
+
+ # Add auth code snippets
+ self._add_auth_section(app_name, app_slug, auth_schemes)
+
+ def _add_auth_section(
+ self,
+ app_name: str,
+ app_slug: str,
+ auth_schemes: t.List[toolkit_retrieve_response.AuthConfigDetail] = None,
+ ) -> None:
+ """Add code snippets for each auth scheme using direct template processing"""
+ if not auth_schemes:
+ return
+
+ self._blocks.append("### Connect Your Account")
+
+ # Group auth schemes by type to avoid duplicates
+ seen_auth_types = set()
+
+```
+
+
+This is a fairly minimal explanation for the amount of code, as most of it is not super related to composio but it will be a good example on seeing behind the scenes of how composio is working and how to leverage the platform further.
\ No newline at end of file
diff --git a/fumadocs/content/examples/vercel-chat.mdx b/fumadocs/content/examples/vercel-chat.mdx
new file mode 100644
index 000000000..a7c7a67b1
--- /dev/null
+++ b/fumadocs/content/examples/vercel-chat.mdx
@@ -0,0 +1,297 @@
+---
+title: Full Stack Chat App
+description: Build a chat interface where users can connect and use their own apps
+---
+
+In this example, you will learn how to build a chatbot that:
+
+- Lets users connect their various apps to the chatbot using the Composio SDK.
+- Uses the Vercel provider in the Composio SDK to handle and execute tool calls from the LLM.
+
+This page gives a high-level overview of the Composio SDK and how it is used in the
+GitHub repository: [composiohq/chat](https://github.com/composiohq/chat). You can
+find the demo live [here](https://chat.composio.dev/).
+
+## Prerequisites
+
+Ensure you've followed the README.md in the [composiohq/chat](https://github.com/composiohq/chat)
+repository to set up the project locally.
+
+## Creating auth configs
+
+For all the apps you want to connect to the chatbot, you need to create their
+respective auth configs. Learn how to create auth configs [here](/docs/authenticating-tools#creating-an-auth-config).
+Once done, your auth configs will be available in the [Composio dashboard](https://app.composio.dev/integrations).
+
+
+ <img src="../../../../assets/images/examples/auth-configs.png" alt="Auth configs" />
+
+
+### Save auth config IDs to environment variables
+
+For this project, the auth config IDs should be saved to the environment variables
+with the `NEXT_PUBLIC_` prefix.
+
+```bash .env.local
+NEXT_PUBLIC_GMAIL_AUTH_CONFIG_ID=ac_1234567890
+NEXT_PUBLIC_GITHUB_AUTH_CONFIG_ID=ac_1234567890
+```
+
+## Create a Composio client instance
+
+We create a Composio client instance for server-side operations like API routes,
+server components, etc.
+
+```typescript lib/service/composio.ts
+import { Composio } from '@composio/core';
+import { VercelProvider } from '@composio/vercel';
+
+const composio = new Composio({
+ apiKey: process.env.COMPOSIO_API_KEY,
+ provider: new VercelProvider(),
+});
+
+export default composio;
+```
+
+## Creating an API for fetching toolkits
+
+The Composio SDK is meant to be used only in server-side code. For client-side
+functionality, we create API endpoints in the `/app/api/` directory. In order to
+list the toolkits and their connection status, we create a Next.js API route to
+fetch the toolkits using Composio SDK.
+
+
+ <img src="../../../../assets/images/examples/toolkits.png" />
+
+
+### 1. Listing connected accounts
+
+First, we fetch all connected accounts for a user and create a mapping of toolkit
+slugs to their connection IDs:
+
+```typescript app/api/composio/toolkits.ts
+export async function GET() {
+ // ... auth logic ...
+
+ // List connected accounts to get connection IDs for each toolkit
+ const connectedAccounts = await composio.connectedAccounts.list({
+ userIds: [session.user.id],
+ });
+
+ const connectedToolkitMap = new Map();
+ connectedAccounts.items.forEach(account => {
+ connectedToolkitMap.set(account.toolkit.slug.toUpperCase(), account.id);
+ });
+
+ // ... continue with toolkit fetching ...
+}
+```
+
+### 2. Fetching toolkit data and building response
+
+Next, we fetch toolkit information for each supported toolkit and combine it with the connection status:
+
+```typescript app/api/composio/toolkits.ts
+export async function GET() {
+ // ... auth logic ...
+ // ... connected accounts mapping ...
+
+ const SUPPORTED_TOOLKITS = ['GMAIL', 'GOOGLECALENDAR', 'GITHUB', 'NOTION'];
+
+ // Fetch toolkit data from slugs
+ const toolkitPromises = SUPPORTED_TOOLKITS.map(async slug => {
+ const toolkit = await composio.toolkits.get(slug);
+ const connectionId = connectedToolkitMap.get(slug.toUpperCase());
+
+ return {
+ name: toolkit.name,
+ slug: toolkit.slug,
+ description: toolkit.meta?.description,
+ logo: toolkit.meta?.logo,
+ categories: toolkit.meta?.categories,
+ isConnected: !!connectionId,
+ connectionId: connectionId || undefined,
+ };
+ });
+
+ const toolkits = await Promise.all(toolkitPromises);
+ return NextResponse.json({ toolkits });
+}
+```
+
+## Managing connections
+
+Users need to connect and disconnect their accounts from the chatbot to enable tool usage. When users click "Connect" on a toolkit, we initiate an OAuth flow, and when they click "Disconnect", we remove their connection.
+
+### 1. Initiating a connection
+
+When a user wants to connect their account, we create a connection request that redirects them to the OAuth provider:
+
+
+ <img src="../../../../assets/images/examples/create-connection.png" />
+
+
+```typescript app/api/connections/initiate/route.ts
+export async function POST(request: Request) {
+ // ... auth and validation ...
+
+ const { authConfigId } = requestBody;
+
+ // Initiate connection with Composio
+ const connectionRequest = await composio.connectedAccounts.initiate(
+ session.user.id,
+ authConfigId
+ );
+
+ return NextResponse.json({
+ redirectUrl: connectionRequest.redirectUrl,
+ connectionId: connectionRequest.id,
+ });
+}
+```
+
+### 2. Checking connection status
+
+After initiating a connection, we need to wait for the OAuth flow to complete. We check the connection status to know when it's ready to use:
+
+
+ <img src="../../../../assets/images/examples/connection-status.png" />
+
+
+```typescript app/api/connections/status/route.ts
+export async function GET(request: Request) {
+ // ... auth and validation ...
+
+ const connectionId = searchParams.get('connectionId');
+
+ // Wait for connection to complete
+ const connection = await composio.connectedAccounts.waitForConnection(connectionId);
+
+ return NextResponse.json({
+ id: connection.id,
+ status: connection.status,
+ authConfig: connection.authConfig,
+ data: connection.data,
+ });
+}
+```
+
+### 3. Deleting a connection
+
+When a user wants to disconnect their account, we remove the connection using the connection ID:
+
+```typescript app/api/connections/delete/route.ts
+export async function DELETE(request: Request) {
+ // ... auth and validation ...
+
+ const connectionId = searchParams.get('connectionId');
+
+ // Delete the connection
+ await composio.connectedAccounts.delete(connectionId);
+
+ return NextResponse.json({
+ success: true,
+ message: 'Connection deleted successfully',
+ });
+}
+```
+
+## Working with tools
+
+Once users have connected their accounts, we need to track which toolkits are enabled and fetch the corresponding tools for the LLM.
+
+### 1. Tracking enabled toolkits
+
+We keep track of which toolkits the user has enabled in the chat interface:
+
+```typescript components/chat.tsx
+const { ... } = useChat({
+ // ... other config ...
+ experimental_prepareRequestBody: (body) => {
+ // Get current toolbar state
+ const currentToolbarState = toolbarStateRef.current;
+ const enabledToolkits = Array.from(
+ currentToolbarState.enabledToolkitsWithStatus.entries(),
+ ).map(([slug, isConnected]) => ({ slug, isConnected }));
+
+ return {
+ // ... other fields ...
+ enabledToolkits,
+ };
+ },
+ // ... other handlers ...
+ });
+```
+
+### 2. Fetching tools for enabled toolkits
+
+We fetch Composio tools based on the enabled toolkit slugs:
+
+```typescript lib/ai/tools/composio.ts
+export async function getComposioTools(userId: string, toolkitSlugs: string[]) {
+ // ... validation ...
+
+ const tools = await composio.tools.get(userId, {
+ toolkits: toolkitSlugs,
+ });
+ return tools || {};
+}
+```
+
+```typescript app/api/chat.ts
+export async function POST(request: Request) {
+ // ... auth and parsing ...
+
+ const toolkitSlugs = enabledToolkits?.map(t => t.slug) || [];
+
+ const composioTools = await getComposioTools(session.user.id, toolkitSlugs);
+
+ const result = streamText({
+ // ... model config ...
+ tools: {
+ ...composioTools,
+ },
+ });
+}
+```
+
+## Bonus: Creating custom component to show tool calls
+
+By default, tool calls appear as raw JSON in the chat interface. To create a better user experience, we can build custom components that display tool calls with proper formatting and loading states.
+
+
+ <img src="../../../../assets/images/examples/custom-tool-component.png" />
+
+
+You can find the `ToolCall` component at `components/tool-call.tsx`. Here's how to integrate it into your message rendering:
+
+```typescript components/messages.tsx
+if (type === 'tool-invocation') {
+ const { toolInvocation } = part;
+ const { toolName, toolCallId, state, args, result } = toolInvocation;
+
+ if (state === 'call') {
+ return (
+ <ToolCall
+ key={toolCallId}
+ toolName={toolName}
+ args={args}
+ isLoading={true}
+ />
+ );
+ }
+
+ if (state === 'result') {
+ return (
+ <ToolCall
+ key={toolCallId}
+ toolName={toolName}
+ args={args}
+ result={result}
+ isLoading={false}
+ />
+ );
+ }
+}
+```