forked from livekit/agents
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
278 lines (225 loc) Β· 9.23 KB
/
Copy pathagent.py
File metadata and controls
278 lines (225 loc) Β· 9.23 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
from __future__ import annotations
import datetime
import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Literal
from zoneinfo import ZoneInfo
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from calendar_api import AvailableSlot, CalComCalendar, Calendar, FakeCalendar, SlotUnavailableError
from dotenv import load_dotenv
from ui_view import UIView
from livekit.agents import (
Agent,
AgentServer,
AgentSession,
JobContext,
RunContext,
ToolError,
beta,
cli,
function_tool,
get_job_context,
inference,
)
from livekit.agents.evals import (
JudgeGroup,
accuracy_judge,
coherence_judge,
conciseness_judge,
handoff_judge,
relevancy_judge,
safety_judge,
task_completion_judge,
tool_use_judge,
)
from livekit.plugins import silero
from livekit.plugins.turn_detector.multilingual import MultilingualModel
load_dotenv()
@dataclass
class Userdata:
cal: Calendar
booked_times: list[str] = field(default_factory=list)
slot_unavailable_count: int = 0
# Optional UI for the LiveKit Playground. ``None`` when the agent
# is running anywhere else β the tool handlers no-op on it and
# the rest of the code stays oblivious to the playground.
ui: UIView | None = None
logger = logging.getLogger("front-desk")
class FrontDeskAgent(Agent):
def __init__(self, *, timezone: str) -> None:
self.tz = ZoneInfo(timezone)
today = datetime.datetime.now(self.tz).strftime("%A, %B %d, %Y")
super().__init__(
instructions=(
f"You are Front-Desk, a helpful and efficient voice assistant. "
f"Today is {today}. Your main goal is to schedule an appointment for the user. "
"This is a voice conversation β speak naturally, clearly, and concisely. "
"When the user says hello or greets you, donβt just respond with a greeting β use it as an opportunity to move things forward. "
"For example, follow up with a helpful question like: 'Would you like to book a time?' "
"When asked for availability, call list_available_slots and offer a few clear, simple options. "
"Say things like 'Monday at 2 PM' β avoid timezones, timestamps, and avoid saying 'AM' or 'PM'. "
"Use natural phrases like 'in the morning' or 'in the evening', and donβt mention the year unless itβs different from the current one. "
"Offer a few options at a time, pause for a response, then guide the user to confirm. "
"If the time is no longer available, let them know gently and offer the next options. "
"Always keep the conversation flowing β be proactive, human, and focused on helping the user schedule with ease."
)
)
self._slots_map: dict[str, AvailableSlot] = {}
async def on_enter(self) -> None:
await self.session.say("Hello, I can help you schedule an appointment!")
@function_tool
async def schedule_appointment(
self,
ctx: RunContext[Userdata],
slot_id: str,
) -> str | None:
"""
Schedule an appointment at the given slot.
Args:
slot_id: The identifier for the selected time slot (as shown in the list of available slots).
"""
if not (slot := self._slots_map.get(slot_id)):
raise ToolError(f"error: slot {slot_id} was not found")
email_result = await beta.workflows.GetEmailTask(chat_ctx=self.chat_ctx)
if ctx.speech_handle.interrupted:
return
ctx.disallow_interruptions()
try:
await ctx.userdata.cal.schedule_appointment(
start_time=slot.start_time, attendee_email=email_result.email_address
)
except SlotUnavailableError:
ctx.userdata.slot_unavailable_count += 1
try:
get_job_context().tagger.add(
"slot:unavailable",
metadata={"count": ctx.userdata.slot_unavailable_count},
)
except RuntimeError:
pass
# exceptions other than ToolError are treated as "An internal error occurred" for the LLM.
# Tell the LLM this slot isn't available anymore
raise ToolError("This slot isn't available anymore") from None
local = slot.start_time.astimezone(self.tz)
ctx.userdata.booked_times.append(local.isoformat())
try:
get_job_context().tagger.add(
"appointment:booked",
metadata={"time": ctx.userdata.booked_times},
)
except RuntimeError:
pass
if ctx.userdata.ui is not None:
ctx.userdata.ui.appointment_booked(slot, self.tz)
return f"The appointment was successfully scheduled for {local.strftime('%A, %B %d, %Y at %H:%M %Z')}."
@function_tool
async def list_available_slots(
self, ctx: RunContext[Userdata], range: Literal["+2week", "+1month", "+3month", "default"]
) -> str:
"""
Return a plain-text list of available slots, one per line.
<slot_id> β <Weekday>, <Month> <Day>, <Year> at <HH:MM> <TZ> (<relative time>)
You must infer the appropriate ``range`` implicitly from the
conversational context and **must not** prompt the user to pick a value
explicitly.
Args:
range: Determines how far ahead to search for free time slots.
"""
now = datetime.datetime.now(self.tz)
lines: list[str] = []
if range == "+2week" or range == "default":
range_days = 14
elif range == "+1month":
range_days = 30
elif range == "+3month":
range_days = 90
slots = await ctx.userdata.cal.list_available_slots(
start_time=now, end_time=now + datetime.timedelta(days=range_days)
)
for slot in slots:
local = slot.start_time.astimezone(self.tz)
delta = local - now
days = delta.days
seconds = delta.seconds
if local.date() == now.date():
if seconds < 3600:
rel = "in less than an hour"
else:
rel = "later today"
elif local.date() == (now.date() + datetime.timedelta(days=1)):
rel = "tomorrow"
elif days < 7:
rel = f"in {days} days"
elif days < 14:
rel = "in 1 week"
else:
rel = f"in {days // 7} weeks"
lines.append(
f"{slot.unique_hash} β {local.strftime('%A, %B %d, %Y')} at "
f"{local:%H:%M} {local.tzname()} ({rel})"
)
self._slots_map[slot.unique_hash] = slot
if ctx.userdata.ui is not None:
ctx.userdata.ui.slots_listed(slots, now, self.tz, range_days)
return "\n".join(lines) or "No slots available at the moment."
server = AgentServer()
async def on_session_end(ctx: JobContext) -> None:
# `on_session_end` runs even if the job crashed before the AgentSession
# started (e.g. a bad timezone, a calendar fault) β make_session_report
# raises in that case, and there's nothing to evaluate anyway.
try:
report = ctx.make_session_report()
except RuntimeError:
return
# Skip evaluation for very short conversations
chat = report.chat_history.copy(exclude_function_call=True, exclude_instructions=True)
if len(chat.items) < 3:
return
judges = JudgeGroup(
llm="openai/gpt-4o-mini",
judges=[
task_completion_judge(),
accuracy_judge(),
tool_use_judge(),
handoff_judge(),
safety_judge(),
relevancy_judge(),
coherence_judge(),
conciseness_judge(),
],
)
await judges.evaluate(report.chat_history)
userdata = ctx.primary_session.userdata
if userdata.booked_times:
ctx.tagger.success()
else:
ctx.tagger.fail(reason="Appointment was not booked")
logger.info("session tags: %s", ctx.tagger.tags)
@server.rtc_session(on_session_end=on_session_end)
async def frontdesk_agent(ctx: JobContext):
await ctx.connect()
timezone = "UTC"
if cal_api_key := os.getenv("CAL_API_KEY", None):
logger.info("CAL_API_KEY detected, using cal.com calendar")
cal = CalComCalendar(api_key=cal_api_key, timezone=timezone)
else:
logger.warning(
"CAL_API_KEY is not set. Falling back to FakeCalendar; set CAL_API_KEY to enable Cal.com integration."
)
cal = FakeCalendar(timezone=timezone)
await cal.initialize()
userdata = Userdata(cal=cal, ui=UIView(ctx))
session = AgentSession[Userdata](
userdata=userdata,
stt=inference.STT("deepgram/nova-3"),
llm=inference.LLM("google/gemini-2.5-flash"),
tts=inference.TTS("cartesia/sonic-3", voice="39b376fc-488e-4d0c-8b37-e00b72059fdd"),
turn_detection=MultilingualModel(),
vad=silero.VAD.load(),
max_tool_steps=1,
)
await session.start(agent=FrontDeskAgent(timezone=timezone), room=ctx.room)
if __name__ == "__main__":
cli.run_app(server)