adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Artifacts Handling on Agentspace

Open ssingh5bmcd opened this issue 1 year ago • 11 comments

Hi folks,

I have ADK Agent that uploads file to RAG Corpus, File is accessed by agent via Artifact tool_context. It works well locally on ADK Web. I am able to get the file uploaded in corpus. When deployed it on Agent Engine and use it from Agentspace app it fails silently in _upload_artifact, unfortunately there is no documentations or anything regarding it. Has anyone faced the similar issue, is there any information how file can be accessed by custom agent on Agentspace custom agent? What code changes will be required for Agentspace? On Agentspace there are no properties like inline_data for getting the data?

from google.adk.agents import LlmAgent
from ..tools import upload_file_tool
from ..utils import AI_MODEL
from google.adk.tools.load_artifacts_tool import load_artifacts_tool

upload_file_agent = LlmAgent(
    name="upload_file_agent",
    model=AI_MODEL,
    description="This AI agent's sole responsibility is to upload a received file by invoking the upload_file_tool.",
    instruction="""
You are an upload-only agent. Your task is simple and focused:
- Receive the user's uploaded file.
- Use the provided tool `upload_file_tool` to upload it.
- Do not generate any additional content or reports.
- Do not perform any actions other than calling the tool to upload the file.
- After calling the tool, respond with a brief confirmation message, such as:
    "File uploaded successfully." only if file succeeds,
""",
    tools=[load_artifacts_tool,upload_file_tool],
)
from google.adk.tools import ToolContext
from google.adk.tools import LongRunningFunctionTool
from google.auth.transport.requests import Request
import httpx  
import json
from ..utils.variables import GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION, GOOGLE_CLOUD_CORPUS_ID

async def _upload_to_rag_rest_api(bytes_data: bytes, filename: str, mime_type: str):
    """
    Upload to RAG corpus using an ASYNCHRONOUS REST API call.
    This is the corrected function.
    """

    from ..utils.auth import credential

    if credential is None:
        return {"status": "error", "error": "Server credentials are not available"}
    
    try:
        # Get access token
        request = Request()
        credential.refresh(request)
        access_token = credential.token
        
        if not access_token:
            return {"status": "error", "error": "Failed to get access token"}
        
        print(f"📤 Uploading {filename} via ASYNC REST API...")
        
        # REST API endpoint for multipart upload
        project_id = GOOGLE_CLOUD_PROJECT
        location = GOOGLE_CLOUD_LOCATION
        corpus_id = GOOGLE_CLOUD_CORPUS_ID
        url = f"https://{location}-aiplatform.googleapis.com/upload/v1beta1/projects/{project_id}/locations/{location}/ragCorpora/{corpus_id}/ragFiles:upload"
    
        headers = {
            "Authorization": f"Bearer {access_token}",
        }

        # Prepare multipart form data
        metadata = {
            "ragFile": {
                "displayName": filename,
                "description": f"File uploaded via REST API from web interface"
            }
        }
        
        files_for_upload = {
            "metadata": (None, json.dumps(metadata), "application/json; charset=UTF-8"),
            "file": (filename, bytes_data, mime_type)
        }
    
        # Use httpx.AsyncClient for the asynchronous network call
        async with httpx.AsyncClient(timeout=300.0) as client:
            response = await client.post(url, headers=headers, files=files_for_upload)
        
        if response.status_code == 200:
            print(f"✅ REST API upload successful!")
            return {"status": "success", "message": f"File {filename} uploaded to RAG corpus via REST API!"}
        else:
            print(f"❌ REST API failed: {response.status_code} - {response.text}")
            return {"status": "error", "error": f"REST API failed: {response.status_code} - {response.text}"}
            
    except Exception as e:
        print(f"❌ REST API error: {e}")
        return {"status": "error", "error": str(e)}


async def _upload_artifact(tool_context: ToolContext):
    """Analyze content of an uploaded artifact"""
    try:
        artifacts = await tool_context.list_artifacts()

        if not artifacts or len(artifacts) != 1:
            return {"status": "error", "error": "Only support processing single artifact."}
        
        artifact_part = artifacts[0]
        artifact = await tool_context.load_artifact(filename=artifact_part)

        blob = artifact.inline_data
        name = blob.display_name
        mime_type = blob.mime_type
        data = blob.data

        # It calls the corrected function above
        result = await _upload_to_rag_rest_api(data, name, mime_type)
        return result

    except Exception as e:
        return {"status": "error", "error": str(e)}

upload_file_tool = LongRunningFunctionTool(_upload_artifact)

ssingh5bmcd avatar Sep 09 '25 08:09 ssingh5bmcd

I was able to dig little deeper and with the help of cloud tracing I was able to able to get the file upload succeed from both local as well as agentspace UI:

        mime_type = None
        data = None
        name = f"{time.time_ns()}.pdf"

        # running on Agent engine (Agentspace)
        if "inlineData" in artifact:
            inline = artifact["inlineData"]
            mime_type = inline.get("mimeType")
            base64data = inline.get("data")
            data = base64.b64decode(base64data)
        else:
            blob = artifact.inline_data
            name = blob.display_name
            mime_type = blob.mime_type
            data = blob.data
        # It calls the corrected function above

I was not able to get the name though, that was not an issue for me.

Suggestions:

  • I have few suggestion to please make the property names and overall Artifact API consistent.
  • Provides upload and download examples which works on local as well as AgentEngine reasoning agent on Agentspace.

Leaving this open as now.

ssingh5bmcd avatar Sep 11 '25 14:09 ssingh5bmcd

Change introduced on 1.17 breaks the behavior of artifacts with Agentspace. Artifacts received from Agentspace do not have inline_data - error triggered in google/adk/artifacts/in_memory_artifact_service.py", line 121

Commit 5a543c0 feat: implement new methods in in-memory artifact service

  • save_artifact with custom_metadata
  • list_artifact_versions
  • get_artifact_version

Please note that there's nothing that can be done in the agent implementation to circumvent the error. The problem happens before the agent is invoked.

For now, reverting to 1.16 allows the agents to still receive files.

onix-rdeandrade avatar Oct 27 '25 14:10 onix-rdeandrade

Seeing this in our Gemini Enterprise deployment too with ADK agents.

Infinnerty avatar Nov 27 '25 17:11 Infinnerty

Is there any timeline when we can expect the fix?

ssingh5bmcd avatar Dec 02 '25 11:12 ssingh5bmcd

@ssingh5bmcd This is a known regression introduced in v1.17+ (commit 5a543c00) where the artifact service checks for inline_data property, but Agentspace sends artifacts with inlineData as a dictionary key instead.

The team is aware and working on a fix to normalize both formats at the framework level.

For immediate needs, please use v1.16 which has proper Agentspace artifact support, or apply the normalization workaround you've already discovered in your agent code.

Thanks!

surajksharma07 avatar Dec 04 '25 09:12 surajksharma07

@yeesian Please have a look into it.

surajksharma07 avatar Dec 04 '25 09:12 surajksharma07

Any update regarding this issue?

a-eid1 avatar Jan 21 '26 10:01 a-eid1

@a-eid1 No fix has been merged yet - the team is still working on normalizing the artifact format between Agentspace (camelCase dictionary) and local ADK (snake_case object).

The issue is assigned and under review.

For immediate needs, v1.16 remains the workaround, though we understand that's not a long-term solution.

I'll escalate to get an update on timeline.

surajksharma07 avatar Jan 22 '26 11:01 surajksharma07

Checked against latest ADK (post v1.23.0) — this bug is still present.

All three artifact service implementations (in_memory_artifact_service.py:122, gcs_artifact_service.py:218, file_artifact_service.py:364) still directly access artifact.inline_data with no normalization for the camelCase inlineData dictionary format that Agentspace sends.

No commits addressing this normalization have been merged since the v1.17 regression (commit 5a543c0).

Workaround remains: downgrade to v1.16 or apply manual dict normalization in agent code (checking for inlineData key as @ssingh5bmcd discovered).

surajksharma07 avatar Feb 04 '26 13:02 surajksharma07

Checked against v1.25.0 (latest stable) — the bug is still unresolved.

surajksharma07 avatar Feb 18 '26 18:02 surajksharma07

@seanzhou1023 Please have a look into it.

surajksharma07 avatar Feb 18 '26 18:02 surajksharma07