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.

docs: rewrite cookbooks to use include regions, add slack summarizer

Sushmitha Mallesh84f324f036f9
diff --git a/docs/content/cookbooks/fast-api.mdx b/docs/content/cookbooks/fast-api.mdx
index 3b37ece2e..cd40b5c0c 100644
--- a/docs/content/cookbooks/fast-api.mdx
+++ b/docs/content/cookbooks/fast-api.mdx
@@ -3,7 +3,7 @@ title: Basic FastAPI Server
description: Build an AI agent with access to 1000+ tools using Composio and FastAPI
---
-[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/example/fast-api)
+[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/fast-api)
This cookbook builds a FastAPI server where users can chat with an AI agent that has access to over 1000 tools like Gmail, GitHub, Slack, Notion, and more. Along the way we'll add endpoints to manage which apps a user has connected.
@@ -34,17 +34,7 @@ OPENAI_API_KEY=your_openai_api_key
`Composio` takes an `OpenAIAgentsProvider` so that when we ask for tools later, they come back in the format the OpenAI Agents SDK expects.
-```python
-from agents import Agent, Runner
-from composio import Composio
-from composio_openai_agents import OpenAIAgentsProvider
-from fastapi import FastAPI
-from pydantic import BaseModel
-
-composio = Composio(provider=OpenAIAgentsProvider())
-
-app = FastAPI()
-```
+<include>../../examples/fast-api/main.py#setup</include>
## Chat endpoint
@@ -52,26 +42,7 @@ The core of the server is a `/chat` endpoint. A user sends a message, and the ag
`composio.create()` creates a **session** scoped to a user. Calling `session.tools()` returns a set of meta tools that let the agent discover tools across all apps, handle OAuth when needed, and execute actions. We pass these to an `Agent` and let `Runner.run_sync` handle the agentic loop.
-```python
-class ChatRequest(BaseModel):
- user_id: str
- message: str
-
-
-def chat(request: ChatRequest):
- session = composio.create(user_id=request.user_id)
- tools = session.tools()
-
- agent = Agent(
- name="Assistant",
- instructions="You are a helpful assistant. Use tools to help the user.",
- tools=tools,
- )
-
- result = Runner.run_sync(starting_agent=agent, input=request.message)
- return {"response": result.final_output}
-```
+<include>../../examples/fast-api/main.py#chat</include>
<Callout>
If the user hasn't connected the app they're trying to use, the agent will automatically
@@ -84,51 +55,23 @@ That's a working agent. But in most apps you'll also want to manage connections
`session.toolkits()` returns every toolkit in the session along with its connection status. We can expose this as a simple GET endpoint so your frontend can render a connections UI.
-```python
[email protected]("/connections/{user_id}")
-def list_connections(user_id: str):
- session = composio.create(user_id=user_id)
- toolkits = session.toolkits()
- return [
- {"toolkit": t.slug, "connected": t.connection.is_active if t.connection else False}
- for t in toolkits.items
- ]
-```
+<include>../../examples/fast-api/main.py#list-connections</include>
If you just need to check a single toolkit, say before kicking off a workflow that requires Gmail, you can scope the session to that toolkit:
-```python
[email protected]("/connections/{user_id}/{toolkit}")
-def check_connection(user_id: str, toolkit: str):
- session = composio.create(user_id=user_id, toolkits=[toolkit])
- toolkits = session.toolkits()
- for t in toolkits.items:
- if t.slug == toolkit:
- return {"toolkit": toolkit, "connected": t.connection.is_active if t.connection else False}
- return {"toolkit": toolkit, "connected": False}
-```
+<include>../../examples/fast-api/main.py#check-connection</include>
## Connecting an app
When a user wants to connect a new app, `session.authorize()` starts the OAuth flow and returns a redirect URL. Your frontend sends the user there, and once they complete auth, they're connected.
-```python
-class ConnectRequest(BaseModel):
- user_id: str
-
-
[email protected]("/connect/{toolkit}")
-def connect_toolkit(toolkit: str, request: ConnectRequest):
- session = composio.create(user_id=request.user_id, toolkits=[toolkit])
- connection_request = session.authorize(toolkit)
- return {"redirect_url": connection_request.redirect_url}
-```
+<include>../../examples/fast-api/main.py#connect</include>
## Complete app
Here's everything together:
-<include>../../example/fast-api/main.py</include>
+<include>../../examples/fast-api/main.py</include>
## Running the server
diff --git a/docs/content/cookbooks/hono.mdx b/docs/content/cookbooks/hono.mdx
index df6ef1074..39b9e56d5 100644
--- a/docs/content/cookbooks/hono.mdx
+++ b/docs/content/cookbooks/hono.mdx
@@ -34,17 +34,7 @@ OPENAI_API_KEY=your_openai_api_key
`Composio` takes an `OpenAIProvider` so that when we ask for tools later, they come back in the format OpenAI expects.
-```typescript
-import { Hono } from 'hono';
-import { OpenAI } from 'openai';
-import { Composio } from '@composio/core';
-import { OpenAIProvider } from '@composio/openai';
-
-const composio = new Composio({ provider: new OpenAIProvider() });
-const openai = new OpenAI();
-
-const app = new Hono();
-```
+<include meta="no-twoslash">../../examples/hono/server.ts#setup</include>
## Chat endpoint
@@ -52,45 +42,7 @@ The core of the server is a `/chat` endpoint. A user sends a message, and the ag
`composio.create()` creates a **session** scoped to a user. Calling `session.tools()` returns a set of meta tools that let the agent discover tools across all apps, handle OAuth when needed, and execute actions. We pass these to OpenAI and loop until the model stops calling tools.
-```typescript
-import { Hono } from 'hono';
-import { OpenAI } from 'openai';
-import { Composio } from '@composio/core';
-import { OpenAIProvider } from '@composio/openai';
-
-declare const composio: Composio<OpenAIProvider>;
-declare const openai: OpenAI;
-const app = new Hono();
-// ---cut---
-app.post("/chat", async (c) => {
- const { userId, message } = await c.req.json();
-
- const session = await composio.create(userId);
- const tools = await session.tools();
-
- const messages: OpenAI.ChatCompletionMessageParam[] = [
- { role: "system", content: "You are a helpful assistant. Use tools to help the user." },
- { role: "user", content: message },
- ];
-
- while (true) {
- const response = await openai.chat.completions.create({
- model: "gpt-4.1",
- tools,
- messages,
- });
-
- const choice = response.choices[0];
- if (!choice.message.tool_calls?.length) {
- return c.json({ response: choice.message.content });
- }
-
- messages.push(choice.message);
- const toolResults = await composio.provider.handleToolCalls(userId, response);
- messages.push(...toolResults);
- }
-});
-```
+<include meta="no-twoslash">../../examples/hono/server.ts#chat</include>
<Callout>
If the user hasn't connected the app they're trying to use, the agent will automatically
@@ -103,73 +55,17 @@ That's a working agent. But in most apps you'll also want to manage connections
`session.toolkits()` returns every toolkit in the session along with its connection status. We can expose this as a simple GET endpoint so your frontend can render a connections UI.
-```typescript
-import { Hono } from 'hono';
-import { Composio } from '@composio/core';
-import { OpenAIProvider } from '@composio/openai';
-
-declare const composio: Composio<OpenAIProvider>;
-const app = new Hono();
-// ---cut---
-app.get("/connections/:userId", async (c) => {
- const userId = c.req.param("userId");
-
- const session = await composio.create(userId);
- const toolkits = await session.toolkits();
-
- return c.json(
- toolkits.items.map((t) => ({
- toolkit: t.slug,
- connected: t.connection?.isActive ?? false,
- }))
- );
-});
-```
+<include meta="no-twoslash">../../examples/hono/server.ts#list-connections</include>
If you just need to check a single toolkit, say before kicking off a workflow that requires Gmail, you can scope the session to that toolkit:
-```typescript
-import { Hono } from 'hono';
-import { Composio } from '@composio/core';
-import { OpenAIProvider } from '@composio/openai';
-
-declare const composio: Composio<OpenAIProvider>;
-const app = new Hono();
-// ---cut---
-app.get("/connections/:userId/:toolkit", async (c) => {
- const userId = c.req.param("userId");
- const toolkit = c.req.param("toolkit");
-
- const session = await composio.create(userId, { toolkits: [toolkit] });
- const result = await session.toolkits();
- const match = result.items.find((t) => t.slug === toolkit);
-
- return c.json({ toolkit, connected: match?.connection?.isActive ?? false });
-});
-```
+<include meta="no-twoslash">../../examples/hono/server.ts#check-connection</include>
## Connecting an app
When a user wants to connect a new app, `session.authorize()` starts the OAuth flow and returns a redirect URL. Your frontend sends the user there, and once they complete auth, they're connected.
-```typescript
-import { Hono } from 'hono';
-import { Composio } from '@composio/core';
-import { OpenAIProvider } from '@composio/openai';
-
-declare const composio: Composio<OpenAIProvider>;
-const app = new Hono();
-// ---cut---
-app.post("/connect/:toolkit", async (c) => {
- const toolkit = c.req.param("toolkit");
- const { userId } = await c.req.json();
-
- const session = await composio.create(userId, { toolkits: [toolkit] });
- const connectionRequest = await session.authorize(toolkit);
-
- return c.json({ redirectUrl: connectionRequest.redirectUrl });
-});
-```
+<include meta="no-twoslash">../../examples/hono/server.ts#connect</include>
## Complete app
diff --git a/docs/content/cookbooks/meta.json b/docs/content/cookbooks/meta.json
index 883ba73b1..dbd9a8cfa 100644
--- a/docs/content/cookbooks/meta.json
+++ b/docs/content/cookbooks/meta.json
@@ -2,8 +2,6 @@
"title": "Cookbooks",
"root": true,
"pages": [
- "---Tutorials---",
- "tutorial-chat-app",
"---Getting Started---",
"templates",
"chat-app",
diff --git a/docs/content/cookbooks/slack-summariser.mdx b/docs/content/cookbooks/slack-summariser.mdx
index 6480f4020..fa250dc4d 100644
--- a/docs/content/cookbooks/slack-summariser.mdx
+++ b/docs/content/cookbooks/slack-summariser.mdx
@@ -1,303 +1,73 @@
---
title: Slack Summarizer
-description: Build an agent that summarizes Slack channel messages
+description: Build a Python script that connects to Slack and summarizes channel messages using Composio and the OpenAI Agents SDK
---
-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`.
+[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/slack-summariser)
+
+This cookbook builds a standalone Python script that connects to a Slack workspace, fetches recent messages from a channel, and summarizes the key topics, decisions, and action items. We'll use **scoped sessions** to limit the agent to Slack tools only.
## Prerequisites
-* Python3.x
+* Python 3.10+
* [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>
-
----
+* [Composio API key](https://platform.composio.dev/settings)
+* [OpenAI API key](https://platform.openai.com/api-keys)
-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`.
+## Project setup
-```python
-from composio import Composio
-from composio_langchain import LangchainProvider
+Create a new project and install dependencies:
-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,
- },
- },
- )
+```bash
+mkdir composio-slack-summarizer && cd composio-slack-summarizer
+uv init && uv add composio composio-openai-agents openai-agents
```
-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
+Add your API keys to a `.env` file:
- return None
+```bash title=".env"
+COMPOSIO_API_KEY=your_composio_api_key
+OPENAI_API_KEY=your_openai_api_key
```
-</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
+## Setting up the client
-# 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,
- )
-```
+`Composio` takes an `OpenAIAgentsProvider` so that tools come back in the format the OpenAI Agents SDK expects.
-Now, when creating tools for your agent always check if the user already has a
-connected account before creating a new one.
+<include>../../examples/slack-summariser/main.py#setup</include>
-```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"],
- )
+## Connecting to Slack
- # Check if there's an active connected account
- for account in connected_accounts.items:
- if account.status == "ACTIVE":
- return True
+Before summarizing, we need to make sure the user has connected their Slack workspace. The `connect` function creates a scoped session with `toolkits=["slack"]` and checks the connection status via `session.toolkits()`. If Slack is not connected, `session.authorize("slack")` starts the OAuth flow and returns a URL for the user to visit. `wait_for_connection()` blocks until they complete it.
- # 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
-```
+<include>../../examples/slack-summariser/main.py#connect</include>
-## Modifiers
+## Summarizing a channel
-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.
+With Slack connected, the `summarize` function creates a session and grabs the tools. We hand them to an agent with focused summarization instructions. `Runner.run_sync` handles the agentic loop: the agent calls the Slack tool to fetch messages and produces a summary.
-```python
-from composio import after_execute
-from composio.types import ToolExecutionResponse
+<include>../../examples/slack-summariser/main.py#summarize</include>
+## Complete script
-@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
+Here is everything together:
- try:
- response["data"]["messages"] = [
- {"user": message["user"], "text": message["text"]}
- for message in response["data"]["messages"]
- if message["type"] == "message"
- ]
- except KeyError:
- pass
+<include>../../examples/slack-summariser/main.py</include>
- return response
-```
+## Running the script
-To register modifiers, include them in the `composio.tools.get` call.
+First, connect your Slack workspace:
-```python
-tools = composio_client.tools.get(
- user_id=user_id,
- toolkits=[SLACK_TOOLKIT],
- modifiers=[clean_conversation_history],
-)
+```bash
+uv run --env-file .env python main.py connect default
```
-## 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.
+If Slack is not connected yet, you'll get an OAuth URL. Open it in your browser and authorize the app. If you've already connected, the script will print "Slack is already connected."
-```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()
+Then run the summarizer:
- agent = create_agent(user_id, composio_client)
- agent.invoke({"input": prompt})
+```bash
+uv run --env-file .env python main.py summarize default general
```
-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
+Replace `general` with any channel name you want to summarize.
diff --git a/docs/content/cookbooks/tutorial-chat-app.mdx b/docs/content/cookbooks/tutorial-chat-app.mdx
deleted file mode 100644
index c9bdd8a6e..000000000
--- a/docs/content/cookbooks/tutorial-chat-app.mdx
+++ /dev/null
@@ -1,415 +0,0 @@
----
-title: Build a Chat App
-description: Build an AI chat app with access to 800+ tools in about 30 lines of backend code
----
-
-Composio gives your AI agent access to 800+ app integrations β€” Gmail, GitHub, Slack, Notion, and more. Today, in about **30 lines of backend code**, we'll build a chat app where your agent can discover tools, authenticate users, and take actions across any app.
-
-After that we'll see how authentication works and how to show tool calls in the UI.
-
-## Create the project
-
-<Callout>
-Before you begin: you'll need Node.js 18+ and API keys for [Composio](https://platform.composio.dev/settings) and [OpenAI](https://platform.openai.com/api-keys).
-</Callout>
-
-Create a new Next.js app and install the dependencies:
-
-```bash
-pnpm create next-app composio-chat --yes
-cd composio-chat
-pnpm install @composio/core @composio/vercel @ai-sdk/openai ai @ai-sdk/react
-```
-
-Add your API keys to a `.env.local` file in the project root:
-
-```bash title=".env.local"
-COMPOSIO_API_KEY=your_composio_api_key
-OPENAI_API_KEY=your_openai_api_key
-```
-
-Start the dev server and keep it running throughout this tutorial:
-
-```bash
-pnpm dev
-```
-
-Open [localhost:3000](http://localhost:3000) β€” you'll see the default Next.js page. We'll replace it with a chat interface shortly.
-
-## How Composio works
-
-Instead of loading 1000+ tools into your agent's context (which would overwhelm any LLM), Composio gives your agent **5 meta tools** that handle everything at runtime:
-
-| Meta tool | What it does |
-|-----------|-------------|
-| `COMPOSIO_SEARCH_TOOLS` | Discover relevant tools across 800+ apps |
-| `COMPOSIO_MANAGE_CONNECTIONS` | Handle OAuth and API key authentication |
-| `COMPOSIO_MULTI_EXECUTE_TOOL` | Execute up to 20 tools in parallel |
-| `COMPOSIO_REMOTE_WORKBENCH` | Run Python code in a persistent sandbox |
-| `COMPOSIO_REMOTE_BASH_TOOL` | Execute bash commands for data processing |
-
-Here's the flow:
-
-```
-User: "Star the composio repo on GitHub"
- ↓
-1. Agent calls COMPOSIO_SEARCH_TOOLS
- β†’ Returns GITHUB_STAR_REPO with input schema
- β†’ Returns connection status (not connected)
- ↓
-2. Agent calls COMPOSIO_MANAGE_CONNECTIONS
- β†’ Returns an auth link for GitHub
- β†’ User clicks link and authorizes
- ↓
-3. Agent calls COMPOSIO_MULTI_EXECUTE_TOOL
- β†’ Executes GITHUB_STAR_REPO
- β†’ Returns success
- ↓
-Done. The repo is starred. ⭐
-```
-
-When you create a **session**, your agent gets these 5 tools. From there, the agent handles discovery, authentication, and execution on its own.
-
-Now let's write the code.
-
-## Your first session
-
-A **session** is the core Composio primitive. It scopes tools and connections to a specific user. One line of code gives your agent access to everything.
-
-Create a new file at `app/api/chat/route.ts`:
-
-```typescript title="app/api/chat/route.ts"
-import { openai } from "@ai-sdk/openai";
-import { Composio } from "@composio/core";
-import { VercelProvider } from "@composio/vercel";
-import {
- streamText,
- convertToModelMessages,
- generateId,
- stepCountIs,
- type UIMessage,
-} from "ai";
-
-const composio = new Composio({ provider: new VercelProvider() });
-
-export async function POST(req: Request) {
- const { messages }: { messages: UIMessage[] } = await req.json();
-
- // Create a session for the user
- const session = await composio.create("user_123");
- const tools = await session.tools();
-
- // Stream the AI response with tool access
- const result = streamText({
- model: openai("gpt-4o"),
- system: "You are a helpful assistant. Use Composio tools to help the user.",
- messages: await convertToModelMessages(messages),
- tools,
- stopWhen: stepCountIs(10),
- });
-
- return result.toUIMessageStreamResponse({
- originalMessages: messages,
- generateMessageId: () => generateId(),
- });
-}
-```
-
-Let's break this down:
-
-1. **`new Composio({ provider: new VercelProvider() })`** initializes Composio with the Vercel AI SDK provider, so tools are returned in the right format.
-2. **`composio.create("user_123")`** creates a session for this user. All tool connections and data are scoped to this ID. In production, you'd use a real user ID from your auth system.
-3. **`session.tools()`** returns the 5 meta tools, formatted for the Vercel AI SDK.
-4. **`streamText`** sends the conversation to GPT-4o along with the tools. The model can now search for tools, authenticate users, and execute actions β€” all through those meta tools.
-5. **`stopWhen: stepCountIs(10)`** limits the agent to 10 steps per request. Each tool call counts as a step.
-
-That's the entire backend. Now let's build the chat UI.
-
-## The chat UI
-
-Replace your `app/page.tsx` with a simple chat interface:
-
-```tsx title="app/page.tsx"
-import React from "react";
-// ---cut---
-"use client";
-
-import { useState } from "react";
-import { useChat } from "@ai-sdk/react";
-import { DefaultChatTransport } from "ai";
-
-export default function Chat() {
- const [input, setInput] = useState("");
- const { messages, sendMessage, status } = useChat({
- transport: new DefaultChatTransport({ api: "/api/chat" }),
- });
-
- const isLoading = status === "streaming" || status === "submitted";
-
- return (
- <main className="max-w-2xl mx-auto p-6">
- <h1 className="text-2xl font-bold mb-6">Composio Chat</h1>
-
- <div className="space-y-4 mb-6 min-h-[200px]">
- {messages.length === 0 && (
- <p className="text-gray-400 text-center py-12">
- Try: &quot;Star the composio repo on GitHub&quot;
- </p>
- )}
- {messages.map((m) => (
- <div key={m.id} className="flex gap-2">
- <span className="font-semibold shrink-0">
- {m.role === "user" ? "You:" : "Agent:"}
- </span>
- <div>
- {m.parts.map((part, i) =>
- part.type === "text" ? <span key={i}>{String(part.text)}</span> : null
- )}
- </div>
- </div>
- ))}
- {isLoading && (
- <p className="text-gray-400 text-sm">Thinking...</p>
- )}
- </div>
-
- <form
- onSubmit={(e) => {
- e.preventDefault();
- if (!input.trim()) return;
- sendMessage({ text: input });
- setInput("");
- }}
- >
- <input
- value={input}
- onChange={(e) => setInput(e.target.value)}
- placeholder="Ask me anything..."
- disabled={isLoading}
- className="w-full p-3 border border-gray-300 rounded-lg"
- />
- </form>
- </main>
- );
-}
-```
-
-The `useChat` hook manages everything: message history, streaming, and state. It sends messages to your `/api/chat` route and streams the response back automatically.
-
-Go to [localhost:3000](http://localhost:3000). You should see the chat interface. Try sending a message like "Hello" β€” the agent will respond.
-
-## Your first tool call
-
-Now try asking the agent to do something real:
-
-```
-Star the composio repo on GitHub
-```
-
-Here's what happens behind the scenes:
-
-1. The agent calls **`COMPOSIO_SEARCH_TOOLS`** with your request. Composio returns the `GITHUB_STAR_REPO` tool along with its input schema and the user's connection status.
-
-2. Since you haven't connected GitHub yet, the agent calls **`COMPOSIO_MANAGE_CONNECTIONS`**. Composio returns an authentication link.
-
-3. The agent shows you the link in the chat. **Click it**, authorize with GitHub, and come back to the chat.
-
-4. Tell the agent you're done (e.g., "Done" or "I've connected"). It retries β€” this time calling **`COMPOSIO_MULTI_EXECUTE_TOOL`** to run `GITHUB_STAR_REPO`.
-
-5. The repo is starred.
-
-The agent handled **discovery**, **authentication**, and **execution** β€” all through the meta tools you gave it with `composio.create()`. You didn't write a single line of tool-specific code.
-
-<Callout>
-This in-chat authentication flow works out of the box. For production apps, you can also [authenticate users ahead of time](/docs/authenticating-users/manually-authenticating) during onboarding.
-</Callout>
-
-## Showing tool calls
-
-Right now tool calls happen invisibly. Let's add a component that shows them β€” the tool name, input, and output β€” so you can see what your agent is doing in real time.
-
-Create `components/ToolCallDisplay.tsx`:
-
-```tsx title="components/ToolCallDisplay.tsx"
-import React from "react";
-// ---cut---
-"use client";
-
-import { useState } from "react";
-
-export function ToolCallDisplay({
- toolName,
- input,
- output,
- isLoading,
-}: {
- toolName: string;
- input: unknown;
- output?: unknown;
- isLoading: boolean;
-}) {
- const [expanded, setExpanded] = useState(false);
-
- return (
- <div
- className={`my-2 rounded-lg border p-2 text-sm ${
- isLoading
- ? "border-blue-200 bg-blue-50"
- : "border-green-200 bg-green-50"
- }`}
- >
- <button
- onClick={() => setExpanded(!expanded)}
- className="flex items-center gap-2 w-full text-left"
- >
- <span>{isLoading ? "⏳" : "βœ…"}</span>
- <code className="font-mono text-xs">{toolName}</code>
- {isLoading && <span className="text-xs text-gray-500">Running...</span>}
- <span className="ml-auto text-xs">{expanded ? "β–²" : "β–Ό"}</span>
- </button>
-
- {expanded && (
- <div className="mt-2 space-y-2">
- <pre className="text-xs bg-white/50 p-2 rounded overflow-auto max-h-32">
- {String(JSON.stringify(input, null, 2))}
- </pre>
- {output != null && (
- <pre className="text-xs bg-white/50 p-2 rounded overflow-auto max-h-32">
- {String(JSON.stringify(output, null, 2))}
- </pre>
- )}
- </div>
- )}
- </div>
- );
-}
-```
-
-Now update `app/page.tsx` to render tool calls:
-
-```tsx title="app/page.tsx"
-// @errors: 2307
-import React from "react";
-declare function ToolCallDisplay(props: { toolName: string; input: unknown; output?: unknown; isLoading: boolean }): React.ReactElement;
-// ---cut---
-"use client";
-
-import { useState } from "react";
-import { useChat } from "@ai-sdk/react";
-import { DefaultChatTransport, getToolName, isToolUIPart } from "ai";
-import { ToolCallDisplay } from "../components/ToolCallDisplay";
-
-export default function Chat() {
- const [input, setInput] = useState("");
- const { messages, sendMessage, status } = useChat({
- transport: new DefaultChatTransport({ api: "/api/chat" }),
- });
-
- const isLoading = status === "streaming" || status === "submitted";
-
- return (
- <main className="max-w-2xl mx-auto p-6">
- <h1 className="text-2xl font-bold mb-6">Composio Chat</h1>
-
- <div className="space-y-4 mb-6 min-h-[200px]">
- {messages.length === 0 && (
- <p className="text-gray-400 text-center py-12">
- Try: &quot;Star the composio repo on GitHub&quot;
- </p>
- )}
- {messages.map((m) => (
- <div key={m.id} className="flex gap-2">
- <span className="font-semibold shrink-0">
- {m.role === "user" ? "You:" : "Agent:"}
- </span>
- <div className="flex-1">
- {m.parts.map((part, i) => {
- if (part.type === "text") {
- return <span key={i}>{String(part.text)}</span>;
- }
- if (isToolUIPart(part)) {
- return (
- <ToolCallDisplay
- key={part.toolCallId}
- toolName={getToolName(part)}
- input={part.input}
- output={
- part.state === "output-available"
- ? part.output
- : undefined
- }
- isLoading={part.state !== "output-available"}
- />
- );
- }
- return null;
- })}
- </div>
- </div>
- ))}
- {isLoading && (
- <p className="text-gray-400 text-sm">Thinking...</p>
- )}
- </div>
-
- <form
- onSubmit={(e) => {
- e.preventDefault();
- if (!input.trim()) return;
- sendMessage({ text: input });
- setInput("");
- }}
- >
- <input
- value={input}
- onChange={(e) => setInput(e.target.value)}
- placeholder="Ask me anything..."
- disabled={isLoading}
- className="w-full p-3 border border-gray-300 rounded-lg"
- />
- </form>
- </main>
- );
-}
-```
-
-Now when the agent uses tools, you'll see expandable cards showing what's happening β€” the tool name while it's running, and the full input/output when you click to expand.
-
-Try sending a few more requests:
-
-- "Summarize my emails from today"
-- "What's on my calendar this week?"
-- "Create a GitHub issue in my repo"
-
-Each one will trigger a different set of tools, and you'll see the full flow: search β†’ authenticate β†’ execute.
-
-## What you built
-
-With about 30 lines of backend code and a simple React frontend, you've built a chat app that:
-
-1. Creates a **session** that gives the agent 5 meta tools
-2. Uses **`COMPOSIO_SEARCH_TOOLS`** to discover the right tools across 800+ apps
-3. Uses **`COMPOSIO_MANAGE_CONNECTIONS`** to handle OAuth inline
-4. Uses **`COMPOSIO_MULTI_EXECUTE_TOOL`** to take actions on the user's behalf
-5. Streams responses and shows tool calls in real time
-
-The key concept is the **session** β€” one line (`composio.create("user_123")`) gives your agent access to every integration Composio supports.
-
-## Next up
-
-We just touched on the basics. Here are some good next steps:
-
-<Cards>
- <Card title="Configuring sessions" href="/docs/configuring-sessions">
- Restrict toolkits, set auth configs, and customize session behavior
- </Card>
- <Card title="Manual authentication" href="/docs/authenticating-users/manually-authenticating">
- Authenticate users during onboarding instead of in-chat
- </Card>
- <Card title="Users & Sessions" href="/docs/users-and-sessions">
- Understand the user model for multi-user production apps
- </Card>
- <Card title="Full Stack Chat App" href="/cookbooks/vercel-chat">
- A production chat app with connection management UI
- </Card>
-</Cards>
diff --git a/docs/example/fast-api/main.py b/docs/examples/fast-api/main.py
similarity index 90%
rename from docs/example/fast-api/main.py
rename to docs/examples/fast-api/main.py
index 4c24b1311..c16acd8c6 100644
--- a/docs/example/fast-api/main.py
+++ b/docs/examples/fast-api/main.py
@@ -1,3 +1,4 @@
+# region setup
from agents import Agent, Runner
from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider
@@ -7,6 +8,7 @@ from pydantic import BaseModel
composio = Composio(provider=OpenAIAgentsProvider())
app = FastAPI()
+# endregion setup
class ChatRequest(BaseModel):
@@ -18,6 +20,7 @@ class ConnectRequest(BaseModel):
user_id: str
+# region chat
@app.post("/chat")
def chat(request: ChatRequest):
"""Send a message to an AI agent with access to all tools."""
@@ -32,8 +35,10 @@ def chat(request: ChatRequest):
result = Runner.run_sync(starting_agent=agent, input=request.message)
return {"response": result.final_output}
+# endregion chat
+# region list-connections
@app.get("/connections/{user_id}")
def list_connections(user_id: str):
"""List all toolkits and their connection status for a user."""
@@ -43,8 +48,10 @@ def list_connections(user_id: str):
{"toolkit": t.slug, "connected": t.connection.is_active if t.connection else False}
for t in toolkits.items
]
+# endregion list-connections
+# region check-connection
@app.get("/connections/{user_id}/{toolkit}")
def check_connection(user_id: str, toolkit: str):
"""Check if a specific toolkit is connected for a user."""
@@ -54,11 +61,14 @@ def check_connection(user_id: str, toolkit: str):
if t.slug == toolkit:
return {"toolkit": toolkit, "connected": t.connection.is_active if t.connection else False}
return {"toolkit": toolkit, "connected": False}
+# endregion check-connection
+# region connect
@app.post("/connect/{toolkit}")
def connect_toolkit(toolkit: str, request: ConnectRequest):
"""Start OAuth for a toolkit. Returns a URL to redirect the user to."""
session = composio.create(user_id=request.user_id, toolkits=[toolkit])
connection_request = session.authorize(toolkit)
return {"redirect_url": connection_request.redirect_url}
+# endregion connect
diff --git a/docs/examples/hono/server.ts b/docs/examples/hono/server.ts
index 345deb69c..75390098f 100644
--- a/docs/examples/hono/server.ts
+++ b/docs/examples/hono/server.ts
@@ -5,12 +5,14 @@ import { OpenAI } from "openai";
import { Composio } from "@composio/core";
import { OpenAIProvider } from "@composio/openai";
+// #region setup
const composio = new Composio({ provider: new OpenAIProvider() });
const openai = new OpenAI();
const app = new Hono();
+// #endregion setup
-// Send a message to an AI agent with access to all tools.
+// #region chat
app.post("/chat", async (c) => {
const { userId, message } = await c.req.json();
@@ -39,8 +41,9 @@ app.post("/chat", async (c) => {
messages.push(...toolResults);
}
});
+// #endregion chat
-// List all toolkits and their connection status for a user.
+// #region list-connections
app.get("/connections/:userId", async (c) => {
const userId = c.req.param("userId");
@@ -54,8 +57,9 @@ app.get("/connections/:userId", async (c) => {
}))
);
});
+// #endregion list-connections
-// Check if a specific toolkit is connected for a user.
+// #region check-connection
app.get("/connections/:userId/:toolkit", async (c) => {
const userId = c.req.param("userId");
const toolkit = c.req.param("toolkit");
@@ -66,8 +70,9 @@ app.get("/connections/:userId/:toolkit", async (c) => {
return c.json({ toolkit, connected: match?.connection?.isActive ?? false });
});
+// #endregion check-connection
-// Start OAuth for a toolkit. Returns a URL to redirect the user to.
+// #region connect
app.post("/connect/:toolkit", async (c) => {
const toolkit = c.req.param("toolkit");
const { userId } = await c.req.json();
@@ -77,6 +82,7 @@ app.post("/connect/:toolkit", async (c) => {
return c.json({ redirectUrl: connectionRequest.redirectUrl });
});
+// #endregion connect
serve({ fetch: app.fetch, port: 8000 });
console.log("Server running on http://localhost:8000");
diff --git a/docs/examples/slack-summariser/main.py b/docs/examples/slack-summariser/main.py
new file mode 100644
index 000000000..2542edbfb
--- /dev/null
+++ b/docs/examples/slack-summariser/main.py
@@ -0,0 +1,73 @@
+import sys
+
+from agents import Agent, Runner
+from composio import Composio
+from composio_openai_agents import OpenAIAgentsProvider
+
+# region setup
+composio = Composio(provider=OpenAIAgentsProvider())
+# endregion setup
+
+
+# region connect
+def connect(user_id: str):
+ """Check if Slack is connected. If not, start OAuth and wait."""
+ session = composio.create(user_id=user_id, toolkits=["slack"])
+ toolkits = session.toolkits()
+
+ for t in toolkits.items:
+ if t.slug == "slack" and t.connection and t.connection.is_active:
+ print("Slack is already connected.")
+ return
+
+ connection_request = session.authorize("slack")
+ print(f"Open this URL to connect Slack:\n{connection_request.redirect_url}")
+ connection_request.wait_for_connection()
+ print("Connected.")
+# endregion connect
+
+
+# region summarize
+def summarize(user_id: str, channel: str):
+ """Fetch recent messages from a Slack channel and summarize them."""
+ session = composio.create(user_id=user_id, toolkits=["slack"])
+ tools = session.tools()
+
+ agent = Agent(
+ name="Slack Summarizer",
+ instructions=(
+ "You summarize Slack channel messages. "
+ "Fetch recent messages from the given channel and provide a concise summary "
+ "of the key topics, decisions, and action items."
+ ),
+ tools=tools,
+ )
+
+ result = Runner.run_sync(
+ starting_agent=agent,
+ input=f"Summarize the recent messages from the #{channel} channel.",
+ )
+ print(result.final_output)
+# endregion summarize
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ print("Usage:")
+ print(" python main.py connect <user_id>")
+ print(" python main.py summarize <user_id> <channel>")
+ sys.exit(1)
+
+ command = sys.argv[1]
+
+ if command == "connect":
+ user_id = sys.argv[2] if len(sys.argv) > 2 else "default"
+ connect(user_id)
+ elif command == "summarize":
+ user_id = sys.argv[2] if len(sys.argv) > 2 else "default"
+ channel = sys.argv[3] if len(sys.argv) > 3 else "general"
+ summarize(user_id, channel)
+ else:
+ print(f"Unknown command: {command}")
+ print("Use 'connect' or 'summarize'.")
+ sys.exit(1)