Skip to content

user files not saved as artifact when using ADK web #2176

Closed

Description

@joseph-cavard

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.

Activity

  1. added
    web
    on Jul 25, 2025
  2. added theissue type on Jul 25, 2025
  3. pretbc commented on Jul 26, 2025

    @pretbc

    I think this never worked - save_input_blobs_as_artifacts

  4. joseph-cavard commented on Jul 28, 2025

    @joseph-cavard
    Author

    I think this never worked - save_input_blobs_as_artifacts

    It works for me. The docs I upload in the UI are saved as artifacts.

  5. pretbc commented on Aug 1, 2025

    @pretbc

    @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

  6. MissArtemis commented on Aug 6, 2025

    @MissArtemis

    May I ask if there's any plan to fix this bug? I have encountered the same issue.

  7. saeed-git-123 commented on Aug 20, 2025

    @saeed-git-123

    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?

  8. joseph-cavard commented on Aug 20, 2025

    @joseph-cavard
    Author

    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?

    yes, I answered you here (#703 (reply in thread)).

  9. anjani-dhrangadhariya commented on Aug 25, 2025

    @anjani-dhrangadhariya

    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?

    Yes, the solution suggested by @joseph-cavard worked for it. I am documenting it in this Medium post. I hope the instructions are helpful.

  10. assigned and unassigned on Sep 2, 2025
  11. Jacksunwei commented on Sep 2, 2025

    @Jacksunwei
    Collaborator

    Thanks for reporting this! @GWeale , could you help take a look at this?

  12. 9 remaining items

  13. GWeale commented on Oct 8, 2025

    @GWeale
    Collaborator

    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!

  14. rubenBhatt93 commented on Oct 9, 2025

    @rubenBhatt93

    @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 ?

  15. kauabh commented on Oct 9, 2025

    @kauabh

    @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

  16. rubenBhatt93 commented on Oct 9, 2025

    @rubenBhatt93

    @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.

  17. vp-code commented on Oct 12, 2025

    @vp-code

    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()],
    )
    
  18. thulelumin commented on Oct 27, 2025

    @thulelumin

    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:

    1. User uploads a file in the chat.
    2. The Agent automatically saves it as an artifact.
    3. The artifact data is passed to the MCP tool for processing.
    4. The MCP tool returns an output file.
    5. 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!


    Image
    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()],
    )
    
  19. svx3 commented on Nov 4, 2025

    @svx3

    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

  20. GWeale commented on Nov 4, 2025

    @GWeale
    Collaborator

    @svx3 Looking into adding something like this thank you for the suggestion

  21. GWeale commented on Nov 10, 2025

    @GWeale
    Collaborator

    We added something like this now, thank you for pointing this out!

  22. Hirokami commented on Nov 19, 2025

    @Hirokami

    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!

    from google.adk.agents.callback_context import CallbackContext
    from google.adk.models import LlmResponse, LlmRequest
    from typing import Optional
    from google.genai import types 
    
    from copy import deepcopy
    
    
    ## Callback function
    ###############################
    
    async def before_model_callback(callback_context: CallbackContext, llm_request: LlmRequest) -> Optional[LlmResponse]:
        """Inspects/modifies the LLM request or skips the call."""
        agent_name = callback_context.agent_name
        print(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 attachment
        if last_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 parts
            for part in llm_request.contents[-1].parts:
                    if part.inline_data and isinstance(part.inline_data, types.Blob):
                        file_name = part.inline_data.display_name
                        mime_type = part.inline_data.mime_type
                        
                        print(f"[Callback] Found file attachment with name: {file_name} and mime type: {mime_type}. Saving file attachment as artifact...")
    
                        # Save the file as artifact
                        await callback_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 = await callback_context.list_artifacts()
    
        available_files_str = "\n".join([f"- {fname}" for fname in available_files])
        print(f"[Callback] Available artifacts: \n{available_files_str}")
    
        # If there are available artifacts, we clean up the LLM request
        if available_files:
            llm_request.contents = clean_llm_request_from_artifacts(llm_request, available_files).contents
            print(f"[Callback] Cleaned LLM request from artifacts.")
    
        ## END #################################################
    
    
        # Debug: print the whole LLM request contents for inspection
        if llm_request.contents:
            print(f"[Callback] Full LLM Request Contents: {llm_request.contents}")
    
        return None  # Proceed with the original LLM call
    
    
    ## Helper functions
    ###############################
    
    def last_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.
        """
        if llm_request.contents and llm_request.contents[-1].role == 'user':
            if llm_request.contents[-1].parts:
                for part in llm_request.contents[-1].parts:
                    if part.inline_data and isinstance(part.inline_data, types.Blob):
                        return True
        return False
    
    
    def clean_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)
        if cleaned_request.contents:
            for content in cleaned_request.contents:
                if content.role == 'user' and content.parts:
                    # Ricostruisce la lista delle parti, escludendo i Blob
                    cleaned_parts = [
                        part for part in content.parts 
                        if not (part.inline_data and isinstance(part.inline_data, types.Blob) and part.inline_data.display_name in available_files)
                    ]
                    content.parts = cleaned_parts
        return cleaned_request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

web

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions