-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
202 lines (160 loc) · 6.26 KB
/
main.py
File metadata and controls
202 lines (160 loc) · 6.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import os
from langchain_core.tools import tool
from langchain.agents import create_agent
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.agents.middleware import HumanInTheLoopMiddleware
from langgraph.checkpoint.memory import InMemorySaver
os.environ["GOOGLE_API_KEY"] = "...your google api key..."
model = ChatGoogleGenerativeAI(model="gemini-2.5-flash-lite")
@tool
def create_calendar_event(
title: str,
start_time: str, # ISO format: "2024-01-15T14:00:00"
end_time: str, # ISO format: "2024-01-15T15:00:00"
attendees: list[str], # email addresses
location: str = ""
) -> str:
"""Create a calendar event. Requires exact ISO datetime format."""
# Stub: In practice, this would call Google Calendar API, Outlook API, etc.
return f"Event created: {title} from {start_time} to {end_time} with {len(attendees)} attendees"
@tool
def send_email(
to: list[str], # email addresses
subject: str,
body: str,
cc: list[str] = []
) -> str:
"""Send an email via email API. Requires properly formatted addresses."""
# Stub: In practice, this would call SendGrid, Gmail API, etc.
return f"Email sent to {', '.join(to)} - Subject: {subject}"
@tool
def get_available_time_slots(
attendees: list[str],
date: str, # ISO format: "2024-01-15"
duration_minutes: int
) -> list[str]:
"""Check calendar availability for given attendees on a specific date."""
# Stub: In practice, this would query calendar APIs
return ["09:00", "14:00", "16:00"]
CALENDAR_AGENT_PROMPT = (
"You are a calendar scheduling assistant. "
"Parse natural language scheduling requests (e.g., 'next Tuesday at 2pm') "
"into proper ISO datetime formats. "
"Use get_available_time_slots to check availability when needed. "
"Use create_calendar_event to schedule events. "
"Always confirm what was scheduled in your final response."
)
calendar_agent = create_agent(
model,
tools=[create_calendar_event, get_available_time_slots],
system_prompt=CALENDAR_AGENT_PROMPT,
middleware=[
HumanInTheLoopMiddleware(
interrupt_on={"create_calendar_event": True},
description_prefix="Calendar event pending approval",
),
],
)
# query = "Schedule a team meeting next Tuesday at 2pm for 1 hour"
# for step in calendar_agent.stream(
# {"messages": [{"role": "user", "content": query}]}
# ):
# for update in step.values():
# for message in update.get("messages", []):
# message.pretty_print()
EMAIL_AGENT_PROMPT = (
"You are an email assistant. "
"Compose professional emails based on natural language requests. "
"Extract recipient information and craft appropriate subject lines and body text. "
"Use send_email to send the message. "
"Always confirm what was sent in your final response."
)
email_agent = create_agent(
model,
tools=[send_email],
system_prompt=EMAIL_AGENT_PROMPT,
middleware=[
HumanInTheLoopMiddleware(
interrupt_on={"send_email": True},
description_prefix="Outbound email pending approval",
),
],
)
# query = "Send the design team a reminder about reviewing the new mockups"
# for step in email_agent.stream(
# {"messages": [{"role": "user", "content": query}]}
# ):
# for update in step.values():
# for message in update.get("messages", []):
# message.pretty_print()
@tool
def schedule_event(request: str) -> str:
"""Schedule calendar events using natural language.
Use this when the user wants to create, modify, or check calendar appointments.
Handles date/time parsing, availability checking, and event creation.
Input: Natural language scheduling request (e.g., 'meeting with design team
next Tuesday at 2pm')
"""
result = calendar_agent.invoke({
"messages": [{"role": "user", "content": request}]
})
return result["messages"][-1].text
@tool
def manage_email(request: str) -> str:
"""Send emails using natural language.
Use this when the user wants to send notifications, reminders, or any email
communication. Handles recipient extraction, subject generation, and email
composition.
Input: Natural language email request (e.g., 'send them a reminder about
the meeting')
"""
result = email_agent.invoke({
"messages": [{"role": "user", "content": request}]
})
return result["messages"][-1].text
SUPERVISOR_PROMPT = (
"You are a helpful personal assistant. "
"You can schedule calendar events and send emails. "
"Break down user requests into appropriate tool calls and coordinate the results. "
"When a request involves multiple actions, use multiple tools in sequence."
)
supervisor_agent = create_agent(
model,
tools=[schedule_event, manage_email],
system_prompt=SUPERVISOR_PROMPT,
checkpointer=InMemorySaver(),
)
# query = "Schedule a team standup for tomorrow at 9am"
# query = (
# "Schedule a meeting with the design team next Tuesday at 2pm for 1 hour, "
# "and send them an email reminder about reviewing the new mockups."
# )
# for step in supervisor_agent.stream(
# {"messages": [{"role": "user", "content": query}]}
# ):
# for update in step.values():
# for message in update.get("messages", []):
# message.pretty_print()
if __name__ == "__main__":
query = (
"Schedule a meeting with the design team next Tuesday at 2pm for 1 hour, "
"and send them an email reminder about reviewing the new mockups."
)
config = {"configurable": {"thread_id": "6"}}
interrupts = []
for step in supervisor_agent.stream(
{"messages": [{"role": "user", "content": query}]},
config,
):
for update in step.values():
if isinstance(update, dict):
for message in update.get("messages", []):
message.pretty_print()
else:
interrupt_ = update[0]
interrupts.append(interrupt_)
print(f"\nINTERRUPTED: {interrupt_.id}")
for interrupt_ in interrupts:
for request in interrupt_.value["action_requests"]:
print(f"INTERRUPTED: {interrupt_.id}")
print(f"{request['description']}\n")