Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
Port guides from docs/revamp into docs/cookbooks-release (#1908)
Sushmitha Mallesh3bcc8c54d96d
diff --git a/fern/docs.yml b/fern/docs.ymlindex 6b7bc4ecb..3f9f25b78 100644--- a/fern/docs.yml+++ b/fern/docs.yml@@ -192,23 +192,32 @@ navigation:icon: rocketskip-slug: truecontents:+ - page: Basic FastAPI Server+ path: pages/dist/examples/fast-api.mdx+ slug: examples/fast-api- page: Basic Hono Server- path: pages/dist/examples/sample-webserver/sample-webserver.mdx- slug: examples/sample-webserver+ path: pages/dist/examples/hono.mdx+ slug: examples/hono+ - section: Productivity & Automation+ icon: zap+ skip-slug: true+ contents:+ - page: Gmail Labeller+ path: pages/dist/examples/utility_agents/gmail_labeler.mdx+ slug: examples/gmail-labeler+ - page: Slack summariser+ path: pages/dist/examples/utility_agents/slack_summariser.mdx+ slug: examples/slack-summariser+ - page: Supabase SQL Agent+ path: pages/dist/examples/utility_agents/supabase_sql_agent.mdx+ slug: examples/supabase-sql-agent- section: Full Stack Applicationsicon: globeskip-slug: truecontents:- page: Full Stack Chat App- path: pages/dist/examples/vercel-composio.mdx- slug: examples/chat-app- - section: Productivity & Automation- icon: zap- skip-slug: true- contents:- - page: AI Gmail Labeller- path: pages/dist/examples/gmail-filterer.mdx- slug: examples/gmail-reaper+ path: pages/dist/examples/chat_applications/vercel_chat.mdx+ slug: examples/vercel-chat- section: Behind the curtainicon: person-boothskip-slug: truediff --git a/fern/pages/src/examples/vercel-composio.mdx b/fern/pages/src/examples/chat_applications/vercel_chat.mdxsimilarity index 85%rename from fern/pages/src/examples/vercel-composio.mdxrename to fern/pages/src/examples/chat_applications/vercel_chat.mdxindex e88686dd0..c1f4ba753 100644--- a/fern/pages/src/examples/vercel-composio.mdx+++ b/fern/pages/src/examples/chat_applications/vercel_chat.mdx@@ -10,29 +10,29 @@ In this example, you will learn how to build a chatbot that:- Lets users connect their various apps to the chatbot using the Composio SDK.- Uses the Vercel provider in the Composio SDK to handle and execute tool calls from the LLM.-This page gives a high-level overview of the Composio SDK and how it is used in the GitHub repository: [composiohq/chat](https://github.com/composiohq/chat).--You can find the demo live [here](https://chat.composio.dev/).+This page gives a high-level overview of the Composio SDK and how it is used in the+GitHub repository: [composiohq/chat](https://github.com/composiohq/chat). You can+find the demo live [here](https://chat.composio.dev/).## Prerequisites-Ensure you've followed the README.md in the [composiohq/chat](https://github.com/composiohq/chat) repository to set up the project locally.+Ensure you've followed the README.md in the [composiohq/chat](https://github.com/composiohq/chat)+repository to set up the project locally.## Creating auth configs-For all the apps you want to connect to the chatbot, you need to create their respective auth configs.--Learn how to create auth configs [here](/docs/authenticating-tools#creating-an-auth-config).--Once done, your auth configs will be available in the <a href="https://platform.composio.dev?next_page=/auth-configs" target="_blank">Composio dashboard</a>.+For all the apps you want to connect to the chatbot, you need to create their+respective auth configs. Learn how to create auth configs [here](/docs/authenticating-tools#creating-an-auth-config).+Once done, your auth configs will be available in the [Composio dashboard](https://app.composio.dev/integrations).<Frame>- <img src="../../../assets/images/examples/auth-configs.png" alt="Auth configs" />+ <img src="../../../../assets/images/examples/auth-configs.png" alt="Auth configs" /></Frame>### Save auth config IDs to environment variables-For this project, the auth config IDs should be saved to the environment variables with the `NEXT_PUBLIC_` prefix.+For this project, the auth config IDs should be saved to the environment variables+with the `NEXT_PUBLIC_` prefix.```bash .env.localNEXT_PUBLIC_GMAIL_AUTH_CONFIG_ID=ac_1234567890@@ -41,7 +41,8 @@ NEXT_PUBLIC_GITHUB_AUTH_CONFIG_ID=ac_1234567890## Create a Composio client instance-We create a Composio client instance for server-side operations like API routes, server components, etc.+We create a Composio client instance for server-side operations like API routes,+server components, etc.```typescript lib/service/composio.tsimport { Composio } from '@composio/core';@@ -57,17 +58,19 @@ export default composio;## Creating an API for fetching toolkits-The Composio SDK is meant to be used only in server-side code. For client-side functionality, we create API endpoints in the `/app/api/` directory.--In order to list the toolkits and their connection status, we create a Next.js API route to fetch the toolkits using Composio SDK.+The Composio SDK is meant to be used only in server-side code. For client-side+functionality, we create API endpoints in the `/app/api/` directory. In order to+list the toolkits and their connection status, we create a Next.js API route to+fetch the toolkits using Composio SDK.<Frame>- <img src="../../../assets/images/examples/toolkits.png" />+ <img src="../../../../assets/images/examples/toolkits.png" /></Frame>### 1. Listing connected accounts-First, we fetch all connected accounts for a user and create a mapping of toolkit slugs to their connection IDs:+First, we fetch all connected accounts for a user and create a mapping of toolkit+slugs to their connection IDs:```typescript app/api/composio/toolkits.tsexport async function GET() {@@ -128,7 +131,7 @@ Users need to connect and disconnect their accounts from the chatbot to enable tWhen a user wants to connect their account, we create a connection request that redirects them to the OAuth provider:<Frame>- <img src="../../../assets/images/examples/create-connection.png" />+ <img src="../../../../assets/images/examples/create-connection.png" /></Frame>```typescript app/api/connections/initiate/route.ts@@ -155,7 +158,7 @@ export async function POST(request: Request) {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:<Frame>- <img src="../../../assets/images/examples/connection-status.png" />+ <img src="../../../../assets/images/examples/connection-status.png" /></Frame>```typescript app/api/connections/status/route.ts@@ -260,7 +263,7 @@ export async function POST(request: Request) {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.<Frame>- <img src="../../../assets/images/examples/custom-tool-component.png" />+ <img src="../../../../assets/images/examples/custom-tool-component.png" /></Frame>You can find the `ToolCall` component at `components/tool-call.tsx`. Here's how to integrate it into your message rendering:diff --git a/fern/pages/src/examples/fast-api.mdx b/fern/pages/src/examples/fast-api.mdxnew file mode 100644index 000000000..45a0a7b2d--- /dev/null+++ b/fern/pages/src/examples/fast-api.mdx@@ -0,0 +1,401 @@+---+title: Basic FastAPI Server+subtitle: "Build a simple Gmail agent with Composio and FastAPI"+image: "https://og.composio.dev/api/og?title=Basic%20FastAPI%20Server" # image for socials+keywords: "fastapi, composio, openai, gmail, agent"+hide-nav-links: false+---++This cookbook will guide you through building agents equipped with tools using `Composio`, `OpenAI`, and `FastAPI`.++## Prerequisites++* Python 3.10++* [UV](https://docs.astral.sh/uv/getting-started/installation/)+* Composio API key+* OpenAI API key++## Building an AI agent that can interact with `gmail` service++First, let's start with building a simple AI agent with Composio tools that lets the agent interact with `gmail`.++```python+from openai import OpenAI+from composio import Composio+from composio_openai import OpenAIProvider+import os++def run_gmail_agent(+ composio_client: Composio[OpenAIProvider],+ openai_client: OpenAI,+ user_id: str, # Composio uses the User ID to store and access user-level authentication tokens.+ prompt: str,+):+ """+ Run the Gmail agent using composio and openai clients.+ """+ # Step 1: Fetch the necessary Gmail tools list with Composio+ tools = composio_client.tools.get(+ user_id=user_id,+ 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+ response = openai_client.chat.completions.create(+ model="gpt-4.1",+ tools=tools,+ messages=[{"role": "user", "content": prompt}],+ )++ # Step 3: Handle tool calls with Composio and return the result+ result = composio_client.provider.handle_tool_calls(response=response, user_id=user_id)+ return result+```++<Note>+This example demonstrates a basic agent without state management or agentic loops,+suitable for simple one-step tasks. For complex multi-step workflows requiring+memory and iterative reasoning, see our cookbooks with frameworks like LangChain,+CrewAI, or AutoGen.+</Note>++To invoke this agent, authenticate your users with Composio's managed authentication service.++## Authenticating users+++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](https://developers.google.com/identity/protocols/oauth2). Once you have the credentials, use the following piece of code to set up authentication for `gmail`.++```python+from composio import Composio+from composio_openai import OpenAIProvider++def create_auth_config(composio_client: Composio[OpenAIProvider]):+ """+ Create a auth config for the gmail toolkit.+ """+ client_id = os.getenv("GMAIL_CLIENT_ID")+ client_secret = os.getenv("GMAIL_CLIENT_SECRET")+ if not client_id or not client_secret:+ raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")++ return composio_client.auth_configs.create(+ toolkit="GMAIL",+ options={+ "name": "default_gmail_auth_config",+ "type": "use_custom_auth",+ "auth_scheme": "OAUTH2",+ "credentials": {+ "client_id": client_id,+ "client_secret": client_secret,+ },+ },+ )+```++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.++```python+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):+ """+ Fetch the auth config for a given user id.+ """+ auth_configs = composio_client.auth_configs.list()+ for auth_config in auth_configs.items:+ if auth_config.toolkit == "GMAIL":+ return auth_config++ return None+```++<Note>+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.+</Note>++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.++```python+from fastapi import FastAPI++# Function to initiate a connected account+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):+ """+ Create a connection for a given user id and auth config id.+ """+ # Fetch or create the auth config for the gmail toolkit+ auth_config = fetch_auth_config(composio_client=composio_client)+ if not auth_config:+ auth_config = create_auth_config(composio_client=composio_client)++ # Create a connection for the user+ return composio_client.connected_accounts.initiate(+ user_id=user_id,+ auth_config_id=auth_config.id,+ )++# Setup FastAPI+app = FastAPI()++# Connection initiation endpoint[email protected]("/connection/create")+def _create_connection(+ request: CreateConnectionRequest,+ composio_client: ComposioClient,+) -> dict:+ """+ Create a connection for a given user id.+ """+ # For demonstration, using a default user_id. Replace with real user logic in production.+ user_id = "default"++ # Create a new connection for the user+ connection_request = create_connection(composio_client=composio_client, user_id=user_id)+ return {+ "connection_id": connection_request.id,+ "redirect_url": connection_request.redirect_url,+ }+```++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.++## Set Up FastAPI service++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.++### Setup dependencies++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.++```python+import os+import typing_extensions as te++from composio import Composio+from composio_openai import OpenAIProvider++from fastapi import Depends++_composio_client: Composio[OpenAIProvider] | None = None++def provide_composio_client():+ """+ Provide a Composio client.+ """+ global _composio_client+ if _composio_client is None:+ _composio_client = Composio(provider=OpenAIProvider())+ return _composio_client+++ComposioClient = te.Annotated[Composio, Depends(provide_composio_client)]+"""+A Composio client dependency.+"""+```++Check [dependencies](./simple_gmail_agent/server/dependencies.py) module for more details.++### Invoke agent via FastAPI++When invoking an agent, make sure you validate the `user_id`.++```python+def check_connected_account_exists(+ composio_client: Composio[OpenAIProvider],+ user_id: str,+):+ """+ Check if a connected account exists for a given user id.+ """+ # Fetch all connected accounts for the user+ connected_accounts = composio_client.connected_accounts.list(+ user_ids=[user_id],+ toolkit_slugs=["GMAIL"],+ )++ # Check if there's an active connected account+ for account in connected_accounts.items:+ if account.status == "ACTIVE":+ return True++ # Ideally you should not have inactive accounts, but if you do, delete them.+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")+ return False++def validate_user_id(user_id: str, composio_client: ComposioClient):+ """+ Validate the user id, if no connected account is found, create a new connection.+ """+ if check_connected_account_exists(composio_client=composio_client, user_id=user_id):+ return user_id++ raise HTTPException(+ status_code=404, detail={"error": "No connected account found for the user id"}+ )++# Endpoint: Run the Gmail agent for a given user id and prompt[email protected]("/agent")+def _run_gmail_agent(+ request: RunGmailAgentRequest,+ composio_client: ComposioClient,+ openai_client: OpenAIClient, # OpenAI client will be injected as dependency+) -> List[ToolExecutionResponse]:+ """+ Run the Gmail agent for a given user id and prompt.+ """+ # For demonstration, using a default user_id. Replace with real user logic in production.+ user_id = "default"++ # Validate the user id before proceeding+ user_id = validate_user_id(user_id=user_id, composio_client=composio_client)++ # Run the Gmail agent using Composio and OpenAI+ result = run_gmail_agent(+ composio_client=composio_client,+ openai_client=openai_client,+ user_id=user_id,+ prompt=request.prompt,+ )+ return result+```++<Note>+Check [server](./simple_gmail_agent/server/) module for service implementation+</Note>++## Putting everything together++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.++<Note>+Before proceeding, check the [code](./simple_gmail_agent/server/api.py) for utility endpoints not discussed in the cookbook+</Note>+++1. Clone the repository+ ```bash+ git clone [email protected]:composiohq/composio-fastapi+ cd composio-fastapi/+ ```+2. Setup environment+ ```bash+ cp .env.example .env+ ```++ Fill the api keys+ ```dotenv+ COMPOSIO_API_KEY=+ OPENAI_API_KEY=+ ```++ Create the virtual env+ ```bash+ make env+ source .venv/bin/activate+ ```+3. Run the HTTP server+ ```bash+ uvicorn simple_gmail_agent.server.api:create_app --factory+ ```+## Testing the API with curl++Assuming the server is running locally on `http://localhost:8000`.++### Check if a connection exists+```bash+curl -X POST http://localhost:8000/connection/exists+```++### Create a connection+Note: The body fields are required by the API schema, but are ignored internally in this example service.+```bash+curl -X POST http://localhost:8000/connection/create \+ -H "Content-Type: application/json" \+ -d '{+ "user_id": "default",+ "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"+ }'+```+Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.++### Check connection status+Use the `connection_id` returned from the create step.+```bash+curl -X POST http://localhost:8000/connection/status \+ -H "Content-Type: application/json" \+ -d '{+ "user_id": "default",+ "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"+ }'+```++### Run the Gmail agent+Requires an active connected account for the `default` user.+```bash+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."+ }'+```++### Fetch emails (direct action)+```bash+curl -X POST http://localhost:8000/actions/fetch_emails \+ -H "Content-Type: application/json" \+ -d '{+ "user_id": "default",+ "limit": 5+ }'+```++These examples are intended solely for testing purposes.++## Using Composio for managed auth and tools++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.++## Best practices++**🎯 Effective Prompts**:+- Be specific: "Send email to [email protected] about tomorrow's 2pm meeting" works better than "send email"+- Include context: "Reply to Sarah's email about the budget with our approval"+- Use natural language: The agent understands conversational requests++**🔒 User Management**:+- Use unique, consistent `user_id` values for each person+- Each user maintains their own Gmail connection+- User IDs can be email addresses, usernames, or any unique identifier+++## Troubleshooting++**Connection Issues**:+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`+- Check if the user has completed Gmail authorization.+- Verify the user_id matches exactly between requests++**API Errors**:+- Check the server logs for detailed error messages+- Ensure request payloads match the expected format+- Visit `/docs` endpoint for API schema validation++**Gmail API Limits**:+- Gmail has rate limits; the agent will handle these gracefully+- For high-volume usage, consider implementing request queuingdiff --git a/fern/pages/src/examples/hello-world.mdx b/fern/pages/src/examples/hello-world.mdxdeleted file mode 100644index d016baa17..000000000--- a/fern/pages/src/examples/hello-world.mdx+++ /dev/null@@ -1,9 +0,0 @@-----title: Hello World!-image: "https://og.composio.dev/api/og?title=Hello%20World%21" # image for socials-description: "A simple example of how to use the Composio SDK to call tools."-keywords: "hello world, composio, sdk, tool calling"-subtitle: ""-hide-nav-links: true-----diff --git a/fern/pages/src/examples/hono.mdx b/fern/pages/src/examples/hono.mdxnew file mode 100644index 000000000..40ddb4383--- /dev/null+++ b/fern/pages/src/examples/hono.mdx@@ -0,0 +1,422 @@+---+title: Basic Hono Server+image: "https://og.composio.dev/api/og?title=Basic%20Hono%20Server" # image for socials+keywords: "hono, composio, openai, gmail, agent"+hide-nav-links: false+description: Build a simple Gmail agent with Composio and Hono.js+---++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`.++## Prerequisites++* Node.js 18.x or higher+* npm or yarn package manager+* Composio API key+* OpenAI API key+* Basic knowledge of OAuth+* Understanding of building HTTP services (preferably using Hono.js)++## Building an AI agent that can interact with `gmail` service++First, let's start with building a simple AI agent embedded with tools from+Composio that lets the agent interact with the `gmail` service.++```typescript+import { OpenAI } from 'openai';+import { Composio } from '@composio/core';+import { OpenAIProvider } from '@composio/openai';++export async function runGmailAgent(+ composioClient: Composio<OpenAIProvider>,+ openaiClient: OpenAI,+ userId: string, // Composio uses the User ID to store and access user-level authentication tokens.+ prompt: string,+): Promise<any[]> {+ // Step 1: Fetch the necessary Gmail tools list with Composio+ const tools = await composioClient.tools.get(+ userId,+ {+ 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 response = await openaiClient.chat.completions.create({+ model: "gpt-4.1",+ tools,+ messages: [{ role: "user", content: prompt }],+ });++ // Step 3: Handle tool calls with Composio and return the result+ const result = await composioClient.provider.handleToolCalls(+ userId,+ response+ );+ return result;+}+```++<Note>+ 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.+</Note>++To invoke this agent, authenticate your users with Composio's managed authentication service.++## Authenticating users++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](https://developers.google.com/identity/protocols/oauth2). Once you have the credentials, use the following piece of code to set up authentication for `gmail`.++```typescript+import { Composio } from '@composio/core';+import { OpenAIProvider } from '@composio/openai';++export async function createAuthConfig(composioClient: Composio<OpenAIProvider>) {+ /**+ * Create a auth config for the gmail toolkit.+ */+ const clientId = process.env.GMAIL_CLIENT_ID;+ const clientSecret = process.env.GMAIL_CLIENT_SECRET;+ if (!clientId || !clientSecret) {+ throw new Error("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set");+ }++ return composioClient.authConfigs.create(+ "GMAIL",+ {+ "name": "default_gmail_auth_config",+ "type": "use_custom_auth",+ "authScheme": "OAUTH2",+ "credentials": {+ "clientId": clientId,+ "clientSecret": clientSecret,+ },+ },+ );+}+```++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.++```typescript+export async function fetchAuthConfig(composioClient: Composio<OpenAIProvider>) {+ /**+ * Fetch the auth config for a given user id.+ */+ const authConfigs = await composioClient.authConfigs.list();+ for (const authConfig of authConfigs.items) {+ if (authConfig.toolkit.slug === "gmail") {+ return authConfig;+ }+ }++ return null;+}+```++<Note>+ 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.+</Note>++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.++```typescript+import { Hono } from 'hono';++// Function to initiate a connected account+export async function createConnection(composioClient: Composio<OpenAIProvider>, userId: string) {+ /**+ * Create a connection for a given user id and auth config id.+ */+ // Fetch or create the auth config for the gmail toolkit+ let authConfig = await fetchAuthConfig(composioClient);+ if (!authConfig) {+ authConfig = await createAuthConfig(composioClient);+ }++ // Create a connection for the user+ return composioClient.connectedAccounts.initiate(+ userId,+ authConfig.id,+ );+}++// Setup Hono+const app = new Hono();++// Connection initiation endpoint+app.post("/connection/create", async (c) => {+ /**+ * Create a connection for a given user id.+ */+ // For demonstration, using a default user_id. Replace with real user logic in production.+ const userId = "default";++ // Create a new connection for the user+ const connectionRequest = await createConnection(composioClient, userId);+ return c.json({+ "connection_id": connectionRequest.id,+ "redirect_url": connectionRequest.redirectUrl,+ });+});+```++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.++## Set Up Hono service++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.++### Setup dependencies++Hono allows dependency injection patterns to simplify the usage of SDK clients that must be singletons. We recommend using composio SDK client as singleton.++```typescript+import { Composio } from '@composio/core';+import { OpenAIProvider } from '@composio/openai';+import { OpenAI } from 'openai';++let _composioClient: Composio<OpenAIProvider> | null = null;++export function provideComposioClient(): Composio<OpenAIProvider> {+ /**+ * Provide a Composio client.+ */+ if (_composioClient === null) {+ _composioClient = new Composio({+ provider: new OpenAIProvider()+ });+ }+ return _composioClient;+}++// A Composio client dependency.+export type ComposioClient = Composio<OpenAIProvider>;+```++Check [config/composio.ts](./src/config/composio.ts) module for more details.++### Invoke agent via Hono++When invoking an agent, make sure you validate the `user_id`.++```typescript+export function checkConnectedAccountExists(+ composioClient: Composio<OpenAIProvider>,+ userId: string,+): Promise<boolean> {+ /**+ * Check if a connected account exists for a given user id.+ */+ // Fetch all connected accounts for the user+ return composioClient.connectedAccounts.list({ userIds: [userId], toolkitSlugs: ["GMAIL"] }).then(connectedAccounts => {++ // Check if there's an active connected account+ for (const account of connectedAccounts.items) {+ if (account.status === "ACTIVE") {+ return true;+ }++ // Ideally you should not have inactive accounts, but if you do, delete them.+ console.log(`[warning] inactive account ${account.id} found for user id: ${userId}`);+ }+ return false;+ });+}++export async function validateUserId(userId: string, composioClient: ComposioClient): Promise<string> {+ /**+ * Validate the user id, if no connected account is found, create a new connection.+ */+ if (await checkConnectedAccountExists(composioClient, userId)) {+ return userId;+ }++ throw new Error("No connected account found for the user id");+}++// Endpoint: Run the Gmail agent for a given user id and prompt+app.post("/agent", async (c) => {+ /**+ * Run the Gmail agent for a given user id and prompt.+ */+ const request = await c.req.json();++ // For demonstration, using a default user_id. Replace with real user logic in production.+ const userId = "default";++ // Validate the user id before proceeding+ await validateUserId(userId, composioClient);++ // Run the Gmail agent using Composio and OpenAI+ const result = await runGmailAgent(+ composioClient,+ openaiClient,+ userId,+ request.prompt,+ );+ return c.json(result);+});+```++<Note>+ Check [src/api.ts](./src/api.ts) module for service implementation+</Note>++## Putting everything together++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.++<Note>+ Before proceeding, check the [code](./src/api.ts) for utility endpoints not discussed in the cookbook+</Note>++1. Clone the repository+ ```bash+ git clone [email protected]:composiohq/composio-hono+ cd composio-hono/+ ```+2. Setup environment++ ```bash+ cp .env.example .env+ ```++ Fill the api keys++ ```dotenv+ COMPOSIO_API_KEY=+ OPENAI_API_KEY=+ ```++ Install dependencies++ ```bash+ npm install+ ```+3. Run the HTTP server+ ```bash+ npm run dev+ ```++## Testing the API with curl++Assuming the server is running locally on `http://localhost:8000`.++### Check if a connection exists++```bash+curl -X POST http://localhost:8000/connection/exists+```++### Create a connection++Note: The body fields are required by the API schema, but are ignored internally in this example service.++```bash+curl -X POST http://localhost:8000/connection/create \+ -H "Content-Type: application/json" \+ -d '{+ "user_id": "default",+ "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"+ }'+```++Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.++### Check connection status++Use the `connection_id` returned from the create step.++```bash+curl -X POST http://localhost:8000/connection/status \+ -H "Content-Type: application/json" \+ -d '{+ "user_id": "default",+ "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"+ }'+```++### Run the Gmail agent++Requires an active connected account for the `default` user.++```bash+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."+ }'+```++### Fetch emails (direct action)++```bash+curl -X POST http://localhost:8000/actions/fetch_emails \+ -H "Content-Type: application/json" \+ -d '{+ "user_id": "default",+ "limit": 5+ }'+```++These examples are intended solely for testing purposes.++## Using Composio for managed auth and tools++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.++## Best practices++**🎯 Effective Prompts**:++* Be specific: "Send email to [[email protected]](mailto:[email protected]) about tomorrow's 2pm meeting" works better than "send email"+* Include context: "Reply to Sarah's email about the budget with our approval"+* Use natural language: The agent understands conversational requests++**🔑 User Management**:++* Use unique, consistent `user_id` values for each person+* Each user maintains their own Gmail connection+* User IDs can be email addresses, usernames, or any unique identifier++## Troubleshooting++**Connection Issues**:++* Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`+* Check if the user has completed Gmail authorization.+* Verify the user\_id matches exactly between requests++**API Errors**:++* Check the server logs for detailed error messages+* Ensure request payloads match the expected format+* Visit `/docs` endpoint for API schema validation++**Gmail API Limits**:++* Gmail has rate limits; the agent will handle these gracefully+* For high-volume usage, consider implementing request queuing\ No newline at end of filediff --git a/fern/pages/src/examples/sample-script.mdx b/fern/pages/src/examples/sample-script.mdxdeleted file mode 100644index 42c9c205f..000000000--- a/fern/pages/src/examples/sample-script.mdx+++ /dev/null@@ -1,27 +0,0 @@-----title: Sample Script-image: "https://og.composio.dev/api/og?title=Sample%20Script" # image for socials-description: "A simple example of a Python script that uses the Composio SDK to call tools."-keywords: "hello world python, composio, sdk, tool calling"-subtitle: ""-hide-nav-links: true------This tutorial will show you the basics of how to use the Composio SDK to call tools.--SAMPLE--```bash-pip install composio==0.8.0-```--Here's a complete Python example that demonstrates the Composio SDK:--<SnippetCode- src="fern/snippets/examples/sample-script/sample-script.py"- startLine={1}- title="Setting up Composio and OpenAI"- highlightStart={17}- highlightEnd={19}-/>-diff --git a/fern/pages/src/examples/sample-webserver/index.ts b/fern/pages/src/examples/sample-webserver/index.tsdeleted file mode 100644index cdd0fe427..000000000--- a/fern/pages/src/examples/sample-webserver/index.ts+++ /dev/null@@ -1,61 +0,0 @@-import { Hono } from 'hono';-import { Composio } from '@composio/core';-import OpenAI from 'openai';--const app = new Hono();--// reads COMPOSIO_API_KEY from the environment variables-// uses OpenAI by default-const composio = new Composio();--const openai = new OpenAI();--// this should be made once and stored in a database-// const authConfigId = (await composio.authConfigs.create('GMAIL')).id;-const authConfigId = 'ac_DUMMY';--app.post('/create-connection', async c => {- const { userId } = await c.req.json();-- const connection = await composio.connectedAccounts.initiate(userId, authConfigId);-- return c.json({- id: connection.id,- // for the user to authorize the connection- redirectUrl: connection.redirectUrl,- });-});--app.post('/send-email', async c => {- const { userId, feedback, overwrite_email } = await c.req.json();-- const tools = await composio.tools.get(userId, {- toolkits: ['GMAIL'],- });-- const completion = await openai.chat.completions.create({- model: 'gpt-4o',- messages: [- {- role: 'system',- content:- 'Send the composio team feedback about their product at [email protected], parse the user feedback and send an email from their account, if they provide an email address, use that, otherwise sent it to [email protected]',- },- {- role: 'user',- content: `- User feedback: ${feedback}- Overwrite email: ${overwrite_email}- `,- },- ],- tools,- tool_choice: 'auto',- });-- const result = await composio.provider.handleToolCalls(userId, completion);-- return c.json({ completion, result });-});--export default app;diff --git a/fern/pages/src/examples/sample-webserver/sample-webserver.mdx b/fern/pages/src/examples/sample-webserver/sample-webserver.mdxdeleted file mode 100644index 528dfa4b3..000000000--- a/fern/pages/src/examples/sample-webserver/sample-webserver.mdx+++ /dev/null@@ -1,132 +0,0 @@-----title: A basic web server-image: "https://og.composio.dev/api/og?title=A%20basic%20web%20server" # image for socials-description: "A simple example of a web server that uses the Composio SDK to call tools."-keywords: "web server, composio, sdk, tool calling"-subtitle: ""-hide-nav-links: true------This tutorial shows you a minimal example of a web server that can use Composio.---### Install dependencies--Using `bun` for this example, it is super convenient for rapid prototyping.--```bash-bun install @composio/core openai hono-```--Please set the following environment variables:--```bash-# .env-COMPOSIO_API_KEY=your_api_key-OPENAI_API_KEY=your_api_key-```--The full source code is available [here](https://github.com/ComposioHQ/composio/blob/next/fern/pages/examples/src/sample-webserver/index.ts).--In this tutorial, we will create an auth config, initiate a connection, and send an email.--### Setup--Basic scaffolding for the server.--<SnippetCode- src="./index.ts"- startLine={1}- endLine={10}- title="Setup"- highlightStart={9}- highlightEnd={9}-/>---### Auth Configs--These are configurations for tools that control how they are authorized, the scopes, and permissions they have. You can learn more about them [here](/docs/authenticating-tools).--For this example, we will create a basic GMAIL auth config.--You are recommended to store these config IDs, so that you can reuse them later.--<SnippetCode- src="./index.ts"- startLine={12}- endLine={16}- title="Auth Configs"-/>---### Initiating a connection--Connections are your users authorizing your tools.--Here we start the connection process. Once your user uses the `redirectUrl` from the response,-they will be redirected to the auth flow.-Once they have authorized the connection, you can use the `id` to get and execute the tools as the user.--<SnippetCode- src="./index.ts"- startLine={16}- endLine={27}- title="Initiating a connection"- highlightStart={19}- highlightEnd={19}-/>--You can test your server by running `bun run index.ts` and then running the following command:--```bash-curl -X POST http://localhost:3000/create-connection \--H "Content-Type: application/json" \--d '{"userId": "123"}'-```--### Sending an email--Now let's send that email.--<SnippetCode- src="./index.ts"- startLine={29}- endLine={59}- title="Sending an email"- highlightStart={56}- highlightEnd={56}-/>--Using the `id` from the connection, we can now send an email.--```bash-curl -X POST http://localhost:3000/send-email \--H "Content-Type: application/json" \--d '{"userId": "123", "feedback": "These docs are great!"}'-```---### Full Code--You can see the full code [here](https://github.com/ComposioHQ/composio/blob/next/fern/pages/src/examples/sample-webserver/index.ts).---### What just happened?--Well, first - we created an instance of our `gmail` tool with our default auth config, then our user authorized that tool with their account and some permissions.--Then we used that `gmail` tool by giving it to OpenAI's `gpt-4o`. The model composed the email and sent it correctly formatted to the Composio team.--### What's next?--This is a fairly basic example, but you can do a lot more with our SDK.--Recommended further reading:--- [Authenticating tools](/docs/authenticating-tools) - understand how to control tool authorization-- [Executing Tools](/docs/executing-tools) - understand how tool execution works-- [Providers](/docs/providers) - want to use something other than OpenAI? We probably support it-- [Tools](/docs/tools) - understand what tools we have--diff --git a/fern/pages/src/examples/tool-generator.mdx b/fern/pages/src/examples/tool-generator.mdxdeleted file mode 100644index 2c9e9e913..000000000--- a/fern/pages/src/examples/tool-generator.mdx+++ /dev/null@@ -1,45 +0,0 @@-----title: Tool Type Generator-image: "https://og.composio.dev/api/og?title=Tool%20Type%20Generator" # image for socials-description: "An example that shows you how to showcase auth scheme and action params for tools"-keywords: "tool type generator, composio, sdk, tool calling"-subtitle: "using raw tool definition to build your own platform on top of Composio"-hide-nav-links: true------This is a bit of a cheeky tutorial as it is dogfooding the `docs` tool generation process.--To motivate this example clearly, in our tools section — we have details about, let's say, the [`Github`](/tools/github) tool, that shows its auth scheme, actions, and their params.--Now why would anyone outside of Composio want to do this? Well, if you are building a platform on top of Composio, perhaps a workflow builder like Langflow, you would want to show some or all of this information to your users.--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.--## How does one build a tool type generator?--In Composio, we have two internal states for tools:--1. Raw tool definition-2. Provider tool definition--The raw tool definition is a generic input-output schema definition that we use internally for tools. We expose it for customers if they want to build on top of it, but it is not the primary way tools are normally used.--The provider tool definition translates this raw tool definition to the specific schema of a provider (by default `openai`).--For building something like this, we need to use the raw tool definition.---## Getting the raw tool definition-----<SnippetCode src="fern/generators/tool_doc_generator/main.py" path="tool_doc_generator/main.py" startLine={532} endLine={534} relativeHighlightStart={2} relativeHighlightEnd={2} wordWrap />--------diff --git a/fern/pages/src/examples/utility_agents/gmail_labeler.mdx b/fern/pages/src/examples/utility_agents/gmail_labeler.mdxnew file mode 100644index 000000000..9abd3bdb9--- /dev/null+++ b/fern/pages/src/examples/utility_agents/gmail_labeler.mdx@@ -0,0 +1,383 @@+---+title: Gmail Labeler+image: "https://og.composio.dev/api/og?title=Gmail%20Labeler" # image for socials+description: Build an Gmail auto labeler agent with Composio and Langchain+keywords: gmail labeler, utility agent, triggers+---++With Composio's managed authentication, tool calling and triggers, it's easy to+build the AI agents that can interact and react the real world events reducing+the boilerplate required to setup and manage the authentication. This cookbook+will walk you through the process of building agents using `Composio`, `LangChain`.++## Prerequisites++* Python3.x+* [UV](https://docs.astral.sh/uv/getting-started/installation/)+* Composio API key+* OpenAI API key+* Understanding of building AI agents (Preferably with LangChain)++## Build gmail agent to label your messages++```python+from composio import Composio+from composio_langchain import LangchainProvider++from langchain import hub+from langchain.agents import AgentExecutor, create_openai_functions_agent+from langchain_openai import ChatOpenAI+++def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):+ """+ Create an agent for a given user id.+ """+ # Step 1: Get all the tools+ tools = composio_client.tools.get(+ user_id=user_id,+ tools=[+ "GMAIL_LIST_LABELS",+ "GMAIL_ADD_LABEL_TO_EMAIL",+ "GMAIL_CREATE_LABEL",+ ],+ )++ # Step 2: Pull relevant agent prompt.+ prompt = hub.pull("hwchase17/openai-functions-agent")++ # Step 3: Initialize chat model.+ openai_client = ChatOpenAI(model="gpt-4-turbo")++ # Step 4: Define agent+ return AgentExecutor(+ agent=create_openai_functions_agent(+ openai_client,+ tools,+ prompt,+ ),+ tools=tools,+ verbose=False,+ )+```++## Authenticating users++To authenticate your users with Composio you need an auth config for the given+app, In this case you need one for gmail. You can create and manage auth configs+from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=gmail).+Composio platform provides composio managed authentication for some apps to help+you fast-track your development, `gmail` being one of them. You can use these+default auth configs for development, but for production you should always use+your own oauth app configuration.++Using dashboard is the preferred way of managing authentication configs, but if+you want to do it manually you can follow the guide below++<details>++<summary>Click to expand</summary>++To create an authentication config for `gmail` you need `client_id` and `client_secret`+from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).+Once you have the required credentials you can use the following piece of+code to set up authentication for `gmail`.++```python+from composio import Composio+from composio_langchain import LangchainProvider++def create_auth_config(composio_client: Composio[OpenAIProvider]):+ """+ Create a auth config for the gmail toolkit.+ """+ client_id = os.getenv("GMAIL_CLIENT_ID")+ client_secret = os.getenv("GMAIL_CLIENT_SECRET")+ if not client_id or not client_secret:+ raise ValueError("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set")++ return composio_client.auth_configs.create(+ toolkit="gmail",+ options={+ "name": "default_gmail_auth_config",+ "type": "use_custom_auth",+ "auth_scheme": "OAUTH2",+ "credentials": {+ "client_id": client_id,+ "client_secret": client_secret,+ },+ },+ )+```++This will create an authentication config for `gmail` which you can use to+authenticate your users for your app. Ideally you should just create one+authentication object per project, so check for an existing auth config+before you create a new one.++```python+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):+ """+ Fetch the auth config for a given user id.+ """+ auth_configs = composio_client.auth_configs.list()+ for auth_config in auth_configs.items:+ if auth_config.toolkit == "gmail":+ return auth_config++ return None+```+</details>++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 the users+to your `gmail` app via composio.++```python+# Function to initiate a connected account+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):+ """+ Create a connection for a given user id and auth config id.+ """+ # Fetch or create the auth config for the gmail toolkit+ auth_config = fetch_auth_config(composio_client=composio_client)+ if not auth_config:+ auth_config = create_auth_config(composio_client=composio_client)++ # Create a connection for the user+ return composio_client.connected_accounts.initiate(+ user_id=user_id,+ auth_config_id=auth_config.id,+ )+```++Now, when creating tools for your agent always check if the user already has a+connected account before creating a new one.++```python+def check_connected_account_exists(+ composio_client: Composio[LangchainProvider],+ user_id: str,+):+ """+ Check if a connected account exists for a given user id.+ """+ # Fetch all connected accounts for the user+ connected_accounts = composio_client.connected_accounts.list(+ user_ids=[user_id],+ toolkit_slugs=["GMAIL"],+ )++ # Check if there's an active connected account+ for account in connected_accounts.items:+ if account.status == "ACTIVE":+ return True++ # Ideally you should not have inactive accounts, but if you do, you should delete them+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")+ return False+```+++## Creating Triggers++You can use triggers to make your agents react to real world events. In this example,+we will use triggers to invoke your agent everytime there's a new message in your+gmail inbox.++```python+# Create a new trigger+def create_trigger(+ composio_client: Composio[LangchainProvider],+ connected_account_id: str,+) -> str:+ """+ Create a trigger.+ """+ response = composio_client.triggers.create(+ slug="GMAIL_NEW_GMAIL_MESSAGE",+ connected_account_id=connected_account_id,+ trigger_config={},+ )+ return response.trigger_id+```++When creating triggers, make sure there are no duplicate triggers. Use following+code as reference for checking if trigger for given connected account exists or not.++```python+def check_trigger_exists(+ composio_client: Composio[LangchainProvider],+ connected_account_id: str,+) -> t.Optional[str]:+ """+ Check if a trigger exists.+ """+ triggers = composio_client.triggers.list_active(+ trigger_names=["GMAIL_NEW_GMAIL_MESSAGE"],+ connected_account_ids=[connected_account_id],+ )+ for trigger in triggers.items:+ return trigger.id+ return None+```+++Once trigger is created, you can listen to events using a trigger subscription.++```python+# Create subscription object+trigger_subscription = composio_client.triggers.subscribe()++# Register event handler+@trigger_subscription.handle(+ trigger_id="<TRIGGER_ID>", # Filter out events that does not belong this trigger id+ trigger_slug="GMAIL_NEW_GMAIL_MESSAGE",+)+def handle_event(event: TriggerEvent):+ print("> Received email with subject: ", event["payload"]["subject"])++# Wait for events+trigger_subscription.wait_forever()+```++## Putting everything together++Let's put together everything by making the agent react to new messages in your+inbox.++```python+# Create a trigger subscription factory++def create_trigger_subscription(+ composio_client: Composio[LangchainProvider],+ trigger_slug: str,+ trigger_id: str,+ agent: AgentExecutor,+):+ """+ Create a trigger subscription for the given agent.+ """+ trigger_subscription = composio_client.triggers.subscribe()++ @trigger_subscription.handle(+ trigger_slug=trigger_slug,+ trigger_id=trigger_id,+ )+ def handle_event(event: TriggerEvent):+ print("> Received email with subject: ", event["payload"]["subject"])+ result = agent.invoke(+ input={+ "input": APPLY_NEW_LABEL.format( # Check `gmail_labeler/prompt.py`+ message_id=event["payload"]["id"],+ message_subject=event["payload"]["subject"],+ message_text=event["payload"]["message_text"],+ )+ }+ )+ print("> Result: ", result["output"])++ return trigger_subscription+```++Package everything as a single entry point.++```python+def run_agent(user_id: str):+ # Create composio client+ composio_client = Composio(provider=LangchainProvider())++ # Validate conected account+ connected_account_id = check_connected_account_exists(composio_client, user_id)+ if connected_account_id is None:+ connection_request = create_connection(composio_client, user_id)+ print(+ f"Authenticate with the following link: {connection_request.redirect_url}"+ )+ connection_request.wait_for_connection()+ connected_account_id = connection_request.id++ # Check if trigger exists, create if not+ trigger_id = check_trigger_exists(+ composio_client=composio_client,+ connected_account_id=connected_account_id,+ )+ if trigger_id is None:+ trigger_id = create_trigger(+ composio_client=composio_client,+ connected_account_id=connected_account_id,+ )++ # Create agent+ agent = create_agent(user_id=user_id, composio_client=composio_client)++ # Create trigger subscription+ trigger_subscription = create_trigger_subscription(+ composio_client=composio_client,+ trigger_slug=GMAIL_NEW_GMAIL_MESSAGE_TRIGGER,+ trigger_id=trigger_id,+ agent=agent,+ )++ # Wait forever+ print("Waiting for events...")+ trigger_subscription.wait_forever()+```++To test the above function as CLI, follow the steps below++1. Clone the repository+ ```bash+ git clone [email protected]:composiohq/gmail-labeler+ cd gmail-labeler/+ ```+2. Setup environment+ ```bash+ cp .env.example .env+ ```++ Fill the api keys+ ```dotenv+ COMPOSIO_API_KEY=+ OPENAI_API_KEY=+ ```++ Create the virtual env+ ```bash+ make env+ source .venv/bin/activate+ ```+3. Run the agent+ ```bash+ python gmail_labeler --user-id "default"+ ```++## Using Composio for managed auth and tools++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+- manage `gmail` oauth app+- manage user connections+- tools for your agents to interact with `gmail`+- Infra for listening to changes in your gmail inbox++Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.++## Best practices++**🔒 User Management**:++- Use unique, consistent `user_id` values for each person+- Each user maintains their own gmail connection+- User IDs can be email addresses, usernames, or any unique identifier++## Troubleshooting++**Connection Issues**:+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`+- Check that the user has completed `gmail` authorization+- Verify the user_id matches exactly between requests++**API Errors**:+- Check the server logs for detailed error messages+- Ensure request payloads match the expected format+- Visit `/docs` endpoint for API schema validationdiff --git a/fern/pages/src/examples/utility_agents/slack_summariser.mdx b/fern/pages/src/examples/utility_agents/slack_summariser.mdxnew file mode 100644index 000000000..60712ae3d--- /dev/null+++ b/fern/pages/src/examples/utility_agents/slack_summariser.mdx@@ -0,0 +1,305 @@+---+title: Slack summariser+image: "https://og.composio.dev/api/og?title=Slack%20summariser" # image for socials+description: Build a slack summarizer using Composio and Langchain+keywords: slack, summariser, utility agent+---++With Composio's managed authentication and tool calling, it's easy to build the+AI agents that can interact with the real world while reducing the boilerplate+required to setup and manage the authentication. This cookbook will walk you through+the process of building agents using `Composio`, `LangChain`.++## Prerequisites++* Python3.x+* [UV](https://docs.astral.sh/uv/getting-started/installation/)+* Composio API key+* OpenAI API key+* Understanding of building AI agents (Preferably with LangChain)++## Build slack agent++Let's start by building an agent that can interact with your slack workspace using Composio.++```python+from composio import Composio+from composio_langchain import LangchainProvider++from langchain import hub+from langchain.agents import AgentExecutor, create_openai_functions_agent+from langchain_openai import ChatOpenAI+++def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):+ """+ Create an agent for a given user id.+ """+ # Step 1: Get all the tools+ tools = composio_client.tools.get(+ user_id=user_id,+ toolkits=["SLACK"],+ )++ # Step 2: Pull relevant agent prompt.+ prompt = hub.pull("hwchase17/openai-functions-agent")++ # Step 3: Initialize chat model.+ openai_client = ChatOpenAI(model="gpt-4-turbo")++ # Step 4: Define agent+ return AgentExecutor(+ agent=create_openai_functions_agent(+ openai_client,+ tools,+ prompt,+ ),+ tools=tools,+ verbose=True,+ )+```+++## Authenticating users++To authenticate your users with Composio you need an auth config for the given+app, In this case you need one for slack. You can create and manage auth configs+from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=slack).++Composio platform provides composio managed authentication for some apps to help+you fast-track your development, `slack` being one of them. You can use these+default auth configs for development, but for production you should always use+your own oauth app configuration.++Using dashboard is the preferred way of managing authentication configs, but if+you want to do it manually you can follow the guide below++<details>++<summary>Click to expand</summary>++---++To create an authentication config for `slack` you need `client_id` and `client_secret`+from your Slack [App](https://api.slack.com/apps). Once you have the required credentials+you can use the following piece of code to set up authentication for `slack`.++```python+from composio import Composio+from composio_langchain import LangchainProvider++def create_auth_config(composio_client: Composio[OpenAIProvider]):+ """+ Create a auth config for the slack toolkit.+ """+ client_id = os.getenv("SLACK_CLIENT_ID")+ client_secret = os.getenv("SLACK_CLIENT_SECRET")+ if not client_id or not client_secret:+ raise ValueError("SLACK_CLIENT_ID and SLACK_CLIENT_SECRET must be set")++ return composio_client.auth_configs.create(+ toolkit="SLACK",+ options={+ "name": "default_slack_auth_config",+ "type": "use_custom_auth",+ "auth_scheme": "OAUTH2",+ "credentials": {+ "client_id": client_id,+ "client_secret": client_secret,+ },+ },+ )+```++This will create an authentication config for `slack` which you can use to+authenticate your users for your app. Ideally you should just create one+authentication object per project, so check for an existing auth config+before you create a new one.++```python+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):+ """+ Fetch the auth config for a given user id.+ """+ auth_configs = composio_client.auth_configs.list()+ for auth_config in auth_configs.items:+ if auth_config.toolkit == "SLACK":+ return auth_config++ return None+```+</details>++Once you have authentication management in place, we can start with connecting+your users to your `slack` app. Let's implement a function to connect the users+to your `slack` app via composio.++```python++# Function to initiate a connected account+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):+ """+ Create a connection for a given user id and auth config id.+ """+ # Fetch or create the auth config for the slack toolkit+ auth_config = fetch_auth_config(composio_client=composio_client)+ if not auth_config:+ auth_config = create_auth_config(composio_client=composio_client)++ # Create a connection for the user+ return composio_client.connected_accounts.initiate(+ user_id=user_id,+ auth_config_id=auth_config.id,+ )+```++Now, when creating tools for your agent always check if the user already has a+connected account before creating a new one.++```python+def check_connected_account_exists(+ composio_client: Composio[LangchainProvider],+ user_id: str,+):+ """+ Check if a connected account exists for a given user id.+ """+ # Fetch all connected accounts for the user+ connected_accounts = composio_client.connected_accounts.list(+ user_ids=[user_id],+ toolkit_slugs=["SLACK"],+ )++ # Check if there's an active connected account+ for account in connected_accounts.items:+ if account.status == "ACTIVE":+ return True++ # Ideally you should not have inactive accounts, but if you do, you should delete them+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")+ return False+```++## Modifiers++In the current setup, we are expanding too much unnecessary tokens because response+from `SLACK_FETCH_CONVERSATION_HISTORY` tool call contains too much unnecessary+information. This can be fixed using `after_execute` modifier. An after execute+modifier is called after a tool execution is complete, here you can process+and modify the response object to make it more easy to consume for your agent.++```python+from composio import after_execute+from composio.types import ToolExecutionResponse+++@after_execute(tools=["SLACK_FETCH_CONVERSATION_HISTORY"])+def clean_conversation_history(+ tool: str,+ toolkit: str,+ response: ToolExecutionResponse,+) -> ToolExecutionResponse:+ """+ Clean the conversation history.+ """+ if not response["data"]["ok"]:+ return response++ try:+ response["data"]["messages"] = [+ {"user": message["user"], "text": message["text"]}+ for message in response["data"]["messages"]+ if message["type"] == "message"+ ]+ except KeyError:+ pass++ return response+```++To register modifiers, include them in the `composio.tools.get` call.++```python+tools = composio_client.tools.get(+ user_id=user_id,+ toolkits=[SLACK_TOOLKIT],+ modifiers=[clean_conversation_history],+)+```++## Putting everything together++So far, we have created an agent with ability to interact with your `slack`+workspace using the `composio` SDK, functions to manage connected accounts+for users and a simple agent runner. Let's package this as a CLI tool.++```python+def run_agent(user_id: str, prompt: str):+ composio_client = Composio(provider=LangchainProvider())+ if not check_connected_account_exists(composio_client, user_id):+ connection_request = create_connection(composio_client, user_id)+ print(+ f"Authenticate with the following link: {connection_request.redirect_url}"+ )+ connection_request.wait_for_connection()++ agent = create_agent(user_id, composio_client)+ agent.invoke({"input": prompt})+```++To test the above function as CLI, follow the steps below++1. Clone the repository+ ```bash+ git clone [email protected]:composiohq/slack-summarizer+ cd slack-summarizer/+ ```+2. Setup environment+ ```bash+ cp .env.example .env+ ```++ Fill the api keys+ ```dotenv+ COMPOSIO_API_KEY=+ OPENAI_API_KEY=+ ```++ Create the virtual env+ ```bash+ make env+ source .venv/bin/activate+ ```+3. Run the agent+ ```bash+ python slack_summariser --user-id "default" --prompt "summarise last 5 messages from #general channel"+ ```++## Using Composio for managed auth and tools++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+- manage `slack` oauth app+- manage user connections+- tools for your agents to interact with `slack`++Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.++## Best practices++**🔒 User Management**:++- Use unique, consistent `user_id` values for each person+- Each user maintains their own slack connection+- User IDs can be email addresses, usernames, or any unique identifier++## Troubleshooting++**Connection Issues**:+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`+- Check that the user has completed `slack` authorization+- Verify the user_id matches exactly between requests++**API Errors**:+- Check the server logs for detailed error messages+- Ensure request payloads match the expected format+- Visit `/docs` endpoint for API schema validationdiff --git a/fern/pages/src/examples/utility_agents/supabase_sql_agent.mdx b/fern/pages/src/examples/utility_agents/supabase_sql_agent.mdxnew file mode 100644index 000000000..e6f2dad07--- /dev/null+++ b/fern/pages/src/examples/utility_agents/supabase_sql_agent.mdx@@ -0,0 +1,256 @@+---+title: Supabase SQL Agent+image: "https://og.composio.dev/api/og?title=Supabase%20SQL%20Agent" # image for socials+description: Build a Supabase SQL Agent with Composio and LlamaIndex.+keywords: supabase, sql, agent, utility agent, llama-index+---++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 guide will walk you through using+the Supabase CLI agent built with `Composio` and `LlamaIndex`.+++## Requirements++* Python 3.9++* [UV](https://docs.astral.sh/uv/getting-started/installation/) (recommended) or pip+* Composio API key+* OpenAI API key+* Understanding of building AI agents (Preferably with LlamaIndex)++## Build an agent to perform Supabase tasks++```python+from composio import Composio+from composio_llamaindex import LlamaIndexProvider++from llama_index.llms.openai import OpenAI+from llama_index.core.agent.workflow import FunctionAgent+from llama_index.core.workflow import Context+++def create_agent(user_id: str, composio_client: Composio[LlamaIndexProvider]):+ """+ Create a function agent that can perform Supabase tasks.+ """++ # Setup client+ llm = OpenAI(model="gpt-4-turbo")++ # Get All the tools+ tools = composio_client.tools.get(+ user_id=user_id,+ tools=[+ "SUPABASE_LIST_ALL_PROJECTS",+ "SUPABASE_BETA_RUN_SQL_QUERY",+ ],+ )++ agent = FunctionAgent(+ tools=tools,+ llm=llm,+ system_prompt=(+ "You are a helpful assistant that can help with supabase queries."+ ),+ )++ # Since this is a continuosly running agent, we need to maintain state across+ # different user messages+ ctx = Context(workflow=agent)+ return agent, ctx+```++This agent can convert your natural language queries to SQL queries and execute+them on supabase for you. For you agent to be able to execute queries, you need+to authenticate the agent for supabase.+++## Authenticating users++To authenticate your users with Composio you need an auth config for the given+app, In this case you need one for supabase. You can create and manage auth configs+from the [dashboard](https://platform.composio.dev/?next_page=/auth-configs?create_auth_config=supabase).+Composio platform provides composio managed authentication for some apps to help+you fast-track your development, `supabase` being one of them. You can use these+default auth configs for development, but for production you should always use+your own oauth app configuration.++Using dashboard is the preferred way of managing authentication configs, but if+you want to do it manually you can follow the guide below++<details>++<summary>Click to expand</summary>++---++To create an authentication config for `supabase` you need `client_id` and `client_secret`+from your from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2).+Once you have the required credentials you can use the following piece of+code to set up authentication for `supabase`.++```python+from composio import Composio+from composio_langchain import LangchainProvider++def create_auth_config(composio_client: Composio[OpenAIProvider]):+ """+ Create a auth config for the supabase toolkit.+ """+ client_id = os.getenv("SUPABASE_CLIENT_ID")+ client_secret = os.getenv("SUPABASE_CLIENT_SECRET")+ if not client_id or not client_secret:+ raise ValueError("SUPABASE_CLIENT_ID and SUPABASE_CLIENT_SECRET must be set")++ return composio_client.auth_configs.create(+ toolkit="supabase",+ options={+ "name": "default_supabase_auth_config",+ "type": "use_custom_auth",+ "auth_scheme": "OAUTH2",+ "credentials": {+ "client_id": client_id,+ "client_secret": client_secret,+ },+ },+ )+```++This will create an authentication config for `supabase` which you can use to+authenticate your users for your app. Ideally you should just create one+authentication object per project, so check for an existing auth config+before you create a new one.++```python+def fetch_auth_config(composio_client: Composio[OpenAIProvider]):+ """+ Fetch the auth config for a given user id.+ """+ auth_configs = composio_client.auth_configs.list()+ for auth_config in auth_configs.items:+ if auth_config.toolkit == "supabase":+ return auth_config++ return None+```+</details>++Once you have authentication management in place, we can start with connecting+your users to your `supabase` app. Let's implement a function to connect the users+to your `supabase` app via composio.++```python+# Function to initiate a connected account+def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):+ """+ Create a connection for a given user id and auth config id.+ """+ # Fetch or create the auth config for the supabase toolkit+ auth_config = fetch_auth_config(composio_client=composio_client)+ if not auth_config:+ auth_config = create_auth_config(composio_client=composio_client)++ # Create a connection for the user+ return composio_client.connected_accounts.initiate(+ user_id=user_id,+ auth_config_id=auth_config.id,+ )+```++Now, when creating tools for your agent always check if the user already has a+connected account before creating a new one.++```python+def check_connected_account_exists(+ composio_client: Composio[LangchainProvider],+ user_id: str,+):+ """+ Check if a connected account exists for a given user id.+ """+ # Fetch all connected accounts for the user+ connected_accounts = composio_client.connected_accounts.list(+ user_ids=[user_id],+ toolkit_slugs=["SUPABASE"],+ )++ # Check if there's an active connected account+ for account in connected_accounts.items:+ if account.status == "ACTIVE":+ return True++ # Ideally you should not have inactive accounts, but if you do, you should delete them+ print(f"[warning] inactive account {account.id} found for user id: {user_id}")+ return False+```+++## Create a chat loop++```python+async def run_loop(user_id: str):+ # Initialize composio client.+ composio_client = Composio(provider=LlamaIndexProvider())++ # Setup connection if required+ if not check_connected_account_exists(+ composio_client=composio_client,+ user_id=user_id,+ ):+ connection_request = create_connection(+ composio_client=composio_client,+ user_id=user_id,+ )+ print(+ f"Authenticate with the following link: {connection_request.redirect_url}"+ )++ # Create agent+ agent, ctx = create_agent(+ user_id=user_id,+ composio_client=composio_client,+ )++ # Run a simple REPL loop+ while True:+ user_input = input("user > ")+ if user_input.lower() == "exit":+ break++ result = await agent.run(user_msg=user_input, ctx=ctx)+ print("agent > ", result)+ print("Exiting...")+```++## Using Composio for managed auth and tools++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 `supabase`+integration without composio you would have to write code to++- manage `supabase` oauth app+- manage user connections+- tools for your agents to interact with `supabase`++Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.++## Best practices++**🔒 User Management**:++- Use unique, consistent `user_id` values for each person+- Each user maintains their own supabase connection+- User IDs can be email addresses, usernames, or any unique identifier++## Troubleshooting++**Connection Issues**:+- Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`+- Check that the user has completed `supabase` authorization+- Verify the user_id matches exactly between requests++**API Errors**:+- Check the server logs for detailed error messages+- Ensure request payloads match the expected format+- Visit `/docs` endpoint for API schema validation