class EmailAssistant(Agent):
inbox_id: str
ws_task: asyncio.Task | None = None
def __init__(self) -> None:
client = Agentinbox()
# By setting the client_id the inbox is created only once.
username = os.getenv("AGENTINBOX_USERNAME")
inbox = client.inboxes.create(username=username, client_id=f"{username}-inbox")
self.inbox_id = inbox.inbox_id
super().__init__(
instructions=f"""
Ты полезный голосовой и почтовый AI-ассистент. Твоё имя — Agent Inbox. Ты получаешь письма на {self.inbox_id}. Можешь отправлять письма и отвечать.
При вызове почтовых инструментов указывай "{self.inbox_id}" как inbox_id. В подписи писем указывай «Agent Inbox».
Говори по-русски.
ВАЖНО: {self.inbox_id} — твой ящик, а не ящик пользователя.
""",
# The Agent Inbox Toolkit has ready-to-go tools for LiveKit agents.
tools=AgentinboxToolkit(client=client).get_tools(
[
"list_threads",
"get_thread",
"get_attachment",
"send_message",
"reply_to_message",
]
),
)
async def _websocket_task(self):
# Open a websocket connection to Agent Inbox.
async with AsyncAgentinbox().websockets.connect() as socket:
# Subscribe to events from the inbox.
await socket.send_subscribe(Subscribe(inbox_ids=[self.inbox_id]))
while True:
data = await socket.recv()
# If a message is received by the inbox, interrupt the current conversation and generate a reply.
if isinstance(data, MessageReceived):
self.session.interrupt()
await self.session.generate_reply(
instructions=f"""Скажи «Я получил письмо», затем прочитай письмо.""",
user_input=data.message.model_dump_json(),
)
# Open the websocket connection and generate a greeting when the agent enters the call.
async def on_enter(self):
self.ws_task = asyncio.create_task(self._websocket_task())
await self.session.generate_reply(
instructions=f"""По-русски поздоровайся с пользователем, представься как Agent Inbox, скажи, что можешь получать письма на {self.inbox_id}, и предложи помощь.""",
allow_interruptions=False,
)
# Close the websocket connection when the agent exits the call.
async def on_exit(self):
if self.ws_task:
self.ws_task.cancel()