@devries-cameron20 / composio Mirror · read-only / commits / 2c8cb9421
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 15:45 UTC

Migrate Examples section from fern

- Add 7 example pages: FastAPI, Hono, Gmail Labeler, Slack Summarizer, Supabase SQL Agent, Vercel Chat, Tool Generator - Clean frontmatter to fumadocs format - Replace <Note> with <Callout> components - Update meta.json with section separators - Update index page with all examples

Sushmithamallesh committed Jan 2, 2026 at 00:54 UTC 2c8cb942122e2c3300c4ca566b24cff4b3fb248e
9 files changed +2346 -7
fumadocs/content/examples/fast-api.mdx new
+398
@@ -0,0 +1,398 @@
1 +---
2 +title: Basic FastAPI Server
3 +description: Build a simple Gmail agent with Composio and FastAPI
4 +---
5 +
6 +This cookbook will guide you through building agents equipped with tools using `Composio`, `OpenAI`, and `FastAPI`.
7 +
8 +## Prerequisites
9 +
10 +* Python 3.10+
11 +* [UV](https://docs.astral.sh/uv/getting-started/installation/)
12 +* Composio API key
13 +* OpenAI API key
14 +
15 +## Building an AI agent that can interact with `gmail` service
16 +
17 +First, let's start with building a simple AI agent with Composio tools that lets the agent interact with `gmail`.
18 +
19 +```python
20 +from openai import OpenAI
21 +from composio import Composio
22 +from composio_openai import OpenAIProvider
23 +import os
24 +
25 +def run_gmail_agent(
26 + composio_client: Composio[OpenAIProvider],
27 + openai_client: OpenAI,
28 + user_id: str, # Composio uses the User ID to store and access user-level authentication tokens.
29 + prompt: str,
30 +):
31 + """
32 + Run the Gmail agent using composio and openai clients.
33 + """
34 + # Step 1: Fetch the necessary Gmail tools list with Composio
35 + tools = composio_client.tools.get(
36 + user_id=user_id,
37 + tools=[
38 + "GMAIL_FETCH_EMAILS",
39 + "GMAIL_SEND_EMAIL",
40 + "GMAIL_CREATE_EMAIL_DRAFT"
41 + ]
42 + )
43 +
44 + # Step 2: Use OpenAI to generate a response based on the prompt and available tools
45 + response = openai_client.chat.completions.create(
46 + model="gpt-4.1",
47 + tools=tools,
48 + messages=[{"role": "user", "content": prompt}],
49 + )
50 +
51 + # Step 3: Handle tool calls with Composio and return the result
52 + result = composio_client.provider.handle_tool_calls(response=response, user_id=user_id)
53 + return result
54 +```
55 +
56 +<Callout>
57 +This example demonstrates a basic agent without state management or agentic loops,
58 +suitable for simple one-step tasks. For complex multi-step workflows requiring
59 +memory and iterative reasoning, see our cookbooks with frameworks like LangChain,
60 +CrewAI, or AutoGen.
61 +</Callout>
62 +
63 +To invoke this agent, authenticate your users with Composio's managed authentication service.
64 +
65 +## Authenticating users
66 +
67 +
68 +To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
69 +
70 +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`.
71 +
72 +```python
73 +from composio import Composio
74 +from composio_openai import OpenAIProvider
75 +
76 +def create_auth_config(composio_client: Composio[OpenAIProvider]):
77 + """
78 + Create a auth config for the gmail toolkit.
79 + """
80 + client_id = os.getenv("GMAIL_CLIENT_ID")
81 + client_secret = os.getenv("GMAIL_CLIENT_SECRET")
82 + if not client_id or not client_secret:
83 + raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")
84 +
85 + return composio_client.auth_configs.create(
86 + toolkit="GMAIL",
87 + options={
88 + "name": "default_gmail_auth_config",
89 + "type": "use_custom_auth",
90 + "auth_scheme": "OAUTH2",
91 + "credentials": {
92 + "client_id": client_id,
93 + "client_secret": client_secret,
94 + },
95 + },
96 + )
97 +```
98 +
99 +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.
100 +
101 +```python
102 +def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
103 + """
104 + Fetch the auth config for a given user id.
105 + """
106 + auth_configs = composio_client.auth_configs.list()
107 + for auth_config in auth_configs.items:
108 + if auth_config.toolkit == "GMAIL":
109 + return auth_config
110 +
111 + return None
112 +```
113 +
114 +<Callout>
115 +Composio platform provides composio managed authentication for some apps to
116 +fast-track your development, `gmail` being one of them. You can use these
117 +default auth configs for development, but for production, always use your
118 +own oauth app configuration.
119 +</Callout>
120 +
121 +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.
122 +
123 +```python
124 +from fastapi import FastAPI
125 +
126 +# Function to initiate a connected account
127 +def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
128 + """
129 + Create a connection for a given user id and auth config id.
130 + """
131 + # Fetch or create the auth config for the gmail toolkit
132 + auth_config = fetch_auth_config(composio_client=composio_client)
133 + if not auth_config:
134 + auth_config = create_auth_config(composio_client=composio_client)
135 +
136 + # Create a connection for the user
137 + return composio_client.connected_accounts.initiate(
138 + user_id=user_id,
139 + auth_config_id=auth_config.id,
140 + )
141 +
142 +# Setup FastAPI
143 +app = FastAPI()
144 +
145 +# Connection initiation endpoint
146 +@app.post("/connection/create")
147 +def _create_connection(
148 + request: CreateConnectionRequest,
149 + composio_client: ComposioClient,
150 +) -> dict:
151 + """
152 + Create a connection for a given user id.
153 + """
154 + # For demonstration, using a default user_id. Replace with real user logic in production.
155 + user_id = "default"
156 +
157 + # Create a new connection for the user
158 + connection_request = create_connection(composio_client=composio_client, user_id=user_id)
159 + return {
160 + "connection_id": connection_request.id,
161 + "redirect_url": connection_request.redirect_url,
162 + }
163 +```
164 +
165 +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.
166 +
167 +## Set Up FastAPI service
168 +
169 +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.
170 +
171 +### Setup dependencies
172 +
173 +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.
174 +
175 +```python
176 +import os
177 +import typing_extensions as te
178 +
179 +from composio import Composio
180 +from composio_openai import OpenAIProvider
181 +
182 +from fastapi import Depends
183 +
184 +_composio_client: Composio[OpenAIProvider] | None = None
185 +
186 +def provide_composio_client():
187 + """
188 + Provide a Composio client.
189 + """
190 + global _composio_client
191 + if _composio_client is None:
192 + _composio_client = Composio(provider=OpenAIProvider())
193 + return _composio_client
194 +
195 +
196 +ComposioClient = te.Annotated[Composio, Depends(provide_composio_client)]
197 +"""
198 +A Composio client dependency.
199 +"""
200 +```
201 +
202 +Check [dependencies](./simple_gmail_agent/server/dependencies.py) module for more details.
203 +
204 +### Invoke agent via FastAPI
205 +
206 +When invoking an agent, make sure you validate the `user_id`.
207 +
208 +```python
209 +def check_connected_account_exists(
210 + composio_client: Composio[OpenAIProvider],
211 + user_id: str,
212 +):
213 + """
214 + Check if a connected account exists for a given user id.
215 + """
216 + # Fetch all connected accounts for the user
217 + connected_accounts = composio_client.connected_accounts.list(
218 + user_ids=[user_id],
219 + toolkit_slugs=["GMAIL"],
220 + )
221 +
222 + # Check if there's an active connected account
223 + for account in connected_accounts.items:
224 + if account.status == "ACTIVE":
225 + return True
226 +
227 + # Ideally you should not have inactive accounts, but if you do, delete them.
228 + print(f"[warning] inactive account {account.id} found for user id: {user_id}")
229 + return False
230 +
231 +def validate_user_id(user_id: str, composio_client: ComposioClient):
232 + """
233 + Validate the user id, if no connected account is found, create a new connection.
234 + """
235 + if check_connected_account_exists(composio_client=composio_client, user_id=user_id):
236 + return user_id
237 +
238 + raise HTTPException(
239 + status_code=404, detail={"error": "No connected account found for the user id"}
240 + )
241 +
242 +# Endpoint: Run the Gmail agent for a given user id and prompt
243 +@app.post("/agent")
244 +def _run_gmail_agent(
245 + request: RunGmailAgentRequest,
246 + composio_client: ComposioClient,
247 + openai_client: OpenAIClient, # OpenAI client will be injected as dependency
248 +) -> List[ToolExecutionResponse]:
249 + """
250 + Run the Gmail agent for a given user id and prompt.
251 + """
252 + # For demonstration, using a default user_id. Replace with real user logic in production.
253 + user_id = "default"
254 +
255 + # Validate the user id before proceeding
256 + user_id = validate_user_id(user_id=user_id, composio_client=composio_client)
257 +
258 + # Run the Gmail agent using Composio and OpenAI
259 + result = run_gmail_agent(
260 + composio_client=composio_client,
261 + openai_client=openai_client,
262 + user_id=user_id,
263 + prompt=request.prompt,
264 + )
265 + return result
266 +```
267 +
268 +<Callout>
269 +Check [server](./simple_gmail_agent/server/) module for service implementation
270 +</Callout>
271 +
272 +## Putting everything together
273 +
274 +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.
275 +
276 +<Callout>
277 +Before proceeding, check the [code](./simple_gmail_agent/server/api.py) for utility endpoints not discussed in the cookbook
278 +</Callout>
279 +
280 +
281 +1. Clone the repository
282 + ```bash
283 + git clone git@github.com:composiohq/composio-fastapi
284 + cd composio-fastapi/
285 + ```
286 +2. Setup environment
287 + ```bash
288 + cp .env.example .env
289 + ```
290 +
291 + Fill the api keys
292 + ```dotenv
293 + COMPOSIO_API_KEY=
294 + OPENAI_API_KEY=
295 + ```
296 +
297 + Create the virtual env
298 + ```bash
299 + make env
300 + source .venv/bin/activate
301 + ```
302 +3. Run the HTTP server
303 + ```bash
304 + uvicorn simple_gmail_agent.server.api:create_app --factory
305 + ```
306 +## Testing the API with curl
307 +
308 +Assuming the server is running locally on `http://localhost:8000`.
309 +
310 +### Check if a connection exists
311 +```bash
312 +curl -X POST http://localhost:8000/connection/exists
313 +```
314 +
315 +### Create a connection
316 +Note: The body fields are required by the API schema, but are ignored internally in this example service.
317 +```bash
318 +curl -X POST http://localhost:8000/connection/create \
319 + -H "Content-Type: application/json" \
320 + -d '{
321 + "user_id": "default",
322 + "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
323 + }'
324 +```
325 +Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.
326 +
327 +### Check connection status
328 +Use the `connection_id` returned from the create step.
329 +```bash
330 +curl -X POST http://localhost:8000/connection/status \
331 + -H "Content-Type: application/json" \
332 + -d '{
333 + "user_id": "default",
334 + "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
335 + }'
336 +```
337 +
338 +### Run the Gmail agent
339 +Requires an active connected account for the `default` user.
340 +```bash
341 +curl -X POST http://localhost:8000/agent \
342 + -H "Content-Type: application/json" \
343 + -d '{
344 + "user_id": "default",
345 + "prompt": "Summarize my latest unread emails from the last 24 hours."
346 + }'
347 +```
348 +
349 +### Fetch emails (direct action)
350 +```bash
351 +curl -X POST http://localhost:8000/actions/fetch_emails \
352 + -H "Content-Type: application/json" \
353 + -d '{
354 + "user_id": "default",
355 + "limit": 5
356 + }'
357 +```
358 +
359 +These examples are intended solely for testing purposes.
360 +
361 +## Using Composio for managed auth and tools
362 +
363 +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
364 +
365 +- manage Gmail OAuth app
366 +- manage user connections
367 +- tools for your agents to interact with Gmail
368 +
369 +Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.
370 +
371 +## Best practices
372 +
373 +**🎯 Effective Prompts**:
374 +- Be specific: "Send email to john@company.com about tomorrow's 2pm meeting" works better than "send email"
375 +- Include context: "Reply to Sarah's email about the budget with our approval"
376 +- Use natural language: The agent understands conversational requests
377 +
378 +**🔒 User Management**:
379 +- Use unique, consistent `user_id` values for each person
380 +- Each user maintains their own Gmail connection
381 +- User IDs can be email addresses, usernames, or any unique identifier
382 +
383 +
384 +## Troubleshooting
385 +
386 +**Connection Issues**:
387 +- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
388 +- Check if the user has completed Gmail authorization.
389 +- Verify the user_id matches exactly between requests
390 +
391 +**API Errors**:
392 +- Check the server logs for detailed error messages
393 +- Ensure request payloads match the expected format
394 +- Visit `/docs` endpoint for API schema validation
395 +
396 +**Gmail API Limits**:
397 +- Gmail has rate limits; the agent will handle these gracefully
398 +- For high-volume usage, consider implementing request queuing
fumadocs/content/examples/gmail-labeler.mdx new
+381
@@ -0,0 +1,381 @@
1 +---
2 +title: Gmail Labeler
3 +description: Build an agent that automatically labels incoming Gmail messages using triggers
4 +---
5 +
6 +With Composio's managed authentication, tool calling and triggers, it's easy to
7 +build the AI agents that can interact and react the real world events reducing
8 +the boilerplate required to setup and manage the authentication. This cookbook
9 +will walk you through the process of building agents using `Composio`, `LangChain`.
10 +
11 +## Prerequisites
12 +
13 +* Python3.x
14 +* [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 gmail agent to label your messages
20 +
21 +```python
22 +from composio import Composio
23 +from composio_langchain import LangchainProvider
24 +
25 +from langchain import hub
26 +from langchain.agents import AgentExecutor, create_openai_functions_agent
27 +from langchain_openai import ChatOpenAI
28 +
29 +
30 +def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):
31 + """
32 + Create an agent for a given user id.
33 + """
34 + # Step 1: Get all the tools
35 + tools = composio_client.tools.get(
36 + user_id=user_id,
37 + tools=[
38 + "GMAIL_LIST_LABELS",
39 + "GMAIL_ADD_LABEL_TO_EMAIL",
40 + "GMAIL_CREATE_LABEL",
41 + ],
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-5")
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=False,
59 + )
60 +```
61 +
62 +## Authenticating users
63 +
64 +To authenticate your users with Composio you need an auth config for the given
65 +app, In this case you need one for gmail. You can create and manage auth configs
66 +from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=gmail).
67 +Composio platform provides composio managed authentication for some apps to help
68 +you fast-track your development, `gmail` 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 +To create an authentication config for `gmail` you need `client_id` and `client_secret`
80 +from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).
81 +Once you have the required credentials you can use the following piece of
82 +code to set up authentication for `gmail`.
83 +
84 +```python
85 +from composio import Composio
86 +from composio_langchain import LangchainProvider
87 +
88 +def create_auth_config(composio_client: Composio[OpenAIProvider]):
89 + """
90 + Create a auth config for the gmail toolkit.
91 + """
92 + client_id = os.getenv("GMAIL_CLIENT_ID")
93 + client_secret = os.getenv("GMAIL_CLIENT_SECRET")
94 + if not client_id or not client_secret:
95 + raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")
96 +
97 + return composio_client.auth_configs.create(
98 + toolkit="gmail",
99 + options={
100 + "name": "default_gmail_auth_config",
101 + "type": "use_custom_auth",
102 + "auth_scheme": "OAUTH2",
103 + "credentials": {
104 + "client_id": client_id,
105 + "client_secret": client_secret,
106 + },
107 + },
108 + )
109 +```
110 +
111 +This will create an authentication config for `gmail` which you can use to
112 +authenticate your users for your app. Ideally you should just create one
113 +authentication object per project, so check for an existing auth config
114 +before you create a new one.
115 +
116 +```python
117 +def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
118 + """
119 + Fetch the auth config for a given user id.
120 + """
121 + auth_configs = composio_client.auth_configs.list()
122 + for auth_config in auth_configs.items:
123 + if auth_config.toolkit == "gmail":
124 + return auth_config
125 +
126 + return None
127 +```
128 +</details>
129 +
130 +Once you have authentication management in place, we can start with connecting
131 +your users to your `gmail` app. Let's implement a function to connect the users
132 +to your `gmail` app via composio.
133 +
134 +```python
135 +# Function to initiate a connected account
136 +def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
137 + """
138 + Create a connection for a given user id and auth config id.
139 + """
140 + # Fetch or create the auth config for the gmail toolkit
141 + auth_config = fetch_auth_config(composio_client=composio_client)
142 + if not auth_config:
143 + auth_config = create_auth_config(composio_client=composio_client)
144 +
145 + # Create a connection for the user
146 + return composio_client.connected_accounts.initiate(
147 + user_id=user_id,
148 + auth_config_id=auth_config.id,
149 + )
150 +```
151 +
152 +Now, when creating tools for your agent always check if the user already has a
153 +connected account before creating a new one.
154 +
155 +```python
156 +def check_connected_account_exists(
157 + composio_client: Composio[LangchainProvider],
158 + user_id: str,
159 +):
160 + """
161 + Check if a connected account exists for a given user id.
162 + """
163 + # Fetch all connected accounts for the user
164 + connected_accounts = composio_client.connected_accounts.list(
165 + user_ids=[user_id],
166 + toolkit_slugs=["GMAIL"],
167 + )
168 +
169 + # Check if there's an active connected account
170 + for account in connected_accounts.items:
171 + if account.status == "ACTIVE":
172 + return True
173 +
174 + # Ideally you should not have inactive accounts, but if you do, you should delete them
175 + print(f"[warning] inactive account {account.id} found for user id: {user_id}")
176 + return False
177 +```
178 +
179 +
180 +## Creating Triggers
181 +
182 +You can use triggers to make your agents react to real world events. In this example,
183 +we will use triggers to invoke your agent everytime there's a new message in your
184 +gmail inbox.
185 +
186 +```python
187 +# Create a new trigger
188 +def create_trigger(
189 + composio_client: Composio[LangchainProvider],
190 + connected_account_id: str,
191 +) -> str:
192 + """
193 + Create a trigger.
194 + """
195 + response = composio_client.triggers.create(
196 + slug="GMAIL_NEW_GMAIL_MESSAGE",
197 + connected_account_id=connected_account_id,
198 + trigger_config={},
199 + )
200 + return response.trigger_id
201 +```
202 +
203 +When creating triggers, make sure there are no duplicate triggers. Use following
204 +code as reference for checking if trigger for given connected account exists or not.
205 +
206 +```python
207 +def check_trigger_exists(
208 + composio_client: Composio[LangchainProvider],
209 + connected_account_id: str,
210 +) -> t.Optional[str]:
211 + """
212 + Check if a trigger exists.
213 + """
214 + triggers = composio_client.triggers.list_active(
215 + trigger_names=["GMAIL_NEW_GMAIL_MESSAGE"],
216 + connected_account_ids=[connected_account_id],
217 + )
218 + for trigger in triggers.items:
219 + return trigger.id
220 + return None
221 +```
222 +
223 +
224 +Once trigger is created, you can listen to events using a trigger subscription.
225 +
226 +```python
227 +# Create subscription object
228 +trigger_subscription = composio_client.triggers.subscribe()
229 +
230 +# Register event handler
231 +@trigger_subscription.handle(
232 + trigger_id="<TRIGGER_ID>", # Filter out events that does not belong this trigger id
233 + trigger_slug="GMAIL_NEW_GMAIL_MESSAGE",
234 +)
235 +def handle_event(event: TriggerEvent):
236 + print("> Received email with subject: ", event["payload"]["subject"])
237 +
238 +# Wait for events
239 +trigger_subscription.wait_forever()
240 +```
241 +
242 +## Putting everything together
243 +
244 +Let's put together everything by making the agent react to new messages in your
245 +inbox.
246 +
247 +```python
248 +# Create a trigger subscription factory
249 +
250 +def create_trigger_subscription(
251 + composio_client: Composio[LangchainProvider],
252 + trigger_slug: str,
253 + trigger_id: str,
254 + agent: AgentExecutor,
255 +):
256 + """
257 + Create a trigger subscription for the given agent.
258 + """
259 + trigger_subscription = composio_client.triggers.subscribe()
260 +
261 + @trigger_subscription.handle(
262 + trigger_slug=trigger_slug,
263 + trigger_id=trigger_id,
264 + )
265 + def handle_event(event: TriggerEvent):
266 + print("> Received email with subject: ", event["payload"]["subject"])
267 + result = agent.invoke(
268 + input={
269 + "input": APPLY_NEW_LABEL.format( # Check `gmail_labeler/prompt.py`
270 + message_id=event["payload"]["id"],
271 + message_subject=event["payload"]["subject"],
272 + message_text=event["payload"]["message_text"],
273 + )
274 + }
275 + )
276 + print("> Result: ", result["output"])
277 +
278 + return trigger_subscription
279 +```
280 +
281 +Package everything as a single entry point.
282 +
283 +```python
284 +def run_agent(user_id: str):
285 + # Create composio client
286 + composio_client = Composio(provider=LangchainProvider())
287 +
288 + # Validate conected account
289 + connected_account_id = check_connected_account_exists(composio_client, user_id)
290 + if connected_account_id is None:
291 + connection_request = create_connection(composio_client, user_id)
292 + print(
293 + f"Authenticate with the following link: {connection_request.redirect_url}"
294 + )
295 + connection_request.wait_for_connection()
296 + connected_account_id = connection_request.id
297 +
298 + # Check if trigger exists, create if not
299 + trigger_id = check_trigger_exists(
300 + composio_client=composio_client,
301 + connected_account_id=connected_account_id,
302 + )
303 + if trigger_id is None:
304 + trigger_id = create_trigger(
305 + composio_client=composio_client,
306 + connected_account_id=connected_account_id,
307 + )
308 +
309 + # Create agent
310 + agent = create_agent(user_id=user_id, composio_client=composio_client)
311 +
312 + # Create trigger subscription
313 + trigger_subscription = create_trigger_subscription(
314 + composio_client=composio_client,
315 + trigger_slug=GMAIL_NEW_GMAIL_MESSAGE_TRIGGER,
316 + trigger_id=trigger_id,
317 + agent=agent,
318 + )
319 +
320 + # Wait forever
321 + print("Waiting for events...")
322 + trigger_subscription.wait_forever()
323 +```
324 +
325 +To test the above function as CLI, follow the steps below
326 +
327 +1. Clone the repository
328 + ```bash
329 + git clone git@github.com:composiohq/gmail-labeler
330 + cd gmail-labeler/
331 + ```
332 +2. Setup environment
333 + ```bash
334 + cp .env.example .env
335 + ```
336 +
337 + Fill the api keys
338 + ```dotenv
339 + COMPOSIO_API_KEY=
340 + OPENAI_API_KEY=
341 + ```
342 +
343 + Create the virtual env
344 + ```bash
345 + make env
346 + source .venv/bin/activate
347 + ```
348 +3. Run the agent
349 + ```bash
350 + python gmail_labeler --user-id "default"
351 + ```
352 +
353 +## Using Composio for managed auth and tools
354 +
355 +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
356 +- manage `gmail` oauth app
357 +- manage user connections
358 +- tools for your agents to interact with `gmail`
359 +- Infra for listening to changes in your gmail inbox
360 +
361 +Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
362 +
363 +## Best practices
364 +
365 +**🔒 User Management**:
366 +
367 +- Use unique, consistent `user_id` values for each person
368 +- Each user maintains their own gmail connection
369 +- User IDs can be email addresses, usernames, or any unique identifier
370 +
371 +## Troubleshooting
372 +
373 +**Connection Issues**:
374 +- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
375 +- Check that the user has completed `gmail` authorization
376 +- Verify the user_id matches exactly between requests
377 +
378 +**API Errors**:
379 +- Check the server logs for detailed error messages
380 +- Ensure request payloads match the expected format
381 +- Visit `/docs` endpoint for API schema validation
fumadocs/content/examples/hono.mdx new
+419
@@ -0,0 +1,419 @@
1 +---
2 +title: Basic Hono Server
3 +description: Build a simple Gmail agent with Composio and Hono.js
4 +---
5 +
6 +With Composio's managed authentication and tool calling, it's easy to build
7 +AI agents that interact with the real world while reducing boilerplate for
8 +setup and authentication management. This cookbook will guide you through
9 +building and serving agents using `Composio`, `OpenAI`, and `Hono.js`.
10 +
11 +## Prerequisites
12 +
13 +* Node.js 18.x or higher
14 +* npm or yarn package manager
15 +* Composio API key
16 +* OpenAI API key
17 +* Basic knowledge of OAuth
18 +* Understanding of building HTTP services (preferably using Hono.js)
19 +
20 +## Building an AI agent that can interact with `gmail` service
21 +
22 +First, let's start with building a simple AI agent embedded with tools from
23 +Composio that lets the agent interact with the `gmail` service.
24 +
25 +```typescript
26 +import { OpenAI } from 'openai';
27 +import { Composio } from '@composio/core';
28 +import { OpenAIProvider } from '@composio/openai';
29 +
30 +export async function runGmailAgent(
31 + composioClient: Composio<OpenAIProvider>,
32 + openaiClient: OpenAI,
33 + userId: string, // Composio uses the User ID to store and access user-level authentication tokens.
34 + prompt: string,
35 +): Promise<any[]> {
36 + // Step 1: Fetch the necessary Gmail tools list with Composio
37 + const tools = await composioClient.tools.get(
38 + userId,
39 + {
40 + tools: [
41 + "GMAIL_FETCH_EMAILS",
42 + "GMAIL_SEND_EMAIL",
43 + "GMAIL_CREATE_EMAIL_DRAFT"
44 + ]
45 + }
46 + );
47 +
48 + // Step 2: Use OpenAI to generate a response based on the prompt and available tools
49 + const response = await openaiClient.chat.completions.create({
50 + model: "gpt-4.1",
51 + tools,
52 + messages: [{ role: "user", content: prompt }],
53 + });
54 +
55 + // Step 3: Handle tool calls with Composio and return the result
56 + const result = await composioClient.provider.handleToolCalls(
57 + userId,
58 + response
59 + );
60 + return result;
61 +}
62 +```
63 +
64 +<Callout>
65 + This is a simple agent without state management and agentic loop implementation,
66 + so the agent can't perform complicated tasks. If you want to understand how
67 + composio can be used with agentic loops, check other cookbooks with more
68 + agentic frameworks.
69 +</Callout>
70 +
71 +To invoke this agent, authenticate your users with Composio's managed authentication service.
72 +
73 +## Authenticating users
74 +
75 +To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
76 +
77 +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`.
78 +
79 +```typescript
80 +import { Composio } from '@composio/core';
81 +import { OpenAIProvider } from '@composio/openai';
82 +
83 +export async function createAuthConfig(composioClient: Composio<OpenAIProvider>) {
84 + /**
85 + * Create a auth config for the gmail toolkit.
86 + */
87 + const clientId = process.env.GMAIL_CLIENT_ID;
88 + const clientSecret = process.env.GMAIL_CLIENT_SECRET;
89 + if (!clientId || !clientSecret) {
90 + throw new Error("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set");
91 + }
92 +
93 + return composioClient.authConfigs.create(
94 + "GMAIL",
95 + {
96 + "name": "default_gmail_auth_config",
97 + "type": "use_custom_auth",
98 + "authScheme": "OAUTH2",
99 + "credentials": {
100 + "clientId": clientId,
101 + "clientSecret": clientSecret,
102 + },
103 + },
104 + );
105 +}
106 +```
107 +
108 +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.
109 +
110 +```typescript
111 +export async function fetchAuthConfig(composioClient: Composio<OpenAIProvider>) {
112 + /**
113 + * Fetch the auth config for a given user id.
114 + */
115 + const authConfigs = await composioClient.authConfigs.list();
116 + for (const authConfig of authConfigs.items) {
117 + if (authConfig.toolkit.slug === "gmail") {
118 + return authConfig;
119 + }
120 + }
121 +
122 + return null;
123 +}
124 +```
125 +
126 +<Callout>
127 + Composio platform provides composio managed authentication for some apps to
128 + fast-track your development, `gmail` being one of them. You can use these
129 + default auth configs for development, but for production, always use your
130 + own oauth app configuration.
131 +</Callout>
132 +
133 +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.
134 +
135 +```typescript
136 +import { Hono } from 'hono';
137 +
138 +// Function to initiate a connected account
139 +export async function createConnection(composioClient: Composio<OpenAIProvider>, userId: string) {
140 + /**
141 + * Create a connection for a given user id and auth config id.
142 + */
143 + // Fetch or create the auth config for the gmail toolkit
144 + let authConfig = await fetchAuthConfig(composioClient);
145 + if (!authConfig) {
146 + authConfig = await createAuthConfig(composioClient);
147 + }
148 +
149 + // Create a connection for the user
150 + return composioClient.connectedAccounts.initiate(
151 + userId,
152 + authConfig.id,
153 + );
154 +}
155 +
156 +// Setup Hono
157 +const app = new Hono();
158 +
159 +// Connection initiation endpoint
160 +app.post("/connection/create", async (c) => {
161 + /**
162 + * Create a connection for a given user id.
163 + */
164 + // For demonstration, using a default user_id. Replace with real user logic in production.
165 + const userId = "default";
166 +
167 + // Create a new connection for the user
168 + const connectionRequest = await createConnection(composioClient, userId);
169 + return c.json({
170 + "connection_id": connectionRequest.id,
171 + "redirect_url": connectionRequest.redirectUrl,
172 + });
173 +});
174 +```
175 +
176 +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.
177 +
178 +## Set Up Hono service
179 +
180 +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.
181 +
182 +### Setup dependencies
183 +
184 +Hono allows dependency injection patterns to simplify the usage of SDK clients that must be singletons. We recommend using composio SDK client as singleton.
185 +
186 +```typescript
187 +import { Composio } from '@composio/core';
188 +import { OpenAIProvider } from '@composio/openai';
189 +import { OpenAI } from 'openai';
190 +
191 +let _composioClient: Composio<OpenAIProvider> | null = null;
192 +
193 +export function provideComposioClient(): Composio<OpenAIProvider> {
194 + /**
195 + * Provide a Composio client.
196 + */
197 + if (_composioClient === null) {
198 + _composioClient = new Composio({
199 + provider: new OpenAIProvider()
200 + });
201 + }
202 + return _composioClient;
203 +}
204 +
205 +// A Composio client dependency.
206 +export type ComposioClient = Composio<OpenAIProvider>;
207 +```
208 +
209 +Check [config/composio.ts](./src/config/composio.ts) module for more details.
210 +
211 +### Invoke agent via Hono
212 +
213 +When invoking an agent, make sure you validate the `user_id`.
214 +
215 +```typescript
216 +export function checkConnectedAccountExists(
217 + composioClient: Composio<OpenAIProvider>,
218 + userId: string,
219 +): Promise<boolean> {
220 + /**
221 + * Check if a connected account exists for a given user id.
222 + */
223 + // Fetch all connected accounts for the user
224 + return composioClient.connectedAccounts.list({ userIds: [userId], toolkitSlugs: ["GMAIL"] }).then(connectedAccounts => {
225 +
226 + // Check if there's an active connected account
227 + for (const account of connectedAccounts.items) {
228 + if (account.status === "ACTIVE") {
229 + return true;
230 + }
231 +
232 + // Ideally you should not have inactive accounts, but if you do, delete them.
233 + console.log(`[warning] inactive account ${account.id} found for user id: ${userId}`);
234 + }
235 + return false;
236 + });
237 +}
238 +
239 +export async function validateUserId(userId: string, composioClient: ComposioClient): Promise<string> {
240 + /**
241 + * Validate the user id, if no connected account is found, create a new connection.
242 + */
243 + if (await checkConnectedAccountExists(composioClient, userId)) {
244 + return userId;
245 + }
246 +
247 + throw new Error("No connected account found for the user id");
248 +}
249 +
250 +// Endpoint: Run the Gmail agent for a given user id and prompt
251 +app.post("/agent", async (c) => {
252 + /**
253 + * Run the Gmail agent for a given user id and prompt.
254 + */
255 + const request = await c.req.json();
256 +
257 + // For demonstration, using a default user_id. Replace with real user logic in production.
258 + const userId = "default";
259 +
260 + // Validate the user id before proceeding
261 + await validateUserId(userId, composioClient);
262 +
263 + // Run the Gmail agent using Composio and OpenAI
264 + const result = await runGmailAgent(
265 + composioClient,
266 + openaiClient,
267 + userId,
268 + request.prompt,
269 + );
270 + return c.json(result);
271 +});
272 +```
273 +
274 +<Callout>
275 + Check [src/api.ts](./src/api.ts) module for service implementation
276 +</Callout>
277 +
278 +## Putting everything together
279 +
280 +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.
281 +
282 +<Callout>
283 + Before proceeding, check the [code](./src/api.ts) for utility endpoints not discussed in the cookbook
284 +</Callout>
285 +
286 +1. Clone the repository
287 + ```bash
288 + git clone git@github.com:composiohq/composio-hono
289 + cd composio-hono/
290 + ```
291 +2. Setup environment
292 +
293 + ```bash
294 + cp .env.example .env
295 + ```
296 +
297 + Fill the api keys
298 +
299 + ```dotenv
300 + COMPOSIO_API_KEY=
301 + OPENAI_API_KEY=
302 + ```
303 +
304 + Install dependencies
305 +
306 + ```bash
307 + npm install
308 + ```
309 +3. Run the HTTP server
310 + ```bash
311 + npm run dev
312 + ```
313 +
314 +## Testing the API with curl
315 +
316 +Assuming the server is running locally on `http://localhost:8000`.
317 +
318 +### Check if a connection exists
319 +
320 +```bash
321 +curl -X POST http://localhost:8000/connection/exists
322 +```
323 +
324 +### Create a connection
325 +
326 +Note: The body fields are required by the API schema, but are ignored internally in this example service.
327 +
328 +```bash
329 +curl -X POST http://localhost:8000/connection/create \
330 + -H "Content-Type: application/json" \
331 + -d '{
332 + "user_id": "default",
333 + "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
334 + }'
335 +```
336 +
337 +Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.
338 +
339 +### Check connection status
340 +
341 +Use the `connection_id` returned from the create step.
342 +
343 +```bash
344 +curl -X POST http://localhost:8000/connection/status \
345 + -H "Content-Type: application/json" \
346 + -d '{
347 + "user_id": "default",
348 + "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
349 + }'
350 +```
351 +
352 +### Run the Gmail agent
353 +
354 +Requires an active connected account for the `default` user.
355 +
356 +```bash
357 +curl -X POST http://localhost:8000/agent \
358 + -H "Content-Type: application/json" \
359 + -d '{
360 + "user_id": "default",
361 + "prompt": "Summarize my latest unread emails from the last 24 hours."
362 + }'
363 +```
364 +
365 +### Fetch emails (direct action)
366 +
367 +```bash
368 +curl -X POST http://localhost:8000/actions/fetch_emails \
369 + -H "Content-Type: application/json" \
370 + -d '{
371 + "user_id": "default",
372 + "limit": 5
373 + }'
374 +```
375 +
376 +These examples are intended solely for testing purposes.
377 +
378 +## Using Composio for managed auth and tools
379 +
380 +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
381 +
382 +* manage Gmail OAuth app
383 +* manage user connections
384 +* tools for your agents to interact with Gmail
385 +
386 +Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.
387 +
388 +## Best practices
389 +
390 +**🎯 Effective Prompts**:
391 +
392 +* Be specific: "Send email to [john@company.com](mailto:john@company.com) about tomorrow's 2pm meeting" works better than "send email"
393 +* Include context: "Reply to Sarah's email about the budget with our approval"
394 +* Use natural language: The agent understands conversational requests
395 +
396 +**🔑 User Management**:
397 +
398 +* Use unique, consistent `user_id` values for each person
399 +* Each user maintains their own Gmail connection
400 +* User IDs can be email addresses, usernames, or any unique identifier
401 +
402 +## Troubleshooting
403 +
404 +**Connection Issues**:
405 +
406 +* Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
407 +* Check if the user has completed Gmail authorization.
408 +* Verify the user\_id matches exactly between requests
409 +
410 +**API Errors**:
411 +
412 +* Check the server logs for detailed error messages
413 +* Ensure request payloads match the expected format
414 +* Visit `/docs` endpoint for API schema validation
415 +
416 +**Gmail API Limits**:
417 +
418 +* Gmail has rate limits; the agent will handle these gracefully
419 +* For high-volume usage, consider implementing request queuing
\ No newline at end of file
fumadocs/content/examples/index.mdx
+10 -6
@@ -7,15 +7,19 @@ Explore practical examples of building AI agents with Composio.
7
8 ## Getting Started
9
10 -- [Basic FastAPI Server](/examples/fast-api) - Build a simple API server with Composio
11 -- [Basic Hono Server](/examples/hono) - Build a Hono server with Composio
10 +- [Basic FastAPI Server](/examples/fast-api) - Build a Gmail agent with FastAPI
11 +- [Basic Hono Server](/examples/hono) - Build a Gmail agent with Hono.js
12
13 ## Productivity & Automation
14
15 -- [Gmail Labeller](/examples/gmail-labeler) - Automatically label emails
16 -- [Slack Summariser](/examples/slack-summariser) - Summarize Slack conversations
17 -- [Supabase SQL Agent](/examples/supabase-sql-agent) - Query databases with AI
15 +- [Gmail Labeler](/examples/gmail-labeler) - Automatically label incoming emails using triggers
16 +- [Slack Summarizer](/examples/slack-summariser) - Summarize Slack channel messages
17 +- [Supabase SQL Agent](/examples/supabase-sql-agent) - Execute SQL queries using natural language
18
19 ## Full Stack Applications
20
21 -- [Full Stack Chat App](/examples/vercel-chat) - Complete chat application example
21 +- [Full Stack Chat App](/examples/vercel-chat) - Build a chat interface with user connections
22 +
23 +## Behind the Curtain
24 +
25 +- [Tool Type Generator](/examples/tool-generator) - Build platforms using raw tool definitions
fumadocs/content/examples/meta.json
+11 -1
@@ -1,7 +1,17 @@
1 {
2 "title": "Examples",
3 + "root": true,
4 "pages": [
5 "---Getting Started---",
5 - "index"
6 + "fast-api",
7 + "hono",
8 + "---Productivity & Automation---",
9 + "gmail-labeler",
10 + "slack-summariser",
11 + "supabase-sql-agent",
12 + "---Full Stack Applications---",
13 + "vercel-chat",
14 + "---Behind the Curtain---",
15 + "tool-generator"
16 ]
17 }
fumadocs/content/examples/slack-summariser.mdx new
+303
@@ -0,0 +1,303 @@
1 +---
2 +title: Slack Summarizer
3 +description: Build an agent that summarizes Slack channel messages
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`.
10 +
11 +## Prerequisites
12 +
13 +* Python3.x
14 +* [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 +---
80 +
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`.
84 +
85 +```python
86 +from composio import Composio
87 +from composio_langchain import LangchainProvider
88 +
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 + )
110 +```
111 +
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
126 +
127 + return None
128 +```
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.
134 +
135 +```python
136 +
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 +```
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=["SLACK"],
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 +## Modifiers
182 +
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.
188 +
189 +```python
190 +from composio import after_execute
191 +from composio.types import ToolExecutionResponse
192 +
193 +
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
205 +
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
214 +
215 + return response
216 +```
217 +
218 +To register modifiers, include them in the `composio.tools.get` call.
219 +
220 +```python
221 +tools = composio_client.tools.get(
222 + user_id=user_id,
223 + toolkits=[SLACK_TOOLKIT],
224 + modifiers=[clean_conversation_history],
225 +)
226 +```
227 +
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.
233 +
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()
243 +
244 + agent = create_agent(user_id, composio_client)
245 + agent.invoke({"input": prompt})
246 +```
247 +
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
fumadocs/content/examples/supabase-sql-agent.mdx new
+254
@@ -0,0 +1,254 @@
1 +---
2 +title: Supabase SQL Agent
3 +description: Build an agent that executes SQL queries on Supabase using natural language
4 +---
5 +
6 +With Composio's managed authentication and tool calling, it's easy to build
7 +AI agents that interact with the real world while reducing boilerplate for
8 +setup and authentication management. This guide will walk you through using
9 +the Supabase CLI agent built with `Composio` and `LlamaIndex`.
10 +
11 +
12 +## Requirements
13 +
14 +* Python 3.10+
15 +* [UV](https://docs.astral.sh/uv/getting-started/installation/) (recommended) or pip
16 +* Composio API key
17 +* OpenAI API key
18 +* Understanding of building AI agents (Preferably with LlamaIndex)
19 +
20 +## Build an agent to perform Supabase tasks
21 +
22 +```python
23 +from composio import Composio
24 +from composio_llamaindex import LlamaIndexProvider
25 +
26 +from llama_index.llms.openai import OpenAI
27 +from llama_index.core.agent.workflow import FunctionAgent
28 +from llama_index.core.workflow import Context
29 +
30 +
31 +def create_agent(user_id: str, composio_client: Composio[LlamaIndexProvider]):
32 + """
33 + Create a function agent that can perform Supabase tasks.
34 + """
35 +
36 + # Setup client
37 + llm = OpenAI(model="gpt-5")
38 +
39 + # Get All the tools
40 + tools = composio_client.tools.get(
41 + user_id=user_id,
42 + tools=[
43 + "SUPABASE_LIST_ALL_PROJECTS",
44 + "SUPABASE_BETA_RUN_SQL_QUERY",
45 + ],
46 + )
47 +
48 + agent = FunctionAgent(
49 + tools=tools,
50 + llm=llm,
51 + system_prompt=(
52 + "You are a helpful assistant that can help with supabase queries."
53 + ),
54 + )
55 +
56 + # Since this is a continuosly running agent, we need to maintain state across
57 + # different user messages
58 + ctx = Context(workflow=agent)
59 + return agent, ctx
60 +```
61 +
62 +This agent can convert your natural language queries to SQL queries and execute
63 +them on supabase for you. For you agent to be able to execute queries, you need
64 +to authenticate the agent for supabase.
65 +
66 +
67 +## Authenticating users
68 +
69 +To authenticate your users with Composio you need an auth config for the given
70 +app, In this case you need one for supabase. You can create and manage auth configs
71 +from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=supabase).
72 +Composio platform provides composio managed authentication for some apps to help
73 +you fast-track your development, `supabase` being one of them. You can use these
74 +default auth configs for development, but for production you should always use
75 +your own oauth app configuration.
76 +
77 +Using dashboard is the preferred way of managing authentication configs, but if
78 +you want to do it manually you can follow the guide below
79 +
80 +<details>
81 +
82 +<summary>Click to expand</summary>
83 +
84 +---
85 +
86 +To create an authentication config for `supabase` you need `client_id` and `client_secret`
87 +from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).
88 +Once you have the required credentials you can use the following piece of
89 +code to set up authentication for `supabase`.
90 +
91 +```python
92 +from composio import Composio
93 +from composio_langchain import LangchainProvider
94 +
95 +def create_auth_config(composio_client: Composio[OpenAIProvider]):
96 + """
97 + Create a auth config for the supabase toolkit.
98 + """
99 + client_id = os.getenv("SUPABASE_CLIENT_ID")
100 + client_secret = os.getenv("SUPABASE_CLIENT_SECRET")
101 + if not client_id or not client_secret:
102 + raise ValueError("SUPABASE_CLIENT_ID and SUPABASE_CLIENT_SECRET must be set")
103 +
104 + return composio_client.auth_configs.create(
105 + toolkit="supabase",
106 + options={
107 + "name": "default_supabase_auth_config",
108 + "type": "use_custom_auth",
109 + "auth_scheme": "OAUTH2",
110 + "credentials": {
111 + "client_id": client_id,
112 + "client_secret": client_secret,
113 + },
114 + },
115 + )
116 +```
117 +
118 +This will create an authentication config for `supabase` which you can use to
119 +authenticate your users for your app. Ideally you should just create one
120 +authentication object per project, so check for an existing auth config
121 +before you create a new one.
122 +
123 +```python
124 +def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
125 + """
126 + Fetch the auth config for a given user id.
127 + """
128 + auth_configs = composio_client.auth_configs.list()
129 + for auth_config in auth_configs.items:
130 + if auth_config.toolkit == "supabase":
131 + return auth_config
132 +
133 + return None
134 +```
135 +</details>
136 +
137 +Once you have authentication management in place, we can start with connecting
138 +your users to your `supabase` app. Let's implement a function to connect the users
139 +to your `supabase` app via composio.
140 +
141 +```python
142 +# Function to initiate a connected account
143 +def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
144 + """
145 + Create a connection for a given user id and auth config id.
146 + """
147 + # Fetch or create the auth config for the supabase toolkit
148 + auth_config = fetch_auth_config(composio_client=composio_client)
149 + if not auth_config:
150 + auth_config = create_auth_config(composio_client=composio_client)
151 +
152 + # Create a connection for the user
153 + return composio_client.connected_accounts.initiate(
154 + user_id=user_id,
155 + auth_config_id=auth_config.id,
156 + )
157 +```
158 +
159 +Now, when creating tools for your agent always check if the user already has a
160 +connected account before creating a new one.
161 +
162 +```python
163 +def check_connected_account_exists(
164 + composio_client: Composio[LangchainProvider],
165 + user_id: str,
166 +):
167 + """
168 + Check if a connected account exists for a given user id.
169 + """
170 + # Fetch all connected accounts for the user
171 + connected_accounts = composio_client.connected_accounts.list(
172 + user_ids=[user_id],
173 + toolkit_slugs=["SUPABASE"],
174 + )
175 +
176 + # Check if there's an active connected account
177 + for account in connected_accounts.items:
178 + if account.status == "ACTIVE":
179 + return True
180 +
181 + # Ideally you should not have inactive accounts, but if you do, you should delete them
182 + print(f"[warning] inactive account {account.id} found for user id: {user_id}")
183 + return False
184 +```
185 +
186 +
187 +## Create a chat loop
188 +
189 +```python
190 +async def run_loop(user_id: str):
191 + # Initialize composio client.
192 + composio_client = Composio(provider=LlamaIndexProvider())
193 +
194 + # Setup connection if required
195 + if not check_connected_account_exists(
196 + composio_client=composio_client,
197 + user_id=user_id,
198 + ):
199 + connection_request = create_connection(
200 + composio_client=composio_client,
201 + user_id=user_id,
202 + )
203 + print(
204 + f"Authenticate with the following link: {connection_request.redirect_url}"
205 + )
206 +
207 + # Create agent
208 + agent, ctx = create_agent(
209 + user_id=user_id,
210 + composio_client=composio_client,
211 + )
212 +
213 + # Run a simple REPL loop
214 + while True:
215 + user_input = input("user > ")
216 + if user_input.lower() == "exit":
217 + break
218 +
219 + result = await agent.run(user_msg=user_input, ctx=ctx)
220 + print("agent > ", result)
221 + print("Exiting...")
222 +```
223 +
224 +## Using Composio for managed auth and tools
225 +
226 +Composio reduces a lot of boilerplate for building AI agents with ability access
227 +and use a wide variety of apps. For example in this cookbook, to build `supabase`
228 +integration without composio you would have to write code to
229 +
230 +- manage `supabase` oauth app
231 +- manage user connections
232 +- tools for your agents to interact with `supabase`
233 +
234 +Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
235 +
236 +## Best practices
237 +
238 +**🔒 User Management**:
239 +
240 +- Use unique, consistent `user_id` values for each person
241 +- Each user maintains their own supabase connection
242 +- User IDs can be email addresses, usernames, or any unique identifier
243 +
244 +## Troubleshooting
245 +
246 +**Connection Issues**:
247 +- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
248 +- Check that the user has completed `supabase` authorization
249 +- Verify the user_id matches exactly between requests
250 +
251 +**API Errors**:
252 +- Check the server logs for detailed error messages
253 +- Ensure request payloads match the expected format
254 +- Visit `/docs` endpoint for API schema validation
fumadocs/content/examples/tool-generator.mdx new
+273
@@ -0,0 +1,273 @@
1 +---
2 +title: Tool Type Generator
3 +description: Build your own platform using raw tool definitions
4 +---
5 +
6 +This is a bit of a checky tutorial as it is dogfooding the `docs` tool generation process.
7 +
8 +To motivate this example clearly, in our tools section — we have details about let's say [`Github`](/tools/github) tool, that shows its auth scheme, actions and their params.
9 +
10 +Now why would anyone outside of Composio want to do this? Well if you are building a platform on top of Composio, perchance a Workflow builder like langflow. You would want to show some or all of this information to your users.
11 +
12 +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.
13 +
14 +## How does one build a tool type generator?
15 +
16 +In composio, we have two internal states for tools
17 +
18 +1. Raw tool definition
19 +2. Provider tool definition
20 +
21 +The raw tool definition is an generic input output schema definition that we internally for tools, we expose it for customers if they want to build on top of it but it is not the primary way tools are normally used.
22 +
23 +The provider tool definition, translates this raw tool definition to the specific schema of a provider (by default `openai`).
24 +
25 +For building something like this, we need to use the raw tool definition.
26 +
27 +
28 +## Getting the raw tool definition
29 +
30 +Of course, you need to initiate the `Composio` sdk first and use a `COMPOSIO_API_KEY` environment variable.
31 +
32 +
33 +```python Python {2} title="tool_doc_generator/main.py" maxLines=40 wordWrap
34 +
35 + def __init__(self, include_local: bool = False):
36 + """
37 +```
38 +
39 +
40 +Let us see an example output for a raw `GMAIL` toolkit, with all of its tools.
41 +
42 +this is just a taste but you can see the full output [here](https://github.com/composio-dev/composio/blob/next/fern/pages/src/examples/tool-generator/output.json).
43 +
44 +```json JSON title="output.json" maxLines=40
45 +[
46 + {
47 + "deprecated": {
48 + "available_versions": [
49 + "0_1",
50 + "latest",
51 + "latest:base"
52 + ],
53 + "display_name": "Modify email labels",
54 + "is_deprecated": false,
55 + "toolkit": {
56 + "logo": "https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/gmail.svg"
57 + },
58 + "version": "0_1",
59 + "displayName": "Modify email labels"
60 + },
61 + "description": "Adds and/or removes specified gmail labels for a message; ensure `message id` and all `label ids` are valid (use 'listlabels' for custom label ids).",
62 + "input_parameters": {
63 + "properties": {
64 + "add_label_ids": {
65 + "default": [],
66 + "description": "Label IDs to add. For custom labels, obtain IDs via 'listLabels'. System labels (e.g., 'INBOX', 'SPAM') can also be used.",
67 + "examples": [
68 + "STARRED",
69 + "IMPORTANT",
70 + "Label_123"
71 + ],
72 + "items": {
73 + "type": "string"
74 + },
75 + "title": "Add Label Ids",
76 + "type": "array"
77 + },
78 + "message_id": {
79 + "description": "Immutable ID of the message to modify (e.g., from 'fetchEmails' or 'fetchMessagesByThreadId').",
80 + "examples": [
81 + "17f1b2b9c1b2a3d4"
82 + ],
83 + "title": "Message Id",
84 + "type": "string"
85 + },
86 + "remove_label_ids": {
87 + "default": [],
88 + "description": "Label IDs to remove. For custom labels, obtain IDs via 'listLabels'. System labels can also be used.",
89 + "examples": [
90 + "UNREAD",
91 + "Label_456"
92 + ],
93 + "items": {
94 + "type": "string"
95 + },
96 + "title": "Remove Label Ids",
97 + "type": "array"
98 + },
99 + "user_id": {
100 + "default": "me",
101 + "description": "User's email address or 'me' for the authenticated user.",
102 + "examples": [
103 + "me",
104 + "user@example.com"
105 + ],
106 + "title": "User Id",
107 + "type": "string"
108 + }
109 + },
110 + "required": [
111 + "message_id"
112 + ],
113 + "title": "AddLabelToEmailRequest",
114 + "type": "object"
115 + },
116 + "name": "Modify email labels",
117 + "no_auth": false,
118 + "output_parameters": {
119 + "properties": {
120 + "data": {
121 + "description": "Data from the action execution",
122 + "properties": {
123 + "response_data": {
124 + "description": "Full `Message` resource with updated labels.",
125 + "title": "Response Data",
126 + "type": "object"
127 + }
128 + },
129 + "required": [
130 + "response_data"
131 + ],
132 + "title": "Data",
133 + "type": "object"
134 + },
135 + "error": {
136 + "anyOf": [
137 + {
138 + "type": "string"
139 + },
140 + {
141 + "type": "null"
142 + }
143 + ],
144 + "default": null,
145 +```
146 +
147 +```sh
148 +jq '.[0] | keys' pages/src/examples/tool-generator/output.json
149 +[
150 + "available_versions",
151 + "deprecated",
152 + "description",
153 + "input_parameters",
154 + "name",
155 + "no_auth",
156 + "output_parameters",
157 + "scopes",
158 + "slug",
159 + "tags",
160 + "toolkit",
161 + "version"
162 +]
163 +```
164 +
165 +There is a bunch of useful information here, around the `input_parameters` and `output_parameters` for this example but `scopes` is very valuable to know what permissions are required for this tool.
166 +
167 +Now from these `input_parameters` and `output_parameters` you can showcase the tool definitions.
168 +
169 +
170 +```python Python title="tool_doc_generator/main.py" maxLines=40
171 + fields = []
172 + _, field_config = field
173 +
174 + for field_list, required in [
175 + (getattr(field_config, "required", []), True),
176 + (getattr(field_config, "optional", []), False),
177 + ]:
178 + for f in field_list:
179 + if hasattr(f, "name"):
180 + fields.append(self._create_param_from_field(f, required))
181 +```
182 +
183 +There is a bunch of other processing things happening here that are super generally relevant, so not going to call them out here that said there is another thing i want to showcase
184 +
185 +## Toolkit Information
186 +
187 +Toolkis are what we call apps or integrations, for us they are a collection of tools. `GMAIL` has `GMAIL_SEND_EMAIL` as a tool.
188 +
189 +Now for building something out like this, you might also want information about the toolkit itself.
190 +
191 +A toolkit has information like `categories` or `auth_schemes`
192 +
193 +```python Python title="tool_doc_generator/main.py" maxLines=40
194 + """
195 + Initialize the tool documentation generator.
196 +
197 + Args:
198 +```
199 +
200 +`auth_schemes` here are `OAUTH2`, `API_KEY` or `BASIC_AUTH`, etc — essentially the types of how one could authenticate with the toolkit.
201 +
202 +```python Python title="tool_doc_generator/main.py" maxLines=40
203 + # Initialize composio client
204 + self.composio = Composio()
205 + self.include_local = include_local
206 +
207 + # For tracking generated tools
208 + self.generated_tools = []
209 + self.problematic_actions = []
210 +
211 + def generate_docs(
212 + self, output_path: Path, max_workers: int | None = None, limit: int | None = None
213 +```
214 +
215 +Here is a way to parse the `auth_scheme` data
216 +
217 +
218 +these are `tuple` objects as they have different schema for specific conditions like `auth_config_creation` or `connected_account_initiation`
219 +
220 +they also have `required` and `optional` fields.
221 +
222 +the context here is there are some fields you need while creating an auth config and some you need while connecting an account. this separation is done by the `tuple` here
223 +
224 +```python Python title="tool_doc_generator/main.py" maxLines=40
225 + auth_schemes: t.Optional[t.List[toolkit_retrieve_response.AuthConfigDetail]] = None,
226 + ) -> None:
227 + schemes = ", ".join(
228 + self._get_auth_type(s) for s in (auth_schemes or []) if self._extract_auth_fields(s)
229 + )
230 + self._blocks.extend(
231 + [
232 + f"""## Connecting to {app_name}
233 +### Create an auth config
234 +Use the dashboard to create an auth config for the {app_name} toolkit. This allows you to connect multiple {app_name} accounts to Composio for agents to use.
235 +
236 +<Steps>
237 + <Step title="Select App">
238 + Navigate to **[{app_name}](https://platform.composio.dev?next_page=/marketplace/{app_name})**.
239 + </Step>
240 + <Step title="Configure Auth Config Settings">
241 + Select among the supported auth schemes of and configure them here.
242 + </Step>
243 + <Step title="Create and Get auth config ID">
244 + Click **"Create {app_name} Auth Config"**. After creation, **copy the displayed ID starting with `ac_`**. This is your auth config ID. This is _not_ a sensitive ID -- you can save it in environment variables or a database.
245 + **This ID will be used to create connections to the toolkit for a given user.**
246 + </Step>
247 +</Steps>
248 +"""
249 + ],
250 + )
251 +
252 + # Add auth code snippets
253 + self._add_auth_section(app_name, app_slug, auth_schemes)
254 +
255 + def _add_auth_section(
256 + self,
257 + app_name: str,
258 + app_slug: str,
259 + auth_schemes: t.List[toolkit_retrieve_response.AuthConfigDetail] = None,
260 + ) -> None:
261 + """Add code snippets for each auth scheme using direct template processing"""
262 + if not auth_schemes:
263 + return
264 +
265 + self._blocks.append("### Connect Your Account")
266 +
267 + # Group auth schemes by type to avoid duplicates
268 + seen_auth_types = set()
269 +
270 +```
271 +
272 +
273 +This is a fairly minimal explanation for the amount of code, as most of it is not super related to composio but it will be a good example on seeing behind the scenes of how composio is working and how to leverage the platform further.
\ No newline at end of file
fumadocs/content/examples/vercel-chat.mdx new
+297
@@ -0,0 +1,297 @@
1 +---
2 +title: Full Stack Chat App
3 +description: Build a chat interface where users can connect and use their own apps
4 +---
5 +
6 +In this example, you will learn how to build a chatbot that:
7 +
8 +- Lets users connect their various apps to the chatbot using the Composio SDK.
9 +- Uses the Vercel provider in the Composio SDK to handle and execute tool calls from the LLM.
10 +
11 +This page gives a high-level overview of the Composio SDK and how it is used in the
12 +GitHub repository: [composiohq/chat](https://github.com/composiohq/chat). You can
13 +find the demo live [here](https://chat.composio.dev/).
14 +
15 +## Prerequisites
16 +
17 +Ensure you've followed the README.md in the [composiohq/chat](https://github.com/composiohq/chat)
18 +repository to set up the project locally.
19 +
20 +## Creating auth configs
21 +
22 +For all the apps you want to connect to the chatbot, you need to create their
23 +respective auth configs. Learn how to create auth configs [here](/docs/authenticating-tools#creating-an-auth-config).
24 +Once done, your auth configs will be available in the [Composio dashboard](https://app.composio.dev/integrations).
25 +
26 +
27 + <img src="../../../../assets/images/examples/auth-configs.png" alt="Auth configs" />
28 +
29 +
30 +### Save auth config IDs to environment variables
31 +
32 +For this project, the auth config IDs should be saved to the environment variables
33 +with the `NEXT_PUBLIC_` prefix.
34 +
35 +```bash .env.local
36 +NEXT_PUBLIC_GMAIL_AUTH_CONFIG_ID=ac_1234567890
37 +NEXT_PUBLIC_GITHUB_AUTH_CONFIG_ID=ac_1234567890
38 +```
39 +
40 +## Create a Composio client instance
41 +
42 +We create a Composio client instance for server-side operations like API routes,
43 +server components, etc.
44 +
45 +```typescript lib/service/composio.ts
46 +import { Composio } from '@composio/core';
47 +import { VercelProvider } from '@composio/vercel';
48 +
49 +const composio = new Composio({
50 + apiKey: process.env.COMPOSIO_API_KEY,
51 + provider: new VercelProvider(),
52 +});
53 +
54 +export default composio;
55 +```
56 +
57 +## Creating an API for fetching toolkits
58 +
59 +The Composio SDK is meant to be used only in server-side code. For client-side
60 +functionality, we create API endpoints in the `/app/api/` directory. In order to
61 +list the toolkits and their connection status, we create a Next.js API route to
62 +fetch the toolkits using Composio SDK.
63 +
64 +
65 + <img src="../../../../assets/images/examples/toolkits.png" />
66 +
67 +
68 +### 1. Listing connected accounts
69 +
70 +First, we fetch all connected accounts for a user and create a mapping of toolkit
71 +slugs to their connection IDs:
72 +
73 +```typescript app/api/composio/toolkits.ts
74 +export async function GET() {
75 + // ... auth logic ...
76 +
77 + // List connected accounts to get connection IDs for each toolkit
78 + const connectedAccounts = await composio.connectedAccounts.list({
79 + userIds: [session.user.id],
80 + });
81 +
82 + const connectedToolkitMap = new Map();
83 + connectedAccounts.items.forEach(account => {
84 + connectedToolkitMap.set(account.toolkit.slug.toUpperCase(), account.id);
85 + });
86 +
87 + // ... continue with toolkit fetching ...
88 +}
89 +```
90 +
91 +### 2. Fetching toolkit data and building response
92 +
93 +Next, we fetch toolkit information for each supported toolkit and combine it with the connection status:
94 +
95 +```typescript app/api/composio/toolkits.ts
96 +export async function GET() {
97 + // ... auth logic ...
98 + // ... connected accounts mapping ...
99 +
100 + const SUPPORTED_TOOLKITS = ['GMAIL', 'GOOGLECALENDAR', 'GITHUB', 'NOTION'];
101 +
102 + // Fetch toolkit data from slugs
103 + const toolkitPromises = SUPPORTED_TOOLKITS.map(async slug => {
104 + const toolkit = await composio.toolkits.get(slug);
105 + const connectionId = connectedToolkitMap.get(slug.toUpperCase());
106 +
107 + return {
108 + name: toolkit.name,
109 + slug: toolkit.slug,
110 + description: toolkit.meta?.description,
111 + logo: toolkit.meta?.logo,
112 + categories: toolkit.meta?.categories,
113 + isConnected: !!connectionId,
114 + connectionId: connectionId || undefined,
115 + };
116 + });
117 +
118 + const toolkits = await Promise.all(toolkitPromises);
119 + return NextResponse.json({ toolkits });
120 +}
121 +```
122 +
123 +## Managing connections
124 +
125 +Users need to connect and disconnect their accounts from the chatbot to enable tool usage. When users click "Connect" on a toolkit, we initiate an OAuth flow, and when they click "Disconnect", we remove their connection.
126 +
127 +### 1. Initiating a connection
128 +
129 +When a user wants to connect their account, we create a connection request that redirects them to the OAuth provider:
130 +
131 +
132 + <img src="../../../../assets/images/examples/create-connection.png" />
133 +
134 +
135 +```typescript app/api/connections/initiate/route.ts
136 +export async function POST(request: Request) {
137 + // ... auth and validation ...
138 +
139 + const { authConfigId } = requestBody;
140 +
141 + // Initiate connection with Composio
142 + const connectionRequest = await composio.connectedAccounts.initiate(
143 + session.user.id,
144 + authConfigId
145 + );
146 +
147 + return NextResponse.json({
148 + redirectUrl: connectionRequest.redirectUrl,
149 + connectionId: connectionRequest.id,
150 + });
151 +}
152 +```
153 +
154 +### 2. Checking connection status
155 +
156 +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:
157 +
158 +
159 + <img src="../../../../assets/images/examples/connection-status.png" />
160 +
161 +
162 +```typescript app/api/connections/status/route.ts
163 +export async function GET(request: Request) {
164 + // ... auth and validation ...
165 +
166 + const connectionId = searchParams.get('connectionId');
167 +
168 + // Wait for connection to complete
169 + const connection = await composio.connectedAccounts.waitForConnection(connectionId);
170 +
171 + return NextResponse.json({
172 + id: connection.id,
173 + status: connection.status,
174 + authConfig: connection.authConfig,
175 + data: connection.data,
176 + });
177 +}
178 +```
179 +
180 +### 3. Deleting a connection
181 +
182 +When a user wants to disconnect their account, we remove the connection using the connection ID:
183 +
184 +```typescript app/api/connections/delete/route.ts
185 +export async function DELETE(request: Request) {
186 + // ... auth and validation ...
187 +
188 + const connectionId = searchParams.get('connectionId');
189 +
190 + // Delete the connection
191 + await composio.connectedAccounts.delete(connectionId);
192 +
193 + return NextResponse.json({
194 + success: true,
195 + message: 'Connection deleted successfully',
196 + });
197 +}
198 +```
199 +
200 +## Working with tools
201 +
202 +Once users have connected their accounts, we need to track which toolkits are enabled and fetch the corresponding tools for the LLM.
203 +
204 +### 1. Tracking enabled toolkits
205 +
206 +We keep track of which toolkits the user has enabled in the chat interface:
207 +
208 +```typescript components/chat.tsx
209 +const { ... } = useChat({
210 + // ... other config ...
211 + experimental_prepareRequestBody: (body) => {
212 + // Get current toolbar state
213 + const currentToolbarState = toolbarStateRef.current;
214 + const enabledToolkits = Array.from(
215 + currentToolbarState.enabledToolkitsWithStatus.entries(),
216 + ).map(([slug, isConnected]) => ({ slug, isConnected }));
217 +
218 + return {
219 + // ... other fields ...
220 + enabledToolkits,
221 + };
222 + },
223 + // ... other handlers ...
224 + });
225 +```
226 +
227 +### 2. Fetching tools for enabled toolkits
228 +
229 +We fetch Composio tools based on the enabled toolkit slugs:
230 +
231 +```typescript lib/ai/tools/composio.ts
232 +export async function getComposioTools(userId: string, toolkitSlugs: string[]) {
233 + // ... validation ...
234 +
235 + const tools = await composio.tools.get(userId, {
236 + toolkits: toolkitSlugs,
237 + });
238 + return tools || {};
239 +}
240 +```
241 +
242 +```typescript app/api/chat.ts
243 +export async function POST(request: Request) {
244 + // ... auth and parsing ...
245 +
246 + const toolkitSlugs = enabledToolkits?.map(t => t.slug) || [];
247 +
248 + const composioTools = await getComposioTools(session.user.id, toolkitSlugs);
249 +
250 + const result = streamText({
251 + // ... model config ...
252 + tools: {
253 + ...composioTools,
254 + },
255 + });
256 +}
257 +```
258 +
259 +## Bonus: Creating custom component to show tool calls
260 +
261 +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.
262 +
263 +
264 + <img src="../../../../assets/images/examples/custom-tool-component.png" />
265 +
266 +
267 +You can find the `ToolCall` component at `components/tool-call.tsx`. Here's how to integrate it into your message rendering:
268 +
269 +```typescript components/messages.tsx
270 +if (type === 'tool-invocation') {
271 + const { toolInvocation } = part;
272 + const { toolName, toolCallId, state, args, result } = toolInvocation;
273 +
274 + if (state === 'call') {
275 + return (
276 + <ToolCall
277 + key={toolCallId}
278 + toolName={toolName}
279 + args={args}
280 + isLoading={true}
281 + />
282 + );
283 + }
284 +
285 + if (state === 'result') {
286 + return (
287 + <ToolCall
288 + key={toolCallId}
289 + toolName={toolName}
290 + args={args}
291 + result={result}
292 + isLoading={false}
293 + />
294 + );
295 + }
296 +}
297 +```