Skip to content
Blog

Handling Binary Payloads: Returning Images, PDFs, and Audio from Tools

How to handle non-text outputs from ADK tools — choosing between inline base64 data parts, artifact storage services, and signed Cloud Storage URLs.

Published on • November 28, 2026

AI Assistant

Modern agent architectures are rarely text-only. Tools frequently generate diagrams, export PDF financial statements, process voice memos, or query satellite imagery. However, raw binary payloads pose severe hazards to LLM context windows: dumping a 5MB PNG as a base64 string directly into a tool return dictionary can instantly consume 100,000+ tokens, exhaust memory, and trigger rate-limit quotas. Handling binary payloads effectively requires choosing the right transfer channel for each media type.

This tutorial covers the three architectural patterns for binary tool returns in ADK: multimodal inline Part objects for Gemini inspection, ADK artifact persistence via ToolContext, and external signed URL redirects.

Payload handling patterns compared

Selecting a storage and transmission pattern depends on whether the LLM needs to inspect the contents or simply deliver an asset link to the user:

PatternTarget consumerToken consumptionMaximum sizeBest suited for
Inline Multimodal PartGemini model directlyHigh (tokens counted by model vision/audio encoder)~20MBCharts to interpret, screenshots to inspect
ADK Artifact ServiceSession user & sub-agentsZero (stored out-of-band; ID returned)100MB+Generated PDF reports, ZIP archives
Signed Cloud Storage URLEnd-user client browserMinimal (plain text URL)GigabytesVideo exports, large raw datasets

If the LLM only needs to inform the user that a PDF is ready, return a download link—never pass the PDF bytes into the context window.

Returning inline multimodal parts for model inspection

When the agent tool renders a visual chart that the model must analyze to answer the user’s question, return a Part or formatted media dict supported by the Gemini multimodal engine:

import base64
from google.genai import types
from google.adk.tools import ToolContext

async def render_financial_chart(quarter: str, ctx: ToolContext) -> dict:
    """Generate and return a performance bar chart for a financial quarter.

    Args:
        quarter (str): Fiscal quarter string, e.g., 'Q3-2026'.
    """
    chart_png_bytes = await chart_renderer.generate_bar_chart(quarter)
    
    # Return a structured multimodal response
    # The image is processed by Gemini's vision encoder
    return {
        "status": "success",
        "mime_type": "image/png",
        "data_base64": base64.b64encode(chart_png_bytes).decode("ascii"),
        "summary": f"Rendered quarterly performance chart for {quarter}."
    }

When Gemini 3.8 Flash receives this tool response, its multimodal processor ingests the image directly into the next turn reasoning block, allowing it to describe trends depicted in the graph.

Storing heavy files with the ADK artifact service

When the tool produces files intended for the user—such as an exported CSV or compiled PDF—use ADK’s built-in ArtifactService through ctx.save_artifact(). The raw binary is stored safely in object storage, and only a lightweight reference enters conversation state:

from google.adk.tools import ToolContext

async def export_audit_log_csv(start_date: str, end_date: str, ctx: ToolContext) -> dict:
    """Export filtered system audit records as a downloadable CSV artifact.

    Args:
        start_date (str): ISO formatted start date.
        end_date (str): ISO formatted end date.
    """
    csv_bytes = await audit_service.generate_csv(start_date, end_date)
    filename = f"audit_{start_date}_to_{end_date}.csv"

    # Persist the file safely outside the LLM context window
    artifact_id = await ctx.save_artifact(
        filename=filename,
        data=csv_bytes,
        mime_type="text/csv"
    )

    # Return only the reference and summary to the LLM
    return {
        "status": "success",
        "artifact_id": artifact_id,
        "filename": filename,
        "size_bytes": len(csv_bytes),
        "summary": f"Generated audit export '{filename}'. The user can download it from the session attachments."
    }

The LLM receives a clean 4-line dictionary and tells the user their download is ready without wasting context on megabytes of raw CSV rows.

Delivering large files via signed Cloud Storage URLs

For multi-gigabyte exports or video streams, write directly to Google Cloud Storage and generate a time-limited signed URL:

from datetime import timedelta
from google.cloud import storage

def generate_signed_download_url(bucket_name: str, blob_name: str) -> str:
    client = storage.Client()
    bucket = client.bucket(bucket_name)
    blob = bucket.blob(blob_name)
    
    return blob.generate_signed_url(
        version="v4",
        expiration=timedelta(minutes=30),
        method="GET"
    )

async def compile_video_summary(job_id: str) -> dict:
    """Render a highlight video and provide a download link."""
    blob_name = f"renders/{job_id}.mp4"
    await video_engine.render_to_gcs("my-agent-bucket", blob_name)
    
    download_url = generate_signed_download_url("my-agent-bucket", blob_name)
    
    return {
        "status": "success",
        "download_url": download_url,
        "expires_in_minutes": 30,
        "summary": "Your highlight video has finished rendering and is available via the download link."
    }

Takeaways

  • Never inject raw binary bytes or unconstrained base64 into tool text returns without checking context size.
  • Use inline multimodal parts only when the model must visually inspect or transcribe the asset.
  • Use ADK’s ctx.save_artifact() for files destined for user download, keeping the LLM turn lightweight.
  • For files exceeding 50MB, offload storage to Cloud Storage and return time-limited signed URLs.
  • Always include a short, human-readable summary string so the model can cite results cleanly.

Further reading