Slack summariser

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
  • 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.

1from composio import Composio
2from composio_langchain import LangchainProvider
3
4from langchain import hub
5from langchain.agents import AgentExecutor, create_openai_functions_agent
6from langchain_openai import ChatOpenAI
7
8
9def create_agent(user_id: str, composio_client: Composio[LangchainProvider]):
10 """
11 Create an agent for a given user id.
12 """
13 # Step 1: Get all the tools
14 tools = composio_client.tools.get(
15 user_id=user_id,
16 toolkits=["SLACK"],
17 )
18
19 # Step 2: Pull relevant agent prompt.
20 prompt = hub.pull("hwchase17/openai-functions-agent")
21
22 # Step 3: Initialize chat model.
23 openai_client = ChatOpenAI(model="gpt-4-turbo")
24
25 # Step 4: Define agent
26 return AgentExecutor(
27 agent=create_openai_functions_agent(
28 openai_client,
29 tools,
30 prompt,
31 ),
32 tools=tools,
33 verbose=True,
34 )

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.

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

Click to expand

To create an authentication config for slack you need client_id and client_secret from your Slack App. Once you have the required credentials you can use the following piece of code to set up authentication for slack.

1from composio import Composio
2from composio_langchain import LangchainProvider
3
4def create_auth_config(composio_client: Composio[OpenAIProvider]):
5 """
6 Create a auth config for the slack toolkit.
7 """
8 client_id = os.getenv("SLACK_CLIENT_ID")
9 client_secret = os.getenv("SLACK_CLIENT_SECRET")
10 if not client_id or not client_secret:
11 raise ValueError("SLACK_CLIENT_ID and SLACK_CLIENT_SECRET must be set")
12
13 return composio_client.auth_configs.create(
14 toolkit="SLACK",
15 options={
16 "name": "default_slack_auth_config",
17 "type": "use_custom_auth",
18 "auth_scheme": "OAUTH2",
19 "credentials": {
20 "client_id": client_id,
21 "client_secret": client_secret,
22 },
23 },
24 )

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.

1def fetch_auth_config(composio_client: Composio[OpenAIProvider]):
2 """
3 Fetch the auth config for a given user id.
4 """
5 auth_configs = composio_client.auth_configs.list()
6 for auth_config in auth_configs.items:
7 if auth_config.toolkit == "SLACK":
8 return auth_config
9
10 return None

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.

1# Function to initiate a connected account
2def create_connection(composio_client: Composio[OpenAIProvider], user_id: str):
3 """
4 Create a connection for a given user id and auth config id.
5 """
6 # Fetch or create the auth config for the slack toolkit
7 auth_config = fetch_auth_config(composio_client=composio_client)
8 if not auth_config:
9 auth_config = create_auth_config(composio_client=composio_client)
10
11 # Create a connection for the user
12 return composio_client.connected_accounts.initiate(
13 user_id=user_id,
14 auth_config_id=auth_config.id,
15 )

Now, when creating tools for your agent always check if the user already has a connected account before creating a new one.

1def check_connected_account_exists(
2 composio_client: Composio[LangchainProvider],
3 user_id: str,
4):
5 """
6 Check if a connected account exists for a given user id.
7 """
8 # Fetch all connected accounts for the user
9 connected_accounts = composio_client.connected_accounts.list(
10 user_ids=[user_id],
11 toolkit_slugs=["SLACK"],
12 )
13
14 # Check if there's an active connected account
15 for account in connected_accounts.items:
16 if account.status == "ACTIVE":
17 return True
18
19 # Ideally you should not have inactive accounts, but if you do, you should delete them
20 print(f"[warning] inactive account {account.id} found for user id: {user_id}")
21 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.

1from composio import after_execute
2from composio.types import ToolExecutionResponse
3
4
5@after_execute(tools=["SLACK_FETCH_CONVERSATION_HISTORY"])
6def clean_conversation_history(
7 tool: str,
8 toolkit: str,
9 response: ToolExecutionResponse,
10) -> ToolExecutionResponse:
11 """
12 Clean the conversation history.
13 """
14 if not response["data"]["ok"]:
15 return response
16
17 try:
18 response["data"]["messages"] = [
19 {"user": message["user"], "text": message["text"]}
20 for message in response["data"]["messages"]
21 if message["type"] == "message"
22 ]
23 except KeyError:
24 pass
25
26 return response

To register modifiers, include them in the composio.tools.get call.

1tools = composio_client.tools.get(
2 user_id=user_id,
3 toolkits=[SLACK_TOOLKIT],
4 modifiers=[clean_conversation_history],
5)

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.

1def run_agent(user_id: str, prompt: str):
2 composio_client = Composio(provider=LangchainProvider())
3 if not check_connected_account_exists(composio_client, user_id):
4 connection_request = create_connection(composio_client, user_id)
5 print(
6 f"Authenticate with the following link: {connection_request.redirect_url}"
7 )
8 connection_request.wait_for_connection()
9
10 agent = create_agent(user_id, composio_client)
11 agent.invoke({"input": prompt})

To test the above function as CLI, follow the steps below

  1. Clone the repository

    $git clone git@github.com:composiohq/slack-summarizer
    >cd slack-summarizer/
  2. Setup environment

    $cp .env.example .env

    Fill the api keys

    1COMPOSIO_API_KEY=
    2OPENAI_API_KEY=

    Create the virtual env

    $make env
    >source .venv/bin/activate
  3. Run the agent

    $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 validation