---
title: "Storing Conversation Attachments and Blobs: Cloud Storage Session Linking"
date: "2026-12-03T08:32:03+07:00"
description: "Put uploads and generated files in ADK artifacts backed by GcsArtifactService — versioned, session- or user-scoped, referenced from state instead of stuffed into it."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-session-attachments-blobs-cloud-storage.jpg"
alt: "Conversation attachment icons flowing into a Cloud Storage bucket and linking back to a session"
tags: ['google-adk', 'artifacts', 'cloud-storage', 'sessions', 'attachments']
---

A user drops a 4 MB PDF into the chat. Your options: base64 it into state (the session document balloons, every subsequent turn re-reads it, and the `SessionService` chokes on serialization), or put it where binary data belongs — **artifacts**, with the session keeping only a filename reference. ADK chose the second answer for you: artifacts are named, versioned blobs managed by an `ArtifactService`, and `GcsArtifactService` puts them in a Cloud Storage bucket.

This post wires attachments end to end: configure the service, save an upload inside a tool, record the reference in state, read it back with versioning, and decide session scope versus `user:` scope — plus the `ValueError` you will hit if you forget to configure the service at all.

## Prerequisites

- ADK installed; a `Runner` with a persistent `SessionService`.
- For production: a GCS bucket and `pip install google-adk` with Google Cloud credentials available to the runtime.
- Comfort with `google.genai.types.Part` — the universal artifact representation.

## 1. Why artifacts, not state

| | Session state | Artifacts |
| --- | --- | --- |
| Payload | Small serializable values | Binary blobs of any size (`Part` with `inline_data`) |
| Read cost | Loaded with the session every turn | Loaded only when you call `load_artifact` |
| Versioning | Overwrite semantics | Automatic — version increments per save |
| Scope | Key prefixes (`user:`, `app:`) | Filename scope (session) or `user:` prefix |
| Storage | With the `SessionService` | `InMemoryArtifactService` or `GcsArtifactService` |
| Event record | `actions.state_delta` | `actions.artifact_delta` (`{filename: version}`) |

Rule of thumb from the artifacts docs: state holds *small configuration and conversational context*; anything file-shaped or large goes to artifacts, with **a reference in state** — never the bytes.

## 2. Configure the `ArtifactService` on the Runner

You must pass an implementation when constructing the `Runner` — if you don't, every `save_artifact` / `load_artifact` / `list_artifact_keys` call on the context raises `ValueError`:

```python
from google.adk.runners import Runner
from google.adk.artifacts import GcsArtifactService  # or InMemoryArtifactService
from google.adk.sessions import InMemorySessionService

artifact_service = GcsArtifactService(bucket_name="my-adk-artifacts")

runner = Runner(
    agent=agent,
    app_name="attachment_app",
    session_service=session_service,
    artifact_service=artifact_service,   # without this: ValueError at save/load
)
```

| Implementation | Persistence | Best for |
| --- | --- | --- |
| `InMemoryArtifactService` | None — lost on restart | Local development and tests |
| `GcsArtifactService` | Yes — objects in a bucket | Production; durable, scalable, encrypted at rest by default |

## 3. Save an attachment from a tool

Inside a tool (or callback), the `ToolContext` / `CallbackContext` exposes the artifact methods. Wrap upload bytes in a `types.Part` and save:

```python
import google.genai.types as types
from google.adk.tools import ToolContext

async def save_attachment(tool_context: ToolContext, filename: str,
                          content_b64: str, mime_type: str) -> dict:
    """Persist a user-uploaded file as a session artifact."""
    import base64

    artifact = types.Part.from_bytes(
        data=base64.b64decode(content_b64),
        mime_type=mime_type,                 # "application/pdf", "image/png", ...
    )
    version = await tool_context.save_artifact(
        filename=filename, artifact=artifact
    )
    # Keep a reference — not the bytes — in state so later turns know it exists.
    tool_context.state["last_attachment"] = {"filename": filename, "version": version}
    return {"filename": filename, "version": version}
```

Two things happen automatically: `save_artifact` assigns the next version number for that filename and scope, and the event generated after your call records `event.actions.artifact_delta == {filename: version}` — the `Runner` confirms the write against the service, exactly as it confirms state through `state_delta`.

## 4. Load and list: versioning does the rest

```python
from google.adk.agents import CallbackContext

async def latest_report(context: CallbackContext) -> bytes | None:
    # version=None (default) -> most recent version
    part = await context.load_artifact(filename="generated_report.pdf")
    if part and part.inline_data:
        return part.inline_data.data
    return None

async def older_draft(context: CallbackContext) -> bytes | None:
    part = await context.load_artifact(filename="generated_report.pdf", version=0)
    return part.inline_data.data if part and part.inline_data else None

async def all_files(context: CallbackContext) -> list[str]:
    return await context.list_artifact_keys()
```

`list_artifact_keys` returns session-scoped filenames **and** that user's user-scoped filenames with the `user:` prefix retained — e.g. `["contract.pdf", "user:profile.png"]`. Versioning is per filename and scope: saving `contract.pdf` again increments its version rather than overwriting, so a conversation that iterates on a document never destroys the previous draft.

## 5. Session scope versus `user:` scope

The filename format decides the namespace:

| Filename | Scope | Accessible from |
| --- | --- | --- |
| `"contract.pdf"` | Session (`app_name` + `user_id` + `session_id`) | Only that conversation |
| `"user:profile.png"` | User (`app_name` + `user_id`) | **Any** session of that user in the app |

Use session scope for conversation-scoped uploads (an attachment analyzed in one chat) and the `user:` prefix for cross-session blobs (a profile picture, a saved template). The reference in state stays a plain filename string either way — the service resolves the namespace.

## 6. Serving files to the client

The artifact service is your internal store; the browser still needs a way to fetch the bytes. Two application-level routes:

1. **App endpoint:** your API loads the artifact with `load_artifact` and streams it back (simplest; keep the endpoint authenticated per user).
2. **Signed URLs (GCS):** for large files, generate a short-lived signed URL from the bucket so bytes bypass your server — application-level code on top of `GcsArtifactService`'s bucket.

Either way, never inline the blob into an agent message or state value: the model does not need the bytes to know a file exists, and the reference in state is what keeps the session document small.

## Checklist

- [ ] `artifact_service=` is passed to the `Runner` — otherwise every artifact call raises `ValueError`.
- [ ] Production uses `GcsArtifactService` (bucket + credentials), not `InMemoryArtifactService`.
- [ ] Files are wrapped as `types.Part.from_bytes(data=..., mime_type=...)` with a correct MIME type.
- [ ] State stores `{filename, version}` references — never raw bytes or base64 payloads.
- [ ] Reads use `load_artifact` with `version=None` for latest or an explicit version for drafts.
- [ ] Session scope is the default; `user:` prefix is reserved for genuinely cross-session files.
- [ ] The client fetch path (app endpoint or signed URL) enforces per-user authorization.
- [ ] Bucket lifecycle/retention rules match your session retention policy so orphaned objects are cleaned up too.

## Conclusion

Attachments are the canonical case for ADK's fourth persistence mechanism: bytes go to an `ArtifactService` — `GcsArtifactService` in production, where Google encrypts them at rest by default — while the session keeps a filename reference and the event log records every write as an `artifact_delta`. Versioning comes free, `user:` prefix gives you cross-session files, and the one configuration mistake (forgetting `artifact_service=`) fails loudly at the first save. Store the blob, keep the reference, and your conversation documents stay small enough to replay.

## References

- https://adk.dev/artifacts/
- https://adk.dev/events/
- https://adk.dev/sessions/state/
- https://adk.dev/sessions/session/
