after_agent_callback is not replacing the agent output but add the callback output to the original agent output
Describe the bug The after_agent_callback is not replacing the original output of the agent but add the output generated by the callback to the original agent's output.
To Reproduce
async def overwrite_refactored_search_results(callback_context: CallbackContext) -> Optional[types.Content]:
"""
Owerwrite the response from the refactored_search_agent.
:param callback_context: the context
:return: a confirmation message that the search was successful or not.
"""
# Get the name of the agent calling this callback
agent_name = callback_context.agent_name
print(f"[Callback] After model call for agent: {agent_name}")
# List the existing state variables for debugging
print(f"[Callback] Existing state variables: {callback_context.state.to_dict().keys()}")
# check if the 'refactored_search_results' variable can be found in the state
if 'refactored_search_results' in callback_context.state and 'search_results' in callback_context.state:
return types.Content(
parts=[types.Part(text="The original search results and the refactored search results have been preserved")],
role="model"
)
else:
return types.Content(
parts=[types.Part(text="Sorry, I was not able to retrieve anything intersting from the Web.")],
role="model"
)
class informationChunk(BaseModel):
companies: List[str] = Field(description="The companies mentioned in the news")
news: str = Field(description="The news content")
date: str = Field(description="The date of the news")
origin: str = Field(description="The origin of the news")
class informationChunks(BaseModel):
informations: List[informationChunk] = Field(description="List of information chunks")
date: str = Field(description="Today's date")
refactor_search_agent = LlmAgent(
model='gemini-2.5-flash',
name='refactor_search_agent',
description='A helpful assistant for refactoring the information found on the web following instructions received from the user',
instruction=REFACTOR_SEARCH_PROMPT,
output_schema=informationChunks,
output_key='refactored_search_results',
after_agent_callback=overwrite_refactored_search_results # type: ignore
)
Expected behavior The agent should display the output generated by the after_agent_callback only.
Screenshots If applicable, add screenshots to help explain your problem.
Desktop (please complete the following information):
- OS: [e.g. macOS, Linux, Windows] Linux
- Python version(python -V): 3.13.7
- ADK version(pip show google-adk): 1.18
Model Information:
- Are you using LiteLLM: No
- Which model is being used(e.g. gemini-2.5-pro): gemini 2.5 Flash
Additional context Add any other context about the problem here.
I think you need to return an LLMResponse object (from google.adk.models import LlmResponse) and not just types.Content
I take it back, that's for after_model_callback. I can recreate the issue as well
I ran your example code
Code
from google.genai import types
from google.adk.agents import LlmAgent
from typing import Optional, List
from pydantic import Field, BaseModel
from google.adk.agents.callback_context import CallbackContext
import asyncio
import dotenv
dotenv.load_dotenv()
async def overwrite_refactored_search_results(callback_context: CallbackContext) -> Optional[types.Content]:
"""
Owerwrite the response from the refactored_search_agent.
:param callback_context: the context
:return: a confirmation message that the search was successful or not.
"""
agent_name = callback_context.agent_name
print(f"[Callback] After model call for agent: {agent_name}")
print(f"[Callback] Existing state variables: {callback_context.state.to_dict().keys()}")
if 'refactored_search_results' in callback_context.state and 'search_results' in callback_context.state:
return types.Content(
parts=[types.Part(text="The original search results and the refactored search results have been preserved")],
role="model"
)
else:
return types.Content(
parts=[types.Part(text="Sorry, I was not able to retrieve anything intersting from the Web.")],
role="model"
)
class informationChunk(BaseModel):
companies: List[str] = Field(description="The companies mentioned in the news")
news: str = Field(description="The news content")
date: str = Field(description="The date of the news")
origin: str = Field(description="The origin of the news")
class informationChunks(BaseModel):
informations: List[informationChunk] = Field(description="List of information chunks")
date: str = Field(description="Today's date")
refactor_search_agent = LlmAgent(
model='gemini-2.5-flash',
name='refactor_search_agent',
description='A helpful assistant for refactoring the information found on the web following instructions received from the user',
instruction="Return randomly generated information that fits the given output schema",
output_schema=informationChunks,
output_key='refactored_search_results',
after_agent_callback=overwrite_refactored_search_results
)
async def main():
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService
from google.genai import types
session_service = InMemorySessionService()
runner = Runner(
agent=refactor_search_agent,
app_name="refactor_search_agent",
session_service=session_service
)
user_content = types.Content(
role='user',
parts=[types.Part(text="Generate sample information chunks about tech companies")]
)
print("Testing refactor_search_agent...\n")
session = await session_service.create_session(
app_name="refactor_search_agent",
user_id="test_user"
)
events = runner.run_async(
user_id="test_user",
session_id=session.id,
new_message=user_content
)
async for event in events:
if event.is_final_response():
print("=== Final Response ===")
print(event.content.parts[0].text)
print("\n=== State Variables ===")
if hasattr(event, 'state') and event.state:
print(event.state)
elif hasattr(event, 'content') and event.content:
print(f"Event: {event.content}")
if __name__ == '__main__':
asyncio.run(main())
and got this output, which shows that we received 2 final_response events
Testing refactor_search_agent...
=== Final Response ===
{"informations": [{"companies": ["TechInnovate Inc.", "GlobalSoft Solutions"], "news": "TechInnovate Inc. announced a record-breaking quarter, largely driven by its new AI-powered cloud services. Competitor GlobalSoft Solutions is reportedly planning a counter-move with a significant acquisition in the cybersecurity sector.", "date": "2024-03-15", "origin": "Reuters Technology News"}, {"companies": ["QuantumLeap Corp.", "Synaptic Systems"], "news": "QuantumLeap Corp. unveiled its prototype quantum computer, claiming unprecedented processing speeds. Analysts suggest this could challenge Synaptic Systems' dominance in high-performance computing within the next five years.", "date": "2024-03-10", "origin": "The Verge"}, {"companies": ["CyberGuard", "DataSecure Inc."], "news": "CyberGuard reported a major data breach affecting millions of user accounts, raising concerns across the industry. This incident has led to increased demand for DataSecure Inc.'s robust encryption solutions.", "date": "2024-03-12", "origin": "Wired Magazine"}], "date": "2024-03-18"}
=== State Variables ===
[Callback] After model call for agent: refactor_search_agent
[Callback] Existing state variables: dict_keys(['refactored_search_results'])
=== Final Response ===
Sorry, I was not able to retrieve anything intersting from the Web.
=== State Variables ===
I started working on a fix for this. It does however look like this is "expected" behavior as a lot of the unittests are built around the event being appended, rather than replacing the first event. It might make sense to unmark the first event as the final response and update documentation accordingly
Thanks @dylan-apex. Yes, accordingly to the documentation, the second event should be the only final response. And, in a sense, both of us think that it is the expected behavior for the after agent callback.
If/once they accept my PR, this will be fixed
Hello,
Thank you for raising this issue.
We tried to reproduce this issue with google-adk==1.20.0 and observed the same issue.
Hello @wyf7107 , could you please have look at this and share your inputs?
I am seeing a similar issue. Thanks in advance for addressing it!
A related question for the team, I did try working around this by making a sequential agent where the first agent in the series extracts the structured output and the second provides a short response (instead of using a callback). That of course didn't work either because the agent response included the responses of both agents in the sequence. I don't suppose there is a way to suppress the output of an agent within a SequentialAgent series?
Hello @rhaslingerinmarket ,
Thank you for your inputs. Could you please share a minimal code example as well? That would be very helpful for others.
Hello @llalitkumarrr sure ... let me put something together best Rob
Hi @llalitkumarrr Here's a minimal example of what I'm seeing. It's entirely possible I'm doing something outrageously stupid, in which case that would be a fantastic resolution.
What I'm trying to do, is do a structured data extraction using output_schema and output_key, but not have the agent show that in it's response. My reading of the docs was that you can do this by replacing the output using an after agent callback, but it isn't working. You can run this example in adk-web (though I see the same behavior in my own runner/event api call)
Here's a screenshot of what I see when running in adk-web. Using google-adk=1.21.0
and here's the code:
from pydantic import BaseModel, Field
from google.adk.agents.llm_agent import LlmAgent
from google.adk.agents.callback_context import CallbackContext
from google.genai import types
class Email(BaseModel):
subject: str = Field(description="The subject line of the email")
body: str = Field(description="The body of the email")
sender: str = Field(description="The sender of the email")
recipient: str = Field(description="The recipient of the email")
async def hide_json(callback_context: CallbackContext) -> types.Content:
return types.Content(parts=[types.Part(text="Email successfully extracted")], role="model")
root_agent = LlmAgent(
name="email_agent",
description="An agent that processes email messages and extracts relevant information.",
instruction="Based on the user's request generate an email according to the structured schema Email.",
model="gemini-2.5-flash",
output_key="email_json",
output_schema=Email,
after_agent_callback=hide_json,
)
incidentally I have "reasons" why I can't wrap the agent in an AgentTool and bury the json that way. I have a case where I needed to do structured extraction more deterministically, so this was part of a custom agent class
@llalitkumarrr hope you had a good holiday. I'm sure you've got lots on your plate but wanted to bump this back to the top of the stack. thanks in advance
@jeromemassot since you were the original author of this issue ... I don't suppose you found a workaround? thx - Rob
@rhaslingerinmarket Really the only thing you can do is intercept the responses before they go to your UI and only take the last final response. You can see the associated PR for an idea of how to do it. You can also use my fork if you dont need any recent features.
thanks @dylan-apex .... hopefully this will be fixed at some point. I figured it should work because it's an example the docs about the use of after agent callbacks ... but seems it doesn't yet.
Hello @ryanaiagent ,
Could you please take a look at the PR associated with this issue and suggest the next steps for merging?
thanks in advance @llalitkumarrr and @ryanaiagent .... I did follow @dylan-apex suggestion and just filtered any json out of of the text my api call uses ... it works for now but it's pretty hacky.
Agree that this seems to be a bug.
The documentation states: "Purpose: Useful for cleanup tasks, post-execution validation, logging the completion of an agent's activity, modifying final state, or augmenting/replacing the agent's final output." here.
But then in the API reference it states: "When the content is present, an additional event with the provided content will be appended to event history as an additional agent response." here
When we want to augment the agents final response we have to use an after_model callback and have a check that it is the final response
I think the implications go beyond just removing the structured output from whatever is displayed to the user. The structured output also remains in the chat history. This may, or may not be the intent, not sure. I ended up having to override a bunch of methods and scrub the chat history to get the desired behavior from my agent.
Thanks for the report, and sorry this sat so long.
The append behaviour is intended. after_agent_callback is defined to append its returned Content after the agent's own response rather than replace it, and that's what the unit tests assert.
The reason it looked like a bug is that our public documentation said the opposite. That was a docs error and it has since been corrected — google/adk-docs#1269.
If you want replacement rather than append, the hook you're looking for is after_model_callback. Its contract is explicit:
Returns: The content to return to the user. When present, the actual model response will be ignored and the provided content will be returned to user.
One caveat specific to your snippet: you have output_schema=informationChunks on refactor_search_agent. With output_schema set, the agent's final text is still validated against that schema before being written to output_key, so a plain-text replacement won't survive that path.
For what you're actually doing — keep the structured result in state, show the user a short confirmation — the cleaner shape is to leave refactor_search_agent as a pure structured-output agent (output_schema + output_key, no callback), and let the parent or next agent produce the user-facing sentence from {refactored_search_results}.
Closing as working-as-intended with the documentation now fixed. Happy to reopen if after_model_callback doesn't get you there.