Skip to content

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

docs: rewrite supabase SQL agent cookbook to use sessions and include regions

Sushmitha Mallesh3f456d5275d9
diff --git a/docs/content/cookbooks/slack-summariser.mdx b/docs/content/cookbooks/slack-summariser.mdx
index fa250dc4d..7b5ba5560 100644
--- a/docs/content/cookbooks/slack-summariser.mdx
+++ b/docs/content/cookbooks/slack-summariser.mdx
@@ -1,6 +1,6 @@
---
title: Slack Summarizer
-description: Build a Python script that connects to Slack and summarizes channel messages using Composio and the OpenAI Agents SDK
+description: Build an agent that summarizes Slack channel messages using Composio
---
[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/slack-summariser)
diff --git a/docs/content/cookbooks/supabase-sql-agent.mdx b/docs/content/cookbooks/supabase-sql-agent.mdx
index 1da4ad390..36ea96a06 100644
--- a/docs/content/cookbooks/supabase-sql-agent.mdx
+++ b/docs/content/cookbooks/supabase-sql-agent.mdx
@@ -3,252 +3,80 @@ title: Supabase SQL Agent
description: Build an agent that executes SQL queries on Supabase using natural language
---
-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`.
+[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/supabase-sql-agent)
+This cookbook builds a CLI agent that connects to your Supabase account and lets you query your databases using natural language. The agent translates plain English into SQL, runs it against your project, and explains the results. We'll use **scoped sessions** to limit the agent to Supabase tools only.
-## Requirements
+## Prerequisites
* Python 3.10+
-* [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-5")
-
- # 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
+* [UV](https://docs.astral.sh/uv/getting-started/installation/)
+* [Composio API key](https://platform.composio.dev/settings)
+* [OpenAI API key](https://platform.openai.com/api-keys)
+
+## Project setup
+
+Create a new project and install dependencies:
+
+```bash
+mkdir composio-supabase-agent && cd composio-supabase-agent
+uv init && uv add composio composio-openai-agents openai-agents
```
-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.
+Add your API keys to a `.env` file:
+```bash title=".env"
+COMPOSIO_API_KEY=your_composio_api_key
+OPENAI_API_KEY=your_openai_api_key
+```
-## Authenticating users
+## Setting up the client
-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.
+`Composio` takes an `OpenAIAgentsProvider` so that tools come back in the format the OpenAI Agents SDK expects.
-Using dashboard is the preferred way of managing authentication configs, but if
-you want to do it manually you can follow the guide below
+<include>../../examples/supabase-sql-agent/main.py#setup</include>
-<details>
+## Connecting to Supabase
-<summary>Click to expand</summary>
+Before running queries, the user needs to connect their Supabase account. The `connect` function creates a scoped session with `toolkits=["supabase"]` and checks the connection status via `session.toolkits()`. If Supabase is not connected, `session.authorize("supabase")` starts the OAuth flow and returns a URL for the user to visit. `wait_for_connection()` blocks until they complete it.
----
+<include>../../examples/supabase-sql-agent/main.py#connect</include>
-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,
- },
- },
- )
-```
+## Querying with natural language
-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,
- )
-```
+With Supabase connected, the `query` function creates a session scoped to `toolkits=["supabase"]` and grabs the tools. We hand them to an agent and run an interactive loop where the user types questions and the agent translates them into SQL.
-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
-```
+<include>../../examples/supabase-sql-agent/main.py#query</include>
+## Complete script
-## 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...")
-```
+Here is everything together:
-## Using Composio for managed auth and tools
+<include>../../examples/supabase-sql-agent/main.py</include>
-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
+## Running the script
-- manage `supabase` oauth app
-- manage user connections
-- tools for your agents to interact with `supabase`
+First, connect your Supabase account:
-Using composio simplifies all of the above to a few lines of code as we've seen the cookbook.
+```bash
+uv run --env-file .env python main.py connect default
+```
-## Best practices
+If Supabase is not connected yet, you'll get an OAuth URL. Open it in your browser and authorize the app.
-**🔒 User Management**:
+Then start the interactive query agent:
-- 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
+```bash
+uv run --env-file .env python main.py query default
+```
-## Troubleshooting
+Try asking things like:
-**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
+```
+you > List all my Supabase projects
+you > Show me all tables in my default project
+you > How many users signed up this week?
+you > What are the top 10 most recent orders?
+```
-**API Errors**:
-- Check the server logs for detailed error messages
-- Ensure request payloads match the expected format
-- Visit `/docs` endpoint for API schema validation
+Type `exit` to quit.
diff --git a/docs/examples/supabase-sql-agent/main.py b/docs/examples/supabase-sql-agent/main.py
new file mode 100644
index 000000000..7d05b86ce
--- /dev/null
+++ b/docs/examples/supabase-sql-agent/main.py
@@ -0,0 +1,84 @@
+import sys
+
+# region setup
+from agents import Agent, Runner
+from composio import Composio
+from composio_openai_agents import OpenAIAgentsProvider
+
+composio = Composio(provider=OpenAIAgentsProvider())
+# endregion setup
+
+
+# region connect
+def connect(user_id: str):
+ """Check if Supabase is connected. If not, start OAuth and wait."""
+ session = composio.create(user_id=user_id, toolkits=["supabase"])
+ toolkits = session.toolkits()
+
+ for t in toolkits.items:
+ if t.slug == "supabase" and t.connection and t.connection.is_active:
+ print("Supabase is already connected.")
+ return
+
+ connection_request = session.authorize("supabase")
+ print(f"Open this URL to connect Supabase:\n{connection_request.redirect_url}")
+ connection_request.wait_for_connection()
+ print("Connected.")
+# endregion connect
+
+
+# region query
+def query(user_id: str):
+ """Interactive loop: ask questions in natural language, get SQL results."""
+ session = composio.create(user_id=user_id, toolkits=["supabase"])
+ tools = session.tools()
+
+ agent = Agent(
+ name="Supabase SQL Agent",
+ instructions=(
+ "You are a Supabase SQL assistant. You help users query their Supabase "
+ "databases using natural language. First list the user's projects to find "
+ "the right database, then translate their questions into SQL queries and "
+ "run them. Always explain the results clearly."
+ ),
+ tools=tools,
+ )
+
+ print("Supabase SQL Agent (type 'exit' to quit)")
+ print("-" * 45)
+
+ last_response_id = None
+ while True:
+ user_input = input("you > ")
+ if user_input.strip().lower() == "exit":
+ break
+
+ result = Runner.run_sync(
+ starting_agent=agent,
+ input=user_input,
+ previous_response_id=last_response_id,
+ )
+ last_response_id = result.last_response_id
+ print(f"agent > {result.final_output}\n")
+# endregion query
+
+
+if __name__ == "__main__":
+ if len(sys.argv) < 2:
+ print("Usage:")
+ print(" python main.py connect <user_id>")
+ print(" python main.py query <user_id>")
+ sys.exit(1)
+
+ command = sys.argv[1]
+
+ if command == "connect":
+ user_id = sys.argv[2] if len(sys.argv) > 2 else "default"
+ connect(user_id)
+ elif command == "query":
+ user_id = sys.argv[2] if len(sys.argv) > 2 else "default"
+ query(user_id)
+ else:
+ print(f"Unknown command: {command}")
+ print("Use 'connect' or 'query'.")
+ sys.exit(1)