@devries-cameron20 / composio-1 / commits / fd1b662ca
Fork 0

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

docs: rewrite FastAPI cookbook to use session-based API

Replace the verbose auth config / connected accounts pattern with the modern session API (composio.create, session.tools, session.authorize, session.toolkits). Switch to OpenAI Agents SDK for the agentic loop. Also install @ai-sdk/react to fix twoslash build error in chat-app tutorial. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Sushmitha Mallesh committed Feb 25, 2026 at 15:49 UTC fd1b662cac43b3ee63631670bf8dd494656e972b
4 files changed +173 -326
docs/bun.lock
+4 -4
@@ -27,7 +27,7 @@
27 "@ai-sdk/anthropic": "^3.0.11",
28 "@ai-sdk/mcp": "^1.0.6",
29 "@ai-sdk/openai": "^3.0.9",
30 - "@ai-sdk/react": "^3.0.99",
30 + "@ai-sdk/react": "^3.0.102",
31 "@anthropic-ai/claude-agent-sdk": "^0.2.5",
32 "@anthropic-ai/sdk": "^0.71.2",
33 "@composio/anthropic": "^0.5.5",
@@ -92,7 +92,7 @@
92
93 "@ai-sdk/provider-v6": ["@ai-sdk/provider@3.0.0", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-m9ka3ptkPQbaHHZHqDXDF9C9B5/Mav0KTdky1k2HZ3/nrW2t1AgObxIVPyGDWQNS9FXT/FS6PIoSjpcP/No8rQ=="],
94
95 - "@ai-sdk/react": ["@ai-sdk/react@3.0.99", "", { "dependencies": { "@ai-sdk/provider-utils": "4.0.15", "ai": "6.0.97", "swr": "^2.2.5", "throttleit": "2.1.0" }, "peerDependencies": { "react": "^18 || ~19.0.1 || ~19.1.2 || ^19.2.1" } }, "sha512-xMsp5br4Dpr/3BYq/jrE8q4YLgViU1KHVq8VB0+dzdLJFU3jKA83uoxpbWqzV/edQOBPgGBSb2CgmV5v77rvzA=="],
95 + "@ai-sdk/react": ["@ai-sdk/react@3.0.102", "", { "dependencies": { "@ai-sdk/provider-utils": "4.0.15", "ai": "6.0.100", "swr": "^2.2.5", "throttleit": "2.1.0" }, "peerDependencies": { "react": "^18 || ~19.0.1 || ~19.1.2 || ^19.2.1" } }, "sha512-WPSYJxk/HM3SWhhxE+WrLhIMbaRLpDHWWYzUlrptXowwEoyliYBYZAkzip/gV8hybT2NyrWnsUh5KRO5iBdsQA=="],
96
97 "@ai-sdk/ui-utils-v5": ["@ai-sdk/ui-utils@1.2.11", "", { "dependencies": { "@ai-sdk/provider": "1.1.3", "@ai-sdk/provider-utils": "2.2.8", "zod-to-json-schema": "^3.24.1" }, "peerDependencies": { "zod": "^3.23.8" } }, "sha512-3zcwCc8ezzFlwp3ZD15wAPjf2Au4s3vAbKsXQVyhxODHcmu0iyPO2Eua6D/vicq/AUm/BAo60r97O6HU+EI0+w=="],
98
@@ -2282,7 +2282,7 @@
2282
2283 "@ai-sdk/provider-utils-v6/@ai-sdk/provider": ["@ai-sdk/provider@3.0.0", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-m9ka3ptkPQbaHHZHqDXDF9C9B5/Mav0KTdky1k2HZ3/nrW2t1AgObxIVPyGDWQNS9FXT/FS6PIoSjpcP/No8rQ=="],
2284
2285 - "@ai-sdk/react/ai": ["ai@6.0.97", "", { "dependencies": { "@ai-sdk/gateway": "3.0.53", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.15", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-eZIAcBymwGhBwncRH/v9pillZNMeRCDkc4BwcvwXerXd7sxjVxRis3ZNCNCpP02pVH4NLs81ljm4cElC4vbNcQ=="],
2285 + "@ai-sdk/react/ai": ["ai@6.0.100", "", { "dependencies": { "@ai-sdk/gateway": "3.0.55", "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.15", "@opentelemetry/api": "1.9.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-BIxhG7M7wvcWCF+IEnZi7WpkRLOM3jR2vJ0mMuohl2UB2i1R/ZUa1cHFel1xI8nWvyUpOoQXKqsM0BAH50EYSQ=="],
2286
2287 "@ai-sdk/ui-utils-v5/@ai-sdk/provider": ["@ai-sdk/provider@1.1.3", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-qZMxYJ0qqX/RfnuIaab+zp8UAeJn/ygXXAffR5I4N0n1IrvA6qBsjc8hXLmBiMV2zoXlifkacF7sEFnYnjBcqg=="],
2288
@@ -2508,7 +2508,7 @@
2508
2509 "@a2a-js/sdk/express/type-is": ["type-is@1.6.18", "", { "dependencies": { "media-typer": "0.3.0", "mime-types": "~2.1.24" } }, "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g=="],
2510
2511 - "@ai-sdk/react/ai/@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.53", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.15", "@vercel/oidc": "3.1.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-QT3FEoNARMRlk8JJVR7L98exiK9C8AGfrEJVbRxBT1yIXKs/N19o/+PsjTRVsARgDJNcy9JbJp1FspKucEat0Q=="],
2511 + "@ai-sdk/react/ai/@ai-sdk/gateway": ["@ai-sdk/gateway@3.0.55", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@ai-sdk/provider-utils": "4.0.15", "@vercel/oidc": "3.1.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-7xMeTJnCjwRwXKVCiv4Ly4qzWvDuW3+W1WIV0X1EFu6W83d4mEhV9bFArto10MeTw40ewuDjrbrZd21mXKohkw=="],
2512
2513 "@eslint/eslintrc/ajv/json-schema-traverse": ["json-schema-traverse@0.4.1", "", {}, "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg=="],
2514
docs/content/cookbooks/fast-api.mdx
+104 -321
@@ -1,388 +1,171 @@
1 ---
2 title: Basic FastAPI Server
3 -description: Build a simple Gmail agent with Composio and FastAPI
3 +description: Build an AI agent with access to 1000+ tools using Composio and FastAPI
4 ---
5
6 -This cookbook will guide you through building agents equipped with tools using `Composio`, `OpenAI`, and `FastAPI`.
6 +[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/example/fast-api)
7 +
8 +This cookbook builds a FastAPI server where users can chat with an AI agent that has access to over 1000 tools like Gmail, GitHub, Slack, Notion, and more. Along the way we'll add endpoints to manage which apps a user has connected.
9
10 ## Prerequisites
11
12 * Python 3.10+
13 * [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
14 +* [Composio API key](https://platform.composio.dev/settings)
15 +* [OpenAI API key](https://platform.openai.com/api-keys)
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 - )
17 +## Project setup
18
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 - )
19 +Create a new project and install dependencies:
20
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
21 +```bash
22 +mkdir composio-fastapi && cd composio-fastapi
23 +uv init && uv add composio composio-openai-agents openai-agents fastapi uvicorn pydantic
24 ```
25
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
26 +Add your API keys to a `.env` file:
27
28 +```bash title=".env"
29 +COMPOSIO_API_KEY=your_composio_api_key
30 +OPENAI_API_KEY=your_openai_api_key
31 +```
32
68 -To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
33 +## Initializing the clients
34
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`.
35 +`Composio` takes an `OpenAIAgentsProvider` so that when we ask for tools later, they come back in the format the OpenAI Agents SDK expects.
36
37 ```python
38 +from agents import Agent, Runner
39 from composio import Composio
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 -```
40 +from composio_openai_agents import OpenAIAgentsProvider
41 +from fastapi import FastAPI
42 +from pydantic import BaseModel
43
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.
44 +composio = Composio(provider=OpenAIAgentsProvider())
45
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
46 +app = FastAPI()
47 ```
48
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>
49 +## Chat endpoint
50 +
51 +The core of the server is a `/chat` endpoint. A user sends a message, and the agent responds, using whatever tools it needs.
52
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.
53 +`composio.create()` creates a **session** scoped to a user. Calling `session.tools()` returns a set of meta tools that let the agent discover tools across all apps, handle OAuth when needed, and execute actions. We pass these to an `Agent` and let `Runner.run_sync` handle the agentic loop.
54
55 ```python
124 -from fastapi import FastAPI
56 +class ChatRequest(BaseModel):
57 + user_id: str
58 + message: str
59
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 - )
60
142 -# Setup FastAPI
143 -app = FastAPI()
61 +@app.post("/chat")
62 +def chat(request: ChatRequest):
63 + session = composio.create(user_id=request.user_id)
64 + tools = session.tools()
65
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 -```
66 + agent = Agent(
67 + name="Assistant",
68 + instructions="You are a helpful assistant. Use tools to help the user.",
69 + tools=tools,
70 + )
71
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.
72 + result = Runner.run_sync(starting_agent=agent, input=request.message)
73 + return {"response": result.final_output}
74 +```
75
167 -## Set Up FastAPI service
76 +<Callout>
77 +If the user hasn't connected the app they're trying to use, the agent will automatically
78 +return an authentication link in its response. The user can complete OAuth and then retry.
79 +</Callout>
80
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.
81 +That's a working agent. But in most apps you'll also want to manage connections outside of chat, for example to show users what's connected or let them connect new apps from a settings page.
82
171 -### Setup dependencies
83 +## Checking connections
84
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.
85 +`session.toolkits()` returns every toolkit in the session along with its connection status. We can expose this as a simple GET endpoint so your frontend can render a connections UI.
86
87 ```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
88 +@app.get("/connections/{user_id}")
89 +def list_connections(user_id: str):
90 + session = composio.create(user_id=user_id)
91 + toolkits = session.toolkits()
92 + return [
93 + {"toolkit": t.slug, "connected": t.connection.is_active if t.connection else False}
94 + for t in toolkits.items
95 + ]
96 +```
97
98 +If you just need to check a single toolkit, say before kicking off a workflow that requires Gmail, you can scope the session to that toolkit:
99
196 -ComposioClient = te.Annotated[Composio, Depends(provide_composio_client)]
197 -"""
198 -A Composio client dependency.
199 -"""
100 +```python
101 +@app.get("/connections/{user_id}/{toolkit}")
102 +def check_connection(user_id: str, toolkit: str):
103 + session = composio.create(user_id=user_id, toolkits=[toolkit])
104 + toolkits = session.toolkits()
105 + for t in toolkits.items:
106 + if t.slug == toolkit:
107 + return {"toolkit": toolkit, "connected": t.connection.is_active if t.connection else False}
108 + return {"toolkit": toolkit, "connected": False}
109 ```
110
202 -### Invoke agent via FastAPI
111 +## Connecting an app
112
204 -When invoking an agent, make sure you validate the `user_id`.
113 +When a user wants to connect a new app, `session.authorize()` starts the OAuth flow and returns a redirect URL. Your frontend sends the user there, and once they complete auth, they're connected.
114
115 ```python
207 -def check_connected_account_exists(
208 - composio_client: Composio[OpenAIProvider],
209 - user_id: str,
210 -):
211 - """
212 - Check if a connected account exists for a given user id.
213 - """
214 - # Fetch all connected accounts for the user
215 - connected_accounts = composio_client.connected_accounts.list(
216 - user_ids=[user_id],
217 - toolkit_slugs=["GMAIL"],
218 - )
116 +class ConnectRequest(BaseModel):
117 + user_id: str
118 +
119
220 - # Check if there's an active connected account
221 - for account in connected_accounts.items:
222 - if account.status == "ACTIVE":
223 - return True
120 +@app.post("/connect/{toolkit}")
121 +def connect_toolkit(toolkit: str, request: ConnectRequest):
122 + session = composio.create(user_id=request.user_id, toolkits=[toolkit])
123 + connection_request = session.authorize(toolkit)
124 + return {"redirect_url": connection_request.redirect_url}
125 +```
126
225 - # Ideally you should not have inactive accounts, but if you do, delete them.
226 - print(f"[warning] inactive account {account.id} found for user id: {user_id}")
227 - return False
127 +## Complete app
128
229 -def validate_user_id(user_id: str, composio_client: ComposioClient):
230 - """
231 - Validate the user id, if no connected account is found, create a new connection.
232 - """
233 - if check_connected_account_exists(composio_client=composio_client, user_id=user_id):
234 - return user_id
129 +Here's everything together:
130
236 - raise HTTPException(
237 - status_code=404, detail={"error": "No connected account found for the user id"}
238 - )
131 +<include>../../example/fast-api/main.py</include>
132
240 -# Endpoint: Run the Gmail agent for a given user id and prompt
241 -@app.post("/agent")
242 -def _run_gmail_agent(
243 - request: RunGmailAgentRequest,
244 - composio_client: ComposioClient,
245 - openai_client: OpenAIClient, # OpenAI client will be injected as dependency
246 -) -> List[ToolExecutionResponse]:
247 - """
248 - Run the Gmail agent for a given user id and prompt.
249 - """
250 - # For demonstration, using a default user_id. Replace with real user logic in production.
251 - user_id = "default"
252 -
253 - # Validate the user id before proceeding
254 - user_id = validate_user_id(user_id=user_id, composio_client=composio_client)
255 -
256 - # Run the Gmail agent using Composio and OpenAI
257 - result = run_gmail_agent(
258 - composio_client=composio_client,
259 - openai_client=openai_client,
260 - user_id=user_id,
261 - prompt=request.prompt,
262 - )
263 - return result
264 -```
133 +## Running the server
134
266 -## Putting everything together
267 -
268 -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.
269 -
270 -
271 -1. Clone the repository
272 - ```bash
273 - git clone git@github.com:composiohq/composio-fastapi
274 - cd composio-fastapi/
275 - ```
276 -2. Setup environment
277 - ```bash
278 - cp .env.example .env
279 - ```
280 -
281 - Fill the api keys
282 - ```dotenv
283 - COMPOSIO_API_KEY=
284 - OPENAI_API_KEY=
285 - ```
286 -
287 - Create the virtual env
288 - ```bash
289 - make env
290 - source .venv/bin/activate
291 - ```
292 -3. Run the HTTP server
293 - ```bash
294 - uvicorn simple_gmail_agent.server.api:create_app --factory
295 - ```
296 -## Testing the API with curl
297 -
298 -Assuming the server is running locally on `http://localhost:8000`.
299 -
300 -### Check if a connection exists
135 ```bash
302 -curl -X POST http://localhost:8000/connection/exists
136 +uv run uvicorn main:app --reload
137 ```
138
305 -### Create a connection
306 -Note: The body fields are required by the API schema, but are ignored internally in this example service.
139 +The server runs at `http://localhost:8000`. Visit `/docs` for the interactive Swagger UI.
140 +
141 +## Testing with cURL
142 +
143 +### Chat with the agent
144 +
145 ```bash
308 -curl -X POST http://localhost:8000/connection/create \
146 +curl -X POST http://localhost:8000/chat \
147 -H "Content-Type: application/json" \
310 - -d '{
311 - "user_id": "default",
312 - "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
313 - }'
148 + -d '{"user_id": "user_123", "message": "Star the composiohq/composio repo on GitHub"}'
149 ```
315 -Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.
150
317 -### Check connection status
318 -Use the `connection_id` returned from the create step.
151 +### List all connections
152 +
153 ```bash
320 -curl -X POST http://localhost:8000/connection/status \
321 - -H "Content-Type: application/json" \
322 - -d '{
323 - "user_id": "default",
324 - "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
325 - }'
154 +curl http://localhost:8000/connections/user_123
155 ```
156
328 -### Run the Gmail agent
329 -Requires an active connected account for the `default` user.
157 +### Check a specific connection
158 +
159 ```bash
331 -curl -X POST http://localhost:8000/agent \
332 - -H "Content-Type: application/json" \
333 - -d '{
334 - "user_id": "default",
335 - "prompt": "Summarize my latest unread emails from the last 24 hours."
336 - }'
160 +curl http://localhost:8000/connections/user_123/gmail
161 ```
162
339 -### Fetch emails (direct action)
163 +### Connect an app
164 +
165 ```bash
341 -curl -X POST http://localhost:8000/actions/fetch_emails \
166 +curl -X POST http://localhost:8000/connect/gmail \
167 -H "Content-Type: application/json" \
343 - -d '{
344 - "user_id": "default",
345 - "limit": 5
346 - }'
168 + -d '{"user_id": "user_123"}'
169 ```
170
349 -These examples are intended solely for testing purposes.
350 -
351 -## Using Composio for managed auth and tools
352 -
353 -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
354 -
355 -- manage Gmail OAuth app
356 -- manage user connections
357 -- tools for your agents to interact with Gmail
358 -
359 -Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.
360 -
361 -## Best practices
362 -
363 -**🎯 Effective Prompts**:
364 -- Be specific: "Send email to john@company.com about tomorrow's 2pm meeting" works better than "send email"
365 -- Include context: "Reply to Sarah's email about the budget with our approval"
366 -- Use natural language: The agent understands conversational requests
367 -
368 -**🔒 User Management**:
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 -
374 -## Troubleshooting
375 -
376 -**Connection Issues**:
377 -- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
378 -- Check if the user has completed Gmail authorization.
379 -- Verify the user_id matches exactly between requests
380 -
381 -**API Errors**:
382 -- Check the server logs for detailed error messages
383 -- Ensure request payloads match the expected format
384 -- Visit `/docs` endpoint for API schema validation
385 -
386 -**Gmail API Limits**:
387 -- Gmail has rate limits; the agent will handle these gracefully
388 -- For high-volume usage, consider implementing request queuing
171 +Open the `redirect_url` from the response in your browser to complete OAuth.
docs/example/fast-api/main.py new
+64
@@ -0,0 +1,64 @@
1 +from agents import Agent, Runner
2 +from composio import Composio
3 +from composio_openai_agents import OpenAIAgentsProvider
4 +from fastapi import FastAPI
5 +from pydantic import BaseModel
6 +
7 +composio = Composio(provider=OpenAIAgentsProvider())
8 +
9 +app = FastAPI()
10 +
11 +
12 +class ChatRequest(BaseModel):
13 + user_id: str
14 + message: str
15 +
16 +
17 +class ConnectRequest(BaseModel):
18 + user_id: str
19 +
20 +
21 +@app.post("/chat")
22 +def chat(request: ChatRequest):
23 + """Send a message to an AI agent with access to all tools."""
24 + session = composio.create(user_id=request.user_id)
25 + tools = session.tools()
26 +
27 + agent = Agent(
28 + name="Assistant",
29 + instructions="You are a helpful assistant. Use tools to help the user.",
30 + tools=tools,
31 + )
32 +
33 + result = Runner.run_sync(starting_agent=agent, input=request.message)
34 + return {"response": result.final_output}
35 +
36 +
37 +@app.get("/connections/{user_id}")
38 +def list_connections(user_id: str):
39 + """List all toolkits and their connection status for a user."""
40 + session = composio.create(user_id=user_id)
41 + toolkits = session.toolkits()
42 + return [
43 + {"toolkit": t.slug, "connected": t.connection.is_active if t.connection else False}
44 + for t in toolkits.items
45 + ]
46 +
47 +
48 +@app.get("/connections/{user_id}/{toolkit}")
49 +def check_connection(user_id: str, toolkit: str):
50 + """Check if a specific toolkit is connected for a user."""
51 + session = composio.create(user_id=user_id, toolkits=[toolkit])
52 + toolkits = session.toolkits()
53 + for t in toolkits.items:
54 + if t.slug == toolkit:
55 + return {"toolkit": toolkit, "connected": t.connection.is_active if t.connection else False}
56 + return {"toolkit": toolkit, "connected": False}
57 +
58 +
59 +@app.post("/connect/{toolkit}")
60 +def connect_toolkit(toolkit: str, request: ConnectRequest):
61 + """Start OAuth for a toolkit. Returns a URL to redirect the user to."""
62 + session = composio.create(user_id=request.user_id, toolkits=[toolkit])
63 + connection_request = session.authorize(toolkit)
64 + return {"redirect_url": connection_request.redirect_url}
docs/package.json
+1 -1
@@ -38,7 +38,7 @@
38 "@ai-sdk/anthropic": "^3.0.11",
39 "@ai-sdk/mcp": "^1.0.6",
40 "@ai-sdk/openai": "^3.0.9",
41 - "@ai-sdk/react": "^3.0.99",
41 + "@ai-sdk/react": "^3.0.102",
42 "@anthropic-ai/claude-agent-sdk": "^0.2.5",
43 "@anthropic-ai/sdk": "^0.71.2",
44 "@composio/anthropic": "^0.5.5",