ERROR:opentelemetry.context:Failed to detach context
** Please make sure you read the contribution guide and file the issues in the right place. ** Contribution guide.
Describe the bug We have deployed our agent. and getting this issue -
Traceback (most recent call last): File "/home/myuser/.local/lib/python3.11/site-packages/opentelemetry/context/init.py", line 155, in detach _RUNTIME_CONTEXT.detach(token) File "/home/myuser/.local/lib/python3.11/site-packages/opentelemetry/context/contextvars_context.py", line 53, in detach self._current_context.reset(token) ValueError: <Token var=<ContextVar name='current_context' default={} at 0x3e20a81529d0> at 0x3e209c1a1340> was created in a different Context
dependencies list in requirements.txt is as follow:-
python-dotenv>=1.0.0 asyncio google-adk==1.4.2 absl-py==2.2.1 cloudpickle==3.1.1 flake8-pyproject==1.2.3 aiohttp==3.10.11 uv==0.7.14 requests>=2.32.3
To Reproduce Steps to reproduce the behavior:
- Install above dependencies
- Run adk web
- Open '....'
- See error
Desktop (please complete the following information):
- Python version(python -V): 13.3
- ADK version(pip show google-adk): 1.4.2
Model Information: For example, which model is being used. gemini-2.5-pro
Same Issue, Weirdly, it happens once in a while.
Same! Want to upvote this!
Same! It happened with me when i am dynamically create agents and pass them to parallel or sequential agents, because opentelemetry have different contextvar(
+1
Same here... Happening every time we try using a ParallelAgent with sub_agents created at runtime.
what i did was just create a patch in the library that removes the error logging in the exception - i still see the logs of my traces and the code of the agents works fine
We’re seeing this issue quite frequently during peak hours, while it occurs less often at night or on weekends.
On Thu, Jul 17, 2025 at 4:28 PM Friendly Neighborhood Droid < @.***> wrote:
vtwoptwo left a comment (google/adk-python#1670) https://github.com/google/adk-python/issues/1670#issuecomment-3083603867
what i did was just create a patch in the library that removes the error logging in the exception - i still see the logs of my traces and the code of the agents works fine
— Reply to this email directly, view it on GitHub https://github.com/google/adk-python/issues/1670#issuecomment-3083603867, or unsubscribe https://github.com/notifications/unsubscribe-auth/BLBOHXPVNZ77SWAAZKYLEKD3I56WPAVCNFSM6AAAAACAGLOOPWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZTAOBTGYYDGOBWG4 . You are receiving this because you are subscribed to this thread.Message ID: @.***>
--
Please note that this email and all files, information, intents and effects contained herein, and conveyed hereby, shall be construed as strictly and absolutely confidential intellectual property of CropIn, intended solely for use by the addressee. Notwithstanding anything contained herein, this email shall not be construed to give rise to any implied contractual relationship between CropIn and/or its representatives and the recipient/s. In spite of due diligence exercised by CropIn to ensure that this email and all attachments herewith are free from viruses/defects, it will be the sole responsibility of the recipient to proceed with caution, and CropIn and/ or its representatives shall not in any way be liable for any unforeseen security breach arising thereof. If this email has reached you in error, or you are not the intended recipient of such email, you should delete this email along with any attachments from your system, after notification to the sender. Any unauthorised dissemination, disclosure and/ or use of the contents of this communication to anyone for any purpose whatsoever, is strictly prohibited and punishable in law.
+1
I think this is likely due to with statement over python generator.
My theory so far, is: after with statement (for otel span tracing) is out of scope and tries to restore the otel token back to original one, the current token is no long the previous one, since python generator is not strictly FILO stack.
I'm looking into how to solve this. I'd appreciate if anyone can help with a minimal reproducible agent setup for either Sequential or Parallel Agent.
Thanks for your all's patience!
@jawoszek could you look into this further?
@aabmass we can use this issue to track the AsyncGenerator + OTel.
+1, this doesn't happen to us in development (locally built docker container) but in production it happens consistently when trying to utilize a tool and pass off to a subagent :/
Got it, I'll copy my comment from the other issue here then
For some context on what is happening see the following:
- https://github.com/python/cpython/issues/118944
- https://github.com/open-telemetry/opentelemetry-python/issues/2606
- https://logfire.pydantic.dev/docs/reference/advanced/generators/ (uses OTel under the hood)
I would recommend this fix https://github.com/python/cpython/issues/118944#issuecomment-2105661088 as a quick and correct workaround if the issue is an async iterator. Changing from start_as_current_span() -> start_span() is not a great fix because it breaks span parent propagation.
@Jacksunwei I'll work on it, thanks @aabmass for hints!
I seem to be getting it every time I run it, not sure what's causing it
The detach errors were fixed in https://github.com/google/adk-python/pull/2383 for most built-in agents (released in https://github.com/google/adk-python/releases/tag/v1.11.0) and in https://github.com/google/adk-python/pull/2601 for parallel agents (to be released next week).
If anyone encounters this while using adk with custom agents or any other custom code, please make sure that all async generators in the custom code are aclosed.
If anyone still encounters the errors with the fixes and no custom code - please let me know.
Thanks @jawoszek for the great work!
@jawoszek I got the same error on a tutorial example, when using langfuse.
The problem seems to be the break statement here:
user_msg = types.Content(role="user", parts=[types.Part(text="hi")])
async for event in runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=user_msg):
if event.is_final_response():
print(event.content.parts[0].text)
break
As soon as I delete the break statement, the error ValueError: <Token var=<ContextVar name='current_context' default={} at 0x00000218493ABBF0> at 0x0000021858D7BA80> was created in a different Context disappears.
The reason, I wrote the break statement was because of the following tutorial, where also a break statement is included in the same context: https://google.github.io/adk-docs/tutorials/agent-team/#step-1-your-first-agent-basic-weather-lookup
I don't know if it is supposed to work despite the break or if this is just sloppy code inside the tutorial?
My versions: google-adk 1.12.0 langfuse 3.3.0 opentelemetry-api 1.36.0 opentelemetry-exporter-gcp-trace 1.9.0 opentelemetry-exporter-otlp-proto-common 1.36.0 opentelemetry-exporter-otlp-proto-http 1.36.0 opentelemetry-proto 1.36.0 opentelemetry-resourcedetector-gcp 1.9.0a0 opentelemetry-sdk 1.36.0 opentelemetry-semantic-conventions 0.57b0
@Netzeband yes, code in the tutorial was not updated with the fix and the break is triggering the issue. The simplest fix is to follow the aclose() example from https://github.com/google/adk-python/blob/ad81aa54de1f38df580915b7f47834ea8e5f1004/contributing/samples/telemetry/main.py#L51-L61 or using contextlib.aclosing.
Thanks for noticing this, I'll update the tutorial.
@jawoszek Thanks for the response and the suggestions, I will try it out.
So I guess the correct way would be something like this (same thing, just no need for try/finally, and notably we can keep break) as per https://docs.python.org/3/library/contextlib.html#contextlib.aclosing
Significantly,
aclosing()supports deterministic cleanup of async generators when they happen to exit early by break or an exception
with contextlib.aclosing (for Python >= 3.10+):
import contextlib
async with contextlib.aclosing(runner.run_async(...)) as agen:
async for event in agen:
# do your thing
# notably, you can use "break" if required, e.g.:
if event.is_final_response():
# ...
break
with a "polyfill" from google.adk (to support Python < 3.10):
from google.adk.utils.context_utils import Aclosing
async with Aclosing(runner.run_async(...)) as agen:
async for event in agen:
# ...