@devries-cameron20 / composio-1 / commits / 84f324f03
Fork 0

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

- Rewrite slack-summariser cookbook with session API + OpenAI Agents SDK - Add docs/examples/slack-summariser/main.py with connect and summarize commands - Replace inline code in FastAPI and Hono cookbooks with <include> using #region markers - Add no-twoslash meta to Hono region includes (partial snippets lack imports) - Consolidate docs/example/ into docs/examples/ (single canonical directory) - Delete superseded tutorial-chat-app.mdx (replaced by chat-app.mdx) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Sushmitha Mallesh committed Feb 25, 2026 at 18:03 UTC 84f324f036f99c6987b71bc4292d3448983973d3
8 files changed +142 -861
docs/content/cookbooks/fast-api.mdx
+7 -64
@@ -3,7 +3,7 @@ title: Basic FastAPI Server
3 description: Build an AI agent with access to 1000+ tools using Composio and FastAPI
4 ---
5
6 -[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/example/fast-api)
6 +[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/fast-api)
7
8 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.
9
@@ -34,17 +34,7 @@ OPENAI_API_KEY=your_openai_api_key
34
35 `Composio` takes an `OpenAIAgentsProvider` so that when we ask for tools later, they come back in the format the OpenAI Agents SDK expects.
36
37 -```python
38 -from agents import Agent, Runner
39 -from composio import Composio
40 -from composio_openai_agents import OpenAIAgentsProvider
41 -from fastapi import FastAPI
42 -from pydantic import BaseModel
43 -
44 -composio = Composio(provider=OpenAIAgentsProvider())
45 -
46 -app = FastAPI()
47 -```
37 +<include>../../examples/fast-api/main.py#setup</include>
38
39 ## Chat endpoint
40
@@ -52,26 +42,7 @@ The core of the server is a `/chat` endpoint. A user sends a message, and the ag
42
43 `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.
44
55 -```python
56 -class ChatRequest(BaseModel):
57 - user_id: str
58 - message: str
59 -
60 -
61 -@app.post("/chat")
62 -def chat(request: ChatRequest):
63 - session = composio.create(user_id=request.user_id)
64 - tools = session.tools()
65 -
66 - agent = Agent(
67 - name="Assistant",
68 - instructions="You are a helpful assistant. Use tools to help the user.",
69 - tools=tools,
70 - )
71 -
72 - result = Runner.run_sync(starting_agent=agent, input=request.message)
73 - return {"response": result.final_output}
74 -```
45 +<include>../../examples/fast-api/main.py#chat</include>
46
47 <Callout>
48 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
55
56 `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.
57
87 -```python
88 -@app.get("/connections/{user_id}")
89 -def list_connections(user_id: str):
90 - session = composio.create(user_id=user_id)
91 - toolkits = session.toolkits()
92 - return [
93 - {"toolkit": t.slug, "connected": t.connection.is_active if t.connection else False}
94 - for t in toolkits.items
95 - ]
96 -```
58 +<include>../../examples/fast-api/main.py#list-connections</include>
59
60 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:
61
100 -```python
101 -@app.get("/connections/{user_id}/{toolkit}")
102 -def check_connection(user_id: str, toolkit: str):
103 - session = composio.create(user_id=user_id, toolkits=[toolkit])
104 - toolkits = session.toolkits()
105 - for t in toolkits.items:
106 - if t.slug == toolkit:
107 - return {"toolkit": toolkit, "connected": t.connection.is_active if t.connection else False}
108 - return {"toolkit": toolkit, "connected": False}
109 -```
62 +<include>../../examples/fast-api/main.py#check-connection</include>
63
64 ## Connecting an app
65
66 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.
67
115 -```python
116 -class ConnectRequest(BaseModel):
117 - user_id: str
118 -
119 -
120 -@app.post("/connect/{toolkit}")
121 -def connect_toolkit(toolkit: str, request: ConnectRequest):
122 - session = composio.create(user_id=request.user_id, toolkits=[toolkit])
123 - connection_request = session.authorize(toolkit)
124 - return {"redirect_url": connection_request.redirect_url}
125 -```
68 +<include>../../examples/fast-api/main.py#connect</include>
69
70 ## Complete app
71
72 Here's everything together:
73
131 -<include>../../example/fast-api/main.py</include>
74 +<include>../../examples/fast-api/main.py</include>
75
76 ## Running the server
77
docs/content/cookbooks/hono.mdx
+5 -109
@@ -34,17 +34,7 @@ OPENAI_API_KEY=your_openai_api_key
34
35 `Composio` takes an `OpenAIProvider` so that when we ask for tools later, they come back in the format OpenAI expects.
36
37 -```typescript
38 -import { Hono } from 'hono';
39 -import { OpenAI } from 'openai';
40 -import { Composio } from '@composio/core';
41 -import { OpenAIProvider } from '@composio/openai';
42 -
43 -const composio = new Composio({ provider: new OpenAIProvider() });
44 -const openai = new OpenAI();
45 -
46 -const app = new Hono();
47 -```
37 +<include meta="no-twoslash">../../examples/hono/server.ts#setup</include>
38
39 ## Chat endpoint
40
@@ -52,45 +42,7 @@ The core of the server is a `/chat` endpoint. A user sends a message, and the ag
42
43 `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.
44
55 -```typescript
56 -import { Hono } from 'hono';
57 -import { OpenAI } from 'openai';
58 -import { Composio } from '@composio/core';
59 -import { OpenAIProvider } from '@composio/openai';
60 -
61 -declare const composio: Composio<OpenAIProvider>;
62 -declare const openai: OpenAI;
63 -const app = new Hono();
64 -// ---cut---
65 -app.post("/chat", async (c) => {
66 - const { userId, message } = await c.req.json();
67 -
68 - const session = await composio.create(userId);
69 - const tools = await session.tools();
70 -
71 - const messages: OpenAI.ChatCompletionMessageParam[] = [
72 - { role: "system", content: "You are a helpful assistant. Use tools to help the user." },
73 - { role: "user", content: message },
74 - ];
75 -
76 - while (true) {
77 - const response = await openai.chat.completions.create({
78 - model: "gpt-4.1",
79 - tools,
80 - messages,
81 - });
82 -
83 - const choice = response.choices[0];
84 - if (!choice.message.tool_calls?.length) {
85 - return c.json({ response: choice.message.content });
86 - }
87 -
88 - messages.push(choice.message);
89 - const toolResults = await composio.provider.handleToolCalls(userId, response);
90 - messages.push(...toolResults);
91 - }
92 -});
93 -```
45 +<include meta="no-twoslash">../../examples/hono/server.ts#chat</include>
46
47 <Callout>
48 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
55
56 `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.
57
106 -```typescript
107 -import { Hono } from 'hono';
108 -import { Composio } from '@composio/core';
109 -import { OpenAIProvider } from '@composio/openai';
110 -
111 -declare const composio: Composio<OpenAIProvider>;
112 -const app = new Hono();
113 -// ---cut---
114 -app.get("/connections/:userId", async (c) => {
115 - const userId = c.req.param("userId");
116 -
117 - const session = await composio.create(userId);
118 - const toolkits = await session.toolkits();
119 -
120 - return c.json(
121 - toolkits.items.map((t) => ({
122 - toolkit: t.slug,
123 - connected: t.connection?.isActive ?? false,
124 - }))
125 - );
126 -});
127 -```
58 +<include meta="no-twoslash">../../examples/hono/server.ts#list-connections</include>
59
60 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:
61
131 -```typescript
132 -import { Hono } from 'hono';
133 -import { Composio } from '@composio/core';
134 -import { OpenAIProvider } from '@composio/openai';
135 -
136 -declare const composio: Composio<OpenAIProvider>;
137 -const app = new Hono();
138 -// ---cut---
139 -app.get("/connections/:userId/:toolkit", async (c) => {
140 - const userId = c.req.param("userId");
141 - const toolkit = c.req.param("toolkit");
142 -
143 - const session = await composio.create(userId, { toolkits: [toolkit] });
144 - const result = await session.toolkits();
145 - const match = result.items.find((t) => t.slug === toolkit);
146 -
147 - return c.json({ toolkit, connected: match?.connection?.isActive ?? false });
148 -});
149 -```
62 +<include meta="no-twoslash">../../examples/hono/server.ts#check-connection</include>
63
64 ## Connecting an app
65
66 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.
67
155 -```typescript
156 -import { Hono } from 'hono';
157 -import { Composio } from '@composio/core';
158 -import { OpenAIProvider } from '@composio/openai';
159 -
160 -declare const composio: Composio<OpenAIProvider>;
161 -const app = new Hono();
162 -// ---cut---
163 -app.post("/connect/:toolkit", async (c) => {
164 - const toolkit = c.req.param("toolkit");
165 - const { userId } = await c.req.json();
166 -
167 - const session = await composio.create(userId, { toolkits: [toolkit] });
168 - const connectionRequest = await session.authorize(toolkit);
169 -
170 - return c.json({ redirectUrl: connectionRequest.redirectUrl });
171 -});
172 -```
68 +<include meta="no-twoslash">../../examples/hono/server.ts#connect</include>
69
70 ## Complete app
71
docs/content/cookbooks/meta.json
-2
@@ -2,8 +2,6 @@
2 "title": "Cookbooks",
3 "root": true,
4 "pages": [
5 - "---Tutorials---",
6 - "tutorial-chat-app",
5 "---Getting Started---",
6 "templates",
7 "chat-app",
docs/content/cookbooks/slack-summariser.mdx
+37 -267
@@ -1,303 +1,73 @@
1 ---
2 title: Slack Summarizer
3 -description: Build an agent that summarizes Slack channel messages
3 +description: Build a Python script that connects to Slack and summarizes channel messages using Composio and the OpenAI Agents SDK
4 ---
5
6 -With Composio's managed authentication and tool calling, it's easy to build the
7 -AI agents that can interact with the real world while reducing the boilerplate
8 -required to setup and manage the authentication. This cookbook will walk you through
9 -the process of building agents using `Composio`, `LangChain`.
6 +[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/slack-summariser)
7 +
8 +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.
9
10 ## Prerequisites
11
13 -* Python3.x
12 +* Python 3.10+
13 * [UV](https://docs.astral.sh/uv/getting-started/installation/)
15 -* Composio API key
16 -* OpenAI API key
17 -* Understanding of building AI agents (Preferably with LangChain)
18 -
19 -## Build slack agent
20 -
21 -Let's start by building an agent that can interact with your slack workspace using Composio.
22 -
23 -```python
24 -from composio import Composio
25 -from composio_langchain import LangchainProvider
26 -
27 -from langchain import hub
28 -from langchain.agents import AgentExecutor, create_openai_functions_agent
29 -from langchain_openai import ChatOpenAI
30 -
31 -
32 -def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):
33 - """
34 - Create an agent for a given user id.
35 - """
36 - # Step 1: Get all the tools
37 - tools = composio_client.tools.get(
38 - user_id=user_id,
39 - toolkits=["SLACK"],
40 - )
41 -
42 - # Step 2: Pull relevant agent prompt.
43 - prompt = hub.pull("hwchase17/openai-functions-agent")
44 -
45 - # Step 3: Initialize chat model.
46 - openai_client = ChatOpenAI(model="gpt-5")
47 -
48 - # Step 4: Define agent
49 - return AgentExecutor(
50 - agent=create_openai_functions_agent(
51 - openai_client,
52 - tools,
53 - prompt,
54 - ),
55 - tools=tools,
56 - verbose=True,
57 - )
58 -```
59 -
60 -
61 -## Authenticating users
62 -
63 -To authenticate your users with Composio you need an auth config for the given
64 -app, In this case you need one for slack. You can create and manage auth configs
65 -from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=slack).
66 -
67 -Composio platform provides composio managed authentication for some apps to help
68 -you fast-track your development, `slack` being one of them. You can use these
69 -default auth configs for development, but for production you should always use
70 -your own oauth app configuration.
71 -
72 -Using dashboard is the preferred way of managing authentication configs, but if
73 -you want to do it manually you can follow the guide below
74 -
75 -<details>
76 -
77 -<summary>Click to expand</summary>
78 -
79 ----
14 +* [Composio API key](https://platform.composio.dev/settings)
15 +* [OpenAI API key](https://platform.openai.com/api-keys)
16
81 -To create an authentication config for `slack` you need `client_id` and `client_secret`
82 -from your Slack [App](https://api.slack.com/apps). Once you have the required credentials
83 -you can use the following piece of code to set up authentication for `slack`.
17 +## Project setup
18
85 -```python
86 -from composio import Composio
87 -from composio_langchain import LangchainProvider
19 +Create a new project and install dependencies:
20
89 -def create_auth_config(composio_client: Composio[OpenAIProvider]):
90 - """
91 - Create a auth config for the slack toolkit.
92 - """
93 - client_id = os.getenv("SLACK_CLIENT_ID")
94 - client_secret = os.getenv("SLACK_CLIENT_SECRET")
95 - if not client_id or not client_secret:
96 - raise ValueError("SLACK_CLIENT_ID and SLACK_CLIENT_SECRET must be set")
97 -
98 - return composio_client.auth_configs.create(
99 - toolkit="SLACK",
100 - options={
101 - "name": "default_slack_auth_config",
102 - "type": "use_custom_auth",
103 - "auth_scheme": "OAUTH2",
104 - "credentials": {
105 - "client_id": client_id,
106 - "client_secret": client_secret,
107 - },
108 - },
109 - )
21 +```bash
22 +mkdir composio-slack-summarizer && cd composio-slack-summarizer
23 +uv init && uv add composio composio-openai-agents openai-agents
24 ```
25
112 -This will create an authentication config for `slack` which you can use to
113 -authenticate your users for your app. Ideally you should just create one
114 -authentication object per project, so check for an existing auth config
115 -before you create a new one.
116 -
117 -```python
118 -def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
119 - """
120 - Fetch the auth config for a given user id.
121 - """
122 - auth_configs = composio_client.auth_configs.list()
123 - for auth_config in auth_configs.items:
124 - if auth_config.toolkit == "SLACK":
125 - return auth_config
26 +Add your API keys to a `.env` file:
27
127 - return None
28 +```bash title=".env"
29 +COMPOSIO_API_KEY=your_composio_api_key
30 +OPENAI_API_KEY=your_openai_api_key
31 ```
129 -</details>
130 -
131 -Once you have authentication management in place, we can start with connecting
132 -your users to your `slack` app. Let's implement a function to connect the users
133 -to your `slack` app via composio.
32
135 -```python
33 +## Setting up the client
34
137 -# Function to initiate a connected account
138 -def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
139 - """
140 - Create a connection for a given user id and auth config id.
141 - """
142 - # Fetch or create the auth config for the slack toolkit
143 - auth_config = fetch_auth_config(composio_client=composio_client)
144 - if not auth_config:
145 - auth_config = create_auth_config(composio_client=composio_client)
146 -
147 - # Create a connection for the user
148 - return composio_client.connected_accounts.initiate(
149 - user_id=user_id,
150 - auth_config_id=auth_config.id,
151 - )
152 -```
35 +`Composio` takes an `OpenAIAgentsProvider` so that tools come back in the format the OpenAI Agents SDK expects.
36
154 -Now, when creating tools for your agent always check if the user already has a
155 -connected account before creating a new one.
37 +<include>../../examples/slack-summariser/main.py#setup</include>
38
157 -```python
158 -def check_connected_account_exists(
159 - composio_client: Composio[LangchainProvider],
160 - user_id: str,
161 -):
162 - """
163 - Check if a connected account exists for a given user id.
164 - """
165 - # Fetch all connected accounts for the user
166 - connected_accounts = composio_client.connected_accounts.list(
167 - user_ids=[user_id],
168 - toolkit_slugs=["SLACK"],
169 - )
39 +## Connecting to Slack
40
171 - # Check if there's an active connected account
172 - for account in connected_accounts.items:
173 - if account.status == "ACTIVE":
174 - return True
41 +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.
42
176 - # Ideally you should not have inactive accounts, but if you do, you should delete them
177 - print(f"[warning] inactive account {account.id} found for user id: {user_id}")
178 - return False
179 -```
43 +<include>../../examples/slack-summariser/main.py#connect</include>
44
181 -## Modifiers
45 +## Summarizing a channel
46
183 -In the current setup, we are expanding too much unnecessary tokens because response
184 -from `SLACK_FETCH_CONVERSATION_HISTORY` tool call contains too much unnecessary
185 -information. This can be fixed using `after_execute` modifier. An after execute
186 -modifier is called after a tool execution is complete, here you can process
187 -and modify the response object to make it more easy to consume for your agent.
47 +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.
48
189 -```python
190 -from composio import after_execute
191 -from composio.types import ToolExecutionResponse
49 +<include>../../examples/slack-summariser/main.py#summarize</include>
50
51 +## Complete script
52
194 -@after_execute(tools=["SLACK_FETCH_CONVERSATION_HISTORY"])
195 -def clean_conversation_history(
196 - tool: str,
197 - toolkit: str,
198 - response: ToolExecutionResponse,
199 -) -> ToolExecutionResponse:
200 - """
201 - Clean the conversation history.
202 - """
203 - if not response["data"]["ok"]:
204 - return response
53 +Here is everything together:
54
206 - try:
207 - response["data"]["messages"] = [
208 - {"user": message["user"], "text": message["text"]}
209 - for message in response["data"]["messages"]
210 - if message["type"] == "message"
211 - ]
212 - except KeyError:
213 - pass
55 +<include>../../examples/slack-summariser/main.py</include>
56
215 - return response
216 -```
57 +## Running the script
58
218 -To register modifiers, include them in the `composio.tools.get` call.
59 +First, connect your Slack workspace:
60
220 -```python
221 -tools = composio_client.tools.get(
222 - user_id=user_id,
223 - toolkits=[SLACK_TOOLKIT],
224 - modifiers=[clean_conversation_history],
225 -)
61 +```bash
62 +uv run --env-file .env python main.py connect default
63 ```
64
228 -## Putting everything together
229 -
230 -So far, we have created an agent with ability to interact with your `slack`
231 -workspace using the `composio` SDK, functions to manage connected accounts
232 -for users and a simple agent runner. Let's package this as a CLI tool.
65 +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."
66
234 -```python
235 -def run_agent(user_id: str, prompt: str):
236 - composio_client = Composio(provider=LangchainProvider())
237 - if not check_connected_account_exists(composio_client, user_id):
238 - connection_request = create_connection(composio_client, user_id)
239 - print(
240 - f"Authenticate with the following link: {connection_request.redirect_url}"
241 - )
242 - connection_request.wait_for_connection()
67 +Then run the summarizer:
68
244 - agent = create_agent(user_id, composio_client)
245 - agent.invoke({"input": prompt})
69 +```bash
70 +uv run --env-file .env python main.py summarize default general
71 ```
72
248 -To test the above function as CLI, follow the steps below
249 -
250 -1. Clone the repository
251 - ```bash
252 - git clone git@github.com:composiohq/slack-summarizer
253 - cd slack-summarizer/
254 - ```
255 -2. Setup environment
256 - ```bash
257 - cp .env.example .env
258 - ```
259 -
260 - Fill the api keys
261 - ```dotenv
262 - COMPOSIO_API_KEY=
263 - OPENAI_API_KEY=
264 - ```
265 -
266 - Create the virtual env
267 - ```bash
268 - make env
269 - source .venv/bin/activate
270 - ```
271 -3. Run the agent
272 - ```bash
273 - python slack_summariser --user-id "default" --prompt "summarise last 5 messages from #general channel"
274 - ```
275 -
276 -## Using Composio for managed auth and tools
277 -
278 -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
279 -- manage `slack` oauth app
280 -- manage user connections
281 -- tools for your agents to interact with `slack`
282 -
283 -Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
284 -
285 -## Best practices
286 -
287 -**🔒 User Management**:
288 -
289 -- Use unique, consistent `user_id` values for each person
290 -- Each user maintains their own slack connection
291 -- User IDs can be email addresses, usernames, or any unique identifier
292 -
293 -## Troubleshooting
294 -
295 -**Connection Issues**:
296 -- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
297 -- Check that the user has completed `slack` authorization
298 -- Verify the user_id matches exactly between requests
299 -
300 -**API Errors**:
301 -- Check the server logs for detailed error messages
302 -- Ensure request payloads match the expected format
303 -- Visit `/docs` endpoint for API schema validation
73 +Replace `general` with any channel name you want to summarize.
docs/content/cookbooks/tutorial-chat-app.mdx deleted
-415
@@ -1,415 +0,0 @@
1 ----
2 -title: Build a Chat App
3 -description: Build an AI chat app with access to 800+ tools in about 30 lines of backend code
4 ----
5 -
6 -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.
7 -
8 -After that we'll see how authentication works and how to show tool calls in the UI.
9 -
10 -## Create the project
11 -
12 -<Callout>
13 -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).
14 -</Callout>
15 -
16 -Create a new Next.js app and install the dependencies:
17 -
18 -```bash
19 -pnpm create next-app composio-chat --yes
20 -cd composio-chat
21 -pnpm install @composio/core @composio/vercel @ai-sdk/openai ai @ai-sdk/react
22 -```
23 -
24 -Add your API keys to a `.env.local` file in the project root:
25 -
26 -```bash title=".env.local"
27 -COMPOSIO_API_KEY=your_composio_api_key
28 -OPENAI_API_KEY=your_openai_api_key
29 -```
30 -
31 -Start the dev server and keep it running throughout this tutorial:
32 -
33 -```bash
34 -pnpm dev
35 -```
36 -
37 -Open [localhost:3000](http://localhost:3000) — you'll see the default Next.js page. We'll replace it with a chat interface shortly.
38 -
39 -## How Composio works
40 -
41 -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:
42 -
43 -| Meta tool | What it does |
44 -|-----------|-------------|
45 -| `COMPOSIO_SEARCH_TOOLS` | Discover relevant tools across 800+ apps |
46 -| `COMPOSIO_MANAGE_CONNECTIONS` | Handle OAuth and API key authentication |
47 -| `COMPOSIO_MULTI_EXECUTE_TOOL` | Execute up to 20 tools in parallel |
48 -| `COMPOSIO_REMOTE_WORKBENCH` | Run Python code in a persistent sandbox |
49 -| `COMPOSIO_REMOTE_BASH_TOOL` | Execute bash commands for data processing |
50 -
51 -Here's the flow:
52 -
53 -```
54 -User: "Star the composio repo on GitHub"
55 - ↓
56 -1. Agent calls COMPOSIO_SEARCH_TOOLS
57 - → Returns GITHUB_STAR_REPO with input schema
58 - → Returns connection status (not connected)
59 - ↓
60 -2. Agent calls COMPOSIO_MANAGE_CONNECTIONS
61 - → Returns an auth link for GitHub
62 - → User clicks link and authorizes
63 - ↓
64 -3. Agent calls COMPOSIO_MULTI_EXECUTE_TOOL
65 - → Executes GITHUB_STAR_REPO
66 - → Returns success
67 - ↓
68 -Done. The repo is starred. ⭐
69 -```
70 -
71 -When you create a **session**, your agent gets these 5 tools. From there, the agent handles discovery, authentication, and execution on its own.
72 -
73 -Now let's write the code.
74 -
75 -## Your first session
76 -
77 -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.
78 -
79 -Create a new file at `app/api/chat/route.ts`:
80 -
81 -```typescript title="app/api/chat/route.ts"
82 -import { openai } from "@ai-sdk/openai";
83 -import { Composio } from "@composio/core";
84 -import { VercelProvider } from "@composio/vercel";
85 -import {
86 - streamText,
87 - convertToModelMessages,
88 - generateId,
89 - stepCountIs,
90 - type UIMessage,
91 -} from "ai";
92 -
93 -const composio = new Composio({ provider: new VercelProvider() });
94 -
95 -export async function POST(req: Request) {
96 - const { messages }: { messages: UIMessage[] } = await req.json();
97 -
98 - // Create a session for the user
99 - const session = await composio.create("user_123");
100 - const tools = await session.tools();
101 -
102 - // Stream the AI response with tool access
103 - const result = streamText({
104 - model: openai("gpt-4o"),
105 - system: "You are a helpful assistant. Use Composio tools to help the user.",
106 - messages: await convertToModelMessages(messages),
107 - tools,
108 - stopWhen: stepCountIs(10),
109 - });
110 -
111 - return result.toUIMessageStreamResponse({
112 - originalMessages: messages,
113 - generateMessageId: () => generateId(),
114 - });
115 -}
116 -```
117 -
118 -Let's break this down:
119 -
120 -1. **`new Composio({ provider: new VercelProvider() })`** initializes Composio with the Vercel AI SDK provider, so tools are returned in the right format.
121 -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.
122 -3. **`session.tools()`** returns the 5 meta tools, formatted for the Vercel AI SDK.
123 -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.
124 -5. **`stopWhen: stepCountIs(10)`** limits the agent to 10 steps per request. Each tool call counts as a step.
125 -
126 -That's the entire backend. Now let's build the chat UI.
127 -
128 -## The chat UI
129 -
130 -Replace your `app/page.tsx` with a simple chat interface:
131 -
132 -```tsx title="app/page.tsx"
133 -import React from "react";
134 -// ---cut---
135 -"use client";
136 -
137 -import { useState } from "react";
138 -import { useChat } from "@ai-sdk/react";
139 -import { DefaultChatTransport } from "ai";
140 -
141 -export default function Chat() {
142 - const [input, setInput] = useState("");
143 - const { messages, sendMessage, status } = useChat({
144 - transport: new DefaultChatTransport({ api: "/api/chat" }),
145 - });
146 -
147 - const isLoading = status === "streaming" || status === "submitted";
148 -
149 - return (
150 - <main className="max-w-2xl mx-auto p-6">
151 - <h1 className="text-2xl font-bold mb-6">Composio Chat</h1>
152 -
153 - <div className="space-y-4 mb-6 min-h-[200px]">
154 - {messages.length === 0 && (
155 - <p className="text-gray-400 text-center py-12">
156 - Try: &quot;Star the composio repo on GitHub&quot;
157 - </p>
158 - )}
159 - {messages.map((m) => (
160 - <div key={m.id} className="flex gap-2">
161 - <span className="font-semibold shrink-0">
162 - {m.role === "user" ? "You:" : "Agent:"}
163 - </span>
164 - <div>
165 - {m.parts.map((part, i) =>
166 - part.type === "text" ? <span key={i}>{String(part.text)}</span> : null
167 - )}
168 - </div>
169 - </div>
170 - ))}
171 - {isLoading && (
172 - <p className="text-gray-400 text-sm">Thinking...</p>
173 - )}
174 - </div>
175 -
176 - <form
177 - onSubmit={(e) => {
178 - e.preventDefault();
179 - if (!input.trim()) return;
180 - sendMessage({ text: input });
181 - setInput("");
182 - }}
183 - >
184 - <input
185 - value={input}
186 - onChange={(e) => setInput(e.target.value)}
187 - placeholder="Ask me anything..."
188 - disabled={isLoading}
189 - className="w-full p-3 border border-gray-300 rounded-lg"
190 - />
191 - </form>
192 - </main>
193 - );
194 -}
195 -```
196 -
197 -The `useChat` hook manages everything: message history, streaming, and state. It sends messages to your `/api/chat` route and streams the response back automatically.
198 -
199 -Go to [localhost:3000](http://localhost:3000). You should see the chat interface. Try sending a message like "Hello" — the agent will respond.
200 -
201 -## Your first tool call
202 -
203 -Now try asking the agent to do something real:
204 -
205 -```
206 -Star the composio repo on GitHub
207 -```
208 -
209 -Here's what happens behind the scenes:
210 -
211 -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.
212 -
213 -2. Since you haven't connected GitHub yet, the agent calls **`COMPOSIO_MANAGE_CONNECTIONS`**. Composio returns an authentication link.
214 -
215 -3. The agent shows you the link in the chat. **Click it**, authorize with GitHub, and come back to the chat.
216 -
217 -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`.
218 -
219 -5. The repo is starred.
220 -
221 -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.
222 -
223 -<Callout>
224 -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.
225 -</Callout>
226 -
227 -## Showing tool calls
228 -
229 -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.
230 -
231 -Create `components/ToolCallDisplay.tsx`:
232 -
233 -```tsx title="components/ToolCallDisplay.tsx"
234 -import React from "react";
235 -// ---cut---
236 -"use client";
237 -
238 -import { useState } from "react";
239 -
240 -export function ToolCallDisplay({
241 - toolName,
242 - input,
243 - output,
244 - isLoading,
245 -}: {
246 - toolName: string;
247 - input: unknown;
248 - output?: unknown;
249 - isLoading: boolean;
250 -}) {
251 - const [expanded, setExpanded] = useState(false);
252 -
253 - return (
254 - <div
255 - className={`my-2 rounded-lg border p-2 text-sm ${
256 - isLoading
257 - ? "border-blue-200 bg-blue-50"
258 - : "border-green-200 bg-green-50"
259 - }`}
260 - >
261 - <button
262 - onClick={() => setExpanded(!expanded)}
263 - className="flex items-center gap-2 w-full text-left"
264 - >
265 - <span>{isLoading ? "⏳" : "✅"}</span>
266 - <code className="font-mono text-xs">{toolName}</code>
267 - {isLoading && <span className="text-xs text-gray-500">Running...</span>}
268 - <span className="ml-auto text-xs">{expanded ? "▲" : "▼"}</span>
269 - </button>
270 -
271 - {expanded && (
272 - <div className="mt-2 space-y-2">
273 - <pre className="text-xs bg-white/50 p-2 rounded overflow-auto max-h-32">
274 - {String(JSON.stringify(input, null, 2))}
275 - </pre>
276 - {output != null && (
277 - <pre className="text-xs bg-white/50 p-2 rounded overflow-auto max-h-32">
278 - {String(JSON.stringify(output, null, 2))}
279 - </pre>
280 - )}
281 - </div>
282 - )}
283 - </div>
284 - );
285 -}
286 -```
287 -
288 -Now update `app/page.tsx` to render tool calls:
289 -
290 -```tsx title="app/page.tsx"
291 -// @errors: 2307
292 -import React from "react";
293 -declare function ToolCallDisplay(props: { toolName: string; input: unknown; output?: unknown; isLoading: boolean }): React.ReactElement;
294 -// ---cut---
295 -"use client";
296 -
297 -import { useState } from "react";
298 -import { useChat } from "@ai-sdk/react";
299 -import { DefaultChatTransport, getToolName, isToolUIPart } from "ai";
300 -import { ToolCallDisplay } from "../components/ToolCallDisplay";
301 -
302 -export default function Chat() {
303 - const [input, setInput] = useState("");
304 - const { messages, sendMessage, status } = useChat({
305 - transport: new DefaultChatTransport({ api: "/api/chat" }),
306 - });
307 -
308 - const isLoading = status === "streaming" || status === "submitted";
309 -
310 - return (
311 - <main className="max-w-2xl mx-auto p-6">
312 - <h1 className="text-2xl font-bold mb-6">Composio Chat</h1>
313 -
314 - <div className="space-y-4 mb-6 min-h-[200px]">
315 - {messages.length === 0 && (
316 - <p className="text-gray-400 text-center py-12">
317 - Try: &quot;Star the composio repo on GitHub&quot;
318 - </p>
319 - )}
320 - {messages.map((m) => (
321 - <div key={m.id} className="flex gap-2">
322 - <span className="font-semibold shrink-0">
323 - {m.role === "user" ? "You:" : "Agent:"}
324 - </span>
325 - <div className="flex-1">
326 - {m.parts.map((part, i) => {
327 - if (part.type === "text") {
328 - return <span key={i}>{String(part.text)}</span>;
329 - }
330 - if (isToolUIPart(part)) {
331 - return (
332 - <ToolCallDisplay
333 - key={part.toolCallId}
334 - toolName={getToolName(part)}
335 - input={part.input}
336 - output={
337 - part.state === "output-available"
338 - ? part.output
339 - : undefined
340 - }
341 - isLoading={part.state !== "output-available"}
342 - />
343 - );
344 - }
345 - return null;
346 - })}
347 - </div>
348 - </div>
349 - ))}
350 - {isLoading && (
351 - <p className="text-gray-400 text-sm">Thinking...</p>
352 - )}
353 - </div>
354 -
355 - <form
356 - onSubmit={(e) => {
357 - e.preventDefault();
358 - if (!input.trim()) return;
359 - sendMessage({ text: input });
360 - setInput("");
361 - }}
362 - >
363 - <input
364 - value={input}
365 - onChange={(e) => setInput(e.target.value)}
366 - placeholder="Ask me anything..."
367 - disabled={isLoading}
368 - className="w-full p-3 border border-gray-300 rounded-lg"
369 - />
370 - </form>
371 - </main>
372 - );
373 -}
374 -```
375 -
376 -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.
377 -
378 -Try sending a few more requests:
379 -
380 -- "Summarize my emails from today"
381 -- "What's on my calendar this week?"
382 -- "Create a GitHub issue in my repo"
383 -
384 -Each one will trigger a different set of tools, and you'll see the full flow: search → authenticate → execute.
385 -
386 -## What you built
387 -
388 -With about 30 lines of backend code and a simple React frontend, you've built a chat app that:
389 -
390 -1. Creates a **session** that gives the agent 5 meta tools
391 -2. Uses **`COMPOSIO_SEARCH_TOOLS`** to discover the right tools across 800+ apps
392 -3. Uses **`COMPOSIO_MANAGE_CONNECTIONS`** to handle OAuth inline
393 -4. Uses **`COMPOSIO_MULTI_EXECUTE_TOOL`** to take actions on the user's behalf
394 -5. Streams responses and shows tool calls in real time
395 -
396 -The key concept is the **session** — one line (`composio.create("user_123")`) gives your agent access to every integration Composio supports.
397 -
398 -## Next up
399 -
400 -We just touched on the basics. Here are some good next steps:
401 -
402 -<Cards>
403 - <Card title="Configuring sessions" href="/docs/configuring-sessions">
404 - Restrict toolkits, set auth configs, and customize session behavior
405 - </Card>
406 - <Card title="Manual authentication" href="/docs/authenticating-users/manually-authenticating">
407 - Authenticate users during onboarding instead of in-chat
408 - </Card>
409 - <Card title="Users & Sessions" href="/docs/users-and-sessions">
410 - Understand the user model for multi-user production apps
411 - </Card>
412 - <Card title="Full Stack Chat App" href="/cookbooks/vercel-chat">
413 - A production chat app with connection management UI
414 - </Card>
415 -</Cards>
docs/examples/fast-api/main.py renamed
+10
@@ -1,3 +1,4 @@
1 +# region setup
2 from agents import Agent, Runner
3 from composio import Composio
4 from composio_openai_agents import OpenAIAgentsProvider
@@ -7,6 +8,7 @@ from pydantic import BaseModel
8 composio = Composio(provider=OpenAIAgentsProvider())
9
10 app = FastAPI()
11 +# endregion setup
12
13
14 class ChatRequest(BaseModel):
@@ -18,6 +20,7 @@ class ConnectRequest(BaseModel):
20 user_id: str
21
22
23 +# region chat
24 @app.post("/chat")
25 def chat(request: ChatRequest):
26 """Send a message to an AI agent with access to all tools."""
@@ -32,8 +35,10 @@ def chat(request: ChatRequest):
35
36 result = Runner.run_sync(starting_agent=agent, input=request.message)
37 return {"response": result.final_output}
38 +# endregion chat
39
40
41 +# region list-connections
42 @app.get("/connections/{user_id}")
43 def list_connections(user_id: str):
44 """List all toolkits and their connection status for a user."""
@@ -43,8 +48,10 @@ def list_connections(user_id: str):
48 {"toolkit": t.slug, "connected": t.connection.is_active if t.connection else False}
49 for t in toolkits.items
50 ]
51 +# endregion list-connections
52
53
54 +# region check-connection
55 @app.get("/connections/{user_id}/{toolkit}")
56 def check_connection(user_id: str, toolkit: str):
57 """Check if a specific toolkit is connected for a user."""
@@ -54,11 +61,14 @@ def check_connection(user_id: str, toolkit: str):
61 if t.slug == toolkit:
62 return {"toolkit": toolkit, "connected": t.connection.is_active if t.connection else False}
63 return {"toolkit": toolkit, "connected": False}
64 +# endregion check-connection
65
66
67 +# region connect
68 @app.post("/connect/{toolkit}")
69 def connect_toolkit(toolkit: str, request: ConnectRequest):
70 """Start OAuth for a toolkit. Returns a URL to redirect the user to."""
71 session = composio.create(user_id=request.user_id, toolkits=[toolkit])
72 connection_request = session.authorize(toolkit)
73 return {"redirect_url": connection_request.redirect_url}
74 +# endregion connect
docs/examples/hono/server.ts
+10 -4
@@ -5,12 +5,14 @@ import { OpenAI } from "openai";
5 import { Composio } from "@composio/core";
6 import { OpenAIProvider } from "@composio/openai";
7
8 +// #region setup
9 const composio = new Composio({ provider: new OpenAIProvider() });
10 const openai = new OpenAI();
11
12 const app = new Hono();
13 +// #endregion setup
14
13 -// Send a message to an AI agent with access to all tools.
15 +// #region chat
16 app.post("/chat", async (c) => {
17 const { userId, message } = await c.req.json();
18
@@ -39,8 +41,9 @@ app.post("/chat", async (c) => {
41 messages.push(...toolResults);
42 }
43 });
44 +// #endregion chat
45
43 -// List all toolkits and their connection status for a user.
46 +// #region list-connections
47 app.get("/connections/:userId", async (c) => {
48 const userId = c.req.param("userId");
49
@@ -54,8 +57,9 @@ app.get("/connections/:userId", async (c) => {
57 }))
58 );
59 });
60 +// #endregion list-connections
61
58 -// Check if a specific toolkit is connected for a user.
62 +// #region check-connection
63 app.get("/connections/:userId/:toolkit", async (c) => {
64 const userId = c.req.param("userId");
65 const toolkit = c.req.param("toolkit");
@@ -66,8 +70,9 @@ app.get("/connections/:userId/:toolkit", async (c) => {
70
71 return c.json({ toolkit, connected: match?.connection?.isActive ?? false });
72 });
73 +// #endregion check-connection
74
70 -// Start OAuth for a toolkit. Returns a URL to redirect the user to.
75 +// #region connect
76 app.post("/connect/:toolkit", async (c) => {
77 const toolkit = c.req.param("toolkit");
78 const { userId } = await c.req.json();
@@ -77,6 +82,7 @@ app.post("/connect/:toolkit", async (c) => {
82
83 return c.json({ redirectUrl: connectionRequest.redirectUrl });
84 });
85 +// #endregion connect
86
87 serve({ fetch: app.fetch, port: 8000 });
88 console.log("Server running on http://localhost:8000");
docs/examples/slack-summariser/main.py new
+73
@@ -0,0 +1,73 @@
1 +import sys
2 +
3 +from agents import Agent, Runner
4 +from composio import Composio
5 +from composio_openai_agents import OpenAIAgentsProvider
6 +
7 +# region setup
8 +composio = Composio(provider=OpenAIAgentsProvider())
9 +# endregion setup
10 +
11 +
12 +# region connect
13 +def connect(user_id: str):
14 + """Check if Slack is connected. If not, start OAuth and wait."""
15 + session = composio.create(user_id=user_id, toolkits=["slack"])
16 + toolkits = session.toolkits()
17 +
18 + for t in toolkits.items:
19 + if t.slug == "slack" and t.connection and t.connection.is_active:
20 + print("Slack is already connected.")
21 + return
22 +
23 + connection_request = session.authorize("slack")
24 + print(f"Open this URL to connect Slack:\n{connection_request.redirect_url}")
25 + connection_request.wait_for_connection()
26 + print("Connected.")
27 +# endregion connect
28 +
29 +
30 +# region summarize
31 +def summarize(user_id: str, channel: str):
32 + """Fetch recent messages from a Slack channel and summarize them."""
33 + session = composio.create(user_id=user_id, toolkits=["slack"])
34 + tools = session.tools()
35 +
36 + agent = Agent(
37 + name="Slack Summarizer",
38 + instructions=(
39 + "You summarize Slack channel messages. "
40 + "Fetch recent messages from the given channel and provide a concise summary "
41 + "of the key topics, decisions, and action items."
42 + ),
43 + tools=tools,
44 + )
45 +
46 + result = Runner.run_sync(
47 + starting_agent=agent,
48 + input=f"Summarize the recent messages from the #{channel} channel.",
49 + )
50 + print(result.final_output)
51 +# endregion summarize
52 +
53 +
54 +if __name__ == "__main__":
55 + if len(sys.argv) < 2:
56 + print("Usage:")
57 + print(" python main.py connect <user_id>")
58 + print(" python main.py summarize <user_id> <channel>")
59 + sys.exit(1)
60 +
61 + command = sys.argv[1]
62 +
63 + if command == "connect":
64 + user_id = sys.argv[2] if len(sys.argv) > 2 else "default"
65 + connect(user_id)
66 + elif command == "summarize":
67 + user_id = sys.argv[2] if len(sys.argv) > 2 else "default"
68 + channel = sys.argv[3] if len(sys.argv) > 3 else "general"
69 + summarize(user_id, channel)
70 + else:
71 + print(f"Unknown command: {command}")
72 + print("Use 'connect' or 'summarize'.")
73 + sys.exit(1)