How do I send the userData at the end of a session...
# ask-ai
m
How do I send the userData at the end of a session as an email to a list of email addresses
t
Thanks for reaching out, Nikki. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Hi there! Just to better assist you, could you please let me know if you're using LiveKit Agents or another backend system to manage your sessions? Also, do you happen to have access to an email service like SMTP or AWS SES that can send emails once a session ends? I'm here to help you through this! Sources: Data packets | LiveKit Docs | context-readmes/USERDATA_GUIDE.md | examples/frontdesk/frontdesk_agent.py
m
I am using liveKit agent to manage sessions and yes have access to SMTP service to send emails once a session ends
t
I understand you're looking to send emails via SMTP with LiveKit. While LiveKit doesn't support this feature out of the box, you can definitely set it up using a custom tool or a backend service. I'd be happy to guide you through creating a custom tool within your LiveKit Agent to send emails, or if you prefer, we can explore how to handle this through an external backend service. Just let me know what works best for you! Sources: examples/README.md | External data and RAG | LiveKit Docs
m
Walk me through both please.
t
I'd be happy to guide you through implementing email functionality for both approaches. Here’s how you can get started: 1. Using a Custom Tool in LiveKit Agent: 1. First, create a custom tool in your LiveKit Agent that connects with your SMTP service. This tool will take care of sending emails right at the end of a session. 2. You can use Python’s
smtplib
library to set up and send emails. Here's a simple example to help you out:
Copy code
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_emails):
    smtp_server = "your.smtp.server"
    smtp_port = 587
    smtp_user = "your_username"
    smtp_password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = smtp_user
    msg['To'] = ", ".join(to_emails)
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(smtp_user, smtp_password)
        server.sendmail(smtp_user, to_emails, msg.as_string())
1. Then, integrate this function into your LiveKit Agent’s workflow so it triggers right when a session ends. 2. Using an External Backend Service: 1. You can also set up a backend service using something like Flask or Node.js that listens for session-end events from LiveKit. 2. Configure your LiveKit Agent to send session data to this backend through a webhook or API call when a session finishes. 3. In your backend, use an SMTP library or a third-party email service (like AWS SES or SendGrid) to send the email. Here's a simple Flask example to illustrate:
Copy code
from flask import Flask, request
import smtplib

app = Flask(__name__)

@app.route('/send-email', methods=['POST'])
def send_email():
    data = request.json
    subject = data['subject']
    body = data['body']
    to_emails = data['to_emails']

    # Use the same smtplib code as above to send the email
    return "Email sent!", 200

if __name__ == '__main__':
    app.run(port=5000)
1. Just a quick reminder to make sure your backend is secure and properly handles authentication and error handling. If you have any questions or need more details on either method, please don’t hesitate to ask—I’m here to help!
m
Lets go with the first option - how do I integrate thhis function into LiveKti Agent's workflow so that at the end of the work - when the chat ends, it triggers this - my current agent """ --- title: Multi-Stage Flow category: flows tags: [flows, openai, assemblyai] difficulty: intermediate description: Shows how to create a multi-stage flow using a series of agents. demonstrates: - Creating a multi-stage flow using a series of agents. --- """ import logging from dotenv import load_dotenv from dataclasses import dataclass, field from typing import Dict, List, Annotated from enum import Enum from pydantic import Field from livekit.agents import JobContext, WorkerOptions, cli from livekit.agents.llm import function_tool from livekit.agents.voice import Agent, AgentSession from livekit.plugins import silero from livekit import api # Load environment and configure logger load_dotenv() logger = logging.getLogger("multi-stage-flow") logger.setLevel(logging.INFO) # Define enums for the choices at each stage class Stage1Choice(str, Enum): OPTION_A = "A" OPTION_B = "B" class Stage2Choice(str, Enum): OPTION_X = "X" OPTION_Y = "Y" class Stage3Choice(str, Enum): OPTION_M = "M" OPTION_N = "N" @dataclass class SurveyData: """Stores all survey responses and state.""" responses: Dict[str, str] = field(_default_factory_=dict) current_stage: int = 1 current_branch: str = "" path_taken: List[str] = field(_default_factory_=list) def record(self, _question_: str, _answer_: str): self.responses[question] = answer self.path_taken.append(f"Stage {self.current_stage} ('{self.current_branch}') - {question}: {answer}") class BaseAgent(Agent): """Base agent class handling job context and common setup.""" def __init__(self, _job_context_: JobContext, _instructions_: str) -> None: self.job_context = _job_context_ super().__init__( instructions=instructions, stt="assemblyai/universal-streaming", llm="openai/gpt-4.1-mini", tts="cartesia/sonic-2:6f84f4b8-58a2-430c-8c79-688dad597532", vad=silero.VAD.load() ) # Stage 1: Preference A or B class Stage1Agent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Stage 1: Do you prefer Option A or Option B?" ) async def on_enter(self) -> None: await self.session.say("Stage 1: Do you prefer Option A or Option B?") @function_tool async def collect_stage1( self, _choice_: Annotated[ Stage1Choice, Field(description="Do you prefer Option A or Option B?") ] ) -> Agent: sd: SurveyData = self.session.userdata sd.record("Prefer A or B", choice.value) sd.current_branch = choice.value if choice == Stage1Choice.OPTION_A: return Stage1ABranchAgent(_job_context_=self.job_context) return Stage1BBranchAgent(_job_context_=self.job_context) class Stage1ABranchAgent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Follow-up: Why do you prefer Option A?" ) async def on_enter(self) -> None: await self.session.say("Why do you prefer Option A?") @function_tool async def collect_A(self, _answer_: str) -> Agent: sd: SurveyData = self.session.userdata sd.record("Why prefer A", answer) sd.current_stage = 2 return Stage2Agent(_job_context_=self.job_context) class Stage1BBranchAgent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Follow-up: Why do you prefer Option B?" ) async def on_enter(self) -> None: await self.session.say("Why do you prefer Option B?") @function_tool async def collect_B(self, _answer_: str) -> Agent: sd: SurveyData = self.session.userdata sd.record("Why prefer B", answer) sd.current_stage = 2 return Stage2Agent(_job_context_=self.job_context) # Stage 2: Preference X or Y class Stage2Agent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Stage 2: Do you prefer Option X or Option Y?" ) async def on_enter(self) -> None: await self.session.say("Stage 2: Do you prefer Option X or Option Y?") @function_tool async def collect_stage2( self, _choice_: Annotated[ Stage2Choice, Field(description="Do you prefer Option X or Option Y?") ] ) -> Agent: sd: SurveyData = self.session.userdata sd.record("Prefer X or Y", choice.value) sd.current_branch = choice.value if choice == Stage2Choice.OPTION_X: return Stage2XBranchAgent(_job_context_=self.job_context) return Stage2YBranchAgent(_job_context_=self.job_context) class Stage2XBranchAgent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Follow-up: What appeals to you about Option X?" ) async def on_enter(self) -> None: await self.session.say("What appeals to you about Option X?") @function_tool async def collect_X(self, _answer_: str) -> Agent: sd: SurveyData = self.session.userdata sd.record("Appeal of X", answer) sd.current_stage = 3 return Stage3Agent(_job_context_=self.job_context) class Stage2YBranchAgent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Follow-up: What appeals to you about Option Y?" ) async def on_enter(self) -> None: await self.session.say("What appeals to you about Option Y?") @function_tool async def collect_Y(self, _answer_: str) -> Agent: sd: SurveyData = self.session.userdata sd.record("Appeal of Y", answer) sd.current_stage = 3 return Stage3Agent(_job_context_=self.job_context) # Stage 3: Preference M or N class Stage3Agent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Stage 3: Do you prefer Option M or Option N?" ) async def on_enter(self) -> None: await self.session.say("Stage 3: Do you prefer Option M or Option N?") @function_tool async def collect_stage3( self, _choice_: Annotated[ Stage3Choice, Field(description="Do you prefer Option M or Option N?") ] ) -> Agent: sd: SurveyData = self.session.userdata sd.record("Prefer M or N", choice.value) branch = choice.value if choice == Stage3Choice.OPTION_M: return Stage3MBranchAgent(_job_context_=self.job_context) return Stage3NBranchAgent(_job_context_=self.job_context) class Stage3MBranchAgent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Follow-up: Why do you prefer Option M?" ) async def on_enter(self) -> None: await self.session.say("Why do you prefer Option M?") @function_tool async def collect_M(self, _answer_: str) -> Agent: sd: SurveyData = self.session.userdata sd.record("Why M", answer) return SummaryAgent(_job_context_=self.job_context) class Stage3NBranchAgent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Follow-up: Why do you prefer Option N?" ) async def on_enter(self) -> None: await self.session.say("Why do you prefer Option N?") @function_tool async def collect_N(self, _answer_: str) -> Agent: sd: SurveyData = self.session.userdata sd.record("Why N", answer) return SummaryAgent(_job_context_=self.job_context) class SummaryAgent(BaseAgent): def __init__(self, _job_context_: JobContext) -> None: super().__init__( _job_context_=_job_context_, instructions="Summarize all responses and end the survey." ) async def on_enter(self) -> None: sd: SurveyData = self.session.userdata summary = "Thank you for completing the survey! Here are your responses:\n" for q, a in sd.responses.items(): summary += f"- {q}: {a}\n" await self.session.say(summary) logger.info("Survey complete. Closing session.") await self.session.aclose() _try_: await self.job_context.api.room.delete_room( api.DeleteRoomRequest(room=self.job_context.room.name) ) except Exception as e: logger.error(f"Error deleting room: {e}") async def entrypoint(_ctx_: JobContext) -> None: session = AgentSession() session.userdata = SurveyData() await session.start( agent=Stage1Agent(_job_context_=ctx), room=ctx.room ) if name == "__main__": cli.run_app(WorkerOptions(_entrypoint_fnc_=entrypoint))
t
I'm glad to help you integrate the email-sending function into your LiveKit Agent's workflow! A great way to do this is by triggering the email function right at the end of the session. Let me walk you through how you can update your existing agent: 1. Add the Email Function:
Copy code
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_emails):
    smtp_server = "your.smtp.server"
    smtp_port = 587
    smtp_user = "your_username"
    smtp_password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = smtp_user
    msg['To'] = ", ".join(to_emails)
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(smtp_user, smtp_password)
        server.sendmail(smtp_user, to_emails, msg.as_string())
2. Modify the SummaryAgent: In your
SummaryAgent
, once you've summarized the responses, you can call the
send_email
function like this:
Copy code
class SummaryAgent(BaseAgent):
    def __init__(self, job_context: JobContext) -> None:
        super().__init__(
            job_context=job_context,
            instructions="Summarize all responses and end the survey."
        )

    async def on_enter(self) -> None:
        sd: SurveyData = self.session.userdata
        summary = "Thank you for completing the survey! Here are your responses:\n"
        for q, a in sd.responses.items():
            summary += f"- {q}: {a}\n"

        await self.session.say(summary)
        logger.info("Survey complete. Closing session.")

        # Send email with survey summary
        try:
            send_email(
                subject="Survey Summary",
                body=summary,
                to_emails=["recipient1@example.com", "recipient2@example.com"]
            )
            logger.info("Email sent successfully.")
        except Exception as e:
            logger.error(f"Error sending email: {e}")

        await self.session.aclose()
        try:
            await self.job_context.api.room.delete_room(
                api.DeleteRoomRequest(room=self.job_context.room.name)
            )
        except Exception as e:
            logger.error(f"Error deleting room: {e}")
3. Test the Workflow: 1. Double-check that your SMTP credentials and server details are all set correctly. 2. Run your agent and complete a session to make sure the email with the session summary is sent smoothly. If you have any questions or run into any issues, please don't hesitate to reach out—I'm here to help!
m
Actually this is my flow - help me update this instead
t
To help you update your existing flow to include the email-sending functionality, you can easily modify the
SummaryAgent
or the final stage of your workflow to trigger the email function. Here’s a friendly guide on how to do it: 1. Add the Email Function:
Copy code
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

def send_email(subject, body, to_emails):
    smtp_server = "your.smtp.server"
    smtp_port = 587
    smtp_user = "your_username"
    smtp_password = "your_password"

    msg = MIMEMultipart()
    msg['From'] = smtp_user
    msg['To'] = ", ".join(to_emails)
    msg['Subject'] = subject

    msg.attach(MIMEText(body, 'plain'))

    with smtplib.SMTP(smtp_server, smtp_port) as server:
        server.starttls()
        server.login(smtp_user, smtp_password)
        server.sendmail(smtp_user, to_emails, msg.as_string())
2. Update the Final Agent (e.g.,
SummaryAgent
):
In your
SummaryAgent
, right after summarizing the responses, you can call the
send_email
function like this:
Copy code
class SummaryAgent(BaseAgent):
    def __init__(self, job_context: JobContext) -> None:
        super().__init__(
            job_context=job_context,
            instructions="Summarize all responses and end the survey."
        )

    async def on_enter(self) -> None:
        sd: SurveyData = self.session.userdata
        summary = "Thank you for completing the survey! Here are your responses:\n"
        for q, a in sd.responses.items():
            summary += f"- {q}: {a}\n"

        await self.session.say(summary)
        logger.info("Survey complete. Closing session.")

        # Send email with survey summary
        try:
            send_email(
                subject="Survey Summary",
                body=summary,
                to_emails=["recipient1@example.com", "recipient2@example.com"]
            )
            logger.info("Email sent successfully.")
        except Exception as e:
            logger.error(f"Error sending email: {e}")

        await self.session.aclose()
        try:
            await self.job_context.api.room.delete_room(
                api.DeleteRoomRequest(room=self.job_context.room.name)
            )
        except Exception as e:
            logger.error(f"Error deleting room: {e}")
3. Test the Updated Flow: 1. Make sure your SMTP credentials and server details are accurate. 2. Run the agent and complete a session to confirm that the email with the session summary is sent successfully. If you have any questions or need help tweaking this further, please don’t hesitate to reach out—I’m here to help!