Bug: Failed to detach context
Describe the bug I have created an agent to find PDF files on a given public website, and then to parallel download. The agent runs successfully. But DOESN'T stop gracefully as the below error is produced: Failed to detach context
To Reproduce Steps to reproduce the behavior:
- Use my agent.py
- Run in UI
- My prompt was:
find all pdf links from this page
https://www.posta-romana.ro/titluri-de-stat.html
then download first 5 pdfs to folder tezaur2025
- See error
2025-04-27 23:07:15,386 - INFO - fast_api.py:634 - Generated event in agent run streaming: {"content":{"parts":[{"text":"I have downloaded the first 5 PDFs to the 'tezaur2025' folder. All downloads were successful.\n"}],"role":"model"},"invocation_id":"e-ab97422f-2aea-46b8-af78-7815ddf6efe4","author":"pdf_downloader","actions":{"state_delta":{},"artifact_delta":{},"requested_auth_configs":{}},"branch":"parallel_download_agent.pdf_downloader","id":"dwYbbIeM","timestamp":1745784434.52612}
2025-04-27 23:07:15,386 - ERROR - __init__.py:157 - Failed to detach context
Traceback (most recent call last):
File "D:\wamp\www\vertex_ai - adk\.venv\lib\site-packages\opentelemetry\context\__init__.py", line 155, in detach
_RUNTIME_CONTEXT.detach(token)
File "D:\wamp\www\vertex_ai - adk\.venv\lib\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 0x00000200EE52DC60> at 0x00000200FAD4C280> was created in a different Context
2025-04-27 23:07:15,386 - ERROR - __init__.py:157 - Failed to detach context
Traceback (most recent call last):
File "D:\wamp\www\vertex_ai - adk\.venv\lib\site-packages\opentelemetry\context\__init__.py", line 155, in detach
_RUNTIME_CONTEXT.detach(token)
File "D:\wamp\www\vertex_ai - adk\.venv\lib\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 0x00000200EE52DC60> at 0x00000200FAF9C640> was created in a different Context
Running into the same issue. Error seems to rise after the LLM Agent calls a custom function tool. I am running the example of loop agent specified in the documentation.
# --- Tool Definition ---
def exit_loop(tool_context: ToolContext):
"""
Call this function ONLY when the critique indicates no further changes are needed, signaling the iterative process should end.
No arguments are needed.
This function returns an empty dictionary.
"""
print(f" [Tool Call] exit_loop triggered by {tool_context.agent_name}")
tool_context.actions.escalate = True
# Return empty dict as tools should typically return JSON-serializable output
return {}
This is the log:
2025-04-28 12:46:28,392 - ERROR - __init__.py:157 - Failed to detach context
Traceback (most recent call last):
File "/opt/miniconda3/envs/v3-cfa/lib/python3.12/site-packages/opentelemetry/context/__init__.py", line 155, in detach
_RUNTIME_CONTEXT.detach(token)
File "/opt/miniconda3/envs/v3-cfa/lib/python3.12/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 0x103b142c0> at 0x11be40f80> was created in a different Context
2025-04-28 12:46:28,393 - ERROR - __init__.py:157 - Failed to detach context
Traceback (most recent call last):
File "/opt/miniconda3/envs/v3-cfa/lib/python3.12/site-packages/opentelemetry/context/__init__.py", line 155, in detach
_RUNTIME_CONTEXT.detach(token)
File "/opt/miniconda3/envs/v3-cfa/lib/python3.12/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 0x103b142c0> at 0x1195bd940> was created in a different Context
2025-04-28 12:46:28,393 - ERROR - __init__.py:157 - Failed to detach context
Traceback (most recent call last):
File "/opt/miniconda3/envs/v3-cfa/lib/python3.12/site-packages/opentelemetry/trace/__init__.py", line 587, in use_span
yield span
File "/opt/miniconda3/envs/v3-cfa/lib/python3.12/site-packages/opentelemetry/sdk/trace/__init__.py", line 1105, in start_as_current_span
yield span
File "/opt/miniconda3/envs/v3-cfa/lib/python3.12/site-packages/opentelemetry/trace/__init__.py", line 452, in start_as_current_span
yield span
File "/opt/miniconda3/envs/v3-cfa/lib/python3.12/site-packages/google/adk/agents/base_agent.py", line 142, in run_async
yield event
GeneratorExit
Seeing this error when running the ParallelAgent example as well:
2025-05-02 13:52:16,160 - INFO - fast_api.py:634 - Generated event in agent run streaming: {"content":{"parts":[{"text":"Carbon capture methods include pre-combustion, post-combustion, oxy-fuel combustion, and direct air capture, each with its own advantages, disadvantages, and stage of development, aimed at capturing CO2 from industrial sources or directly from the atmosphere for storage or utilization. These methods are being developed and deployed by various companies and organizations, with ongoing research focusing on improving their efficiency and scalability.\n"}],"role":"model"},"invocation_id":"e-ddd9c3fb-be3d-4bdf-aca7-71bf2f9e6987","author":"CarbonCaptureResearcher","actions":{"state_delta":{"carbon_capture_result":"Carbon capture methods include pre-combustion, post-combustion, oxy-fuel combustion, and direct air capture, each with its own advantages, disadvantages, and stage of development, aimed at capturing CO2 from industrial sources or directly from the atmosphere for storage or utilization. These methods are being developed and deployed by various companies and organizations, with ongoing research focusing on improving their efficiency and scalability.\n"},"artifact_delta":{},"requested_auth_configs":{}},"branch":"ParallelWebResearchAgent.CarbonCaptureResearcher","id":"Uq9XKFfI","timestamp":1746219134.809205}
2025-05-02 13:52:16,160 - ERROR - __init__.py:157 - Failed to detach context
Traceback (most recent call last):
File "/Users/arvind.chandrashekar/Projects/aiops_db-agent/.venv/lib/python3.12/site-packages/opentelemetry/context/__init__.py", line 155, in detach
_RUNTIME_CONTEXT.detach(token)
File "/Users/arvind.chandrashekar/Projects/aiops_db-agent/.venv/lib/python3.12/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 0x107677740> at 0x11d76b200> was created in a different Context
2025-05-02 13:52:16,161 - ERROR - __init__.py:157 - Failed to detach context
Traceback (most recent call last):
File "/Users/arvind.chandrashekar/Projects/aiops_db-agent/.venv/lib/python3.12/site-packages/opentelemetry/context/__init__.py", line 155, in detach
_RUNTIME_CONTEXT.detach(token)
File "/Users/arvind.chandrashekar/Projects/aiops_db-agent/.venv/lib/python3.12/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 0x107677740> at 0x11d7d8d00> was created in a different Context
2025-05-02 13:52:16,179 - INFO - google_llm.py:83 - Sending out request, model: gemini-2.0-flash, backend: vertex, stream: False
2025-05-02 13:52:16,179 - INFO - google_llm.py:89 -
LLM Request:
Note that I swapped out the google_search for a google_search_agent that I passed as an AgentTool:
google_search_agent = LlmAgent(
name="GoogleSearchAgent",
model=GEMINI_MODEL,
instruction="""Your job is to mock search results from Google Search. You will receive a search query and must return a list of mock search results.""",
description="Mocks Google Search results for given queries.",
)
researcher_agent_1 = LlmAgent(
name="RenewableEnergyResearcher",
model=GEMINI_MODEL,
instruction="""You are an AI Research Assistant specializing in energy.
Research the latest advancements in 'renewable energy sources'.
Use the Google Search tool provided.
Summarize your key findings concisely (1-2 sentences).
Output *only* the summary.
""",
description="Researches renewable energy sources.",
tools=[AgentTool(google_search_agent)],
# Store result in state for the merger agent
output_key="renewable_energy_result"
)
same error
researcher_agent_1 = LlmAgent( name="RenewableEnergyResearcher", model=GEMINI_MODEL, instruction="""简短说明下可再生能源。""", output_key="renewable_energy_result" )
Researcher 2: Electric Vehicles
researcher_agent_2 = LlmAgent( name="EVResearcher", model=GEMINI_MODEL, instruction="""简短说明下电动汽车""", output_key="ev_technology_result" )
Researcher 3: Carbon Capture
researcher_agent_3 = LlmAgent( name="CarbonCaptureResearcher", model=GEMINI_MODEL, instruction="""简短说明下碳捕集。""", output_key="carbon_capture_result" )
parallel_research_agent = ParallelAgent( name="ParallelWebResearchAgent", sub_agents=[researcher_agent_1, researcher_agent_2, researcher_agent_3], )
merger_agent = LlmAgent( name="SynthesisAgent", model=GEMINI_MODEL, # Or potentially a more powerful model if needed for synthesis instruction="""您是一个AI助手,负责将研究结果整合成一份结构化报告。
您的主要任务是综合以下研究摘要,明确将发现归因于其来源领域。使用标题对每个主题进行结构化回答。确保报告连贯,并顺畅地整合关键点。
关键:您的整个回答必须完全基于以下“输入摘要”中提供的信息。不要添加任何外部知识、事实或不在这些特定摘要中出现的细节。
输入摘要:
-
可再生能源: {renewable_energy_result}
-
电动汽车: {ev_technology_result}
-
碳捕集: {carbon_capture_result}
输出格式:
总结
仅输出以下格式的结构化报告。不要包括此结构之外的引言或结论性短语,并严格遵循仅使用提供的输入摘要内容。 """, )
root_agent = SequentialAgent( name="ResearchAndSynthesisPipeline", sub_agents=[parallel_research_agent, merger_agent], )
Is this an issue with fast-api specifically?
am also facing the issue with my agent. Ref Ticket Link - https://github.com/google/adk-python/issues/1670
Disabling OTEL (I'm using Langfuse + LiteLLM) removes this error for me.
This is likely an instance of https://github.com/open-telemetry/opentelemetry-python/issues/2606 . Sadly I'm not a OTEL ninja 🤦🏽
https://github.com/google/adk-python/pull/566 should be a fix for this too
Another related one: https://github.com/google/adk-python/issues/1670