Skip to content

Commit

Permalink
feat: scheduling agent docs added
Browse files Browse the repository at this point in the history
  • Loading branch information
Prat011 committed Dec 18, 2024
1 parent bb3e468 commit 79896ca
Showing 1 changed file with 189 additions and 93 deletions.
282 changes: 189 additions & 93 deletions docs/sdrkit/ai-scheduling-agent.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -21,109 +21,204 @@ pip install composio-llamaindex python-dotenv

<Step title="Connecting to tools and models">
```bash connect to required tools
composio add peopledatalabs
composio add googlesheets
composio add gmail
composio add googlecalendar

export OPENAI_API_KEY="<your-openai-api-key>"
```
</Step>

<Step title="Importing the required libraries">
```python import required libraries
from composio_llamaindex import ComposioToolSet, App, Action
import os
import time
import dotenv
import re
from datetime import datetime
from composio_llamaindex import App, ComposioToolSet, Action
from llama_index.core.agent import FunctionCallingAgentWorker
from llama_index.core.llms import ChatMessage
from llama_index.llms.openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
from composio.client.collections import TriggerEventData

dotenv.load_dotenv()
```
</Step>

<Step title="Initializing the Tools and the LLM">
```python initialize toolset and llm
toolset = ComposioToolSet(api_key="")
tools = toolset.get_tools(apps=[App.PEOPLEDATALABS, App.GOOGLESHEETS])
schedule_tool = composio_toolset.get_tools(
actions=[
Action.GOOGLECALENDAR_FIND_FREE_SLOTS,
Action.GOOGLECALENDAR_CREATE_EVENT,
Action.GMAIL_CREATE_EMAIL_DRAFT
]
)

llm = OpenAI(model="gpt-4o")

date_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
timezone = datetime.now().astimezone().tzinfo
```
</Step>

<Step title="Setting up Function Calling Worker">
```python setup function calling worker
spreadsheetid = '14T4e0j1XsWjriQYeFMgkM2ihyvLAplPqB9q8hytytcw'
# Set up prefix messages for the agent
prefix_messages = [
<Step title="Create callback function">
```python create callback function
listener = composio_toolset.create_trigger_listener()
@listener.callback(filters={"trigger_name": "GMAIL_NEW_GMAIL_MESSAGE"})
def callback_new_message(event: TriggerEventData) -> None:
# Using the information from Trigger, execute the agent
print("here in the function")
payload = event.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
print(sender_mail)

prefix_messages = [
ChatMessage(
role="system",
content=(
f"""
You are a lead research agent. Based on user input, find 10 relevant leads using people data labs.
After finding the leads, create a Google Sheet with the details for the lead description, and spreadsheet ID: ${spreadsheetid}.
Print the list of people and their details and the link to the google sheet."""
You are an AI assistant specialized in creating calendar events based on email information.
Current DateTime: {date_time} and timezone {timezone}. All the conversations happen in IST timezone.
Pass empty config ("config": {{}}) for the function calls, if you get an error about not passing config.
Analyze email, and create event on calendar depending on the email content.
You should also draft an email in response to the sender of the previous email
"""

),
)
]

agent = FunctionCallingAgentWorker(
tools=tools,
llm=llm,
prefix_messages=prefix_messages,
max_function_calls=10,
allow_parallel_tool_calls=False,
verbose=True,
).as_agent()
)
]
agent = FunctionCallingAgentWorker(
tools=schedule_tool, # Tools available for the agent to use
llm=llm, # Language model for processing requests
prefix_messages=prefix_messages, # Initial system messages for context
max_function_calls=10, # Maximum number of function calls allowed
allow_parallel_tool_calls=False, # Disallow parallel tool calls
verbose=True, # Enable verbose output
).as_agent()
analyze_email_task = f"""
1. Analyze the email content and decide if an event should be created.
a. The email was received from {sender_mail}
b. The content of the email is: {message}
c. The thread id is: {thread_id}.
2. If you decide to create an event, try to find a free slot
using Google Calendar Find Free Slots action.
3. Once you find a free slot, use Google Calendar Create Event
action to create the event at a free slot and send the invite to {sender_mail}.
If an event was created, draft a confirmation email for the created event.
The receiver of the mail is: {sender_mail}, the subject should be meeting scheduled and body
should describe what the meeting is about
"""
response = agent.chat(analyze_email_task)
print(response)
```
</Step>

<Step title="Executing the Agent">
<Step title="Activating the Listener">
```python run the agent
lead_description = 'Senior frontend developers in San Francisco'
user_input = f"Create a lead list based on the description: {lead_description}"
response = agent.chat(user_input)
print("Listener started!")
print("Waiting for email")
listener.listen()
```
</Step>

<Step title='Final Code'>
```python final code
from composio_llamaindex import ComposioToolSet, App, Action
# Import necessary libraries
import os
import time
import dotenv
import re
from datetime import datetime
from composio_llamaindex import App, ComposioToolSet, Action
from llama_index.core.agent import FunctionCallingAgentWorker
from llama_index.core.llms import ChatMessage
from llama_index.llms.openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
toolset = ComposioToolSet(api_key="")
tools = toolset.get_tools(apps=[App.PEOPLEDATALABS, App.GOOGLESHEETS])
from composio.client.collections import TriggerEventData

dotenv.load_dotenv()

composio_toolset = ComposioToolSet()

schedule_tool = composio_toolset.get_tools(
actions=[
Action.GOOGLECALENDAR_FIND_FREE_SLOTS,
Action.GOOGLECALENDAR_CREATE_EVENT,
Action.GMAIL_CREATE_EMAIL_DRAFT
]
)

llm = OpenAI(model="gpt-4o")

spreadsheetid = '14T4e0j1XsWjriQYeFMgkM2ihyvLAplPqB9q8hytytcw'
# Set up prefix messages for the agent
prefix_messages = [
date_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
timezone = datetime.now().astimezone().tzinfo

listener = composio_toolset.create_trigger_listener()
@listener.callback(filters={"trigger_name": "GMAIL_NEW_GMAIL_MESSAGE"})
def callback_new_message(event: TriggerEventData) -> None:
# Using the information from Trigger, execute the agent
print("here in the function")
payload = event.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
print(sender_mail)

prefix_messages = [
ChatMessage(
role="system",
content=(
f"""
You are a lead research agent. Based on user input, find 10 relevant leads using people data labs.
After finding the leads, create a Google Sheet with the details for the lead description, and spreadsheet ID: ${spreadsheetid}.
Print the list of people and their details and the link to the google sheet."""
You are an AI assistant specialized in creating calendar events based on email information.
Current DateTime: {date_time} and timezone {timezone}. All the conversations happen in IST timezone.
Pass empty config ("config": {{}}) for the function calls, if you get an error about not passing config.
Analyze email, and create event on calendar depending on the email content.
You should also draft an email in response to the sender of the previous email
"""

),
)
]

agent = FunctionCallingAgentWorker(
tools=tools,
llm=llm,
prefix_messages=prefix_messages,
max_function_calls=10,
allow_parallel_tool_calls=False,
verbose=True,
).as_agent()

lead_description = 'Senior frontend developers in San Francisco'
user_input = f"Create a lead list based on the description: {lead_description}"
response = agent.chat(user_input)
)
]
agent = FunctionCallingAgentWorker(
tools=schedule_tool,
llm=llm,
prefix_messages=prefix_messages,
max_function_calls=10,
allow_parallel_tool_calls=False,
verbose=True,
).as_agent()
analyze_email_task = f"""
1. Analyze the email content and decide if an event should be created.
a. The email was received from {sender_mail}
b. The content of the email is: {message}
c. The thread id is: {thread_id}.
2. If you decide to create an event, try to find a free slot
using Google Calendar Find Free Slots action.
3. Once you find a free slot, use Google Calendar Create Event
action to create the event at a free slot and send the invite to {sender_mail}.
If an event was created, draft a confirmation email for the created event.
The receiver of the mail is: {sender_mail}, the subject should be meeting scheduled and body
should describe what the meeting is about
"""
response = agent.chat(analyze_email_task)
print(response)

print("Listener started!")
print("Waiting for email")
listener.listen()
```
</Step>
</Steps>
Expand Down Expand Up @@ -204,50 +299,51 @@ await toolset.client.triggers.subscribe(async (data) => {

<Step title='Final Code'>
```javascript final code
import { ChatOpenAI } from "@langchain/openai";
import { createOpenAIFunctionsAgent, AgentExecutor } from "langchain/agents";
import { pull } from "langchain/hub";
import dotenv from 'dotenv';
import { LangchainToolSet } from "composio-core";

import { openai } from "@ai-sdk/openai";
import { VercelAIToolSet, Composio, OpenAIToolSet } from "composio-core";
import dotenv from "dotenv";
import { generateText } from "ai";
dotenv.config();

const llm = new ChatOpenAI({
model: "gpt-4-turbo",
apiKey: process.env.OPENAI_API_KEY,
});

const toolset = new LangchainToolSet({
apiKey: process.env.COMPOSIO_API_KEY,
});

const tools = await toolset.getTools({
apps: ["tavily"]
// Setup toolset
const toolset = new VercelAIToolSet({
apiKey: process.env.COMPOSIO_API_KEY,
});

const prompt = await pull("hwchase17/openai-functions-agent");

const additional = `You are a market research agent that finds niche ideas that can be built and marketed.
Your users are primarily indie hackers who want to build something new and are looking for ideas. The input will
be a domain or a category and your job is to research extensively and find ideas that can be marketed.
Also write the content to market a tool built with this idea. It should be very very specific and not too long.`;

const agent = await createOpenAIFunctionsAgent({
llm,
tools,
prompt,
});
// Subscribe to triggers and perform actions
await toolset.client.triggers.subscribe(async (data) => {
console.log("trigger received", data);
const payload = data.payload;
const message = payload.messageText;
const sender = payload.sender;
const threadId = payload.threadId;
const entity_id = 'default';

// Setup entity and ensure connection
const entity = await toolset.client.getEntity(entity_id);

// Retrieve tools for the specified app
const tools = await toolset.getTools({ apps: ["googlecalendar","gmail"] }, entity.id);

// Generate text using the model and tools
const output = await generateText({
model: openai("gpt-4o"),
streamText: false,
tools: tools,
prompt: `
This is a message from ${sender}: ${message}
Threadid:${threadId}
This is the date: ${new Date().toISOString()}
You are a scheduling agent, Read the email received and understand the content.
After understanding the content, create a calendar event with the details.
Then reply to the email with the calendar event details. If thread id is not provided, create a draft email.
`,
maxToolRoundtrips: 5,
});

console.log("🎉Output from agent: ", output.text);

const agentExecutor = new AgentExecutor({
agent,
tools,
verbose: true,
});
const domain = 'AI SaaS'
const result = await agentExecutor.invoke({
input: additional + 'This is the domain:' + domain
});
console.log('🎉Output from agent: ', result.output);

```
</Step>
Expand Down

0 comments on commit 79896ca

Please sign in to comment.