Skip to main content

AI email agent using Composio

Open In Colab Open on GitHub

This notebook demonstrates how to create an AI Email agent using Composio’s Gmail tool with autogen to create an agent that will automatically respond to emails based on provided instructions.

Composio allows an AI agent or LLM to easily connect to apps like Gmail, Slack, Trello etc. The key features of Composio are:

  • Repository of Tools: Composio allows LLMs and agents to integrate with 100+ apps (Github, Salesforce, File Manager, Code Execution & More) to perform actions & subscribe to triggers(events).

  • Frameworks & LLM Agnostic: Composio provides out of box support for 10+ popular agentic frameworks and works with all the LLM providers using function calling.

  • Managed Auth: Composio helps manage authentication for all users/agents from a single dashboard.

Visit Composio Docs to learn more.

The notebook demonstrates how to create a Gmail integration with Composio, set up a trigger for new emails, initialize agents with tools and finally we’ll see the agent in action.

Requirements

Some extra dependencies are needed for this notebook, which can be installed via pip:

pip install autogen-agentchat~=0.2 composio-autogen

For more information, please refer to the installation guide.

Composio Setup

To get started with using Composio’s Gmail tool, we need to create an integration between Composio and Gmail. This can be done using a simple command -

!composio add gmail

To set up a trigger(basically a listener) for new emails -

!composio triggers enable gmail_new_gmail_message

This enables the gmail_new_gmail_message trigger, which is fired when a new email is received in the connected account.

import os

from composio_autogen import Action, ComposioToolSet

from autogen.agentchat import AssistantAgent, UserProxyAgent

os.environ["OPENAI_API_KEY"] = "YOUR_API_KEY"

Initialize agents

llm_config = {"config_list": [{"model": "gpt-4o", "api_key": os.environ.get("OPENAI_API_KEY")}]}

# Prompt for email assistant
email_assistant_prompt = """
You are an AI email assistant specialized in drafting replies to emails.
You create appropriate and professional replies to emails based on the content of the email.
After executing the GMAIL_REPLY_TO_THREAD action and sending the email to the user, respond with TERMINATE.
"""

# Initialize AssistantAgent
chatbot = AssistantAgent(
"chatbot",
system_message=email_assistant_prompt,
llm_config=llm_config,
)

# Initialize UserProxyAgent
user_proxy = UserProxyAgent(
"user_proxy",
is_termination_msg=lambda x: x.get("content", "") and "TERMINATE" in x.get("content", ""),
human_input_mode="NEVER",
code_execution_config=False,
llm_config=llm_config,
)

Initialize Composio’s Toolset

Now, we initialize Composio’s toolset and get the tools and actions we need for the agent. Then, we register the tools with the UserProxyAgent.

The agent can then call the tools using function calling.

# Initialize Composio Toolset
composio_toolset = ComposioToolSet()

# Get the required tools and register them with the agents
email_tools = composio_toolset.register_tools(
caller=user_proxy,
executor=chatbot,
actions=[
Action.GMAIL_REPLY_TO_THREAD,
],
)

Here, we get the GMAIL_REPLY_TO_THREAD action, which is just a function that can be used to reply to an email. We’ll be using this action to reply to emails automatically when they arrive.

Create trigger listener

Now, we create a listener for the trigger that we created above. This listener will listen for new emails and when a new email arrives, it’ll provide data associated with the email like the sender email, email content etc. This data will be used by the attached callback function to invoke the agent and to send a reply to the email.

The @listener.callback decorator registers the function it decorates as a callback for a specific event trigger, in this case, when a new Gmail message is received (GMAIL_NEW_GMAIL_MESSAGE). It listens for the specified trigger and invokes the decorated function (callback_new_message) when the event occurs.

After extracting the relevant data from the trigger payload, we start a conversation between user_proxy and chatbot to send a reply to the received email.

# Create a trigger listener
listener = composio_toolset.create_trigger_listener()


@listener.callback(filters={"trigger_name": "GMAIL_NEW_GMAIL_MESSAGE"})
def callback_new_message(event) -> None:
# Get the payload and extract relevant information
payload = event.payload # Email payload
thread_id = payload.get("threadId")
message = payload.get("messageText")
sender_mail = payload.get("sender")
if sender_mail is None:
print("No sender email found")
return

analyze_email_task = f"""
Analyze the email content and create an appropriate reply.
a. The email was received from {sender_mail}
b. The content of the email is: {message}
c. The thread id is: {thread_id}.
"""
# Initiate the conversation
res = user_proxy.initiate_chat(chatbot, message=analyze_email_task)
print(res.summary)


print("Subscribed to triggers!")
# Start listening
listener.listen()
INFO:composio.utils.shared:Creating trigger subscription
INFO:composio.utils.shared:Received trigger event with trigger ID: ea36d63f-5cc9-4581-9a19-b647e7468697 and trigger name: GMAIL_NEW_GMAIL_MESSAGE
INFO:composio.utils.shared:Executing `GMAIL_REPLY_TO_THREAD` with params={'thread_id': '1922811a78db4...', 'message_body': "Hi John,\n\nI'm doing well, thank you! How about you?\n\nBest,\n[Your Name]", 'recipient_email': 'example_email@gmail.com'} and metadata={} connected_account_i...
INFO:composio.utils.shared:Got response={'successfull': True, 'data': {'response_data': {'id': '1922811c1b3ed...', 'threadId': '1922811a78db4...', 'labelIds': ['SENT']}}, 'error': None} from action=<composio.client.enums._action.Action object at 0x7d50554c4310> with params={'thread_...
Subscribed to triggers!
user_proxy (to chatbot):


Analyze the email content and create an appropriate reply.
a. The email was received from John Doe <example_email@gmail.com>
b. The content of the email is: hey, how are you?

c. The thread id is: 1922811a78db4....


--------------------------------------------------------------------------------
chatbot (to user_proxy):

GMAIL_REPLY_TO_THREAD thread_id: 1922811a78db4... message:
Hi John,

I'm doing well, thank you! How about you?

Best,
[Your Name]

--------------------------------------------------------------------------------
user_proxy (to chatbot):

***** Suggested tool call (call_qGQzJ6XgyO8LKSSFnwkQhSCz): GMAIL_REPLY_TO_THREAD_8c4b19f45c *****
Arguments:
{"thread_id":"1922811a78db4...","message_body":"Hi John,\n\nI'm doing well, thank you! How about you?\n\nBest,\n[Your Name]","recipient_email":"example_email@gmail.com"}
*************************************************************************************************

--------------------------------------------------------------------------------

>>>>>>>> EXECUTING FUNCTION GMAIL_REPLY_TO_THREAD_8c4b19f45c...
chatbot (to user_proxy):

chatbot (to user_proxy):

***** Response from calling tool (call_qGQzJ6XgyO8LKSSFnwkQhSCz) *****
{"successfull": true, "data": {"response_data": {"id": "1922811c1b3ed...", "threadId": "1922811a78db4...", "labelIds": ["SENT"]}}, "error": null}
**********************************************************************

--------------------------------------------------------------------------------
user_proxy (to chatbot):

I've replied to the email with the following message:

Hi John,

I'm doing well, thank you! How about you?

Best,
[Your Name]

Is there anything else you need?

--------------------------------------------------------------------------------
chatbot (to user_proxy):

TERMINATE

--------------------------------------------------------------------------------