Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 40 additions & 29 deletions src/google/adk/flows/llm_flows/context/_contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,8 +500,7 @@ def _get_contents(
Returns:
A list of processed contents.
"""
accumulated_input_transcription = ''
accumulated_output_transcription = ''
accumulated_transcription = ''

# Filter out events that are annulled by a rewind, so the rewound history is
# never sent to the LLM. This is the same rewind logic the context compactor
Expand All @@ -515,6 +514,14 @@ def _get_contents(
)
tool_call_ids = _collect_function_call_ids(rewind_filtered_events)

# Preserve adjacency before filtering removes content-less turn boundaries.
next_event_by_id = {
id(event): next_event
for event, next_event in zip(
rewind_filtered_events, rewind_filtered_events[1:]
)
}

# Parse the events, leaving the contents and the function calls and
# responses from the current agent.
raw_filtered_events = [
Expand Down Expand Up @@ -567,39 +574,43 @@ def _get_contents(
for i in range(len(events_to_process)):
event = events_to_process[i]
if not event.content:
# Convert transcription into normal event
if event.input_transcription and event.input_transcription.text:
accumulated_input_transcription += event.input_transcription.text
next_input_transcription = (
events_to_process[i + 1].input_transcription
if i != len(events_to_process) - 1
else None
)
if next_input_transcription and next_input_transcription.text:
continue
event = event.model_copy(deep=True)
event.input_transcription = None
event.content = types.Content(
role='user',
parts=[types.Part(text=accumulated_input_transcription)],
field = (
'input_transcription'
if event.input_transcription and event.input_transcription.text
else 'output_transcription'
)
transcription: types.Transcription | None = getattr(event, field)
if transcription and transcription.text:
accumulated_transcription += transcription.text
next_event = (
events_to_process[i + 1] if i + 1 < len(events_to_process) else None
)
accumulated_input_transcription = ''
elif event.output_transcription and event.output_transcription.text:
accumulated_output_transcription += event.output_transcription.text
next_output_transcription = (
events_to_process[i + 1].output_transcription
if i != len(events_to_process) - 1
else None
next_transcription: types.Transcription | None = getattr(
next_event, field, None
)
if next_output_transcription and next_output_transcription.text:
if (
not transcription.finished
and not event.turn_complete
and not event.interrupted
and next_event is not None
and next_event_by_id.get(id(event)) is next_event
and not next_event.content
and next_transcription
and next_transcription.text
and not next_transcription.finished
and event.author == next_event.author
and event.invocation_id == next_event.invocation_id
and event.live_session_id == next_event.live_session_id
and event.branch == next_event.branch
):
continue
event = event.model_copy(deep=True)
event.output_transcription = None
setattr(event, field, None)
event.content = types.Content(
role='model',
parts=[types.Part(text=accumulated_output_transcription)],
role='user' if field == 'input_transcription' else 'model',
parts=[types.Part(text=accumulated_transcription)],
)
accumulated_output_transcription = ''
accumulated_transcription = ''

is_other_reply = _is_other_agent_reply(agent_name, event)

Expand Down
160 changes: 160 additions & 0 deletions tests/unittests/flows/llm_flows/context/test_contents.py
Original file line number Diff line number Diff line change
Expand Up @@ -2583,3 +2583,163 @@ async def test_include_contents_none_ignores_submitted_tool_result_without_match
pass

assert llm_request.contents == [types.UserContent("current turn question")]


@pytest.mark.parametrize("output", [False, True])
@pytest.mark.parametrize(
"boundary",
[
"finished",
"finished_turn_complete",
"invocation",
"live_session",
"turn_complete",
"interrupted",
],
)
def test_transcriptions_keep_turn_boundaries(
output: bool, boundary: str
) -> None:
"""Separate utterances from the same speaker retain their own text."""
field = "output_transcription" if output else "input_transcription"
author = "test_agent" if output else "user"
events = [
Event(
author=author,
invocation_id="inv1",
**{
field: types.Transcription(
text=text, finished=boundary.startswith("finished")
)
},
)
for text in ("first", "second")
]
if boundary == "invocation":
events[1].invocation_id = "inv2"
elif boundary == "live_session":
events[1].live_session_id = "live2"
elif boundary == "finished_turn_complete":
events.insert(1, Event(author="test_agent", turn_complete=True))
elif boundary in ("turn_complete", "interrupted"):
events.insert(1, Event(author="test_agent", **{boundary: True}))

result = contents._get_contents(None, events, "test_agent")

role = "model" if output else "user"
assert result == [
types.Content(role=role, parts=[types.Part(text="first")]),
types.Content(
role="user" if output and boundary == "live_session" else role,
parts=[
testing_utils.other_agent_preamble_part(),
testing_utils.other_agent_part("[test_agent] said:", "second"),
]
if output and boundary == "live_session"
else [types.Part(text="second")],
),
]


@pytest.mark.parametrize("output", [False, True])
@pytest.mark.parametrize("finished", [False, None])
def test_unfinished_transcription_chunks_merge(
output: bool, finished: bool | None
) -> None:
"""Consecutive unfinished chunks from one turn still form one utterance."""
field = "output_transcription" if output else "input_transcription"
events = [
Event(
author="test_agent" if output else "user",
invocation_id="inv1",
**{field: types.Transcription(text=text, finished=finished)},
)
for text in ("hello", " there")
]
originals = [event.model_copy(deep=True) for event in events]

result = contents._get_contents(None, events, "test_agent")

assert result == [
types.Content(
role="model" if output else "user",
parts=[types.Part(text="hello there")],
)
]
assert events == originals


@pytest.mark.parametrize("output", [False, True])
@pytest.mark.parametrize("finished_first", [False, True])
def test_finished_transcription_is_not_merged_with_partial(
output: bool, finished_first: bool
) -> None:
"""A finished record stays separate from an adjacent unfinished record."""
field = "output_transcription" if output else "input_transcription"
events = [
Event(
author="test_agent" if output else "user",
**{field: types.Transcription(text=text, finished=finished)},
)
for text, finished in (
("first", finished_first),
("second", not finished_first),
)
]

result = contents._get_contents(None, events, "test_agent")

assert [part.text for content in result for part in content.parts or []] == [
"first",
"second",
]


def test_input_and_output_transcriptions_remain_separate() -> None:
"""Input and output text keep their respective user and model roles."""
events = [
Event(author="user", input_transcription=types.Transcription(text="hi")),
Event(
author="test_agent",
output_transcription=types.Transcription(text="hello"),
),
]

result = contents._get_contents(None, events, "test_agent")

assert result == [
types.Content(role="user", parts=[types.Part(text="hi")]),
types.Content(role="model", parts=[types.Part(text="hello")]),
]


@pytest.mark.asyncio
@pytest.mark.parametrize("output", [False, True])
async def test_finished_transcriptions_survive_session_round_trip(
output: bool,
) -> None:
"""Persisted final live records remain separate when replayed as history."""
from google.adk.sessions import InMemorySessionService

service = InMemorySessionService()
session = await service.create_session(app_name="app", user_id="user")
field = "output_transcription" if output else "input_transcription"
for text in ("first", "second"):
await service.append_event(
session=session,
event=Event(
author="test_agent" if output else "user",
**{field: types.Transcription(text=text, finished=True)},
),
)
restored = await service.get_session(
app_name="app", user_id="user", session_id=session.id
)

assert restored is not None
result = contents._get_contents(None, restored.events, "test_agent")

assert [part.text for content in result for part in content.parts or []] == [
"first",
"second",
]
Original file line number Diff line number Diff line change
Expand Up @@ -683,3 +683,40 @@ async def test_relayed_tool_call_arguments_are_fenced():
)
assert relayed.count(_END_MARKER) == 1
assert relayed.endswith(_END_MARKER)


@pytest.mark.asyncio
@pytest.mark.parametrize("finished", [False, True])
async def test_output_transcriptions_keep_each_speakers_attribution(
finished: bool,
) -> None:
"""Adjacent live output records preserve each agent's quoted words."""
agent = Agent(model="gemini-2.5-flash", name="current_agent")
llm_request = LlmRequest(model="gemini-2.5-flash")
invocation_context = await testing_utils.create_invocation_context(
agent=agent
)
invocation_context.session.events = [
Event(
author=author,
invocation_id="inv1",
output_transcription=types.Transcription(
text=text, finished=finished
),
)
for author, text in (("agent_a", "one"), ("agent_b", "two"))
]

async for _ in request_processor.run_async(invocation_context, llm_request):
pass

assert llm_request.contents == [
types.Content(
role="user",
parts=[
testing_utils.other_agent_preamble_part(),
testing_utils.other_agent_part(f"[{author}] said:", text),
],
)
for author, text in (("agent_a", "one"), ("agent_b", "two"))
]