Skip to content

feat: add turn_id to Event for grouping streaming chunks by LLM call#4815

Closed
ferponse wants to merge 1 commit into
google:mainfrom
ferponse:feat/add-turn-id-to-streaming-events
Closed

feat: add turn_id to Event for grouping streaming chunks by LLM call#4815
ferponse wants to merge 1 commit into
google:mainfrom
ferponse:feat/add-turn-id-to-streaming-events

Conversation

@ferponse

Copy link
Copy Markdown
Contributor

Summary

  • Adds an optional turn_id field to Event that groups all streaming chunks belonging to the same LLM call
  • Within a single invocation the LLM may be called multiple times (text → tool call → text). Each call produces events that share the same turn_id, while id changes on every yield
  • Consumers can use this field to trivially separate streaming chunks into message bubbles without brittle heuristics based on event type transitions

Problem

When using runner.run_async() with StreamingMode.SSE, there is no way to distinguish which partial streaming chunks belong to which LLM response turn. The invocation_id is shared across all events in the invocation, and id changes on every yield. The only workaround is observing transition patterns (partial→function_call→function_response), which is fragile.

Solution

A new turn_id: Optional[str] field on Event:

  • Generated once per LLM call in _run_one_step_async
  • Remains the same across all partial chunks and the final aggregated event of that call
  • Changes when a new LLM call starts (next iteration of the while True loop in run_async)
  • Also set in the BIDI (live streaming) flow for consistency
  • None by default, so existing code is unaffected

Changes

File Change
src/google/adk/events/event.py Added turn_id field with docstring
src/google/adk/flows/llm_flows/base_llm_flow.py Generate and assign turn_id when creating model_response_event (SSE + BIDI flows)
tests/unittests/flows/llm_flows/test_turn_id.py 3 new tests covering partial chunks grouping, final response, and multi-turn separation

Test plan

  • test_partial_chunks_share_same_turn_id — partial chunks from one LLM call share the same turn_id
  • test_turn_id_present_on_final_response — a single final response carries a turn_id
  • test_different_llm_calls_get_different_turn_ids — events from separate LLM calls (text → tool → text) have different turn_ids
  • All 443 existing flow + runner tests pass unchanged

@google-cla

google-cla Bot commented Mar 13, 2026

Copy link
Copy Markdown

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a significant enhancement to how streaming events from Large Language Models (LLMs) are managed and consumed. By adding a turn_id to Event objects, it provides a robust and explicit mechanism to group related streaming chunks that originate from a single LLM response turn. This change simplifies the processing of streaming data, enabling more reliable and intuitive construction of user interfaces that display LLM outputs.

Highlights

  • New turn_id field: An optional turn_id field was added to the Event class to group all streaming chunks belonging to the same LLM call.
  • Improved streaming chunk grouping: This field allows consumers to trivially separate streaming chunks into message bubbles without relying on fragile heuristic patterns.
  • Turn ID generation: The turn_id is generated once per LLM call and remains constant across all partial chunks and the final aggregated event of that call, changing only when a new LLM call starts.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/google/adk/events/event.py
    • Added the turn_id field with a detailed docstring to the Event class.
  • src/google/adk/flows/llm_flows/base_llm_flow.py
    • Implemented the generation and assignment of turn_id when creating model_response_event for both Server-Sent Events (SSE) and Bidirectional (BIDI) streaming flows.
  • tests/unittests/flows/llm_flows/test_turn_id.py
    • Added new unit tests to verify that partial chunks share the same turn_id.
    • Added a test to ensure turn_id is present on final response events.
    • Included a test to confirm that different LLM calls receive distinct turn_ids.
Activity
  • The author ferponse has introduced a new feature to add turn_id to Event objects.
  • Comprehensive tests have been added to validate the functionality of turn_id across various streaming scenarios.
  • The test plan confirms that all existing flow and runner tests pass, indicating no regressions.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@adk-bot

adk-bot commented Mar 13, 2026

Copy link
Copy Markdown
Collaborator

Response from ADK Triaging Agent

Hello @ferponse, thank you for creating this PR!

Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA). You can visit https://cla.developers.google.com/ to see your current agreements or to sign a new one.

This information will help reviewers to review your PR more efficiently. Thanks!

@adk-bot adk-bot added the core [Component] This issue is related to the core interface and implementation label Mar 13, 2026

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a turn_id to the Event class, which is a great addition for grouping streaming chunks from a single LLM call. The implementation for the non-live run_async flow looks correct. However, the implementation for the live streaming (run_live) flow has a critical issue where a new turn_id is generated for every chunk, which defeats the purpose of this feature. I've left a specific comment with a suggested fix. Additionally, the new tests only cover the run_async flow; adding tests for the run_live flow would be beneficial to prevent such issues.

id=Event.new_id(),
invocation_id=invocation_context.invocation_id,
author=get_author_for_event(llm_response),
turn_id=Event.new_id(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

In the live streaming flow (_receive_from_model), a new turn_id is generated for every event chunk. This prevents grouping chunks that belong to the same LLM turn. The turn_id should remain constant for all events within a single turn.

To fix this, the turn_id should be managed within the scope of _receive_from_model. It should be initialized once before the event-receiving loop and only regenerated after a turn is complete (i.e., when an event with llm_response.turn_complete=True is received).

Example of the logic:

# Inside _receive_from_model
turn_id = Event.new_id()
try:
    while True:
        async with Aclosing(llm_connection.receive()) as agen:
            async for llm_response in agen:
                # ...
                model_response_event = Event(
                    # ...,
                    turn_id=turn_id, # Use the same turn_id for all chunks
                )
                # ... (process and yield event)
                # ...
                if llm_response.turn_complete:
                    turn_id = Event.new_id() # Generate new id for the next turn

Additionally, please consider adding a unit test for the live streaming scenario to verify this behavior.

When using StreamingMode.SSE, all partial chunks from the same LLM call
now share a stable turn_id (1-based integer counter). This allows
consumers to trivially group streaming chunks by turn without fragile
heuristics based on event type transitions.

The invocation_id groups all events in a single agent invocation, while
id changes on every yield. The new turn_id sits in between: it stays
constant across all events produced by one LLM call and increments when
a new call starts (e.g. after tool execution).
@ferponse ferponse force-pushed the feat/add-turn-id-to-streaming-events branch from ed704ea to dc971b9 Compare March 13, 2026 11:45
@ferponse

Copy link
Copy Markdown
Contributor Author

Closing in favour of a new PR with improved implementation (turn_id as integer counter instead of UUID).

@ferponse ferponse closed this Mar 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core [Component] This issue is related to the core interface and implementation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants