m
hi
t
Thanks for reaching out, Rahib. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
I'd love to help you out! Could you please share a bit more about your question or the issue you're experiencing? That way, I can make sure to assist you in the best possible way.
m
When using AgentTask while collecting information i ask agent to spell it back character by character to user. But when it is spelling back the agent is either very fast or very slow or sometime it just messes up some characters. How do i solve this speec issue ? I am using cartesia? Below is an example of my tool that store phone numbers and returns the text for llm to respond to user accordingly :
Copy code
@function_tool
    async def update_phone(self, ctx: RunContext, phone: str) -> str:
        """
        Call this when you hear the phone number.

        Args:
            ctx: RunContext with speech_handle
            phone: Phone number (any format)

        Returns:
            Confirmation with digit-by-digit readback

        Raises:
            ToolError: If phone format is invalid
        """
        try:
            normalized = normalize_phone_number(phone)

            if len(normalized) < 10:
                raise ToolError(
                    f"Phone number too short: {phone}. "
                    "Please provide the full 10-digit number."
                )

            self._current_phone = normalized
            self._last_update_speech_handle = ctx.speech_handle

            logger.info(f"Phone updated: {normalized}")

            # Read back digit by digit
            digits_spelled = "-".join(normalized)
            return (
                None,
                f"User phone number {digits_spelled} spell back to user for validtion.",
            )

        except Exception as e:
            logger.error(f"Phone validation error: {e}")
            raise ToolError(
                f"Invalid phone number format: {phone}. "
                "Please provide the number again clearly."
            )
t
I understand how important it is to get the speech speed and accuracy just right during digit-by-digit readback in your AgentTask implementation. Here are some friendly suggestions that might help: 1. Adjust Speech Speed: You can tweak the TTS engine's speed parameter to find the perfect pace—slowing it down or speeding it up as needed. For instance, with ElevenLabs, setting the speed to 0.7 makes the speech slower, while 1.2 speeds it up. This is easily done on the fly using the
update_options()
method. 2. Enable Aligned Transcription: Turning on aligned transcription forwarding helps keep the speech and transcription perfectly in sync, which really boosts clarity during readback. Just enable this in your
AgentSession
by setting
use_tts_aligned_transcript=True
. 3. Optimize for Clarity: For digit-by-digit scenarios, slowing down the speech speed can make a big difference. Also, try to avoid ambiguous characters in the output. You might even create a function to adjust the speed dynamically when it’s needed most. 4. Monitor Latency: Sometimes, high latency can make things feel less accurate. Using LiveKit’s metrics API to keep an eye on performance can help, and deploying your agent close to AI services will minimize delays. I hope these tips make your user experience smoother and clearer during digit readbacks. If you’d like, I’m here to help you with any part of the implementation—just let me know! Sources: pipeline-tts/elevenlabs_change_speed.py | ElevenLabs TTS plugin guide | LiveKit Docs | Cartesia TTS plugin guide | LiveKit Docs | Getting Help & Troubleshooting | livekit/livekit_composite | DeepWiki | Community & Support | livekit/livekit_composite | DeepWiki
m
can i create a tts_node in AgentTask ?
t
Absolutely, you can create and use a
tts_node
within an
AgentTask
in LiveKit. The
tts_node
is a key part of the STT-LLM-TTS pipeline, and it’s what helps turn text segments generated by the LLM into synthesized audio. By default, it uses the TTS setup configured in your agent, but you also have the flexibility to customize it! For example, you might want to try a different TTS engine, tweak the text before it’s synthesized, or add some special audio processing. This method works with an asynchronous stream of text and returns an asynchronous stream of audio frames, making it quite efficient. If you’d like, I’m here to help you step-by-step with implementing or customizing the
tts_node
. Just let me know! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | Pipeline nodes and hooks | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs
m
how do i integrate cartesia specific guidelines like cartesia has
Copy code
Hello, my name is Sonic.<break time="1s"/>Nice to meet you.
<break> and elevenlabs support ssml and all that should i like pus that in the return of my function tool call ?
t
I'm happy to help you integrate SSML tags like
<break>
in LiveKit's AgentTask for both Cartesia and ElevenLabs TTS. Here's a simple guide to get you started: 1. For ElevenLabs: You’ll want to enable SSML parsing by setting
enable_ssml_parsing=True
in your TTS configuration. This lets you use tags such as
<break time="1s"/>
to add pauses. Here’s a quick example:
Copy code
tts = elevenlabs.TTS(
    voice_id="your_voice_id",
    enable_ssml_parsing=True
)
await agent_output.emit("Hello<break time=\"1s\"/>world!")
2. For Cartesia: Great news—Cartesia supports SSML right out of the box! You can include tags like
<break>
directly in your input text. Here’s how it looks:
Copy code
tts = cartesia.TTS(
    model="sonic-2",
    voice="your_voice_id"
)
await agent_output.emit("Hello<break time=\"1s\"/>world!")
Since SSML is a standardized markup language, tags like
<break>
work across platforms, not just with Cartesia. If you want, I’m here to help you test this in your setup or answer any questions you have—just let me know! Sources: livekit-plugins/livekit-plugins-cartesia/livekit/plugins/cartesia/tts.py | ElevenLabs TTS plugin guide | LiveKit Docs | Cartesia TTS plugin guide | LiveKit Docs | Agent speech and audio | LiveKit Docs
m
how do i do this in my agent task ? while keeping it natural and conversation I noticed that while collecting info and all that in the AgentTask the agent sounds very robotic below is my agent
Copy code
"""CollectClientInfoTask - Systematic client information collection.

AgentTask that collects and validates client information when no database match
is found. Returns strongly-typed CollectedClientInfo result.

Following LiveKit GetEmailTask pattern for structured data collection.
"""

import logging
from typing import Optional

from livekit.agents import AgentTask, RunContext
from livekit.agents.llm import ToolError, function_tool

from ..state.session_state import CollectedClientInfo
from ..tools.notion_tools import normalize_phone_number, validate_email

logger = logging.getLogger("collect_client_info_task")


class CollectClientInfoTask(AgentTask[CollectedClientInfo]):
    """Systematically collects client information with validation.

    This task takes control of the session to collect:
    - First name and last name
    - Company name
    - Phone number
    - Email address (optional for proxy callers)

    Returns CollectedClientInfo with all required fields validated.

    Example:
        >>> task = CollectClientInfoTask(chat_ctx=turn_ctx)
        >>> result = await session.run_task(task)
        >>> print(result.first_name, result.last_name)
    """

    def __init__(self, chat_ctx=None):
        """Initialize task with comprehensive instructions.

        Args:
            chat_ctx: Optional chat context to preserve conversation history
        """
        instructions = """You are part of a broader system whose responsibility is to collect and confirm the following information from the caller in a conversational manner:
1. Full Name
2. Phone number
3. Email address
4. Company name
5. Whether this call is being made on behalf of someone else

Treat all input as noisy voice transcription. Expect users to speak data in natural form, with possible variations and filler words. Normalize silently without explaining corrections.  
Collect each field individually, in the order above, unless the user volunteers them earlier. Always call the relevant tool immediately when you detect the information.  

For each field:  

- **Names**: Extract and normalize first and last names. If the name is complex (e.g. unusual spelling, uncommon names, acronyms), spell it back character-by-character.  
- **Phone numbers**: Normalize to digits only. Read back digit-by-digit. Prompt for missing or ambiguous digits.  
- **Emails**: Expect formats like "john dot doe at gmail dot com". Convert spoken patterns into symbols (`dot → .`, `underscore → _`, `dash → -`, `plus → +`, `at → @`). Prompt for missing parts (before or after '@') if unclear. Spell back if complex.  
- **Company name**: Capture the name exactly as spoken. If an acronym, spell it out.  
- **Proxy call**: Detect if user is calling on behalf of someone else (phrases like "calling for", "on behalf of") and confirm with `mark_as_proxy_caller`. If yes, make email optional.  

General rules:  
- If a tool call fails, retry asking the user for clarification or re-input until successful. Do not complete the conversation until all required information is collected and confirmed.  
- Do not invent data. Always stick to what the user says, correcting silently.  
- Ignore unrelated input. Do not generate greetings or commentary.  
- Always explicitly invoke the relevant tool when applicable. Do not simulate tool usage.  

Order of confirmation:  
1. Confirm name via `update_name`.  
2. Confirm phone via `update_phone`.  
3. Confirm email via `update_email` (unless proxy caller).  
4. Confirm company via `update_company`.  
5. Ask if calling on behalf of someone else, call `mark_as_proxy_caller` if applicable.  
6. Once all required fields are collected, call `confirm_all_info` only after explicit user confirmation ("yes", "correct", "that's right").  

If the user declines to provide required information, call `decline_collection` with the reason.
"""

        super().__init__(instructions=instructions, chat_ctx=chat_ctx)

        # Task state (separate from session state)
        self._current_first_name = ""
        self._current_last_name = ""
        self._current_company = ""
        self._current_phone = ""
        self._current_email = ""
        self._is_proxy_caller = False

        # Speech handle tracking for hallucination prevention
        self._last_update_speech_handle: Optional[object] = None

    async def on_enter(self) -> None:
        """Start the information collection process.

        Reviews chat history for any information already provided,
        then validates with user before asking for missing pieces.
        """
        logger.info("CollectClientInfoTask entered - starting collection")
       

    @function_tool
    async def update_name(
        self, ctx: RunContext, first_name: str, last_name: str
    ) -> str:
        """Call this function when user has provided their name or made a correction in their name.

        Args:
            ctx: RunContext with speech_handle
            first_name: User's first name
            last_name: User's last name

        Returns:
            Confirmation message with spelled-back name

        Raises:
            ToolError: If names are empty
        """
        if not first_name or not last_name:
            raise ToolError("Both first name and last name are required")

        self._current_first_name = first_name.strip()
        self._current_last_name = last_name.strip()
        self._last_update_speech_handle = ctx.speech_handle

        logger.info(f"Name updated: {first_name} {last_name}")

        # Spell back character-by-character
        first_spelled = "-".join(first_name.upper())
        last_spelled = "-".join(last_name.upper())

        return (
            f"Name updated: {first_name} {last_name}. "
            f"Let me spell that back: {first_spelled} {last_spelled}. "
            "Is that correct?"
        )

    @function_tool
    async def update_company(self, ctx: RunContext, company: str) -> str:
        """
        Call this when you hear the company name.

        Args:
            ctx: RunContext with speech_handle
            company: Company name

        Returns:
            Confirmation message

        Raises:
            ToolError: If company is empty
        """
        if not company:
            raise ToolError("Company name cannot be empty")

        self._current_company = company.strip()
        self._last_update_speech_handle = ctx.speech_handle
Copy code
# Handle acronyms - spell them out
        if len(company) <= 6 and company.isupper():
            spelled = "-".join(company)
            return f"Company: {company}, spelled {spelled}. Is that correct?"

        return f"User company name {company}. Spell it back to user for validation."

    @function_tool
    async def update_phone(self, ctx: RunContext, phone: str) -> str:
        """
        Call this when you hear the phone number.

        Args:
            ctx: RunContext with speech_handle
            phone: Phone number (any format)

        Returns:
            Confirmation with digit-by-digit readback

        Raises:
            ToolError: If phone format is invalid
        """
        try:
            normalized = normalize_phone_number(phone)

            if len(normalized) < 10:
                raise ToolError(
                    f"Phone number too short: {phone}. "
                    "Please provide the full 10-digit number."
                )

            self._current_phone = normalized
            self._last_update_speech_handle = ctx.speech_handle


            # Read back digit by digit
            digits_spelled = "-".join(normalized)
            return (
                None,
                f"User phone number {digits_spelled} spell back to user for validtion.",
            )

        except Exception as e:
            logger.error(f"Phone validation error: {e}")
            raise ToolError(
                f"Invalid phone number format: {phone}. "
                "Please provide the number again clearly."
            )

    @function_tool
    async def update_email(self, ctx: RunContext, email: str) -> str:
        """
        Call this when you hear the email address.

        Args:
            ctx: RunContext with speech_handle
            email: Email address

        Returns:
            Confirmation with character-by-character spelling

        Raises:
            ToolError: If email format is invalid
        """
        if not validate_email(email):
            raise ToolError(
                f"Invalid email format: {email}. "
                "Please spell it character by character: "
                "j-a-k-e @ c-l-o-u-d-m-e-t-r-i-c . c-a"
            )

        self._current_email = email.strip().lower()
        self._last_update_speech_handle = ctx.speech_handle

        # Spell back character by character
        spelled = " ".join(list(email))
        return None, f"User Email address: {spelled} spell back to user for validation."

    @function_tool
    async def mark_as_proxy_caller(self, ctx: RunContext) -> str:
        """Mark caller as calling on behalf of someone else.

        Call this if the user mentions "calling for someone else" or
        "calling on behalf of".

        Args:
            ctx: RunContext

        Returns:
            Confirmation message
        """
        self._is_proxy_caller = True

        logger.info("Marked as proxy caller - email optional")

        return (
            "Understood, you're calling on behalf of someone else. "
            "Email will be optional in that case."
        )

    @function_tool
    async def confirm_all_info(self, ctx: RunContext) -> None:
        """Confirm all information is correct and complete the task.

        ONLY call this AFTER the user explicitly confirms all information
        is correct. User must say "yes", "correct", "that's right", etc.

        Args:
            ctx: RunContext with speech_handle

        Raises:
            ToolError: If validation fails or missing required fields
        """
        # Hallucination prevention: ensure user actually confirmed
        if ctx.speech_handle == self._last_update_speech_handle:
            raise ToolError(
                "Please wait for the user to confirm before calling this tool. "
                "The user must explicitly say something like 'yes that's correct', "
                "'yes', 'correct', or 'that's right'."
            )

        # Validate required fields
        missing = []
        if not self._current_first_name:
            missing.append("first name")
        if not self._current_last_name:
            missing.append("last name")
        if not self._current_company:
            missing.append("company")
        if not self._current_phone:
            missing.append("phone number")

        if missing:
            raise ToolError(
                f"Missing required information: {', '.join(missing)}. "
                "Please collect all required fields before confirming."
            )

        # Email validation for non-proxy callers
        if not self._is_proxy_caller and not self._current_email:
            raise ToolError(
                "Email is required for direct callers. "
                "If this is a proxy call, call mark_as_proxy_caller first."
            )


        self.complete(
            CollectedClientInfo(
                first_name=self._current_first_name,
                last_name=self._current_last_name,
                company=self._current_company,
                phone=self._current_phone,
                email=self._current_email if self._current_email else None,
                is_proxy_caller=self._is_proxy_caller,
            )
        )
t
I'd love to help you make your AgentTask sound more natural and conversational! Here are some friendly tips you can try: 1. Use TTS Voice Instructions: You can set clear, high-level instructions for the TTS engine to guide the tone and delivery. For instance, telling it to use a "natural, conversational tone" when you start the TTS engine can make a big difference. 2. Leverage SSML: SSML tags like
<prosody>
let you adjust pitch, rate, and volume, while
<break>
helps insert natural pauses. For example:
<prosody rate="slow" pitch="medium">Hello! How can I help you today?</prosody>
3. Dynamic Speech Customization: You might want to design your LLM to output responses that include both the spoken text and voice instructions. This way, you can dynamically tweak the TTS engine’s settings for each response, making things feel more personalized. 4. Enhance Conversational Flow: Adding natural interjections like "Hmm," or "I see," and varying tone and pacing can really bring empathy or urgency into your speech. Using pauses (
<break>
) gives a nice breathing space, especially in emotional or complex parts. If you'd like, I’m here to help you implement these techniques specifically for your AgentTask setup or with any TTS provider you’re working with. Just let me know! Sources: livekit-agents/livekit/agents/voice/agent_activity.py | ElevenLabs TTS plugin guide | LiveKit Docs | Amazon Polly TTS plugin guide | LiveKit Docs | Tool definition and use | LiveKit Docs | Pipeline nodes and hooks | LiveKit Docs
m
can i dothis ? await self.session.say( """<prosody rate="slow" pitch="medium">Hello! How can I help you today?</prosody>""" ) will this work ? as per ssml for cartesia ?
t
Hi there! I wanted to share a quick tip about using SSML tags like
<prosody>
with
self.session.say()
in Cartesia TTS on LiveKit. These tags can’t be used directly, but don’t worry—you can still adjust prosody, such as speed, pitch, and emotion, by using the
speed
and
emotion
parameters in the Cartesia TTS setup. Here’s a simple example to help you get started:
Copy code
from livekit.plugins import cartesia

tts = cartesia.TTS(
    model="sonic-2",
    voice="your_voice_id",
    speed=0.8,  # Slower speech
    emotion="friendly"  # Adjust tone
)
await self.session.say("Hello! How can I help you today?")
This way, your prosody settings will work smoothly. If you have any questions or want me to walk you through it, just let me know—I’m here to help! Sources: Agent speech and audio | LiveKit Docs | livekit-plugins/livekit-plugins-cartesia/livekit/plugins/cartesia/tts.py | plugins/cartesia/src/tts.ts | complex-agents/medical_office_triage/triage.py | Cartesia TTS plugin guide | LiveKit Docs
m
if i use elevenlabs can i do like this ? await self.session.say( """<prosody rate="slow" pitch="medium">Hello! How can I help you today?</prosody>""" ) ?
t
Absolutely, you can use SSML tags like
<prosody>
in
self.session.say()
for ElevenLabs TTS! Just a quick heads-up: you’ll need to enable SSML parsing explicitly to make it work. You can do this by setting
enable_ssml_parsing=True
when you initialize your ElevenLabs TTS instance. Here’s a simple example to guide you:
Copy code
from livekit.plugins import elevenlabs

tts = elevenlabs.TTS(
    enable_ssml_parsing=True,
    model="eleven_turbo_v2_5"
)
await self.session.say(
    """<prosody rate=\"slow\" pitch=\"+5%\">Hello, this is slower and higher-pitched.</prosody>"""
)
If you have any questions or need a hand with setting this up, please don’t hesitate to reach out—I’m here to help! Sources: ElevenLabs TTS plugin guide | LiveKit Docs