With Composio's managed authentication and tool calling, it's easy to build
AI agents that interact with the real world while reducing boilerplate for
setup and authentication management. This cookbook will guide you through
building and serving agents using Composio, OpenAI, and Hono.js.
OpenAI,userId: stringuserId: string, // Composio uses the User ID to store and access user-level authentication tokens.prompt: stringprompt: string,):interface Promise<T>
Represents the completion of an asynchronous operation
Promise<any[]> { // Step 1: Fetch the necessary Gmail tools list with Composio constconst tools: OpenAiToolCollectiontools = awaitcomposioClient: Composio<OpenAIProvider>composioClient.Composio<OpenAIProvider>.tools: Tools<unknown, unknown, OpenAIProvider>
Get a list of tools from Composio based on filters.
This method fetches the tools from the Composio API and wraps them using the provider.
@paramuserId - The user id to get the tools for@paramfilters - The filters to apply when fetching tools@paramoptions - Optional provider options including modifiers@returnsThe wrapped tools collection@example```typescript
// Get tools from the GitHub toolkit
const tools = await composio.tools.get('default', {
toolkits: ['github'],
limit: 10
});
// Get tools with search
const searchTools = await composio.tools.get('default', {
search: 'user',
limit: 10
});
// Get a specific tool by slug
const hackerNewsUserTool = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
// Get a tool with schema modifications
const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', {
modifySchema: (toolSlug, toolkitSlug, schema) => {
// Customize the tool schema
return {...schema, description: 'Custom description'};
}
});
```
get(userId: stringuserId, {tools: string[]tools: [ "GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL", "GMAIL_CREATE_EMAIL_DRAFT" ] } ); // Step 2: Use OpenAI to generate a response based on the prompt and available tools const
**Starting a new project?** We recommend trying
[Responses](https://platform.openai.com/docs/api-reference/responses) to take
advantage of the latest OpenAI platform features. Compare
[Chat Completions with Responses](https://platform.openai.com/docs/guides/responses-vs-chat-completions?api-mode=responses).
---
Creates a model response for the given chat conversation. Learn more in the
[text generation](https://platform.openai.com/docs/guides/text-generation),
[vision](https://platform.openai.com/docs/guides/vision), and
[audio](https://platform.openai.com/docs/guides/audio) guides.
Parameter support can differ depending on the model used to generate the
response, particularly for newer reasoning models. Parameters that are only
supported for reasoning models are noted below. For the current state of
unsupported parameters in reasoning models,
[refer to the reasoning guide](https://platform.openai.com/docs/guides/reasoning).
Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a
wide range of models with different capabilities, performance characteristics,
and price points. Refer to the
[model guide](https://platform.openai.com/docs/models) to browse and compare
available models.
A list of tools the model may call. You can provide either
[custom tools](https://platform.openai.com/docs/guides/function-calling#custom-tools)
or [function tools](https://platform.openai.com/docs/guides/function-calling).
A list of messages comprising the conversation so far. Depending on the
[model](https://platform.openai.com/docs/models) you use, different message
types (modalities) are supported, like
[text](https://platform.openai.com/docs/guides/text-generation),
[images](https://platform.openai.com/docs/guides/vision), and
[audio](https://platform.openai.com/docs/guides/audio).
Handles tool calls from OpenAI's chat completion response.
This method processes tool calls from an OpenAI chat completion response,
executes each tool call, and returns the results.
@paramuserId - The user ID for authentication and tracking@paramchatCompletion - The chat completion response from OpenAI@paramoptions - Optional execution options@parammodifiers - Optional execution modifiers@returnsArray of tool execution results as JSON strings@example```typescript
// Handle tool calls from a chat completion response
const chatCompletion = {
choices: [
{
message: {
tool_calls: [
{
id: 'call_abc123',
type: 'function',
function: {
name: 'SEARCH_TOOL',
arguments: '{"query":"composio documentation"}'
}
}
]
}
}
]
};
const results = await provider.handleToolCalls(
'user123',
chatCompletion,
{ connectedAccountId: 'conn_xyz456' }
);
console.log(results); // Array of tool execution results
```
This is a simple agent without state management and agentic loop implementation,
so the agent can't perform complicated tasks. If you want to understand how
composio can be used with agentic loops, check other cookbooks with more
agentic frameworks.
To invoke this agent, authenticate your users with Composio's managed authentication service.
To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
To create an authentication config for gmail you need client_id and client_secret from your Google OAuth Console. Once you have the credentials, use the following piece of code to set up authentication for gmail.
import { class Composio<TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider>
This is the core class for Composio.
It is used to initialize the Composio SDK and provide a global configuration.
Composio } from '@composio/core';import { class OpenAIProviderOpenAIProvider } from '@composio/openai';export async function
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.
The `process.env` property returns an object containing the user environment.
See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html).
An example of this object looks like:
```js
{
TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node'
}
```
It is possible to modify this object, but such modifications will not be
reflected outside the Node.js process, or (unless explicitly requested)
to other `Worker` threads.
In other words, the following example would not work:
```bash
node -e 'process.env.foo = "bar"' && echo $foo
```
While the following will:
```js
import { env } from 'node:process';
env.foo = 'bar';
console.log(env.foo);
```
Assigning a property on `process.env` will implicitly convert the value
to a string. **This behavior is deprecated.** Future versions of Node.js may
throw an error when the value is not a string, number, or boolean.
```js
import { env } from 'node:process';
env.test = null;
console.log(env.test);
// => 'null'
env.test = undefined;
console.log(env.test);
// => 'undefined'
```
Use `delete` to delete a property from `process.env`.
```js
import { env } from 'node:process';
env.TEST = 1;
delete env.TEST;
console.log(env.TEST);
// => undefined
```
On Windows operating systems, environment variables are case-insensitive.
```js
import { env } from 'node:process';
env.TEST = 1;
console.log(env.test);
// => 1
```
Unless explicitly specified when creating a `Worker` instance,
each `Worker` thread has its own copy of `process.env`, based on its
parent thread's `process.env`, or whatever was specified as the `env` option
to the `Worker` constructor. Changes to `process.env` will not be visible
across `Worker` threads, and only the main thread can make changes that
are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner
unlike the main thread.
@sincev0.1.27
env.string | undefinedGMAIL_CLIENT_SECRET; if (!const clientId: string | undefined
Create a auth config for the gmail toolkit.
clientId|| !const clientSecret: string | undefinedclientSecret) { throw new
Error("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set"); } returncomposioClient: Composio<OpenAIProvider>composioClient.Composio<OpenAIProvider>.authConfigs: AuthConfigs
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.
Lists authentication configurations based on provided filter criteria.
This method retrieves auth configs from the Composio API, transforms them to the SDK format,
and supports filtering by various parameters.
@paramquery - Optional query parameters for filtering auth configs@returnsA paginated list of auth configurations@throws{ValidationError} If the query parameters or response fail validation@example```typescript
// List all auth configs
const allConfigs = await composio.authConfigs.list();
// List auth configs for a specific toolkit
const githubConfigs = await composio.authConfigs.list({
toolkit: 'github'
});
// List Composio-managed auth configs
const managedConfigs = await composio.authConfigs.list({
isComposioManaged: true
});
```
Composio platform provides composio managed authentication for some apps to
fast-track your development, gmail being one of them. You can use these
default auth configs for development, but for production, always use your
own oauth app configuration.
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.
// Function to initiate a connected accountexport async functionfunction createConnection(composioClient: Composio<OpenAIProvider>, userId: string): Promise<ConnectionRequest>createConnection(composioClient: Composio<OpenAIProvider>composioClient:class Composio<TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider>
This is the core class for Composio.
It is used to initialize the Composio SDK and provide a global configuration.
Composio<class OpenAIProviderOpenAIProvider>, userId: stringuserId: string) { /** * Create a connection for a given user id and auth config id. */ // Fetch or create the auth config for the gmail toolkit let
let authConfig: { id: string;} | null
Create a connection for a given user id and auth config id.
authConfig= await
function fetchAuthConfig(client: Composio<OpenAIProvider>): Promise<{ id: string;} | null>
fetchAuthConfig(composioClient: Composio<OpenAIProvider>composioClient); if (!
let authConfig: { id: string;} | null
Create a connection for a given user id and auth config id.
authConfig) {
let authConfig: { id: string;} | null
Create a connection for a given user id and auth config id.
authConfig= await
function createAuthConfig(client: Composio<OpenAIProvider>): Promise<{ id: string;}>
createAuthConfig(composioClient: Composio<OpenAIProvider>composioClient); } // Create a connection for the user returncomposioClient: Composio<OpenAIProvider>composioClient.Composio<OpenAIProvider>.connectedAccounts: ConnectedAccounts
Compound function to create a new connected account.
This function creates a new connected account and returns a connection request.
Users can then wait for the connection to be established using the `waitForConnection` method.
@paramuserId - User ID of the connected account@paramauthConfigId - Auth config ID of the connected account@paramoptions - Options for creating a new connected account@returnsConnection request object@example```typescript
// For OAuth2 authentication
const connectionRequest = await composio.connectedAccounts.initiate(
'user_123',
'auth_config_123',
{
callbackUrl: 'https://your-app.com/callback',
config: AuthScheme.OAuth2({
access_token: 'your_access_token',
token_type: 'Bearer'
})
}
);
// For API Key authentication
const connectionRequest = await composio.connectedAccounts.initiate(
'user_123',
'auth_config_123',
{
config: AuthScheme.ApiKey({
api_key: 'your_api_key'
})
}
);
// For Basic authentication
const connectionRequest = await composio.connectedAccounts.initiate(
'user_123',
'auth_config_123',
{
config: AuthScheme.Basic({
username: 'your_username',
password: 'your_password'
})
}
);
```@linkhttps://docs.composio.dev/reference/connected-accounts/create-connected-account
initiate(userId: stringuserId,
let authConfig: { id: string;}
Create a connection for a given user id and auth config id.
post("/connection/create", async (c: Context<BlankEnv, "/connection/create", BlankInput>c) => { /** * Create a connection for a given user id. */ // For demonstration, using a default user_id. Replace with real user logic in production. constconst userId: "default"
Create a connection for a given user id.
userId = "default"; // Create a new connection for the user constconst connectionRequest: ConnectionRequestconnectionRequest = awaitfunction createConnection(composioClient: Composio<OpenAIProvider>, userId: string): Promise<ConnectionRequest>createConnection(const composioClient: Composio<OpenAIProvider>composioClient, const userId: "default"
We will use Hono.js 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.
Hono allows dependency injection patterns to simplify the usage of SDK clients that must be singletons. We recommend using composio SDK client as singleton.
import { class Composio<TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider>
This is the core class for Composio.
It is used to initialize the Composio SDK and provide a global configuration.
Composio } from '@composio/core';import { class OpenAIProviderOpenAIProvider } from '@composio/openai';import { class OpenAI
This is the core class for Composio.
It is used to initialize the Composio SDK and provide a global configuration.
Composio<class OpenAIProviderOpenAIProvider> { /** * Provide a Composio client. */ if (let _composioClient: Composio<OpenAIProvider> | null_composioClient=== null) {let _composioClient: Composio<OpenAIProvider> | null_composioClient= newnew Composio<OpenAIProvider>(config?: ComposioConfig<OpenAIProvider> | undefined): Composio<OpenAIProvider>
Creates a new instance of the Composio SDK.
The constructor initializes the SDK with the provided configuration options,
sets up the API client, and initializes all core models (tools, toolkits, etc.).
@paramconfig - Configuration options for the Composio SDK@paramconfig.apiKey - The API key for authenticating with the Composio API@paramconfig.baseURL - The base URL for the Composio API (defaults to production URL)@paramconfig.allowTracking - Whether to allow anonymous usage analytics@paramconfig.provider - The provider to use for this Composio instance (defaults to OpenAIProvider)@example```typescript
// Initialize with default configuration
const composio = new Composio();
// Initialize with custom API key and base URL
const composio = new Composio({
apiKey: 'your-api-key',
baseURL: 'https://api.composio.dev'
});
// Initialize with custom provider
const composio = new Composio({
apiKey: 'your-api-key',
provider: new CustomProvider()
});
```
Composio({ provider?: OpenAIProvider | undefined
The tool provider to use for this Composio instance.
@examplenew OpenAIProvider()
provider: newnew OpenAIProvider(): OpenAIProvider
Creates a new instance of the OpenAIProvider.
This is the default provider for the Composio SDK and is automatically
available without additional installation.
@example```typescript
// The OpenAIProvider is used by default when initializing Composio
const composio = new Composio({
apiKey: 'your-api-key'
});
// You can also explicitly specify it
const composio = new Composio({
apiKey: 'your-api-key',
provider: new OpenAIProvider()
});
```
Represents the completion of an asynchronous operation
Promise<boolean> { /** * Check if a connected account exists for a given user id. */ // Fetch all connected accounts for the user returncomposioClient: Composio<OpenAIProvider>composioClient.Composio<OpenAIProvider>.connectedAccounts: ConnectedAccounts
Lists all connected accounts based on provided filter criteria.
This method retrieves connected accounts from the Composio API with optional filtering.
@paramquery - Optional query parameters for filtering connected accounts@returnsA paginated list of connected accounts@throws{ValidationError} If the query fails validation against the expected schema@example```typescript
// List all connected accounts
const allAccounts = await composio.connectedAccounts.list();
// List accounts for a specific user
const userAccounts = await composio.connectedAccounts.list({
userIds: ['user123']
});
// List accounts for a specific toolkit
const githubAccounts = await composio.connectedAccounts.list({
toolkitSlugs: ['github']
});
```
Attaches callbacks for the resolution and/or rejection of the Promise.
@paramonfulfilled The callback to execute when the Promise is resolved.@paramonrejected The callback to execute when the Promise is rejected.@returnsA Promise for the completion of which ever callback is executed.
account.status: "INITIALIZING" | "INITIATED" | "ACTIVE" | "FAILED" | "EXPIRED" | "INACTIVE"status=== "ACTIVE") { return true; } // Ideally you should not have inactive accounts, but if you do, delete them.var console: Console
The `console` module provides a simple debugging console that is similar to the
JavaScript console mechanism provided by web browsers.
The module exports two specific components:
* A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream.
* A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and
[`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module.
_**Warning**_: The global console object's methods are neither consistently
synchronous like the browser APIs they resemble, nor are they consistently
asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for
more information.
Example using the global `console`:
```js
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
```
Example using the `Console` class:
```js
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
```
Prints to `stdout` with newline. Multiple arguments can be passed, with the
first used as the primary message and all additional used as substitution
values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html)
(the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)).
```js
const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
```
See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
Represents the completion of an asynchronous operation
Promise<string> { /** * Validate the user id, if no connected account is found, create a new connection. */ if (awaitfunction checkConnectedAccountExists(composioClient: Composio<OpenAIProvider>, userId: string): Promise<boolean>checkConnectedAccountExists(composioClient: Composio<OpenAIProvider>composioClient, userId: stringuserId)) { returnuserId: stringuserId; } throw new
Error("No connected account found for the user id");}// Endpoint: Run the Gmail agent for a given user id and promptconst app: Hono<BlankEnv, BlankSchema, "/">app.
post("/agent", async (c: Context<BlankEnv, "/agent", BlankInput>c) => { /** * Run the Gmail agent for a given user id and prompt. */ constconst request: any
Run the Gmail agent for a given user id and prompt.
json(); // For demonstration, using a default user_id. Replace with real user logic in production. constconst userId: "default"userId = "default"; // Validate the user id before proceeding awaitfunction validateUserId(userId: string, composioClient: Composio<OpenAIProvider>): Promise<string>validateUserId(const userId: "default"userId, const composioClient: Composio<OpenAIProvider>composioClient); // Run the Gmail agent using Composio and OpenAI constconst result: any[]result = awaitfunction runGmailAgent(c: Composio<OpenAIProvider>, o: OpenAI, u: string, p: string): Promise<any[]>runGmailAgent(const composioClient: Composio<OpenAIProvider>composioClient,const openaiClient: OpenAIopenaiClient,const userId: "default"userId,const request: any
Run the Gmail agent for a given user id and prompt.
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.
Before proceeding, check the code for utility endpoints not discussed in the cookbook
Requires an active connected account for the default user.
curl -X POST http://localhost:8000/agent \ -H "Content-Type: application/json" \ -d '{ "user_id": "default", "prompt": "Summarize my latest unread emails from the last 24 hours." }'
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
manage Gmail OAuth app
manage user connections
tools for your agents to interact with Gmail
Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.