Skip to content

fix: provide correct context for OTel tracing in parallel_agent.py #2559

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
10 changes: 8 additions & 2 deletions src/google/adk/agents/parallel_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from __future__ import annotations

import asyncio
import contextvars
from typing import Any
from typing import AsyncGenerator
from typing import ClassVar
Expand Down Expand Up @@ -63,8 +64,11 @@ async def _merge_agent_run(
Yields:
Event: The next event from the merged generator.
"""
# asyncio.create_task seems to be using a wrong context and breaks context
# propagation for OTel traces. To fix it, we pass the context explicitly.
ctx = contextvars.copy_context()
tasks = [
asyncio.create_task(events_for_one_agent.__anext__())
asyncio.create_task(events_for_one_agent.__anext__(), context=ctx)
for events_for_one_agent in agent_runs
]
pending_tasks = set(tasks)
Expand All @@ -80,7 +84,9 @@ async def _merge_agent_run(
# Find the generator that produced this event and move it on.
for i, original_task in enumerate(tasks):
if task == original_task:
new_task = asyncio.create_task(agent_runs[i].__anext__())
new_task = asyncio.create_task(
agent_runs[i].__anext__(), context=ctx
)
tasks[i] = new_task
pending_tasks.add(new_task)
break # stop iterating once found
Expand Down
Loading