Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Mirrored from https://github.com/Camo67/composio.git
Synced Nov 22, 20:45 UTC
Port guides from docs/revamp into docs/cookbooks-release (#1908)
Co-authored-by: sohamganatra <sohamganatra1@gmail.com>
Sushmitha Mallesh committed
Sep 20, 2025 at 22:17 UTC
3bcc8c54d96d218a89962e9846073170a349a329
12 files changed
+1810
-305
fern/docs.yml
+20
-11
@@ -192,23 +192,32 @@ navigation:
192
icon: rocket
193
skip-slug: true
194
contents:
195
+ - page: Basic FastAPI Server
196
+ path: pages/dist/examples/fast-api.mdx
197
+ slug: examples/fast-api
198
- page: Basic Hono Server
196
- path: pages/dist/examples/sample-webserver/sample-webserver.mdx
197
- slug: examples/sample-webserver
199
+ path: pages/dist/examples/hono.mdx
200
+ slug: examples/hono
201
+ - section: Productivity & Automation
202
+ icon: zap
203
+ skip-slug: true
204
+ contents:
205
+ - page: Gmail Labeller
206
+ path: pages/dist/examples/utility_agents/gmail_labeler.mdx
207
+ slug: examples/gmail-labeler
208
+ - page: Slack summariser
209
+ path: pages/dist/examples/utility_agents/slack_summariser.mdx
210
+ slug: examples/slack-summariser
211
+ - page: Supabase SQL Agent
212
+ path: pages/dist/examples/utility_agents/supabase_sql_agent.mdx
213
+ slug: examples/supabase-sql-agent
214
- section: Full Stack Applications
215
icon: globe
216
skip-slug: true
217
contents:
218
- page: Full Stack Chat App
203
- path: pages/dist/examples/vercel-composio.mdx
204
- slug: examples/chat-app
205
- - section: Productivity & Automation
206
- icon: zap
207
- skip-slug: true
208
- contents:
209
- - page: AI Gmail Labeller
210
- path: pages/dist/examples/gmail-filterer.mdx
211
- slug: examples/gmail-reaper
219
+ path: pages/dist/examples/chat_applications/vercel_chat.mdx
220
+ slug: examples/vercel-chat
221
- section: Behind the curtain
222
icon: person-booth
223
skip-slug: true
fern/pages/src/examples/chat_applications/vercel_chat.mdx
renamed
+23
-20
@@ -10,29 +10,29 @@ In this example, you will learn how to build a chatbot that:
10
- Lets users connect their various apps to the chatbot using the Composio SDK.
11
- Uses the Vercel provider in the Composio SDK to handle and execute tool calls from the LLM.
12
13
-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).
14
-
15
-You can find the demo live [here](https://chat.composio.dev/).
13
+This page gives a high-level overview of the Composio SDK and how it is used in the
14
+GitHub repository: [composiohq/chat](https://github.com/composiohq/chat). You can
15
+find the demo live [here](https://chat.composio.dev/).
16
17
## Prerequisites
18
19
-Ensure you've followed the README.md in the [composiohq/chat](https://github.com/composiohq/chat) repository to set up the project locally.
19
+Ensure you've followed the README.md in the [composiohq/chat](https://github.com/composiohq/chat)
20
+repository to set up the project locally.
21
22
## Creating auth configs
23
23
-For all the apps you want to connect to the chatbot, you need to create their respective auth configs.
24
-
25
-Learn how to create auth configs [here](/docs/authenticating-tools#creating-an-auth-config).
26
-
27
-Once done, your auth configs will be available in the <a href="https://platform.composio.dev?next_page=/auth-configs" target="_blank">Composio dashboard</a>.
24
+For all the apps you want to connect to the chatbot, you need to create their
25
+respective auth configs. Learn how to create auth configs [here](/docs/authenticating-tools#creating-an-auth-config).
26
+Once done, your auth configs will be available in the [Composio dashboard](https://app.composio.dev/integrations).
27
28
<Frame>
30
- <img src="../../../assets/images/examples/auth-configs.png" alt="Auth configs" />
29
+ <img src="../../../../assets/images/examples/auth-configs.png" alt="Auth configs" />
30
</Frame>
31
32
### Save auth config IDs to environment variables
33
35
-For this project, the auth config IDs should be saved to the environment variables with the `NEXT_PUBLIC_` prefix.
34
+For this project, the auth config IDs should be saved to the environment variables
35
+with the `NEXT_PUBLIC_` prefix.
36
37
```bash .env.local
38
NEXT_PUBLIC_GMAIL_AUTH_CONFIG_ID=ac_1234567890
@@ -41,7 +41,8 @@ NEXT_PUBLIC_GITHUB_AUTH_CONFIG_ID=ac_1234567890
41
42
## Create a Composio client instance
43
44
-We create a Composio client instance for server-side operations like API routes, server components, etc.
44
+We create a Composio client instance for server-side operations like API routes,
45
+server components, etc.
46
47
```typescript lib/service/composio.ts
48
import { Composio } from '@composio/core';
@@ -57,17 +58,19 @@ export default composio;
58
59
## Creating an API for fetching toolkits
60
60
-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.
61
-
62
-In order to list the toolkits and their connection status, we create a Next.js API route to fetch the toolkits using Composio SDK.
61
+The Composio SDK is meant to be used only in server-side code. For client-side
62
+functionality, we create API endpoints in the `/app/api/` directory. In order to
63
+list the toolkits and their connection status, we create a Next.js API route to
64
+fetch the toolkits using Composio SDK.
65
66
<Frame>
65
- <img src="../../../assets/images/examples/toolkits.png" />
67
+ <img src="../../../../assets/images/examples/toolkits.png" />
68
</Frame>
69
70
### 1. Listing connected accounts
71
70
-First, we fetch all connected accounts for a user and create a mapping of toolkit slugs to their connection IDs:
72
+First, we fetch all connected accounts for a user and create a mapping of toolkit
73
+slugs to their connection IDs:
74
75
```typescript app/api/composio/toolkits.ts
76
export async function GET() {
@@ -128,7 +131,7 @@ Users need to connect and disconnect their accounts from the chatbot to enable t
131
When a user wants to connect their account, we create a connection request that redirects them to the OAuth provider:
132
133
<Frame>
131
- <img src="../../../assets/images/examples/create-connection.png" />
134
+ <img src="../../../../assets/images/examples/create-connection.png" />
135
</Frame>
136
137
```typescript app/api/connections/initiate/route.ts
@@ -155,7 +158,7 @@ export async function POST(request: Request) {
158
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:
159
160
<Frame>
158
- <img src="../../../assets/images/examples/connection-status.png" />
161
+ <img src="../../../../assets/images/examples/connection-status.png" />
162
</Frame>
163
164
```typescript app/api/connections/status/route.ts
@@ -260,7 +263,7 @@ export async function POST(request: Request) {
263
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.
264
265
<Frame>
263
- <img src="../../../assets/images/examples/custom-tool-component.png" />
266
+ <img src="../../../../assets/images/examples/custom-tool-component.png" />
267
</Frame>
268
269
You can find the `ToolCall` component at `components/tool-call.tsx`. Here's how to integrate it into your message rendering:
fern/pages/src/examples/fast-api.mdx
new
+401
@@ -0,0 +1,401 @@
1
+---
2
+title: Basic FastAPI Server
3
+subtitle: "Build a simple Gmail agent with Composio and FastAPI"
4
+image: "https://og.composio.dev/api/og?title=Basic%20FastAPI%20Server" # image for socials
5
+keywords: "fastapi, composio, openai, gmail, agent"
6
+hide-nav-links: false
7
+---
8
+
9
+This cookbook will guide you through building agents equipped with tools using `Composio`, `OpenAI`, and `FastAPI`.
10
+
11
+## Prerequisites
12
+
13
+* Python 3.10+
14
+* [UV](https://docs.astral.sh/uv/getting-started/installation/)
15
+* Composio API key
16
+* OpenAI API key
17
+
18
+## Building an AI agent that can interact with `gmail` service
19
+
20
+First, let's start with building a simple AI agent with Composio tools that lets the agent interact with `gmail`.
21
+
22
+```python
23
+from openai import OpenAI
24
+from composio import Composio
25
+from composio_openai import OpenAIProvider
26
+import os
27
+
28
+def run_gmail_agent(
29
+ composio_client: Composio[OpenAIProvider],
30
+ openai_client: OpenAI,
31
+ user_id: str, # Composio uses the User ID to store and access user-level authentication tokens.
32
+ prompt: str,
33
+):
34
+ """
35
+ Run the Gmail agent using composio and openai clients.
36
+ """
37
+ # Step 1: Fetch the necessary Gmail tools list with Composio
38
+ tools = composio_client.tools.get(
39
+ user_id=user_id,
40
+ tools=[
41
+ "GMAIL_FETCH_EMAILS",
42
+ "GMAIL_SEND_EMAIL",
43
+ "GMAIL_CREATE_EMAIL_DRAFT"
44
+ ]
45
+ )
46
+
47
+ # Step 2: Use OpenAI to generate a response based on the prompt and available tools
48
+ response = openai_client.chat.completions.create(
49
+ model="gpt-4.1",
50
+ tools=tools,
51
+ messages=[{"role": "user", "content": prompt}],
52
+ )
53
+
54
+ # Step 3: Handle tool calls with Composio and return the result
55
+ result = composio_client.provider.handle_tool_calls(response=response, user_id=user_id)
56
+ return result
57
+```
58
+
59
+<Note>
60
+This example demonstrates a basic agent without state management or agentic loops,
61
+suitable for simple one-step tasks. For complex multi-step workflows requiring
62
+memory and iterative reasoning, see our cookbooks with frameworks like LangChain,
63
+CrewAI, or AutoGen.
64
+</Note>
65
+
66
+To invoke this agent, authenticate your users with Composio's managed authentication service.
67
+
68
+## Authenticating users
69
+
70
+
71
+To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
72
+
73
+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`.
74
+
75
+```python
76
+from composio import Composio
77
+from composio_openai import OpenAIProvider
78
+
79
+def create_auth_config(composio_client: Composio[OpenAIProvider]):
80
+ """
81
+ Create a auth config for the gmail toolkit.
82
+ """
83
+ client_id = os.getenv("GMAIL_CLIENT_ID")
84
+ client_secret = os.getenv("GMAIL_CLIENT_SECRET")
85
+ if not client_id or not client_secret:
86
+ raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")
87
+
88
+ return composio_client.auth_configs.create(
89
+ toolkit="GMAIL",
90
+ options={
91
+ "name": "default_gmail_auth_config",
92
+ "type": "use_custom_auth",
93
+ "auth_scheme": "OAUTH2",
94
+ "credentials": {
95
+ "client_id": client_id,
96
+ "client_secret": client_secret,
97
+ },
98
+ },
99
+ )
100
+```
101
+
102
+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.
103
+
104
+```python
105
+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
106
+ """
107
+ Fetch the auth config for a given user id.
108
+ """
109
+ auth_configs = composio_client.auth_configs.list()
110
+ for auth_config in auth_configs.items:
111
+ if auth_config.toolkit == "GMAIL":
112
+ return auth_config
113
+
114
+ return None
115
+```
116
+
117
+<Note>
118
+Composio platform provides composio managed authentication for some apps to
119
+fast-track your development, `gmail` being one of them. You can use these
120
+default auth configs for development, but for production, always use your
121
+own oauth app configuration.
122
+</Note>
123
+
124
+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.
125
+
126
+```python
127
+from fastapi import FastAPI
128
+
129
+# Function to initiate a connected account
130
+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
131
+ """
132
+ Create a connection for a given user id and auth config id.
133
+ """
134
+ # Fetch or create the auth config for the gmail toolkit
135
+ auth_config = fetch_auth_config(composio_client=composio_client)
136
+ if not auth_config:
137
+ auth_config = create_auth_config(composio_client=composio_client)
138
+
139
+ # Create a connection for the user
140
+ return composio_client.connected_accounts.initiate(
141
+ user_id=user_id,
142
+ auth_config_id=auth_config.id,
143
+ )
144
+
145
+# Setup FastAPI
146
+app = FastAPI()
147
+
148
+# Connection initiation endpoint
149
+@app.post("/connection/create")
150
+def _create_connection(
151
+ request: CreateConnectionRequest,
152
+ composio_client: ComposioClient,
153
+) -> dict:
154
+ """
155
+ Create a connection for a given user id.
156
+ """
157
+ # For demonstration, using a default user_id. Replace with real user logic in production.
158
+ user_id = "default"
159
+
160
+ # Create a new connection for the user
161
+ connection_request = create_connection(composio_client=composio_client, user_id=user_id)
162
+ return {
163
+ "connection_id": connection_request.id,
164
+ "redirect_url": connection_request.redirect_url,
165
+ }
166
+```
167
+
168
+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.
169
+
170
+## Set Up FastAPI service
171
+
172
+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.
173
+
174
+### Setup dependencies
175
+
176
+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.
177
+
178
+```python
179
+import os
180
+import typing_extensions as te
181
+
182
+from composio import Composio
183
+from composio_openai import OpenAIProvider
184
+
185
+from fastapi import Depends
186
+
187
+_composio_client: Composio[OpenAIProvider] | None = None
188
+
189
+def provide_composio_client():
190
+ """
191
+ Provide a Composio client.
192
+ """
193
+ global _composio_client
194
+ if _composio_client is None:
195
+ _composio_client = Composio(provider=OpenAIProvider())
196
+ return _composio_client
197
+
198
+
199
+ComposioClient = te.Annotated[Composio, Depends(provide_composio_client)]
200
+"""
201
+A Composio client dependency.
202
+"""
203
+```
204
+
205
+Check [dependencies](./simple_gmail_agent/server/dependencies.py) module for more details.
206
+
207
+### Invoke agent via FastAPI
208
+
209
+When invoking an agent, make sure you validate the `user_id`.
210
+
211
+```python
212
+def check_connected_account_exists(
213
+ composio_client: Composio[OpenAIProvider],
214
+ user_id: str,
215
+):
216
+ """
217
+ Check if a connected account exists for a given user id.
218
+ """
219
+ # Fetch all connected accounts for the user
220
+ connected_accounts = composio_client.connected_accounts.list(
221
+ user_ids=[user_id],
222
+ toolkit_slugs=["GMAIL"],
223
+ )
224
+
225
+ # Check if there's an active connected account
226
+ for account in connected_accounts.items:
227
+ if account.status == "ACTIVE":
228
+ return True
229
+
230
+ # Ideally you should not have inactive accounts, but if you do, delete them.
231
+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")
232
+ return False
233
+
234
+def validate_user_id(user_id: str, composio_client: ComposioClient):
235
+ """
236
+ Validate the user id, if no connected account is found, create a new connection.
237
+ """
238
+ if check_connected_account_exists(composio_client=composio_client, user_id=user_id):
239
+ return user_id
240
+
241
+ raise HTTPException(
242
+ status_code=404, detail={"error": "No connected account found for the user id"}
243
+ )
244
+
245
+# Endpoint: Run the Gmail agent for a given user id and prompt
246
+@app.post("/agent")
247
+def _run_gmail_agent(
248
+ request: RunGmailAgentRequest,
249
+ composio_client: ComposioClient,
250
+ openai_client: OpenAIClient, # OpenAI client will be injected as dependency
251
+) -> List[ToolExecutionResponse]:
252
+ """
253
+ Run the Gmail agent for a given user id and prompt.
254
+ """
255
+ # For demonstration, using a default user_id. Replace with real user logic in production.
256
+ user_id = "default"
257
+
258
+ # Validate the user id before proceeding
259
+ user_id = validate_user_id(user_id=user_id, composio_client=composio_client)
260
+
261
+ # Run the Gmail agent using Composio and OpenAI
262
+ result = run_gmail_agent(
263
+ composio_client=composio_client,
264
+ openai_client=openai_client,
265
+ user_id=user_id,
266
+ prompt=request.prompt,
267
+ )
268
+ return result
269
+```
270
+
271
+<Note>
272
+Check [server](./simple_gmail_agent/server/) module for service implementation
273
+</Note>
274
+
275
+## Putting everything together
276
+
277
+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.
278
+
279
+<Note>
280
+Before proceeding, check the [code](./simple_gmail_agent/server/api.py) for utility endpoints not discussed in the cookbook
281
+</Note>
282
+
283
+
284
+1. Clone the repository
285
+ ```bash
286
+ git clone git@github.com:composiohq/composio-fastapi
287
+ cd composio-fastapi/
288
+ ```
289
+2. Setup environment
290
+ ```bash
291
+ cp .env.example .env
292
+ ```
293
+
294
+ Fill the api keys
295
+ ```dotenv
296
+ COMPOSIO_API_KEY=
297
+ OPENAI_API_KEY=
298
+ ```
299
+
300
+ Create the virtual env
301
+ ```bash
302
+ make env
303
+ source .venv/bin/activate
304
+ ```
305
+3. Run the HTTP server
306
+ ```bash
307
+ uvicorn simple_gmail_agent.server.api:create_app --factory
308
+ ```
309
+## Testing the API with curl
310
+
311
+Assuming the server is running locally on `http://localhost:8000`.
312
+
313
+### Check if a connection exists
314
+```bash
315
+curl -X POST http://localhost:8000/connection/exists
316
+```
317
+
318
+### Create a connection
319
+Note: The body fields are required by the API schema, but are ignored internally in this example service.
320
+```bash
321
+curl -X POST http://localhost:8000/connection/create \
322
+ -H "Content-Type: application/json" \
323
+ -d '{
324
+ "user_id": "default",
325
+ "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
326
+ }'
327
+```
328
+Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.
329
+
330
+### Check connection status
331
+Use the `connection_id` returned from the create step.
332
+```bash
333
+curl -X POST http://localhost:8000/connection/status \
334
+ -H "Content-Type: application/json" \
335
+ -d '{
336
+ "user_id": "default",
337
+ "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
338
+ }'
339
+```
340
+
341
+### Run the Gmail agent
342
+Requires an active connected account for the `default` user.
343
+```bash
344
+curl -X POST http://localhost:8000/agent \
345
+ -H "Content-Type: application/json" \
346
+ -d '{
347
+ "user_id": "default",
348
+ "prompt": "Summarize my latest unread emails from the last 24 hours."
349
+ }'
350
+```
351
+
352
+### Fetch emails (direct action)
353
+```bash
354
+curl -X POST http://localhost:8000/actions/fetch_emails \
355
+ -H "Content-Type: application/json" \
356
+ -d '{
357
+ "user_id": "default",
358
+ "limit": 5
359
+ }'
360
+```
361
+
362
+These examples are intended solely for testing purposes.
363
+
364
+## Using Composio for managed auth and tools
365
+
366
+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
367
+
368
+- manage Gmail OAuth app
369
+- manage user connections
370
+- tools for your agents to interact with Gmail
371
+
372
+Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.
373
+
374
+## Best practices
375
+
376
+**🎯 Effective Prompts**:
377
+- Be specific: "Send email to john@company.com about tomorrow's 2pm meeting" works better than "send email"
378
+- Include context: "Reply to Sarah's email about the budget with our approval"
379
+- Use natural language: The agent understands conversational requests
380
+
381
+**🔒 User Management**:
382
+- Use unique, consistent `user_id` values for each person
383
+- Each user maintains their own Gmail connection
384
+- User IDs can be email addresses, usernames, or any unique identifier
385
+
386
+
387
+## Troubleshooting
388
+
389
+**Connection Issues**:
390
+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
391
+- Check if the user has completed Gmail authorization.
392
+- Verify the user_id matches exactly between requests
393
+
394
+**API Errors**:
395
+- Check the server logs for detailed error messages
396
+- Ensure request payloads match the expected format
397
+- Visit `/docs` endpoint for API schema validation
398
+
399
+**Gmail API Limits**:
400
+- Gmail has rate limits; the agent will handle these gracefully
401
+- For high-volume usage, consider implementing request queuing
fern/pages/src/examples/hello-world.mdx
deleted
-9
@@ -1,9 +0,0 @@
1
----
2
-title: Hello World!
3
-image: "https://og.composio.dev/api/og?title=Hello%20World%21" # image for socials
4
-description: "A simple example of how to use the Composio SDK to call tools."
5
-keywords: "hello world, composio, sdk, tool calling"
6
-subtitle: ""
7
-hide-nav-links: true
8
----
9
-
fern/pages/src/examples/hono.mdx
new
+422
@@ -0,0 +1,422 @@
1
+---
2
+title: Basic Hono Server
3
+image: "https://og.composio.dev/api/og?title=Basic%20Hono%20Server" # image for socials
4
+keywords: "hono, composio, openai, gmail, agent"
5
+hide-nav-links: false
6
+description: Build a simple Gmail agent with Composio and Hono.js
7
+---
8
+
9
+With Composio's managed authentication and tool calling, it's easy to build
10
+AI agents that interact with the real world while reducing boilerplate for
11
+setup and authentication management. This cookbook will guide you through
12
+building and serving agents using `Composio`, `OpenAI`, and `Hono.js`.
13
+
14
+## Prerequisites
15
+
16
+* Node.js 18.x or higher
17
+* npm or yarn package manager
18
+* Composio API key
19
+* OpenAI API key
20
+* Basic knowledge of OAuth
21
+* Understanding of building HTTP services (preferably using Hono.js)
22
+
23
+## Building an AI agent that can interact with `gmail` service
24
+
25
+First, let's start with building a simple AI agent embedded with tools from
26
+Composio that lets the agent interact with the `gmail` service.
27
+
28
+```typescript
29
+import { OpenAI } from 'openai';
30
+import { Composio } from '@composio/core';
31
+import { OpenAIProvider } from '@composio/openai';
32
+
33
+export async function runGmailAgent(
34
+ composioClient: Composio<OpenAIProvider>,
35
+ openaiClient: OpenAI,
36
+ userId: string, // Composio uses the User ID to store and access user-level authentication tokens.
37
+ prompt: string,
38
+): Promise<any[]> {
39
+ // Step 1: Fetch the necessary Gmail tools list with Composio
40
+ const tools = await composioClient.tools.get(
41
+ userId,
42
+ {
43
+ tools: [
44
+ "GMAIL_FETCH_EMAILS",
45
+ "GMAIL_SEND_EMAIL",
46
+ "GMAIL_CREATE_EMAIL_DRAFT"
47
+ ]
48
+ }
49
+ );
50
+
51
+ // Step 2: Use OpenAI to generate a response based on the prompt and available tools
52
+ const response = await openaiClient.chat.completions.create({
53
+ model: "gpt-4.1",
54
+ tools,
55
+ messages: [{ role: "user", content: prompt }],
56
+ });
57
+
58
+ // Step 3: Handle tool calls with Composio and return the result
59
+ const result = await composioClient.provider.handleToolCalls(
60
+ userId,
61
+ response
62
+ );
63
+ return result;
64
+}
65
+```
66
+
67
+<Note>
68
+ This is a simple agent without state management and agentic loop implementation,
69
+ so the agent can't perform complicated tasks. If you want to understand how
70
+ composio can be used with agentic loops, check other cookbooks with more
71
+ agentic frameworks.
72
+</Note>
73
+
74
+To invoke this agent, authenticate your users with Composio's managed authentication service.
75
+
76
+## Authenticating users
77
+
78
+To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
79
+
80
+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`.
81
+
82
+```typescript
83
+import { Composio } from '@composio/core';
84
+import { OpenAIProvider } from '@composio/openai';
85
+
86
+export async function createAuthConfig(composioClient: Composio<OpenAIProvider>) {
87
+ /**
88
+ * Create a auth config for the gmail toolkit.
89
+ */
90
+ const clientId = process.env.GMAIL_CLIENT_ID;
91
+ const clientSecret = process.env.GMAIL_CLIENT_SECRET;
92
+ if (!clientId || !clientSecret) {
93
+ throw new Error("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set");
94
+ }
95
+
96
+ return composioClient.authConfigs.create(
97
+ "GMAIL",
98
+ {
99
+ "name": "default_gmail_auth_config",
100
+ "type": "use_custom_auth",
101
+ "authScheme": "OAUTH2",
102
+ "credentials": {
103
+ "clientId": clientId,
104
+ "clientSecret": clientSecret,
105
+ },
106
+ },
107
+ );
108
+}
109
+```
110
+
111
+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.
112
+
113
+```typescript
114
+export async function fetchAuthConfig(composioClient: Composio<OpenAIProvider>) {
115
+ /**
116
+ * Fetch the auth config for a given user id.
117
+ */
118
+ const authConfigs = await composioClient.authConfigs.list();
119
+ for (const authConfig of authConfigs.items) {
120
+ if (authConfig.toolkit.slug === "gmail") {
121
+ return authConfig;
122
+ }
123
+ }
124
+
125
+ return null;
126
+}
127
+```
128
+
129
+<Note>
130
+ Composio platform provides composio managed authentication for some apps to
131
+ fast-track your development, `gmail` being one of them. You can use these
132
+ default auth configs for development, but for production, always use your
133
+ own oauth app configuration.
134
+</Note>
135
+
136
+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.
137
+
138
+```typescript
139
+import { Hono } from 'hono';
140
+
141
+// Function to initiate a connected account
142
+export async function createConnection(composioClient: Composio<OpenAIProvider>, userId: string) {
143
+ /**
144
+ * Create a connection for a given user id and auth config id.
145
+ */
146
+ // Fetch or create the auth config for the gmail toolkit
147
+ let authConfig = await fetchAuthConfig(composioClient);
148
+ if (!authConfig) {
149
+ authConfig = await createAuthConfig(composioClient);
150
+ }
151
+
152
+ // Create a connection for the user
153
+ return composioClient.connectedAccounts.initiate(
154
+ userId,
155
+ authConfig.id,
156
+ );
157
+}
158
+
159
+// Setup Hono
160
+const app = new Hono();
161
+
162
+// Connection initiation endpoint
163
+app.post("/connection/create", async (c) => {
164
+ /**
165
+ * Create a connection for a given user id.
166
+ */
167
+ // For demonstration, using a default user_id. Replace with real user logic in production.
168
+ const userId = "default";
169
+
170
+ // Create a new connection for the user
171
+ const connectionRequest = await createConnection(composioClient, userId);
172
+ return c.json({
173
+ "connection_id": connectionRequest.id,
174
+ "redirect_url": connectionRequest.redirectUrl,
175
+ });
176
+});
177
+```
178
+
179
+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.
180
+
181
+## Set Up Hono service
182
+
183
+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.
184
+
185
+### Setup dependencies
186
+
187
+Hono allows dependency injection patterns to simplify the usage of SDK clients that must be singletons. We recommend using composio SDK client as singleton.
188
+
189
+```typescript
190
+import { Composio } from '@composio/core';
191
+import { OpenAIProvider } from '@composio/openai';
192
+import { OpenAI } from 'openai';
193
+
194
+let _composioClient: Composio<OpenAIProvider> | null = null;
195
+
196
+export function provideComposioClient(): Composio<OpenAIProvider> {
197
+ /**
198
+ * Provide a Composio client.
199
+ */
200
+ if (_composioClient === null) {
201
+ _composioClient = new Composio({
202
+ provider: new OpenAIProvider()
203
+ });
204
+ }
205
+ return _composioClient;
206
+}
207
+
208
+// A Composio client dependency.
209
+export type ComposioClient = Composio<OpenAIProvider>;
210
+```
211
+
212
+Check [config/composio.ts](./src/config/composio.ts) module for more details.
213
+
214
+### Invoke agent via Hono
215
+
216
+When invoking an agent, make sure you validate the `user_id`.
217
+
218
+```typescript
219
+export function checkConnectedAccountExists(
220
+ composioClient: Composio<OpenAIProvider>,
221
+ userId: string,
222
+): Promise<boolean> {
223
+ /**
224
+ * Check if a connected account exists for a given user id.
225
+ */
226
+ // Fetch all connected accounts for the user
227
+ return composioClient.connectedAccounts.list({ userIds: [userId], toolkitSlugs: ["GMAIL"] }).then(connectedAccounts => {
228
+
229
+ // Check if there's an active connected account
230
+ for (const account of connectedAccounts.items) {
231
+ if (account.status === "ACTIVE") {
232
+ return true;
233
+ }
234
+
235
+ // Ideally you should not have inactive accounts, but if you do, delete them.
236
+ console.log(`[warning] inactive account ${account.id} found for user id: ${userId}`);
237
+ }
238
+ return false;
239
+ });
240
+}
241
+
242
+export async function validateUserId(userId: string, composioClient: ComposioClient): Promise<string> {
243
+ /**
244
+ * Validate the user id, if no connected account is found, create a new connection.
245
+ */
246
+ if (await checkConnectedAccountExists(composioClient, userId)) {
247
+ return userId;
248
+ }
249
+
250
+ throw new Error("No connected account found for the user id");
251
+}
252
+
253
+// Endpoint: Run the Gmail agent for a given user id and prompt
254
+app.post("/agent", async (c) => {
255
+ /**
256
+ * Run the Gmail agent for a given user id and prompt.
257
+ */
258
+ const request = await c.req.json();
259
+
260
+ // For demonstration, using a default user_id. Replace with real user logic in production.
261
+ const userId = "default";
262
+
263
+ // Validate the user id before proceeding
264
+ await validateUserId(userId, composioClient);
265
+
266
+ // Run the Gmail agent using Composio and OpenAI
267
+ const result = await runGmailAgent(
268
+ composioClient,
269
+ openaiClient,
270
+ userId,
271
+ request.prompt,
272
+ );
273
+ return c.json(result);
274
+});
275
+```
276
+
277
+<Note>
278
+ Check [src/api.ts](./src/api.ts) module for service implementation
279
+</Note>
280
+
281
+## Putting everything together
282
+
283
+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.
284
+
285
+<Note>
286
+ Before proceeding, check the [code](./src/api.ts) for utility endpoints not discussed in the cookbook
287
+</Note>
288
+
289
+1. Clone the repository
290
+ ```bash
291
+ git clone git@github.com:composiohq/composio-hono
292
+ cd composio-hono/
293
+ ```
294
+2. Setup environment
295
+
296
+ ```bash
297
+ cp .env.example .env
298
+ ```
299
+
300
+ Fill the api keys
301
+
302
+ ```dotenv
303
+ COMPOSIO_API_KEY=
304
+ OPENAI_API_KEY=
305
+ ```
306
+
307
+ Install dependencies
308
+
309
+ ```bash
310
+ npm install
311
+ ```
312
+3. Run the HTTP server
313
+ ```bash
314
+ npm run dev
315
+ ```
316
+
317
+## Testing the API with curl
318
+
319
+Assuming the server is running locally on `http://localhost:8000`.
320
+
321
+### Check if a connection exists
322
+
323
+```bash
324
+curl -X POST http://localhost:8000/connection/exists
325
+```
326
+
327
+### Create a connection
328
+
329
+Note: The body fields are required by the API schema, but are ignored internally in this example service.
330
+
331
+```bash
332
+curl -X POST http://localhost:8000/connection/create \
333
+ -H "Content-Type: application/json" \
334
+ -d '{
335
+ "user_id": "default",
336
+ "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
337
+ }'
338
+```
339
+
340
+Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.
341
+
342
+### Check connection status
343
+
344
+Use the `connection_id` returned from the create step.
345
+
346
+```bash
347
+curl -X POST http://localhost:8000/connection/status \
348
+ -H "Content-Type: application/json" \
349
+ -d '{
350
+ "user_id": "default",
351
+ "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
352
+ }'
353
+```
354
+
355
+### Run the Gmail agent
356
+
357
+Requires an active connected account for the `default` user.
358
+
359
+```bash
360
+curl -X POST http://localhost:8000/agent \
361
+ -H "Content-Type: application/json" \
362
+ -d '{
363
+ "user_id": "default",
364
+ "prompt": "Summarize my latest unread emails from the last 24 hours."
365
+ }'
366
+```
367
+
368
+### Fetch emails (direct action)
369
+
370
+```bash
371
+curl -X POST http://localhost:8000/actions/fetch_emails \
372
+ -H "Content-Type: application/json" \
373
+ -d '{
374
+ "user_id": "default",
375
+ "limit": 5
376
+ }'
377
+```
378
+
379
+These examples are intended solely for testing purposes.
380
+
381
+## Using Composio for managed auth and tools
382
+
383
+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
384
+
385
+* manage Gmail OAuth app
386
+* manage user connections
387
+* tools for your agents to interact with Gmail
388
+
389
+Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.
390
+
391
+## Best practices
392
+
393
+**🎯 Effective Prompts**:
394
+
395
+* Be specific: "Send email to [john@company.com](mailto:john@company.com) about tomorrow's 2pm meeting" works better than "send email"
396
+* Include context: "Reply to Sarah's email about the budget with our approval"
397
+* Use natural language: The agent understands conversational requests
398
+
399
+**🔑 User Management**:
400
+
401
+* Use unique, consistent `user_id` values for each person
402
+* Each user maintains their own Gmail connection
403
+* User IDs can be email addresses, usernames, or any unique identifier
404
+
405
+## Troubleshooting
406
+
407
+**Connection Issues**:
408
+
409
+* Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
410
+* Check if the user has completed Gmail authorization.
411
+* Verify the user\_id matches exactly between requests
412
+
413
+**API Errors**:
414
+
415
+* Check the server logs for detailed error messages
416
+* Ensure request payloads match the expected format
417
+* Visit `/docs` endpoint for API schema validation
418
+
419
+**Gmail API Limits**:
420
+
421
+* Gmail has rate limits; the agent will handle these gracefully
422
+* For high-volume usage, consider implementing request queuing
\ No newline at end of file
fern/pages/src/examples/sample-script.mdx
deleted
-27
@@ -1,27 +0,0 @@
1
----
2
-title: Sample Script
3
-image: "https://og.composio.dev/api/og?title=Sample%20Script" # image for socials
4
-description: "A simple example of a Python script that uses the Composio SDK to call tools."
5
-keywords: "hello world python, composio, sdk, tool calling"
6
-subtitle: ""
7
-hide-nav-links: true
8
----
9
-
10
-This tutorial will show you the basics of how to use the Composio SDK to call tools.
11
-
12
-SAMPLE
13
-
14
-```bash
15
-pip install composio==0.8.0
16
-```
17
-
18
-Here's a complete Python example that demonstrates the Composio SDK:
19
-
20
-<SnippetCode
21
- src="fern/snippets/examples/sample-script/sample-script.py"
22
- startLine={1}
23
- title="Setting up Composio and OpenAI"
24
- highlightStart={17}
25
- highlightEnd={19}
26
-/>
27
-
fern/pages/src/examples/sample-webserver/index.ts
deleted
-61
@@ -1,61 +0,0 @@
1
-import { Hono } from 'hono';
2
-import { Composio } from '@composio/core';
3
-import OpenAI from 'openai';
4
-
5
-const app = new Hono();
6
-
7
-// reads COMPOSIO_API_KEY from the environment variables
8
-// uses OpenAI by default
9
-const composio = new Composio();
10
-
11
-const openai = new OpenAI();
12
-
13
-// this should be made once and stored in a database
14
-// const authConfigId = (await composio.authConfigs.create('GMAIL')).id;
15
-const authConfigId = 'ac_DUMMY';
16
-
17
-app.post('/create-connection', async c => {
18
- const { userId } = await c.req.json();
19
-
20
- const connection = await composio.connectedAccounts.initiate(userId, authConfigId);
21
-
22
- return c.json({
23
- id: connection.id,
24
- // for the user to authorize the connection
25
- redirectUrl: connection.redirectUrl,
26
- });
27
-});
28
-
29
-app.post('/send-email', async c => {
30
- const { userId, feedback, overwrite_email } = await c.req.json();
31
-
32
- const tools = await composio.tools.get(userId, {
33
- toolkits: ['GMAIL'],
34
- });
35
-
36
- const completion = await openai.chat.completions.create({
37
- model: 'gpt-4o',
38
- messages: [
39
- {
40
- role: 'system',
41
- content:
42
- 'Send the composio team feedback about their product at feedback@composio.dev, parse the user feedback and send an email from their account, if they provide an email address, use that, otherwise sent it to feedback@composio.dev',
43
- },
44
- {
45
- role: 'user',
46
- content: `
47
- User feedback: ${feedback}
48
- Overwrite email: ${overwrite_email}
49
- `,
50
- },
51
- ],
52
- tools,
53
- tool_choice: 'auto',
54
- });
55
-
56
- const result = await composio.provider.handleToolCalls(userId, completion);
57
-
58
- return c.json({ completion, result });
59
-});
60
-
61
-export default app;
fern/pages/src/examples/sample-webserver/sample-webserver.mdx
deleted
-132
@@ -1,132 +0,0 @@
1
----
2
-title: A basic web server
3
-image: "https://og.composio.dev/api/og?title=A%20basic%20web%20server" # image for socials
4
-description: "A simple example of a web server that uses the Composio SDK to call tools."
5
-keywords: "web server, composio, sdk, tool calling"
6
-subtitle: ""
7
-hide-nav-links: true
8
----
9
-
10
-This tutorial shows you a minimal example of a web server that can use Composio.
11
-
12
-
13
-### Install dependencies
14
-
15
-Using `bun` for this example, it is super convenient for rapid prototyping.
16
-
17
-```bash
18
-bun install @composio/core openai hono
19
-```
20
-
21
-Please set the following environment variables:
22
-
23
-```bash
24
-# .env
25
-COMPOSIO_API_KEY=your_api_key
26
-OPENAI_API_KEY=your_api_key
27
-```
28
-
29
-The full source code is available [here](https://github.com/ComposioHQ/composio/blob/next/fern/pages/examples/src/sample-webserver/index.ts).
30
-
31
-In this tutorial, we will create an auth config, initiate a connection, and send an email.
32
-
33
-### Setup
34
-
35
-Basic scaffolding for the server.
36
-
37
-<SnippetCode
38
- src="./index.ts"
39
- startLine={1}
40
- endLine={10}
41
- title="Setup"
42
- highlightStart={9}
43
- highlightEnd={9}
44
-/>
45
-
46
-
47
-### Auth Configs
48
-
49
-These are configurations for tools that control how they are authorized, the scopes, and permissions they have. You can learn more about them [here](/docs/authenticating-tools).
50
-
51
-For this example, we will create a basic GMAIL auth config.
52
-
53
-You are recommended to store these config IDs, so that you can reuse them later.
54
-
55
-<SnippetCode
56
- src="./index.ts"
57
- startLine={12}
58
- endLine={16}
59
- title="Auth Configs"
60
-/>
61
-
62
-
63
-### Initiating a connection
64
-
65
-Connections are your users authorizing your tools.
66
-
67
-Here we start the connection process. Once your user uses the `redirectUrl` from the response,
68
-they will be redirected to the auth flow.
69
-Once they have authorized the connection, you can use the `id` to get and execute the tools as the user.
70
-
71
-<SnippetCode
72
- src="./index.ts"
73
- startLine={16}
74
- endLine={27}
75
- title="Initiating a connection"
76
- highlightStart={19}
77
- highlightEnd={19}
78
-/>
79
-
80
-You can test your server by running `bun run index.ts` and then running the following command:
81
-
82
-```bash
83
-curl -X POST http://localhost:3000/create-connection \
84
--H "Content-Type: application/json" \
85
--d '{"userId": "123"}'
86
-```
87
-
88
-### Sending an email
89
-
90
-Now let's send that email.
91
-
92
-<SnippetCode
93
- src="./index.ts"
94
- startLine={29}
95
- endLine={59}
96
- title="Sending an email"
97
- highlightStart={56}
98
- highlightEnd={56}
99
-/>
100
-
101
-Using the `id` from the connection, we can now send an email.
102
-
103
-```bash
104
-curl -X POST http://localhost:3000/send-email \
105
--H "Content-Type: application/json" \
106
--d '{"userId": "123", "feedback": "These docs are great!"}'
107
-```
108
-
109
-
110
-### Full Code
111
-
112
-You can see the full code [here](https://github.com/ComposioHQ/composio/blob/next/fern/pages/src/examples/sample-webserver/index.ts).
113
-
114
-
115
-### What just happened?
116
-
117
-Well, first - we created an instance of our `gmail` tool with our default auth config, then our user authorized that tool with their account and some permissions.
118
-
119
-Then we used that `gmail` tool by giving it to OpenAI's `gpt-4o`. The model composed the email and sent it correctly formatted to the Composio team.
120
-
121
-### What's next?
122
-
123
-This is a fairly basic example, but you can do a lot more with our SDK.
124
-
125
-Recommended further reading:
126
-
127
-- [Authenticating tools](/docs/authenticating-tools) - understand how to control tool authorization
128
-- [Executing Tools](/docs/executing-tools) - understand how tool execution works
129
-- [Providers](/docs/providers) - want to use something other than OpenAI? We probably support it
130
-- [Tools](/docs/tools) - understand what tools we have
131
-
132
-
fern/pages/src/examples/tool-generator.mdx
deleted
-45
@@ -1,45 +0,0 @@
1
----
2
-title: Tool Type Generator
3
-image: "https://og.composio.dev/api/og?title=Tool%20Type%20Generator" # image for socials
4
-description: "An example that shows you how to showcase auth scheme and action params for tools"
5
-keywords: "tool type generator, composio, sdk, tool calling"
6
-subtitle: "using raw tool definition to build your own platform on top of Composio"
7
-hide-nav-links: true
8
----
9
-
10
-This is a bit of a cheeky tutorial as it is dogfooding the `docs` tool generation process.
11
-
12
-To motivate this example clearly, in our tools section — we have details about, let's say, the [`Github`](/tools/github) tool, that shows its auth scheme, actions, and their params.
13
-
14
-Now why would anyone outside of Composio want to do this? Well, if you are building a platform on top of Composio, perhaps a workflow builder like Langflow, you would want to show some or all of this information to your users.
15
-
16
-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.
17
-
18
-## How does one build a tool type generator?
19
-
20
-In Composio, we have two internal states for tools:
21
-
22
-1. Raw tool definition
23
-2. Provider tool definition
24
-
25
-The raw tool definition is a generic input-output schema definition that we use 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.
26
-
27
-The provider tool definition translates this raw tool definition to the specific schema of a provider (by default `openai`).
28
-
29
-For building something like this, we need to use the raw tool definition.
30
-
31
-
32
-## Getting the raw tool definition
33
-
34
-
35
-
36
-
37
-<SnippetCode src="fern/generators/tool_doc_generator/main.py" path="tool_doc_generator/main.py" startLine={532} endLine={534} relativeHighlightStart={2} relativeHighlightEnd={2} wordWrap />
38
-
39
-
40
-
41
-
42
-
43
-
44
-
45
-
fern/pages/src/examples/utility_agents/gmail_labeler.mdx
new
+383
@@ -0,0 +1,383 @@
1
+---
2
+title: Gmail Labeler
3
+image: "https://og.composio.dev/api/og?title=Gmail%20Labeler" # image for socials
4
+description: Build an Gmail auto labeler agent with Composio and Langchain
5
+keywords: gmail labeler, utility agent, triggers
6
+---
7
+
8
+With Composio's managed authentication, tool calling and triggers, it's easy to
9
+build the AI agents that can interact and react the real world events reducing
10
+the boilerplate required to setup and manage the authentication. This cookbook
11
+will walk you through the process of building agents using `Composio`, `LangChain`.
12
+
13
+## Prerequisites
14
+
15
+* Python3.x
16
+* [UV](https://docs.astral.sh/uv/getting-started/installation/)
17
+* Composio API key
18
+* OpenAI API key
19
+* Understanding of building AI agents (Preferably with LangChain)
20
+
21
+## Build gmail agent to label your messages
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
+ tools=[
40
+ "GMAIL_LIST_LABELS",
41
+ "GMAIL_ADD_LABEL_TO_EMAIL",
42
+ "GMAIL_CREATE_LABEL",
43
+ ],
44
+ )
45
+
46
+ # Step 2: Pull relevant agent prompt.
47
+ prompt = hub.pull("hwchase17/openai-functions-agent")
48
+
49
+ # Step 3: Initialize chat model.
50
+ openai_client = ChatOpenAI(model="gpt-4-turbo")
51
+
52
+ # Step 4: Define agent
53
+ return AgentExecutor(
54
+ agent=create_openai_functions_agent(
55
+ openai_client,
56
+ tools,
57
+ prompt,
58
+ ),
59
+ tools=tools,
60
+ verbose=False,
61
+ )
62
+```
63
+
64
+## Authenticating users
65
+
66
+To authenticate your users with Composio you need an auth config for the given
67
+app, In this case you need one for gmail. You can create and manage auth configs
68
+from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=gmail).
69
+Composio platform provides composio managed authentication for some apps to help
70
+you fast-track your development, `gmail` being one of them. You can use these
71
+default auth configs for development, but for production you should always use
72
+your own oauth app configuration.
73
+
74
+Using dashboard is the preferred way of managing authentication configs, but if
75
+you want to do it manually you can follow the guide below
76
+
77
+<details>
78
+
79
+<summary>Click to expand</summary>
80
+
81
+To create an authentication config for `gmail` you need `client_id` and `client_secret`
82
+from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).
83
+Once you have the required credentials you can use the following piece of
84
+code to set up authentication for `gmail`.
85
+
86
+```python
87
+from composio import Composio
88
+from composio_langchain import LangchainProvider
89
+
90
+def create_auth_config(composio_client: Composio[OpenAIProvider]):
91
+ """
92
+ Create a auth config for the gmail toolkit.
93
+ """
94
+ client_id = os.getenv("GMAIL_CLIENT_ID")
95
+ client_secret = os.getenv("GMAIL_CLIENT_SECRET")
96
+ if not client_id or not client_secret:
97
+ raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")
98
+
99
+ return composio_client.auth_configs.create(
100
+ toolkit="gmail",
101
+ options={
102
+ "name": "default_gmail_auth_config",
103
+ "type": "use_custom_auth",
104
+ "auth_scheme": "OAUTH2",
105
+ "credentials": {
106
+ "client_id": client_id,
107
+ "client_secret": client_secret,
108
+ },
109
+ },
110
+ )
111
+```
112
+
113
+This will create an authentication config for `gmail` which you can use to
114
+authenticate your users for your app. Ideally you should just create one
115
+authentication object per project, so check for an existing auth config
116
+before you create a new one.
117
+
118
+```python
119
+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
120
+ """
121
+ Fetch the auth config for a given user id.
122
+ """
123
+ auth_configs = composio_client.auth_configs.list()
124
+ for auth_config in auth_configs.items:
125
+ if auth_config.toolkit == "gmail":
126
+ return auth_config
127
+
128
+ return None
129
+```
130
+</details>
131
+
132
+Once you have authentication management in place, we can start with connecting
133
+your users to your `gmail` app. Let's implement a function to connect the users
134
+to your `gmail` app via composio.
135
+
136
+```python
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 gmail 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
+```
153
+
154
+Now, when creating tools for your agent always check if the user already has a
155
+connected account before creating a new one.
156
+
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=["GMAIL"],
169
+ )
170
+
171
+ # Check if there's an active connected account
172
+ for account in connected_accounts.items:
173
+ if account.status == "ACTIVE":
174
+ return True
175
+
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
+```
180
+
181
+
182
+## Creating Triggers
183
+
184
+You can use triggers to make your agents react to real world events. In this example,
185
+we will use triggers to invoke your agent everytime there's a new message in your
186
+gmail inbox.
187
+
188
+```python
189
+# Create a new trigger
190
+def create_trigger(
191
+ composio_client: Composio[LangchainProvider],
192
+ connected_account_id: str,
193
+) -> str:
194
+ """
195
+ Create a trigger.
196
+ """
197
+ response = composio_client.triggers.create(
198
+ slug="GMAIL_NEW_GMAIL_MESSAGE",
199
+ connected_account_id=connected_account_id,
200
+ trigger_config={},
201
+ )
202
+ return response.trigger_id
203
+```
204
+
205
+When creating triggers, make sure there are no duplicate triggers. Use following
206
+code as reference for checking if trigger for given connected account exists or not.
207
+
208
+```python
209
+def check_trigger_exists(
210
+ composio_client: Composio[LangchainProvider],
211
+ connected_account_id: str,
212
+) -> t.Optional[str]:
213
+ """
214
+ Check if a trigger exists.
215
+ """
216
+ triggers = composio_client.triggers.list_active(
217
+ trigger_names=["GMAIL_NEW_GMAIL_MESSAGE"],
218
+ connected_account_ids=[connected_account_id],
219
+ )
220
+ for trigger in triggers.items:
221
+ return trigger.id
222
+ return None
223
+```
224
+
225
+
226
+Once trigger is created, you can listen to events using a trigger subscription.
227
+
228
+```python
229
+# Create subscription object
230
+trigger_subscription = composio_client.triggers.subscribe()
231
+
232
+# Register event handler
233
+@trigger_subscription.handle(
234
+ trigger_id="<TRIGGER_ID>", # Filter out events that does not belong this trigger id
235
+ trigger_slug="GMAIL_NEW_GMAIL_MESSAGE",
236
+)
237
+def handle_event(event: TriggerEvent):
238
+ print("> Received email with subject: ", event["payload"]["subject"])
239
+
240
+# Wait for events
241
+trigger_subscription.wait_forever()
242
+```
243
+
244
+## Putting everything together
245
+
246
+Let's put together everything by making the agent react to new messages in your
247
+inbox.
248
+
249
+```python
250
+# Create a trigger subscription factory
251
+
252
+def create_trigger_subscription(
253
+ composio_client: Composio[LangchainProvider],
254
+ trigger_slug: str,
255
+ trigger_id: str,
256
+ agent: AgentExecutor,
257
+):
258
+ """
259
+ Create a trigger subscription for the given agent.
260
+ """
261
+ trigger_subscription = composio_client.triggers.subscribe()
262
+
263
+ @trigger_subscription.handle(
264
+ trigger_slug=trigger_slug,
265
+ trigger_id=trigger_id,
266
+ )
267
+ def handle_event(event: TriggerEvent):
268
+ print("> Received email with subject: ", event["payload"]["subject"])
269
+ result = agent.invoke(
270
+ input={
271
+ "input": APPLY_NEW_LABEL.format( # Check `gmail_labeler/prompt.py`
272
+ message_id=event["payload"]["id"],
273
+ message_subject=event["payload"]["subject"],
274
+ message_text=event["payload"]["message_text"],
275
+ )
276
+ }
277
+ )
278
+ print("> Result: ", result["output"])
279
+
280
+ return trigger_subscription
281
+```
282
+
283
+Package everything as a single entry point.
284
+
285
+```python
286
+def run_agent(user_id: str):
287
+ # Create composio client
288
+ composio_client = Composio(provider=LangchainProvider())
289
+
290
+ # Validate conected account
291
+ connected_account_id = check_connected_account_exists(composio_client, user_id)
292
+ if connected_account_id is None:
293
+ connection_request = create_connection(composio_client, user_id)
294
+ print(
295
+ f"Authenticate with the following link: {connection_request.redirect_url}"
296
+ )
297
+ connection_request.wait_for_connection()
298
+ connected_account_id = connection_request.id
299
+
300
+ # Check if trigger exists, create if not
301
+ trigger_id = check_trigger_exists(
302
+ composio_client=composio_client,
303
+ connected_account_id=connected_account_id,
304
+ )
305
+ if trigger_id is None:
306
+ trigger_id = create_trigger(
307
+ composio_client=composio_client,
308
+ connected_account_id=connected_account_id,
309
+ )
310
+
311
+ # Create agent
312
+ agent = create_agent(user_id=user_id, composio_client=composio_client)
313
+
314
+ # Create trigger subscription
315
+ trigger_subscription = create_trigger_subscription(
316
+ composio_client=composio_client,
317
+ trigger_slug=GMAIL_NEW_GMAIL_MESSAGE_TRIGGER,
318
+ trigger_id=trigger_id,
319
+ agent=agent,
320
+ )
321
+
322
+ # Wait forever
323
+ print("Waiting for events...")
324
+ trigger_subscription.wait_forever()
325
+```
326
+
327
+To test the above function as CLI, follow the steps below
328
+
329
+1. Clone the repository
330
+ ```bash
331
+ git clone git@github.com:composiohq/gmail-labeler
332
+ cd gmail-labeler/
333
+ ```
334
+2. Setup environment
335
+ ```bash
336
+ cp .env.example .env
337
+ ```
338
+
339
+ Fill the api keys
340
+ ```dotenv
341
+ COMPOSIO_API_KEY=
342
+ OPENAI_API_KEY=
343
+ ```
344
+
345
+ Create the virtual env
346
+ ```bash
347
+ make env
348
+ source .venv/bin/activate
349
+ ```
350
+3. Run the agent
351
+ ```bash
352
+ python gmail_labeler --user-id "default"
353
+ ```
354
+
355
+## Using Composio for managed auth and tools
356
+
357
+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
358
+- manage `gmail` oauth app
359
+- manage user connections
360
+- tools for your agents to interact with `gmail`
361
+- Infra for listening to changes in your gmail inbox
362
+
363
+Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
364
+
365
+## Best practices
366
+
367
+**🔒 User Management**:
368
+
369
+- Use unique, consistent `user_id` values for each person
370
+- Each user maintains their own gmail connection
371
+- User IDs can be email addresses, usernames, or any unique identifier
372
+
373
+## Troubleshooting
374
+
375
+**Connection Issues**:
376
+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
377
+- Check that the user has completed `gmail` authorization
378
+- Verify the user_id matches exactly between requests
379
+
380
+**API Errors**:
381
+- Check the server logs for detailed error messages
382
+- Ensure request payloads match the expected format
383
+- Visit `/docs` endpoint for API schema validation
fern/pages/src/examples/utility_agents/slack_summariser.mdx
new
+305
@@ -0,0 +1,305 @@
1
+---
2
+title: Slack summariser
3
+image: "https://og.composio.dev/api/og?title=Slack%20summariser" # image for socials
4
+description: Build a slack summarizer using Composio and Langchain
5
+keywords: slack, summariser, utility agent
6
+---
7
+
8
+With Composio's managed authentication and tool calling, it's easy to build the
9
+AI agents that can interact with the real world while reducing the boilerplate
10
+required to setup and manage the authentication. This cookbook will walk you through
11
+the process of building agents using `Composio`, `LangChain`.
12
+
13
+## Prerequisites
14
+
15
+* Python3.x
16
+* [UV](https://docs.astral.sh/uv/getting-started/installation/)
17
+* Composio API key
18
+* OpenAI API key
19
+* Understanding of building AI agents (Preferably with LangChain)
20
+
21
+## Build slack agent
22
+
23
+Let's start by building an agent that can interact with your slack workspace using Composio.
24
+
25
+```python
26
+from composio import Composio
27
+from composio_langchain import LangchainProvider
28
+
29
+from langchain import hub
30
+from langchain.agents import AgentExecutor, create_openai_functions_agent
31
+from langchain_openai import ChatOpenAI
32
+
33
+
34
+def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):
35
+ """
36
+ Create an agent for a given user id.
37
+ """
38
+ # Step 1: Get all the tools
39
+ tools = composio_client.tools.get(
40
+ user_id=user_id,
41
+ toolkits=["SLACK"],
42
+ )
43
+
44
+ # Step 2: Pull relevant agent prompt.
45
+ prompt = hub.pull("hwchase17/openai-functions-agent")
46
+
47
+ # Step 3: Initialize chat model.
48
+ openai_client = ChatOpenAI(model="gpt-4-turbo")
49
+
50
+ # Step 4: Define agent
51
+ return AgentExecutor(
52
+ agent=create_openai_functions_agent(
53
+ openai_client,
54
+ tools,
55
+ prompt,
56
+ ),
57
+ tools=tools,
58
+ verbose=True,
59
+ )
60
+```
61
+
62
+
63
+## Authenticating users
64
+
65
+To authenticate your users with Composio you need an auth config for the given
66
+app, In this case you need one for slack. You can create and manage auth configs
67
+from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=slack).
68
+
69
+Composio platform provides composio managed authentication for some apps to help
70
+you fast-track your development, `slack` being one of them. You can use these
71
+default auth configs for development, but for production you should always use
72
+your own oauth app configuration.
73
+
74
+Using dashboard is the preferred way of managing authentication configs, but if
75
+you want to do it manually you can follow the guide below
76
+
77
+<details>
78
+
79
+<summary>Click to expand</summary>
80
+
81
+---
82
+
83
+To create an authentication config for `slack` you need `client_id` and `client_secret`
84
+from your Slack [App](https://api.slack.com/apps). Once you have the required credentials
85
+you can use the following piece of code to set up authentication for `slack`.
86
+
87
+```python
88
+from composio import Composio
89
+from composio_langchain import LangchainProvider
90
+
91
+def create_auth_config(composio_client: Composio[OpenAIProvider]):
92
+ """
93
+ Create a auth config for the slack toolkit.
94
+ """
95
+ client_id = os.getenv("SLACK_CLIENT_ID")
96
+ client_secret = os.getenv("SLACK_CLIENT_SECRET")
97
+ if not client_id or not client_secret:
98
+ raise ValueError("SLACK_CLIENT_ID and SLACK_CLIENT_SECRET must be set")
99
+
100
+ return composio_client.auth_configs.create(
101
+ toolkit="SLACK",
102
+ options={
103
+ "name": "default_slack_auth_config",
104
+ "type": "use_custom_auth",
105
+ "auth_scheme": "OAUTH2",
106
+ "credentials": {
107
+ "client_id": client_id,
108
+ "client_secret": client_secret,
109
+ },
110
+ },
111
+ )
112
+```
113
+
114
+This will create an authentication config for `slack` which you can use to
115
+authenticate your users for your app. Ideally you should just create one
116
+authentication object per project, so check for an existing auth config
117
+before you create a new one.
118
+
119
+```python
120
+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
121
+ """
122
+ Fetch the auth config for a given user id.
123
+ """
124
+ auth_configs = composio_client.auth_configs.list()
125
+ for auth_config in auth_configs.items:
126
+ if auth_config.toolkit == "SLACK":
127
+ return auth_config
128
+
129
+ return None
130
+```
131
+</details>
132
+
133
+Once you have authentication management in place, we can start with connecting
134
+your users to your `slack` app. Let's implement a function to connect the users
135
+to your `slack` app via composio.
136
+
137
+```python
138
+
139
+# Function to initiate a connected account
140
+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
141
+ """
142
+ Create a connection for a given user id and auth config id.
143
+ """
144
+ # Fetch or create the auth config for the slack toolkit
145
+ auth_config = fetch_auth_config(composio_client=composio_client)
146
+ if not auth_config:
147
+ auth_config = create_auth_config(composio_client=composio_client)
148
+
149
+ # Create a connection for the user
150
+ return composio_client.connected_accounts.initiate(
151
+ user_id=user_id,
152
+ auth_config_id=auth_config.id,
153
+ )
154
+```
155
+
156
+Now, when creating tools for your agent always check if the user already has a
157
+connected account before creating a new one.
158
+
159
+```python
160
+def check_connected_account_exists(
161
+ composio_client: Composio[LangchainProvider],
162
+ user_id: str,
163
+):
164
+ """
165
+ Check if a connected account exists for a given user id.
166
+ """
167
+ # Fetch all connected accounts for the user
168
+ connected_accounts = composio_client.connected_accounts.list(
169
+ user_ids=[user_id],
170
+ toolkit_slugs=["SLACK"],
171
+ )
172
+
173
+ # Check if there's an active connected account
174
+ for account in connected_accounts.items:
175
+ if account.status == "ACTIVE":
176
+ return True
177
+
178
+ # Ideally you should not have inactive accounts, but if you do, you should delete them
179
+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")
180
+ return False
181
+```
182
+
183
+## Modifiers
184
+
185
+In the current setup, we are expanding too much unnecessary tokens because response
186
+from `SLACK_FETCH_CONVERSATION_HISTORY` tool call contains too much unnecessary
187
+information. This can be fixed using `after_execute` modifier. An after execute
188
+modifier is called after a tool execution is complete, here you can process
189
+and modify the response object to make it more easy to consume for your agent.
190
+
191
+```python
192
+from composio import after_execute
193
+from composio.types import ToolExecutionResponse
194
+
195
+
196
+@after_execute(tools=["SLACK_FETCH_CONVERSATION_HISTORY"])
197
+def clean_conversation_history(
198
+ tool: str,
199
+ toolkit: str,
200
+ response: ToolExecutionResponse,
201
+) -> ToolExecutionResponse:
202
+ """
203
+ Clean the conversation history.
204
+ """
205
+ if not response["data"]["ok"]:
206
+ return response
207
+
208
+ try:
209
+ response["data"]["messages"] = [
210
+ {"user": message["user"], "text": message["text"]}
211
+ for message in response["data"]["messages"]
212
+ if message["type"] == "message"
213
+ ]
214
+ except KeyError:
215
+ pass
216
+
217
+ return response
218
+```
219
+
220
+To register modifiers, include them in the `composio.tools.get` call.
221
+
222
+```python
223
+tools = composio_client.tools.get(
224
+ user_id=user_id,
225
+ toolkits=[SLACK_TOOLKIT],
226
+ modifiers=[clean_conversation_history],
227
+)
228
+```
229
+
230
+## Putting everything together
231
+
232
+So far, we have created an agent with ability to interact with your `slack`
233
+workspace using the `composio` SDK, functions to manage connected accounts
234
+for users and a simple agent runner. Let's package this as a CLI tool.
235
+
236
+```python
237
+def run_agent(user_id: str, prompt: str):
238
+ composio_client = Composio(provider=LangchainProvider())
239
+ if not check_connected_account_exists(composio_client, user_id):
240
+ connection_request = create_connection(composio_client, user_id)
241
+ print(
242
+ f"Authenticate with the following link: {connection_request.redirect_url}"
243
+ )
244
+ connection_request.wait_for_connection()
245
+
246
+ agent = create_agent(user_id, composio_client)
247
+ agent.invoke({"input": prompt})
248
+```
249
+
250
+To test the above function as CLI, follow the steps below
251
+
252
+1. Clone the repository
253
+ ```bash
254
+ git clone git@github.com:composiohq/slack-summarizer
255
+ cd slack-summarizer/
256
+ ```
257
+2. Setup environment
258
+ ```bash
259
+ cp .env.example .env
260
+ ```
261
+
262
+ Fill the api keys
263
+ ```dotenv
264
+ COMPOSIO_API_KEY=
265
+ OPENAI_API_KEY=
266
+ ```
267
+
268
+ Create the virtual env
269
+ ```bash
270
+ make env
271
+ source .venv/bin/activate
272
+ ```
273
+3. Run the agent
274
+ ```bash
275
+ python slack_summariser --user-id "default" --prompt "summarise last 5 messages from #general channel"
276
+ ```
277
+
278
+## Using Composio for managed auth and tools
279
+
280
+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
281
+- manage `slack` oauth app
282
+- manage user connections
283
+- tools for your agents to interact with `slack`
284
+
285
+Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
286
+
287
+## Best practices
288
+
289
+**🔒 User Management**:
290
+
291
+- Use unique, consistent `user_id` values for each person
292
+- Each user maintains their own slack connection
293
+- User IDs can be email addresses, usernames, or any unique identifier
294
+
295
+## Troubleshooting
296
+
297
+**Connection Issues**:
298
+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
299
+- Check that the user has completed `slack` authorization
300
+- Verify the user_id matches exactly between requests
301
+
302
+**API Errors**:
303
+- Check the server logs for detailed error messages
304
+- Ensure request payloads match the expected format
305
+- Visit `/docs` endpoint for API schema validation
fern/pages/src/examples/utility_agents/supabase_sql_agent.mdx
new
+256
@@ -0,0 +1,256 @@
1
+---
2
+title: Supabase SQL Agent
3
+image: "https://og.composio.dev/api/og?title=Supabase%20SQL%20Agent" # image for socials
4
+description: Build a Supabase SQL Agent with Composio and LlamaIndex.
5
+keywords: supabase, sql, agent, utility agent, llama-index
6
+---
7
+
8
+With Composio's managed authentication and tool calling, it's easy to build
9
+AI agents that interact with the real world while reducing boilerplate for
10
+setup and authentication management. This guide will walk you through using
11
+the Supabase CLI agent built with `Composio` and `LlamaIndex`.
12
+
13
+
14
+## Requirements
15
+
16
+* Python 3.9+
17
+* [UV](https://docs.astral.sh/uv/getting-started/installation/) (recommended) or pip
18
+* Composio API key
19
+* OpenAI API key
20
+* Understanding of building AI agents (Preferably with LlamaIndex)
21
+
22
+## Build an agent to perform Supabase tasks
23
+
24
+```python
25
+from composio import Composio
26
+from composio_llamaindex import LlamaIndexProvider
27
+
28
+from llama_index.llms.openai import OpenAI
29
+from llama_index.core.agent.workflow import FunctionAgent
30
+from llama_index.core.workflow import Context
31
+
32
+
33
+def create_agent(user_id: str, composio_client: Composio[LlamaIndexProvider]):
34
+ """
35
+ Create a function agent that can perform Supabase tasks.
36
+ """
37
+
38
+ # Setup client
39
+ llm = OpenAI(model="gpt-4-turbo")
40
+
41
+ # Get All the tools
42
+ tools = composio_client.tools.get(
43
+ user_id=user_id,
44
+ tools=[
45
+ "SUPABASE_LIST_ALL_PROJECTS",
46
+ "SUPABASE_BETA_RUN_SQL_QUERY",
47
+ ],
48
+ )
49
+
50
+ agent = FunctionAgent(
51
+ tools=tools,
52
+ llm=llm,
53
+ system_prompt=(
54
+ "You are a helpful assistant that can help with supabase queries."
55
+ ),
56
+ )
57
+
58
+ # Since this is a continuosly running agent, we need to maintain state across
59
+ # different user messages
60
+ ctx = Context(workflow=agent)
61
+ return agent, ctx
62
+```
63
+
64
+This agent can convert your natural language queries to SQL queries and execute
65
+them on supabase for you. For you agent to be able to execute queries, you need
66
+to authenticate the agent for supabase.
67
+
68
+
69
+## Authenticating users
70
+
71
+To authenticate your users with Composio you need an auth config for the given
72
+app, In this case you need one for supabase. You can create and manage auth configs
73
+from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=supabase).
74
+Composio platform provides composio managed authentication for some apps to help
75
+you fast-track your development, `supabase` being one of them. You can use these
76
+default auth configs for development, but for production you should always use
77
+your own oauth app configuration.
78
+
79
+Using dashboard is the preferred way of managing authentication configs, but if
80
+you want to do it manually you can follow the guide below
81
+
82
+<details>
83
+
84
+<summary>Click to expand</summary>
85
+
86
+---
87
+
88
+To create an authentication config for `supabase` you need `client_id` and `client_secret`
89
+from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).
90
+Once you have the required credentials you can use the following piece of
91
+code to set up authentication for `supabase`.
92
+
93
+```python
94
+from composio import Composio
95
+from composio_langchain import LangchainProvider
96
+
97
+def create_auth_config(composio_client: Composio[OpenAIProvider]):
98
+ """
99
+ Create a auth config for the supabase toolkit.
100
+ """
101
+ client_id = os.getenv("SUPABASE_CLIENT_ID")
102
+ client_secret = os.getenv("SUPABASE_CLIENT_SECRET")
103
+ if not client_id or not client_secret:
104
+ raise ValueError("SUPABASE_CLIENT_ID and SUPABASE_CLIENT_SECRET must be set")
105
+
106
+ return composio_client.auth_configs.create(
107
+ toolkit="supabase",
108
+ options={
109
+ "name": "default_supabase_auth_config",
110
+ "type": "use_custom_auth",
111
+ "auth_scheme": "OAUTH2",
112
+ "credentials": {
113
+ "client_id": client_id,
114
+ "client_secret": client_secret,
115
+ },
116
+ },
117
+ )
118
+```
119
+
120
+This will create an authentication config for `supabase` which you can use to
121
+authenticate your users for your app. Ideally you should just create one
122
+authentication object per project, so check for an existing auth config
123
+before you create a new one.
124
+
125
+```python
126
+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
127
+ """
128
+ Fetch the auth config for a given user id.
129
+ """
130
+ auth_configs = composio_client.auth_configs.list()
131
+ for auth_config in auth_configs.items:
132
+ if auth_config.toolkit == "supabase":
133
+ return auth_config
134
+
135
+ return None
136
+```
137
+</details>
138
+
139
+Once you have authentication management in place, we can start with connecting
140
+your users to your `supabase` app. Let's implement a function to connect the users
141
+to your `supabase` app via composio.
142
+
143
+```python
144
+# Function to initiate a connected account
145
+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
146
+ """
147
+ Create a connection for a given user id and auth config id.
148
+ """
149
+ # Fetch or create the auth config for the supabase toolkit
150
+ auth_config = fetch_auth_config(composio_client=composio_client)
151
+ if not auth_config:
152
+ auth_config = create_auth_config(composio_client=composio_client)
153
+
154
+ # Create a connection for the user
155
+ return composio_client.connected_accounts.initiate(
156
+ user_id=user_id,
157
+ auth_config_id=auth_config.id,
158
+ )
159
+```
160
+
161
+Now, when creating tools for your agent always check if the user already has a
162
+connected account before creating a new one.
163
+
164
+```python
165
+def check_connected_account_exists(
166
+ composio_client: Composio[LangchainProvider],
167
+ user_id: str,
168
+):
169
+ """
170
+ Check if a connected account exists for a given user id.
171
+ """
172
+ # Fetch all connected accounts for the user
173
+ connected_accounts = composio_client.connected_accounts.list(
174
+ user_ids=[user_id],
175
+ toolkit_slugs=["SUPABASE"],
176
+ )
177
+
178
+ # Check if there's an active connected account
179
+ for account in connected_accounts.items:
180
+ if account.status == "ACTIVE":
181
+ return True
182
+
183
+ # Ideally you should not have inactive accounts, but if you do, you should delete them
184
+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")
185
+ return False
186
+```
187
+
188
+
189
+## Create a chat loop
190
+
191
+```python
192
+async def run_loop(user_id: str):
193
+ # Initialize composio client.
194
+ composio_client = Composio(provider=LlamaIndexProvider())
195
+
196
+ # Setup connection if required
197
+ if not check_connected_account_exists(
198
+ composio_client=composio_client,
199
+ user_id=user_id,
200
+ ):
201
+ connection_request = create_connection(
202
+ composio_client=composio_client,
203
+ user_id=user_id,
204
+ )
205
+ print(
206
+ f"Authenticate with the following link: {connection_request.redirect_url}"
207
+ )
208
+
209
+ # Create agent
210
+ agent, ctx = create_agent(
211
+ user_id=user_id,
212
+ composio_client=composio_client,
213
+ )
214
+
215
+ # Run a simple REPL loop
216
+ while True:
217
+ user_input = input("user > ")
218
+ if user_input.lower() == "exit":
219
+ break
220
+
221
+ result = await agent.run(user_msg=user_input, ctx=ctx)
222
+ print("agent > ", result)
223
+ print("Exiting...")
224
+```
225
+
226
+## Using Composio for managed auth and tools
227
+
228
+Composio reduces a lot of boilerplate for building AI agents with ability access
229
+and use a wide variety of apps. For example in this cookbook, to build `supabase`
230
+integration without composio you would have to write code to
231
+
232
+- manage `supabase` oauth app
233
+- manage user connections
234
+- tools for your agents to interact with `supabase`
235
+
236
+Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
237
+
238
+## Best practices
239
+
240
+**🔒 User Management**:
241
+
242
+- Use unique, consistent `user_id` values for each person
243
+- Each user maintains their own supabase connection
244
+- User IDs can be email addresses, usernames, or any unique identifier
245
+
246
+## Troubleshooting
247
+
248
+**Connection Issues**:
249
+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
250
+- Check that the user has completed `supabase` authorization
251
+- Verify the user_id matches exactly between requests
252
+
253
+**API Errors**:
254
+- Check the server logs for detailed error messages
255
+- Ensure request payloads match the expected format
256
+- Visit `/docs` endpoint for API schema validation