@devries-cameron20 / composio Mirror · read-only / commits / 1f0baa7f6
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, 05:45 UTC

docs: add "Build a Chat App" tutorial to examples

Adds a step-by-step tutorial showing how to build a chat app with Composio's tool router using Vercel AI SDK + Next.js. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

Sushmithamallesh committed Feb 9, 2026 at 16:11 UTC 1f0baa7f64a922e79aea61cc4e9f5ef7fa327623
2 files changed +417
docs/content/cookbooks/meta.json
+2
@@ -2,6 +2,8 @@
2 "title": "Cookbooks",
3 "root": true,
4 "pages": [
5 + "---Tutorials---",
6 + "tutorial-chat-app",
7 "---Getting Started---",
8 "templates",
9 "chat-app",
docs/content/cookbooks/tutorial-chat-app.mdx new
+415
@@ -0,0 +1,415 @@
1 +---
2 +title: Build a Chat App
3 +description: Build an AI chat app with access to 800+ tools in about 30 lines of backend code
4 +---
5 +
6 +Composio gives your AI agent access to 800+ app integrations — Gmail, GitHub, Slack, Notion, and more. Today, in about **30 lines of backend code**, we'll build a chat app where your agent can discover tools, authenticate users, and take actions across any app.
7 +
8 +After that we'll see how authentication works and how to show tool calls in the UI.
9 +
10 +## Create the project
11 +
12 +<Callout>
13 +Before you begin: you'll need Node.js 18+ and API keys for [Composio](https://platform.composio.dev/settings) and [OpenAI](https://platform.openai.com/api-keys).
14 +</Callout>
15 +
16 +Create a new Next.js app and install the dependencies:
17 +
18 +```bash
19 +pnpm create next-app composio-chat --yes
20 +cd composio-chat
21 +pnpm install @composio/core @composio/vercel @ai-sdk/openai ai @ai-sdk/react
22 +```
23 +
24 +Add your API keys to a `.env.local` file in the project root:
25 +
26 +```bash title=".env.local"
27 +COMPOSIO_API_KEY=your_composio_api_key
28 +OPENAI_API_KEY=your_openai_api_key
29 +```
30 +
31 +Start the dev server and keep it running throughout this tutorial:
32 +
33 +```bash
34 +pnpm dev
35 +```
36 +
37 +Open [localhost:3000](http://localhost:3000) — you'll see the default Next.js page. We'll replace it with a chat interface shortly.
38 +
39 +## How Composio works
40 +
41 +Instead of loading 1000+ tools into your agent's context (which would overwhelm any LLM), Composio gives your agent **5 meta tools** that handle everything at runtime:
42 +
43 +| Meta tool | What it does |
44 +|-----------|-------------|
45 +| `COMPOSIO_SEARCH_TOOLS` | Discover relevant tools across 800+ apps |
46 +| `COMPOSIO_MANAGE_CONNECTIONS` | Handle OAuth and API key authentication |
47 +| `COMPOSIO_MULTI_EXECUTE_TOOL` | Execute up to 20 tools in parallel |
48 +| `COMPOSIO_REMOTE_WORKBENCH` | Run Python code in a persistent sandbox |
49 +| `COMPOSIO_REMOTE_BASH_TOOL` | Execute bash commands for data processing |
50 +
51 +Here's the flow:
52 +
53 +```
54 +User: "Star the composio repo on GitHub"
55 + ↓
56 +1. Agent calls COMPOSIO_SEARCH_TOOLS
57 + → Returns GITHUB_STAR_REPO with input schema
58 + → Returns connection status (not connected)
59 + ↓
60 +2. Agent calls COMPOSIO_MANAGE_CONNECTIONS
61 + → Returns an auth link for GitHub
62 + → User clicks link and authorizes
63 + ↓
64 +3. Agent calls COMPOSIO_MULTI_EXECUTE_TOOL
65 + → Executes GITHUB_STAR_REPO
66 + → Returns success
67 + ↓
68 +Done. The repo is starred. ⭐
69 +```
70 +
71 +When you create a **session**, your agent gets these 5 tools. From there, the agent handles discovery, authentication, and execution on its own.
72 +
73 +Now let's write the code.
74 +
75 +## Your first session
76 +
77 +A **session** is the core Composio primitive. It scopes tools and connections to a specific user. One line of code gives your agent access to everything.
78 +
79 +Create a new file at `app/api/chat/route.ts`:
80 +
81 +```typescript title="app/api/chat/route.ts"
82 +import { openai } from "@ai-sdk/openai";
83 +import { Composio } from "@composio/core";
84 +import { VercelProvider } from "@composio/vercel";
85 +import {
86 + streamText,
87 + convertToModelMessages,
88 + generateId,
89 + stepCountIs,
90 + type UIMessage,
91 +} from "ai";
92 +
93 +const composio = new Composio({ provider: new VercelProvider() });
94 +
95 +export async function POST(req: Request) {
96 + const { messages }: { messages: UIMessage[] } = await req.json();
97 +
98 + // Create a session for the user
99 + const session = await composio.create("user_123");
100 + const tools = await session.tools();
101 +
102 + // Stream the AI response with tool access
103 + const result = streamText({
104 + model: openai("gpt-4o"),
105 + system: "You are a helpful assistant. Use Composio tools to help the user.",
106 + messages: await convertToModelMessages(messages),
107 + tools,
108 + stopWhen: stepCountIs(10),
109 + });
110 +
111 + return result.toUIMessageStreamResponse({
112 + originalMessages: messages,
113 + generateMessageId: () => generateId(),
114 + });
115 +}
116 +```
117 +
118 +Let's break this down:
119 +
120 +1. **`new Composio({ provider: new VercelProvider() })`** initializes Composio with the Vercel AI SDK provider, so tools are returned in the right format.
121 +2. **`composio.create("user_123")`** creates a session for this user. All tool connections and data are scoped to this ID. In production, you'd use a real user ID from your auth system.
122 +3. **`session.tools()`** returns the 5 meta tools, formatted for the Vercel AI SDK.
123 +4. **`streamText`** sends the conversation to GPT-4o along with the tools. The model can now search for tools, authenticate users, and execute actions — all through those meta tools.
124 +5. **`stopWhen: stepCountIs(10)`** limits the agent to 10 steps per request. Each tool call counts as a step.
125 +
126 +That's the entire backend. Now let's build the chat UI.
127 +
128 +## The chat UI
129 +
130 +Replace your `app/page.tsx` with a simple chat interface:
131 +
132 +```tsx title="app/page.tsx"
133 +import React from "react";
134 +// ---cut---
135 +"use client";
136 +
137 +import { useState } from "react";
138 +import { useChat } from "@ai-sdk/react";
139 +import { DefaultChatTransport } from "ai";
140 +
141 +export default function Chat() {
142 + const [input, setInput] = useState("");
143 + const { messages, sendMessage, status } = useChat({
144 + transport: new DefaultChatTransport({ api: "/api/chat" }),
145 + });
146 +
147 + const isLoading = status === "streaming" || status === "submitted";
148 +
149 + return (
150 + <main className="max-w-2xl mx-auto p-6">
151 + <h1 className="text-2xl font-bold mb-6">Composio Chat</h1>
152 +
153 + <div className="space-y-4 mb-6 min-h-[200px]">
154 + {messages.length === 0 && (
155 + <p className="text-gray-400 text-center py-12">
156 + Try: &quot;Star the composio repo on GitHub&quot;
157 + </p>
158 + )}
159 + {messages.map((m) => (
160 + <div key={m.id} className="flex gap-2">
161 + <span className="font-semibold shrink-0">
162 + {m.role === "user" ? "You:" : "Agent:"}
163 + </span>
164 + <div>
165 + {m.parts.map((part, i) =>
166 + part.type === "text" ? <span key={i}>{String(part.text)}</span> : null
167 + )}
168 + </div>
169 + </div>
170 + ))}
171 + {isLoading && (
172 + <p className="text-gray-400 text-sm">Thinking...</p>
173 + )}
174 + </div>
175 +
176 + <form
177 + onSubmit={(e) => {
178 + e.preventDefault();
179 + if (!input.trim()) return;
180 + sendMessage({ text: input });
181 + setInput("");
182 + }}
183 + >
184 + <input
185 + value={input}
186 + onChange={(e) => setInput(e.target.value)}
187 + placeholder="Ask me anything..."
188 + disabled={isLoading}
189 + className="w-full p-3 border border-gray-300 rounded-lg"
190 + />
191 + </form>
192 + </main>
193 + );
194 +}
195 +```
196 +
197 +The `useChat` hook manages everything: message history, streaming, and state. It sends messages to your `/api/chat` route and streams the response back automatically.
198 +
199 +Go to [localhost:3000](http://localhost:3000). You should see the chat interface. Try sending a message like "Hello" — the agent will respond.
200 +
201 +## Your first tool call
202 +
203 +Now try asking the agent to do something real:
204 +
205 +```
206 +Star the composio repo on GitHub
207 +```
208 +
209 +Here's what happens behind the scenes:
210 +
211 +1. The agent calls **`COMPOSIO_SEARCH_TOOLS`** with your request. Composio returns the `GITHUB_STAR_REPO` tool along with its input schema and the user's connection status.
212 +
213 +2. Since you haven't connected GitHub yet, the agent calls **`COMPOSIO_MANAGE_CONNECTIONS`**. Composio returns an authentication link.
214 +
215 +3. The agent shows you the link in the chat. **Click it**, authorize with GitHub, and come back to the chat.
216 +
217 +4. Tell the agent you're done (e.g., "Done" or "I've connected"). It retries — this time calling **`COMPOSIO_MULTI_EXECUTE_TOOL`** to run `GITHUB_STAR_REPO`.
218 +
219 +5. The repo is starred.
220 +
221 +The agent handled **discovery**, **authentication**, and **execution** — all through the meta tools you gave it with `composio.create()`. You didn't write a single line of tool-specific code.
222 +
223 +<Callout>
224 +This in-chat authentication flow works out of the box. For production apps, you can also [authenticate users ahead of time](/docs/authenticating-users/manually-authenticating) during onboarding.
225 +</Callout>
226 +
227 +## Showing tool calls
228 +
229 +Right now tool calls happen invisibly. Let's add a component that shows them — the tool name, input, and output — so you can see what your agent is doing in real time.
230 +
231 +Create `components/ToolCallDisplay.tsx`:
232 +
233 +```tsx title="components/ToolCallDisplay.tsx"
234 +import React from "react";
235 +// ---cut---
236 +"use client";
237 +
238 +import { useState } from "react";
239 +
240 +export function ToolCallDisplay({
241 + toolName,
242 + input,
243 + output,
244 + isLoading,
245 +}: {
246 + toolName: string;
247 + input: unknown;
248 + output?: unknown;
249 + isLoading: boolean;
250 +}) {
251 + const [expanded, setExpanded] = useState(false);
252 +
253 + return (
254 + <div
255 + className={`my-2 rounded-lg border p-2 text-sm ${
256 + isLoading
257 + ? "border-blue-200 bg-blue-50"
258 + : "border-green-200 bg-green-50"
259 + }`}
260 + >
261 + <button
262 + onClick={() => setExpanded(!expanded)}
263 + className="flex items-center gap-2 w-full text-left"
264 + >
265 + <span>{isLoading ? "⏳" : "✅"}</span>
266 + <code className="font-mono text-xs">{toolName}</code>
267 + {isLoading && <span className="text-xs text-gray-500">Running...</span>}
268 + <span className="ml-auto text-xs">{expanded ? "▲" : "▼"}</span>
269 + </button>
270 +
271 + {expanded && (
272 + <div className="mt-2 space-y-2">
273 + <pre className="text-xs bg-white/50 p-2 rounded overflow-auto max-h-32">
274 + {String(JSON.stringify(input, null, 2))}
275 + </pre>
276 + {output != null && (
277 + <pre className="text-xs bg-white/50 p-2 rounded overflow-auto max-h-32">
278 + {String(JSON.stringify(output, null, 2))}
279 + </pre>
280 + )}
281 + </div>
282 + )}
283 + </div>
284 + );
285 +}
286 +```
287 +
288 +Now update `app/page.tsx` to render tool calls:
289 +
290 +```tsx title="app/page.tsx"
291 +import React from "react";
292 +declare function ToolCallDisplay(props: { toolName: string; input: unknown; output?: unknown; isLoading: boolean }): React.ReactElement;
293 +// ---cut---
294 +"use client";
295 +
296 +import { useState } from "react";
297 +import { useChat } from "@ai-sdk/react";
298 +import { DefaultChatTransport, getToolName, isToolUIPart } from "ai";
299 +// @ts-ignore
300 +import { ToolCallDisplay } from "../components/ToolCallDisplay";
301 +
302 +export default function Chat() {
303 + const [input, setInput] = useState("");
304 + const { messages, sendMessage, status } = useChat({
305 + transport: new DefaultChatTransport({ api: "/api/chat" }),
306 + });
307 +
308 + const isLoading = status === "streaming" || status === "submitted";
309 +
310 + return (
311 + <main className="max-w-2xl mx-auto p-6">
312 + <h1 className="text-2xl font-bold mb-6">Composio Chat</h1>
313 +
314 + <div className="space-y-4 mb-6 min-h-[200px]">
315 + {messages.length === 0 && (
316 + <p className="text-gray-400 text-center py-12">
317 + Try: &quot;Star the composio repo on GitHub&quot;
318 + </p>
319 + )}
320 + {messages.map((m) => (
321 + <div key={m.id} className="flex gap-2">
322 + <span className="font-semibold shrink-0">
323 + {m.role === "user" ? "You:" : "Agent:"}
324 + </span>
325 + <div className="flex-1">
326 + {m.parts.map((part, i) => {
327 + if (part.type === "text") {
328 + return <span key={i}>{String(part.text)}</span>;
329 + }
330 + if (isToolUIPart(part)) {
331 + return (
332 + <ToolCallDisplay
333 + key={part.toolCallId}
334 + toolName={getToolName(part)}
335 + input={part.input}
336 + output={
337 + part.state === "output-available"
338 + ? part.output
339 + : undefined
340 + }
341 + isLoading={part.state !== "output-available"}
342 + />
343 + );
344 + }
345 + return null;
346 + })}
347 + </div>
348 + </div>
349 + ))}
350 + {isLoading && (
351 + <p className="text-gray-400 text-sm">Thinking...</p>
352 + )}
353 + </div>
354 +
355 + <form
356 + onSubmit={(e) => {
357 + e.preventDefault();
358 + if (!input.trim()) return;
359 + sendMessage({ text: input });
360 + setInput("");
361 + }}
362 + >
363 + <input
364 + value={input}
365 + onChange={(e) => setInput(e.target.value)}
366 + placeholder="Ask me anything..."
367 + disabled={isLoading}
368 + className="w-full p-3 border border-gray-300 rounded-lg"
369 + />
370 + </form>
371 + </main>
372 + );
373 +}
374 +```
375 +
376 +Now when the agent uses tools, you'll see expandable cards showing what's happening — the tool name while it's running, and the full input/output when you click to expand.
377 +
378 +Try sending a few more requests:
379 +
380 +- "Summarize my emails from today"
381 +- "What's on my calendar this week?"
382 +- "Create a GitHub issue in my repo"
383 +
384 +Each one will trigger a different set of tools, and you'll see the full flow: search → authenticate → execute.
385 +
386 +## What you built
387 +
388 +With about 30 lines of backend code and a simple React frontend, you've built a chat app that:
389 +
390 +1. Creates a **session** that gives the agent 5 meta tools
391 +2. Uses **`COMPOSIO_SEARCH_TOOLS`** to discover the right tools across 800+ apps
392 +3. Uses **`COMPOSIO_MANAGE_CONNECTIONS`** to handle OAuth inline
393 +4. Uses **`COMPOSIO_MULTI_EXECUTE_TOOL`** to take actions on the user's behalf
394 +5. Streams responses and shows tool calls in real time
395 +
396 +The key concept is the **session** — one line (`composio.create("user_123")`) gives your agent access to every integration Composio supports.
397 +
398 +## Next up
399 +
400 +We just touched on the basics. Here are some good next steps:
401 +
402 +<Cards>
403 + <Card title="Configuring sessions" href="/docs/configuring-sessions">
404 + Restrict toolkits, set auth configs, and customize session behavior
405 + </Card>
406 + <Card title="Manual authentication" href="/docs/authenticating-users/manually-authenticating">
407 + Authenticate users during onboarding instead of in-chat
408 + </Card>
409 + <Card title="Users & Sessions" href="/docs/users-and-sessions">
410 + Understand the user model for multi-user production apps
411 + </Card>
412 + <Card title="Full Stack Chat App" href="/examples/vercel-chat">
413 + A production chat app with connection management UI
414 + </Card>
415 +</Cards>