class Assistant(Agent): def _init_(self, room:...
# ask-ai
f
class Assistant(Agent): def _init_(self, room: rtc.Room): self.room = room super()._init_( instructions="You are an AI Tutor assistant. Your role is to help students learn effectively." ) async def llm_node( self, chat_ctx: llm.ChatContext, tools: list[FunctionTool], model_settings: ModelSettings, ) -> AsyncIterable[llm.ChatChunk]: """Process tags in order: speak, action, speak, action alternately.""" buffer = "" async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings): if chunk.delta and chunk.delta.content: buffer += chunk.delta.content # Process tags in the order they appear while True: # Find the positions of the next speak and action_list tags speak_start = buffer.find("<speak>") action_start = buffer.find("<action_list>") # Determine which tag comes first if speak_start == -1 and action_start == -1: # No complete tags found break # Process whichever tag comes first if speak_start != -1 and (action_start == -1 or speak_start < action_start): # Process <speak> tag first speak_end = buffer.find("</speak>") if speak_end > speak_start: text_between = buffer[speak_start + 7:speak_end].strip() if text_between: print(f"Speaking: {text_between}") handle = self.session.say(text_between) await handle print(f"Finished speaking: {text_between}") # Remove processed tag from buffer buffer = buffer[:speak_start] + buffer[speak_end + 8:] else: # Incomplete tag, wait for more content break elif action_start != -1: # Process <action_list> tag first action_end = buffer.find("</action_list>") if action_end > action_start: text_between = buffer[action_start + 13:action_end] if text_between: print(f"Processing actions: {text_between}") actions_list = json.loads(text_between) # Add your action processing logic here # Remove processed tag from buffer buffer = buffer[:action_start] + buffer[action_end + 14:] else: # Incomplete tag, wait for more content break this code is not working, like code gets stuck at this print statement print(f"Speaking: {text_between}") Why so? I want it to sequentially perform the speak and the action item lists, how can i do it?
t
Thanks for reaching out, arpit. I'm an AI assistant and I'm here to help. Give me a moment while I research this topic.
Thank you for sharing your code! To better understand why it might be getting stuck at
print(f"Speaking: {text_between}")
, could you please help me with a few details? • Where does the
text_between
variable come from? Is it from an external framework or maybe a custom XML/SSML structure? • Are there any asynchronous operations involved, like TTS or audio playback, that could be waiting to finish after the print statement? • Is the
self.session.say
method part of a particular library or framework? If yes, which one? Knowing these will really help us get to the bottom of this and find the best way to fix it together. Sources: Modifying LLM output before TTS | LiveKit Docs | Docs::Agents | livekit-agents/livekit/agents/voice/agent_activity.py | realtime-agents/openai-realtime-tools.py
f
yes, so basically, i am parsing the chunks at llm_node and then using it <speak> text_between </speak> this is the text_between and then i am trying to use speak using session.say, but i want to do it asynchronously. like i want to await here
t
I’m glad you asked about processing
<speak>
and
<action_list>
tags sequentially, especially when working with asynchronous operations like
session.say
. Using the
SpeechHandle
object returned by
session.say
is a great way to make sure the next step only begins once the speech has finished. Here’s a friendly example of how you might adjust your code:
Copy code
async def process_structured_response(self, content: str):
    # Extract structured tags
    speak_sections = extract_speak_tags(content)
    action_lists = extract_action_list_tags(content)

    # Process each speak section sequentially
    for speak_text in speak_sections:
        speech_handle = self.session.say(speak_text)
        await speech_handle

        if speech_handle.interrupted:
            break

    # Process action lists after all speech completes
    if not speech_handle.interrupted:
        for action_list in action_lists:
            await self.execute_actions_sequentially(action_list)
This way, you can be confident that: • Each
<speak>
section is spoken fully before moving on. • Actions inside
<action_list>
run only after all the speech has finished. • If there’s an interruption during speech, it’s handled smoothly by stopping any remaining actions. Please don’t hesitate to reach out if you’d like me to walk you through this further or help with implementation. I’m here to support you! Sources: Agent speech and audio | LiveKit Docs | Docs::Agents | livekit-agents/livekit/agents/voice/agent_activity.py | chain-of-thought-tts/README.mdoc | Events and error handling | LiveKit Docs
f
class Assistant(Agent): def __init__(self, room: rtc.Room): super().__init__( instructions="You are an AI Tutor assistant. Your role is to help students learn effectively." ) self.room = room # Single, ordered work queue (bounded → natural backpressure) self._queue: asyncio.Queue[WorkItem] = asyncio.Queue(maxsize=16) # Background consumer that will "keep working if there is any task" self._worker_task: Optional[asyncio.Task] = None # LiveKit injects self.session on start; set type hint to keep editors happy session: AgentSession # type: ignore async def on_enter(self) -> None: # Start the consumer once if self._worker_task is None: self._worker_task = asyncio.create_task(self._worker(), name="actor-worker") async def on_exit(self) -> None: # Stop the consumer cleanly if self._worker_task: self._worker_task.cancel() try: await self._worker_task except asyncio.CancelledError: pass self._worker_task = None async def _worker(self) -> None: """ Continuously drains the queue. As soon as the first task is enqueued, this coroutine wakes up and starts processing; it keeps working while there are items in the queue. """ while True: kind, payload = await self._queue.get() try: if kind == "speak": print(f"START SPEAKING: {payload}") await self.session.say(payload, allow_interruptions=True) print(f"FINISHED SPEAKING: {payload}") elif kind == "action": print("ACTION START") print(f"ACTIONS RECEIVED:\n{payload}") # TODO: replace with your real action executor await asyncio.sleep(10) print("ACTION END (10s window complete)") finally: self._queue.task_done() async def llm_node( self, chat_ctx: llm.ChatContext, tools: list[FunctionTool], model_settings: ModelSettings, ) -> AsyncIterable[llm.ChatChunk]: buffer = "" tag_pairs = [ ("<speak>", "</speak>", "speak"), ("<action_list>", "</action_list>", "action"), ] async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings): # Always yield empty chunk to keep generator alive # This allows worker to run concurrently yield llm.ChatChunk( id = "fferf", delta= None, usage= None ) if chunk.delta and chunk.delta.content: buffer += chunk.delta.content while True: earliest = None for open_tag, close_tag, kind in tag_pairs: s = buffer.find(open_tag) if s == -1: continue e = buffer.find(close_tag, s + len(open_tag)) if e == -1: continue if earliest is None or s < earliest[0]: earliest = (s, e, kind, open_tag, close_tag) if earliest is None: break s, e, kind, open_tag, close_tag = earliest inner = buffer[s + len(open_tag): e].strip() buffer = buffer[:s] + buffer[e + len(close_tag):] if inner: await self._queue.put((kind, inner)) print(f"ENQUEUED {kind.upper()}: {inner}") break this is my current agent, can you give me a code for this
t
Thank you for sharing your implementation! You’ve already set up a thoughtful and well-structured approach for handling the
<speak>
and
<action_list>
tags sequentially using an asynchronous queue. To help you along, here’s a slightly refined version of your agent with some minor improvements for clarity and functionality:
Copy code
class Assistant(Agent):
    def __init__(self, room: rtc.Room):
        super().__init__(
            instructions="You are an AI Tutor assistant. Your role is to help students learn effectively."
        )
        self.room = room

        # Single, ordered work queue (bounded → natural backpressure)
        self._queue: asyncio.Queue[tuple[str, str]] = asyncio.Queue(maxsize=16)

        # Background consumer that will "keep working if there is any task"
        self._worker_task: Optional[asyncio.Task] = None

    # LiveKit injects self.session on start; set type hint to keep editors happy
    session: AgentSession  # type: ignore

    async def on_enter(self) -> None:
        # Start the consumer once
        if self._worker_task is None:
            self._worker_task = asyncio.create_task(self._worker(), name="actor-worker")

    async def on_exit(self) -> None:
        # Stop the consumer cleanly
        if self._worker_task:
            self._worker_task.cancel()
            try:
                await self._worker_task
            except asyncio.CancelledError:
                pass
            self._worker_task = None

    async def _worker(self) -> None:
        """
        Continuously drains the queue. As soon as the first task is enqueued,
        this coroutine wakes up and starts processing; it keeps working while
        there are items in the queue.
        """
        while True:
            kind, payload = await self._queue.get()
            try:
                if kind == "speak":
                    print(f"START SPEAKING: {payload}")
                    await self.session.say(payload, allow_interruptions=True)
                    print(f"FINISHED SPEAKING: {payload}")

                elif kind == "action":
                    print("ACTION START")
                    print(f"ACTIONS RECEIVED:\n{payload}")
                    # TODO: replace with your real action executor
                    await asyncio.sleep(10)
                    print("ACTION END (10s window complete)")
            finally:
                self._queue.task_done()

    async def llm_node(
        self,
        chat_ctx: llm.ChatContext,
        tools: list[FunctionTool],
        model_settings: ModelSettings,
    ) -> AsyncIterable[llm.ChatChunk]:
        buffer = ""
        tag_pairs = [
            ("<speak>", "</speak>", "speak"),
            ("<action_list>", "</action_list>", "action"),
        ]

        async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
            # Always yield empty chunk to keep generator alive
            # This allows worker to run concurrently
            yield llm.ChatChunk(
                id="fferf",
                delta=None,
                usage=None
            )

            if chunk.delta and chunk.delta.content:
                buffer += chunk.delta.content

            while True:
                earliest = None
                for open_tag, close_tag, kind in tag_pairs:
                    s = buffer.find(open_tag)
                    if s == -1:
                        continue
                    e = buffer.find(close_tag, s + len(open_tag))
                    if e == -1:
                        continue
                    if earliest is None or s < earliest[0]:
                        earliest = (s, e, kind, open_tag, close_tag)

                if earliest is None:
                    break

                s, e, kind, open_tag, close_tag = earliest
                inner = buffer[s + len(open_tag): e].strip()
                buffer = buffer[:s] + buffer[e + len(close_tag):]

                if inner:
                    await self._queue.put((kind, inner))
                    print(f"ENQUEUED {kind.upper()}: {inner}")
                    break
This setup helps ensure: • That
<speak>
and
<action_list>
tags are processed one after the other in a neat, orderly fashion using a bounded queue, which naturally handles backpressure. • A smooth startup and shutdown of the worker through
on_enter
and
on_exit
methods, keeping things clean and efficient. • The ability to process LLM chunks concurrently while keeping the order intact in your queue. Please feel free to reach out if you’d like me to walk you through any part of this or if you want to explore more tweaks together. I’m here to help!
f
it is not working, it is first collecting all the chunks , processing them and after it have all the chunks, it start speaking and taking actions, i want it to do as soon as it have one work in the queue.
t
I totally understand wanting your tasks to be processed right away as they come in. To make that happen, you can tweak your implementation so it doesn’t wait for all chunks to pile up. The trick is to have a continuous polling loop in your worker task that jumps into action as soon as something is added to the queue. Here’s a refreshed version of your worker function that should help:
Copy code
async def _worker(self) -> None:
    """
    Continuously drains the queue. As soon as the first task is enqueued,
    this coroutine wakes up and starts processing; it keeps working while
    there are items in the queue.
    """
    while True:
        kind, payload = await self._queue.get()  # Process immediately when an item is enqueued
        try:
            if kind == "speak":
                print(f"START SPEAKING: {payload}")
                await self.session.say(payload, allow_interruptions=True)
                print(f"FINISHED SPEAKING: {payload}")

            elif kind == "action":
                print("ACTION START")
                print(f"ACTIONS RECEIVED:\n{payload}")
                # Replace with your real action executor
                await asyncio.sleep(10)
                print("ACTION END (10s window complete)")
        finally:
            self._queue.task_done()  # Mark the task as done
This way, each task gets handled right when it’s enqueued, no waiting around for all chunks to gather. If you have any questions or want to explore this further, just let me know—I’m here to help! Sources: livekit-agents/livekit/agents/ipc/proc_pool.py | Debugging Audio/Video Sync Issues in LiveKit Publishing | meditation_assistant/README.mdoc | stream_audio.py
f
async def _worker(self) -> None: """ Continuously drains the queue. As soon as the first task is enqueued, this coroutine wakes up and starts processing; it keeps working while there are items in the queue. """ while True: kind, payload = await self._queue.get() try: if kind == "speak": print(f"START SPEAKING: {payload}") await self.session.say(payload, allow_interruptions=True) print(f"FINISHED SPEAKING: {payload}") elif kind == "action": print("ACTION START") print(f"ACTIONS RECEIVED:\n{payload}") # TODO: replace with your real action executor await asyncio.sleep(10) print("ACTION END (10s window complete)") finally: self._queue.task_done() it is currently doing that?
t
Thank you for sharing your implementation! Your current
_worker
function is set up to process tasks right away as they enter the queue. The line
await self._queue.get()
makes sure the worker picks up each task as soon as it’s available, and
self._queue.task_done()
nicely marks the task as completed after it’s processed. If you’re noticing any delays or that tasks are being processed in batches, it might be helpful to take a closer look at how tasks are being added to the queue or how the
llm_node
function is interacting with it. For instance, if
llm_node
is holding onto chunks before adding them to the queue, that could be causing the delay you’re seeing. To make sure tasks are processed immediately, you might want to check that: • Tasks are being added to
self._queue
as soon as they’re identified within
llm_node
. • The
yield
statement inside
llm_node
isn’t causing any unintended pauses. If you’d like, I’m here to help review your
llm_node
function or debug the task flow together. Just let me know!
f
how does your llm event loop work, if i return soemthing to eventloop and then llm have more chunks to process, will event loop go to llm_node again or can call some else functions as well?
t
Thank you for your question! Let me walk you through how the LLM event loop in LiveKit handles chunk processing within the
llm_node
. It processes chunks one after another, without interrupting the current task to call other functions. Instead, it keeps going through all the chunks available from the LLM stream within the same asyncio task execution. Here’s a simple breakdown: • The
llm_node
yields chunks (these can be plain strings or
llm.ChatChunk
objects) one by one. • All chunks get processed inside a single async for loop, which makes sure the current LLM inference finishes before moving on to anything else. • Only when the LLM stream is fully done does the pipeline move forward to the next steps, like TTS or other nodes. This approach helps ensure the LLM response stream is fully and reliably processed before the event loop shifts focus. If you’d like me to clarify anything further or if you have specific scenarios you’re curious about, please feel free to ask—I’m here to help! Sources: Pipeline nodes and hooks | LiveKit Docs | livekit-agents/livekit/agents/voice/agent_session.py | Agents v0.x migration guide - Python | LiveKit Docs | Agents v0.x migration guide - Node.js | LiveKit Docs
f
• All chunks get processed inside a single async for loop, which makes sure the current LLM inference finishes before moving on to anything else. is this the reason i am not able to call speak function and take action list?
t
Hi there! It looks like this might be why your
speak
function and
action_list
aren’t being processed as you expected. Because the LLM inference task handles all chunks within a single async for loop, it doesn’t give control back to the event loop until it finishes processing all the chunks. This can cause tasks like enqueuing
speak
or
action_list
to be delayed until the entire LLM response is done. To help with this, you can tweak your
llm_node
implementation to yield control back to the event loop right after enqueuing each task. For instance, adding an
await asyncio.sleep(0)
or something similar lets the event loop handle those enqueued tasks right away:
Copy code
async def llm_node(self, chat_ctx, tools, model_settings):
    buffer = ""
    tag_pairs = [
        ("<speak>", "</speak>", "speak"),
        ("<action_list>", "</action_list>", "action"),
    ]

    async for chunk in Agent.default.llm_node(self, chat_ctx, tools, model_settings):
        if chunk.delta and chunk.delta.content:
            buffer += chunk.delta.content

        while True:
            earliest = None
            for open_tag, close_tag, kind in tag_pairs:
                s = buffer.find(open_tag)
                if s == -1:
                    continue
                e = buffer.find(close_tag, s + len(open_tag))
                if e == -1:
                    continue
                if earliest is None or s < earliest[0]:
                    earliest = (s, e, kind, open_tag, close_tag)

            if earliest is None:
                break

            s, e, kind, open_tag, close_tag = earliest
            inner = buffer[s + len(open_tag): e].strip()
            buffer = buffer[:s] + buffer[e + len(close_tag):]

            if inner:
                await self._queue.put((kind, inner))
                print(f"ENQUEUED {kind.upper()}: {inner}")
                await asyncio.sleep(0)  # Yield control to event loop
                break
This way, the event loop can jump in and process enqueued tasks like
speak
and
action_list
right away, even while the LLM is still generating chunks. Please feel free to reach out if you’d like any more help with implementing this—I’m here to support you!