adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Live Mode: User text messages aren't saved to session history

Open ac-machache opened this issue 1 year ago • 2 comments

Issue: Text input not saved in session history during run_live

When I use an agent in run_live mode, I've found a critical bug: if the user sends a plain text message, it's sent to the model, but it never gets saved to the session history. The model gets the message for the current turn, but the conversation context is immediately lost for all future turns.

This only happens with text. Audio input works fine because the Gemini API sends back a transcription event, which the ADK correctly saves. The API doesn't "echo" back plain text, so the ADK was never creating a user event for it.


The Workaround

The solution is to make sure the ADK creates a user event for text messages before they are sent to the model. After a lot of debugging, we found the right way to do this without breaking the asyncio loop or causing other bugs.

The workaround involves two changes to src/google/adk/flows/llm_flows/base_llm_flow.py:


1. Update _send_to_model to be an async generator that yields a user event for text messages

This is the core of the workaround. It creates the event at the source:

if (
    live_request.content
    and live_request.content.parts
    and live_request.content.parts[0].text
):
    user_event = Event(
        invocation_id=invocation_context.invocation_id,
        author='user',
        content=live_request.content,
    )
    yield user_event  # <-- This creates the event we were missing
    await llm_connection.send_content(live_request.content)

2. Update the run_live method to handle the event generator properly

To avoid a TypeError, use a background handler that consumes the generator and puts the events onto an asyncio.Queue. The main run_live loop then pulls events from that queue.

# In run_live:
async def send_handler():
    """Consumes the _send_to_model generator and puts events on the queue."""
    async for event in self._send_to_model(llm_connection, invocation_context):
        await event_queue.put(event)

# ... (similar handler for _receive_from_model)

send_task = asyncio.create_task(send_handler())
receive_task = asyncio.create_task(receive_handler())

# The main loop is now simple and just pulls from the queue
while True:
    event = await event_queue.get()
    if event is None:
        break
    yield event

Full Updated Code

async def run_live(
    self,
    invocation_context: InvocationContext,
) -> AsyncGenerator[Event, None]:
    """Runs the flow using live api."""
    llm_request = LlmRequest()
    event_id = Event.new_id()

    async for event in self._preprocess_async(invocation_context, llm_request):
        yield event
    if invocation_context.end_invocation:
        return

    llm = self.__get_llm(invocation_context)
    async with llm.connect(llm_request) as llm_connection:
        if llm_request.contents:
            with tracer.start_as_current_span('send_data'):
                if invocation_context.transcription_cache:
                    from . import audio_transcriber
                    audio_transcriber = audio_transcriber.AudioTranscriber(
                        init_client=True if invocation_context.run_config.input_audio_transcription is None else False
                    )
                    contents = audio_transcriber.transcribe_file(invocation_context)
                    await llm_connection.send_history(contents)
                    invocation_context.transcription_cache = None
                    trace_send_data(invocation_context, event_id, contents)
                else:
                    await llm_connection.send_history(llm_request.contents)
                    trace_send_data(invocation_context, event_id, llm_request.contents)

        event_queue = asyncio.Queue()

        async def send_handler():
            async for event in self._send_to_model(llm_connection, invocation_context):
                await event_queue.put(event)

        async def receive_handler():
            try:
                async for event in self._receive_from_model(
                    llm_connection, event_id, invocation_context, llm_request
                ):
                    await event_queue.put(event)
            finally:
                await event_queue.put(None)

        send_task = asyncio.create_task(send_handler())
        receive_task = asyncio.create_task(receive_handler())
        tasks = {send_task, receive_task}

        try:
            while True:
                event = await event_queue.get()
                if event is None:
                    break
                yield event

                if event.get_function_responses():
                    invocation_context.live_request_queue.send_content(event.content)
                if (
                    event.content
                    and event.content.parts
                    and event.content.parts[0].function_response
                    and event.content.parts[0].function_response.name == 'transfer_to_agent'
                ):
                    await asyncio.sleep(1)
                    send_task.cancel()
                    await llm_connection.close()
                if (
                    event.content
                    and event.content.parts
                    and event.content.parts[0].function_response
                    and event.content.parts[0].function_response.name == 'task_completed'
                ):
                    await asyncio.sleep(1)
                    send_task.cancel()
                    return
        finally:
            for task in tasks:
                if not task.done():
                    task.cancel()
            await asyncio.gather(*tasks, return_exceptions=True)

async def _send_to_model(
    self,
    llm_connection: BaseLlmConnection,
    invocation_context: InvocationContext,
) -> AsyncGenerator[Event, None]:
    """Sends data to model and yields user events for text messages."""
    while True:
        live_request_queue = invocation_context.live_request_queue
        try:
            live_request = await asyncio.wait_for(
                live_request_queue.get(), timeout=0.25
            )

            if invocation_context.active_streaming_tools:
                for active_streaming_tool in invocation_context.active_streaming_tools.values():
                    if active_streaming_tool.stream:
                        active_streaming_tool.stream.send(live_request)
            await asyncio.sleep(0)
        except asyncio.TimeoutError:
            continue

        if live_request.close:
            await llm_connection.close()
            return

        if live_request.activity_start:
            await llm_connection.send_realtime(types.ActivityStart())
        elif live_request.activity_end:
            await llm_connection.send_realtime(types.ActivityEnd())
        elif live_request.blob:
            if not invocation_context.transcription_cache:
                invocation_context.transcription_cache = []
            if not invocation_context.run_config.input_audio_transcription:
                invocation_context.transcription_cache.append(
                    TranscriptionEntry(role='user', data=live_request.blob)
                )
            await llm_connection.send_realtime(live_request.blob)

        if (
            live_request.content
            and live_request.content.parts
            and live_request.content.parts[0].text
        ):
            user_event = Event(
                invocation_id=invocation_context.invocation_id,
                author='user',
                content=live_request.content,
            )
            yield user_event
            await llm_connection.send_content(live_request.content)
        elif live_request.content:
            await llm_connection.send_content(live_request.content)

ac-machache avatar Jul 25 '25 11:07 ac-machache

We are working on the support.

hangfei avatar Aug 15 '25 19:08 hangfei

This is fixed now. Please try the latest version.

hangfei avatar Nov 08 '25 04:11 hangfei