You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
user files not saved as artifact when using ADK web #2176
When using the command adk web to test my agent, I face the following issues:
When documents are added to the chat, they are not saved as artifacts.
It is impossible to run using adk web and your customer runner and/or modify RunConfig() when using ADK web.
From what I have seen, it seems to be something with the RunConfig() default parameters, especially the save_input_blobs_as_artifacts parameter that is by default set at False. Therefore, in the Runner._append_new_message_to_session, the documents are never stored in an artifact.
I tested it by modifying the google.adk.runners.py file's if condition at line 306 and removing the save_input_blobs_as_artifacts, and it works just fine.
My idea for a solution would be to accept or detect a runner initialized in the agent file in the adk web command to directly use the user-chosen parameter for the test using the UI.
Reacted by Piyush, Anjani , Shivendra66Degrees, HuKang and MiroslavPetrik
@GWeale The use case which you provided in the medium article , i am unable to test as it always gives session id not found. I tried integrating the artifacts plugin by defining App as you mentioned but the moment i introduced App definition i start getting session not found.
@GWeale The use case which you provided in the medium article , i am unable to test as it always gives session id not found. I tried integrating the artifacts plugin by defining App as you mentioned but the moment i introduced App definition i start getting session not found.
@GWeale The use case which you provided in the medium article , i am unable to test as it always gives session id not found. I tried integrating the artifacts plugin by defining App as you mentioned but the moment i introduced App definition i start getting session not found.
Can anyone help me ?
Same
I solved it by mentioning the app_name exactly same as the parent directory name.
Posting a small working example, for others who come searching. Works with ADK 1.15.1, Python 3.12
import os,sys,io
from google.adk.agents import Agent
from google.adk.tools import ToolContext,load_artifacts
from google.adk.apps import App
from google.adk.plugins.save_files_as_artifacts_plugin import SaveFilesAsArtifactsPlugin
############################################################
async def Process_User_File(tool_context: ToolContext)-> dict:
'''
Reads a file from a user and counts the number of lines
Arguments:
tool_context: The ADK context object used to load the artifact.
Returns a dict {message: str}
'''
d = {'message':''}
artifacts = await tool_context.list_artifacts()
most_recent_file = artifacts[-1]
try:
artifact_content = await tool_context.load_artifact(filename=most_recent_file)
file_name = artifact_content.inline_data.display_name
data_bytes = artifact_content.inline_data.data
nlines = len(io.BytesIO(data_bytes).readlines())
d['message'] = f'The uploaded file has {nlines} lines'
except Exception as e:
d['message'] = str(e)
return d
############################################################
root_agent = Agent(
name="FileReader",
model="gemini-2.0-flash",
description=("Testing file reader"),
instruction=('''
You will help with the uploading of a file and counting lines in the file.
Upon a user request
* ask the user to upload the file
* wait for load_artifacts to complete
* call Process_User_File with the tool context
* Respond to the user with the returned dict from Process_User_File
'''
),
tools=[load_artifacts,Process_User_File],
)
app = App(
name="FileReader",
root_agent=root_agent,
plugins=[SaveFilesAsArtifactsPlugin()],
)
Reacted by Jeffrey Dick, Sandeep and Arnab Chaudhury
I’ve been testing the newly released SaveFilesAsArtifactsPlugin(), but I’m still unable to retrieve the saved artifact or its content. Could someone please take a look at my project setup and confirm if I might be missing something? 🙏 Much appreciated!
Context:
I’m building a Google Agent using google-adk that connects to an MCP server. The MCP server handles PDF operations such as extract, merge, and add watermark.
Expected flow:
User uploads a file in the chat.
The Agent automatically saves it as an artifact.
The artifact data is passed to the MCP tool for processing.
The MCP tool returns an output file.
The Agent saves this output as an artifact and returns it to the user in the chat.
Thanks in advance for any insights or suggestions!
from __future__ import annotations
import os
import uuid
import base64
import logging
from typing import Any, Dict
import io
from google.adk.plugins.save_files_as_artifacts_plugin import SaveFilesAsArtifactsPlugin
from google.adk.tools import load_artifacts
from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.tools.tool_context import ToolContext
from google.adk.tools.mcp_tool.mcp_toolset import (
McpToolset,
StdioConnectionParams,
StdioServerParameters,
)
from google.genai import types as gt
async def check_uploaded_document(tool_context: ToolContext) -> Dict[str, str]:
"""
Automatically detects and loads the most recently uploaded document.
Args:
tool_context: The context object provided by the ADK framework, containing state.
Returns:
A dictionary with filename, mime_type, and data_b64.
"""
try:
artifact_ids = await tool_context.list_artifacts()
print(f"Found {len(artifact_ids)} artifacts: {artifact_ids}")
# Check if any artifacts exist
if not artifact_ids:
return {
"status": "no_artifacts",
"message": "No files uploaded yet. Please upload a document first.",
"filename": "",
"mime_type": "",
"data_b64": ""
}
# Get the most recent artifact (last in the list)
artifact_id = artifact_ids[-1]
print(f"Reading artifact with ID: {artifact_id}")
# Load the artifact
artifact_content = await tool_context.load_artifact(artifact_id)
print("The doc type: ", artifact_content.inline_data.mime_type)
file_name = artifact_content.inline_data.display_name
pdf_bytes = artifact_content.inline_data.data
return {
"status": "success",
"filename": file_name,
"mime_type": artifact_content.inline_data.mime_type,
"data_b64": base64.b64encode(pdf_bytes).decode("utf-8")
}
except Exception as e:
print(f"Error in check_uploaded_document: {e}")
return {
"status": "error",
"message": f"Failed to load artifact: {e}",
"filename": "",
"mime_type": "",
"data_b64": ""
}
async def save_to_artifact(tool_context: ToolContext, args: Dict[str, Any]) -> Dict[str, Any]:
"""Save MCP tool output back to artifacts."""
filename = args.get("filename", f"result_{uuid.uuid4().hex[:8]}.pdf")
content_b64 = args.get("content", "")
mime_type = args.get("mime_type", "application/pdf")
if not content_b64:
return {"status": "error", "message": "No content to save"}
try:
data = base64.b64decode(content_b64)
part = gt.Part.from_bytes(data=data, mime_type=mime_type)
version = await tool_context.save_artifact(filename, part)
return {
"status": "success",
"filename": filename,
"version": version,
"size_bytes": len(data)
}
except Exception as e:
return {"status": "error", "message": f"Save failed: {e}"}
pdf_lumin_mcp = McpToolset(
connection_params=StdioConnectionParams(
command="python3",
args=["path_to_mcp_server"],
timeout=30.0,
server_params=StdioServerParameters(
command="python3",
args=["path_to_mcp_server"],
),
)
)
root_agent = Agent(
name="unified_pdf_agent",
model="gemini-2.0-flash",
description="Simplified PDF agent with automatic artifact saving.",
instruction=(
"You are a PDF processing agent. Files uploaded by users are automatically saved as artifacts.\n"
"\n"
"1. When user uploads a file and asks for processing (split, merge, OCR, etc.), automatically:\n"
" - Use `load_artifacts` to load the uploaded file\n"
" - Use `check_uploaded_document` to get the file data\n"
" - If `check_uploaded_document` returns status 'no_artifacts', ask user to upload a file first\n"
" - If successful, process the file with appropriate MCP tools\n"
" - Return results to user\n"
"\n"
"EXAMPLES:\n"
"- User: 'split this into 2 PDFs' + uploads file → automatically split the uploaded file\n"
"- User: 'extract text from this' + uploads file → automatically OCR the uploaded file\n"
"- User: 'merge these files' + uploads files → automatically merge the uploaded files\n"
"- User: 'split this' but no file uploaded → ask user to upload a file first\n"
"\n"
tools=[
check_uploaded_document,
save_to_artifact,
load_artifacts,
pdf_lumin_mcp,
]
)
app = App(
name='unified_pdf_agent_app',
root_agent=root_agent,
plugins=[SaveFilesAsArtifactsPlugin()],
)
I was able to get it to work, @thulelumin . I suspect your tool desscription for load_artifacts may need to be updated. try this: - load_artifacts: Call if the user uploaded a file that you're wanting to pass to other tools via the Tool Context
Hi everyone! I was struggling with the "session id not found" and thanks to this post I was able to make it works! Anyway I noticed that even if the artifacts are visible using a custom tool that calls tool_context.list_artifacts(), I cannot see artifacts into "Artifact" tab on the left of the adk web front-end.
Anyway, before encountering this "canonical" solution, I was trying to build a custom one by myself. So I write a custom before_model_callback in order to:
catch the llm_request
extract the file from the Part list of the latest message
search for a Blob
saving the Blob as Artifact
clean from llm_request all Blob Part that is already been transformed to Artifact
I'm not pretty sure about I managed the last step. I have to clean the llm_request every time I make a request because I'm not able to edit the original object. Anyway it seems to works because on the printed llm_request.contents shows me that the Blob Part has gone away (also confirmed by the response times) but in certain situations the Blob part comes back into the print log. So if someone know how to address this problem I guess I can keep my code because with this I'm able to see artifacts into "Artifact" ahah
I share with you the callback, just attach it to the agent and it could be plug-n-play.
Thank you in advance!
fromgoogle.adk.agents.callback_contextimportCallbackContextfromgoogle.adk.modelsimportLlmResponse, LlmRequestfromtypingimportOptionalfromgoogle.genaiimporttypesfromcopyimportdeepcopy## Callback function###############################asyncdefbefore_model_callback(callback_context: CallbackContext, llm_request: LlmRequest) ->Optional[LlmResponse]:
"""Inspects/modifies the LLM request or skips the call."""agent_name=callback_context.agent_nameprint(f"[Callback] Before model call for agent: <{agent_name}>")
########################################## Save file attachments as artifacts ##########################################print(f"[Callback] Inspecting last user message for file attachments...")
# Check if the last user message contains a file attachmentiflast_user_message_contains_file(llm_request):
print(f"[Callback] Last user message contains a file attachment.")
# So we can assume that there is at least one file attachment# therefore we can safely iterate over the partsforpartinllm_request.contents[-1].parts:
ifpart.inline_dataandisinstance(part.inline_data, types.Blob):
file_name=part.inline_data.display_namemime_type=part.inline_data.mime_typeprint(f"[Callback] Found file attachment with name: {file_name} and mime type: {mime_type}. Saving file attachment as artifact...")
# Save the file as artifactawaitcallback_context.save_artifact(
file_name,
types.Part.from_bytes(
data=part.inline_data.data,
mime_type=mime_type),
)
print(f"[Callback] File attachment '{file_name}' saved as artifact.")
# Add a text part to the LLM request indicating that the file has been saved as artifact# !!! This is crucial because if only a file is uploaded without any message the LLM will go into an error !!!llm_request.contents[-1].parts.append(
types.Part.from_text(
text=f"Il file denominato '{file_name}' di tipo '{mime_type}' è stato salvato come artifact e può essere caricato usando il tool [load_artifacts]."
)
)
else:
print(f"[Callback] No file attachment found in the last user message.")
## END ########################################################################################### Clean up LLM request from already loaded artifacts ##########################################################print(f"[Callback] Inspecting available artifacts...")
available_files=awaitcallback_context.list_artifacts()
available_files_str="\n".join([f"- {fname}"forfnameinavailable_files])
print(f"[Callback] Available artifacts: \n{available_files_str}")
# If there are available artifacts, we clean up the LLM requestifavailable_files:
llm_request.contents=clean_llm_request_from_artifacts(llm_request, available_files).contentsprint(f"[Callback] Cleaned LLM request from artifacts.")
## END ################################################## Debug: print the whole LLM request contents for inspectionifllm_request.contents:
print(f"[Callback] Full LLM Request Contents: {llm_request.contents}")
returnNone# Proceed with the original LLM call## Helper functions###############################deflast_user_message_contains_file(llm_request: LlmRequest) ->bool:
""" Checks if the last user message contains a file attachment. Returns: - the file name if found - otherwise returns None. """ifllm_request.contentsandllm_request.contents[-1].role=='user':
ifllm_request.contents[-1].parts:
forpartinllm_request.contents[-1].parts:
ifpart.inline_dataandisinstance(part.inline_data, types.Blob):
returnTruereturnFalsedefclean_llm_request_from_artifacts(llm_request: LlmRequest, available_files: list[str]) ->LlmRequest:
""" Cleans the entire LLM request history from artifacts (inline Blobs) by iterating through all user messages. Returns: - the cleaned LLM request. """cleaned_request=deepcopy(llm_request)
ifcleaned_request.contents:
forcontentincleaned_request.contents:
ifcontent.role=='user'andcontent.parts:
# Ricostruisce la lista delle parti, escludendo i Blobcleaned_parts= [
partforpartincontent.partsifnot (part.inline_dataandisinstance(part.inline_data, types.Blob) andpart.inline_data.display_nameinavailable_files)
]
content.parts=cleaned_partsreturncleaned_request
Activity
pretbc commentedon Jul 26, 2025
I think this never worked - save_input_blobs_as_artifacts
joseph-cavard commentedon Jul 28, 2025
It works for me. The docs I upload in the UI are saved as artifacts.
pretbc commentedon Aug 1, 2025
@joseph-cavard It seems to be right, I discover that (in my example ) the issue with artifacts has root cause in LiteLLM that can not handle mimeTypes
MissArtemis commentedon Aug 6, 2025
May I ask if there's any plan to fix this bug? I have encountered the same issue.
saeed-git-123 commentedon Aug 20, 2025
Have you found a way to upload a file via the ADK web UI, save it as an artifact, and then load it for use in subsequent functions?
joseph-cavard commentedon Aug 20, 2025
yes, I answered you here (#703 (reply in thread)).
anjani-dhrangadhariya commentedon Aug 25, 2025
Yes, the solution suggested by @joseph-cavard worked for it. I am documenting it in this Medium post. I hope the instructions are helpful.
Jacksunwei commentedon Sep 2, 2025
Thanks for reporting this! @GWeale , could you help take a look at this?
fix: Enable saving input blobs as artifacts in ADK web server for issue
9 remaining items
GWeale commentedon Oct 8, 2025
Hi, We decided to move forward with a plugin to save artifacts, SaveFilesAsArtifactsPlugin(). Hopefully this will solve the problems. Here is a use case of the new plugin, https://medium.com/google-cloud/2-minute-adk-manage-context-efficiently-with-artifacts-6fcc6683d274. If you are noticing issues still with artifacts please reopen!
rubenBhatt93 commentedon Oct 9, 2025
@GWeale The use case which you provided in the medium article , i am unable to test as it always gives session id not found. I tried integrating the artifacts plugin by defining App as you mentioned but the moment i introduced App definition i start getting session not found.
Can anyone help me ?
kauabh commentedon Oct 9, 2025
Same
rubenBhatt93 commentedon Oct 9, 2025
I solved it by mentioning the app_name exactly same as the parent directory name.
vp-code commentedon Oct 12, 2025
Posting a small working example, for others who come searching. Works with ADK 1.15.1, Python 3.12
thulelumin commentedon Oct 27, 2025
Hi everyone,
I’ve been testing the newly released
SaveFilesAsArtifactsPlugin(), but I’m still unable to retrieve the saved artifact or its content. Could someone please take a look at my project setup and confirm if I might be missing something? 🙏 Much appreciated!Context:
I’m building a Google Agent using google-adk that connects to an MCP server. The MCP server handles PDF operations such as extract, merge, and add watermark.
Expected flow:
Thanks in advance for any insights or suggestions!
svx3 commentedon Nov 4, 2025
I was able to get it to work, @thulelumin . I suspect your tool desscription for load_artifacts may need to be updated. try this:
- load_artifacts: Call if the user uploaded a file that you're wanting to pass to other tools via the Tool ContextGWeale commentedon Nov 4, 2025
@svx3 Looking into adding something like this thank you for the suggestion
GWeale commentedon Nov 10, 2025
We added something like this now, thank you for pointing this out!
Hirokami commentedon Nov 19, 2025
Hi everyone! I was struggling with the "session id not found" and thanks to this post I was able to make it works! Anyway I noticed that even if the artifacts are visible using a custom tool that calls
tool_context.list_artifacts(), I cannot see artifacts into "Artifact" tab on the left of theadk webfront-end.Anyway, before encountering this "canonical" solution, I was trying to build a custom one by myself. So I write a custom before_model_callback in order to:
I'm not pretty sure about I managed the last step. I have to clean the
llm_requestevery time I make a request because I'm not able to edit the original object. Anyway it seems to works because on the printedllm_request.contentsshows me that the Blob Part has gone away (also confirmed by the response times) but in certain situations the Blob part comes back into the print log. So if someone know how to address this problem I guess I can keep my code because with this I'm able to see artifacts into "Artifact" ahahI share with you the callback, just attach it to the agent and it could be plug-n-play.
Thank you in advance!
fix: Adds plugin to save artifacts for issue google#2176
fix: Enable saving input blobs as artifacts in ADK web server for issue
fix: Enable saving input blobs as artifacts in ADK web server for issue
fix: Adds plugin to save artifacts for issue google#2176