---
title: "Google ADK Artifacts: How to Use and Apply Them in AI Agents in Multiple Ways"
date: "2026-12-04T14:17:22+07:00"
description: "A practical guide to ADK's ArtifactService — what artifacts are, how to wire them into a Runner, and seven real patterns for applying them in AI agents: pipeline handoffs, attachments, tool outputs, cross-session files, workspaces, versioning, and compliance."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/google-adk-artifacts-how-to-use-and-apply.jpg"
alt: "Google ADK Artifacts: How to Use and Apply Them in AI Agents in Multiple Ways"
tags: ['google-adk', 'artifacts', 'session-state', 'adk-tools', 'architecture']
---

Every agent project reaches the same wall at some point: the agent produces something that does not fit in a chat message. A 900 KB chart. A 4 MB uploaded PDF. A generated report the user wants to download. An intermediate table a later pipeline stage needs. The instinct is always the same — base64 it into `session.state`, or paste it into the next prompt — and the result is always the same: a bloated session document, a token bill that scales with your file sizes, and a model trying to reason about a data URI.

Google ADK has a dedicated primitive for exactly this case: **Artifacts** — named, versioned binary blobs managed by an `ArtifactService`, referenced from state as plain strings. This article maps the mechanism and then walks through seven distinct ways to apply it in a real agent.

---

## 1. The mechanism in one page

### Two channels, two kinds of data

ADK splits persistence into four mechanisms — sessions, state, memory, and artifacts — and the artifact/state split is the one that stops prompt pollution:

```
   stage 1 "chart"                stage 2 "narrative"
┌───────────────────────┐      ┌──────────────────────────┐
│ state:                │      │ state:                   │
│  chart_file = "..."   │  ──► │  chart_file = "..."      │  (pointer: ~40 chars)
│  chart_version  = 3   │      │  chart_caption = "..."   │
├───────────────────────┤      ├──────────────────────────┤
│ ArtifactService       │      │ prompt receives:         │
│  "chart.png" v3       │  ──► │  caption + source table  │  (never the bytes)
│  (900 KB binary)      │ load │  or a text rendering     │
└───────────────────────┘      └──────────────────────────┘
```

- **State holds pointers** — a filename, a version number, a caption, a size. Small, serializable, cheap to send to a model.
- **Artifacts hold bytes** — images, PDFs, audio, CSV exports, generated reports. Loaded only when something explicitly asks for them.

The rule of thumb: *if a value would not survive being printed in a log, it belongs in an artifact, not in `session.state`.*

### Core mechanics worth knowing

- **Storage is delegated.** `BaseArtifactService` implementations do the persisting: `InMemoryArtifactService` for local development, `GcsArtifactService` for durable Google Cloud Storage.
- **Payloads are `google.genai.types.Part` objects**, carrying bytes plus a MIME type in `inline_data`. The MIME type — not the file extension — is what tells a downstream consumer how to interpret the bytes.
- **Everything is versioned.** `save_artifact` assigns and returns the next version number for a filename. `load_artifact` with no version returns the latest; with `version=N` it returns exactly that one. Re-saving `chart.png` creates version 4 without destroying version 3.
- **Filenames are namespaced.** `"report.pdf"` is scoped to app + user + session. Prefixing with `user:` (`"user:profile.png"`) makes it reachable from any session of that user within the app.
- **Writes are recorded on the event.** After a save, the event carries `actions.artifact_delta == {filename: version}` — the `Runner` confirms the write against the service, exactly as it confirms state through `state_delta`. Your run log documents what was written, for free.

### Wiring: the one non-negotiable step

No artifact service, no artifacts. Calling `save_artifact` / `load_artifact` / `list_artifact_keys` without a service configured on the `Runner` raises `ValueError`:

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

session_service = InMemorySessionService()
artifact_service = InMemoryArtifactService()   # swap for GcsArtifactService() in prod

runner = Runner(
    agent=root_agent,
    app_name="my_agent_app",
    session_service=session_service,
    artifact_service=artifact_service,          # this line is the feature switch
)
```

Use `InMemoryArtifactService` while iterating — everything vanishes on restart — and switch to `GcsArtifactService(bucket_name=...)` for anything that must survive deploys, be shared across sessions via the `user:` prefix, or be audited later.

### Reading and writing from inside the framework

Tools and callbacks get the methods through their injected context (`ToolContext`, `CallbackContext`):

```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)

    # Reference, not bytes, so later turns know the file exists.
    tool_context.state["last_attachment"] = {"filename": filename, "version": version}
    return {"filename": filename, "version": version, "summary": f"Saved {filename}."}
```

And the read side:

```python
part = await context.load_artifact("generated_report.pdf")              # latest
part = await context.load_artifact("generated_report.pdf", version=0)   # pinned
keys = await context.list_artifact_keys()   # ["contract.pdf", "user:profile.png"]
```

That is the whole primitive. The interesting part is the *ways* you can put it to work.

---

## 2. Way 1 — Moving data between pipeline stages without polluting prompts

The canonical multi-agent use case. A chart-generating stage produces a 900 KB PNG that the narrative stage must account for but must never see as bytes.

**Producer** saves the artifact and returns metadata only:

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

def render_chart(table_csv: str, tool_context: ToolContext) -> dict:
    """Render a table to a PNG chart, save it as an artifact, publish a pointer.

    Args:
        table_csv: The source data as CSV text.

    Returns:
        Pointer metadata only — no bytes ever enter the model's context.
    """
    png_bytes = my_renderer.render(table_csv)
    part = types.Part.from_bytes(data=png_bytes, mime_type="image/png")

    version = tool_context.save_artifact("chart.png", part)

    tool_context.state["chart_file"] = "chart.png"
    tool_context.state["chart_version"] = version
    tool_context.state["chart_caption"] = f"Line chart of {len(table_csv.splitlines())} rows"

    return {"status": "ok", "filename": "chart.png", "version": version,
            "note": "Pointer stored in state. Do not reproduce image data."}
```

**Consumer** has three escalating options — pick the cheapest one that works:

- **Option A — talk about it.** Reference `{chart_file?}` and `{chart_version?}` in the instruction and let the model reason from the caption and source stats. No bytes are loaded at all. This is usually enough.
- **Option B — inject rendered text on purpose.** ADK's instruction templating understands artifacts directly: `{artifact.chart.png}` inserts the artifact's *text* content. Correct for text-ish artifacts (CSV, JSON, log excerpts); wrong for a PNG or PDF, where it injects noise the model cannot use.
- **Option C — load bytes inside a tool.** When a stage must genuinely process the file, load it in a tool where bytes stay in program memory, compute a finding, and return *that*:

```python
def describe_chart(tool_context: ToolContext) -> dict:
    """Load the latest saved chart for structured inspection."""
    part = tool_context.load_artifact("chart.png")
    if part is None:
        return {"status": "missing", "message": "No chart saved in this session."}

    blob = part.inline_data
    findings = my_vision_model.describe(blob.data, blob.mime_type)   # bytes live here only
    return {"status": "ok", "mime_type": blob.mime_type,
            "bytes": len(blob.data), "findings": findings}
```

ADK also ships a `LoadArtifactsTool` that lets a model list and pull artifacts on demand — useful when the file isn't known until runtime. The discipline is the same: what comes back is text the model can use, not a dump it must wade through.

**Pin versions in pipelines.** `load_artifact("chart.png")` with no version returns the *latest* — right for conversational flows, wrong for pipelines where stage 3 must read exactly what stage 2 produced. Store `chart_version` in state and call `load_artifact(filename, version=...)` so a re-run cannot silently change what the next stage analyzed.

---

## 3. Way 2 — Storing conversation attachments and user uploads

A user drops a 4 MB PDF into chat. Base64 into state bloats every subsequent turn and can choke the `SessionService` on serialization. Artifacts are the intended home; the session keeps only a filename reference.

Two design decisions:

### Session scope vs `user:` scope

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

Session scope for conversation-scoped uploads; the `user:` prefix for genuinely cross-session files (profile picture, saved template). The reference in state stays a plain filename string either way — the service resolves the namespace.

### Serving bytes to the client

The artifact service is your *internal* store; the browser still needs a fetch path:

1. **App endpoint:** your API loads the artifact with `load_artifact` and streams it back — simplest, keep it authenticated per user. If you serve the agent through `adk api_server`, ADK already ships this endpoint (next section).
2. **Signed URLs (GCS):** for large files, generate a short-lived signed URL from the bucket so bytes bypass your server entirely.

Never inline the blob into an agent message or state value for the sake of delivery: the model does not need the bytes to know a file exists.

---

## 4. Showing artifacts over the ADK API server

`adk api_server` (or `fast_api.py` in your own FastAPI app) exposes the artifact store over REST. The client's job is always the same three steps:

1. **Read the pointer.** A `/run` event carries `actions.artifactDelta` — a `{filename: version}` map telling you *what changed*, not the bytes.
2. **Fetch.** One `GET` per file against the artifacts endpoint, with `?version=` to pin the exact version the delta named.
3. **Decode and render.** The body is a `google.genai.types.Part`: `inlineData.data` is base64, `inlineData.mimeType` is the contract for how to display it.

### The endpoints

All artifact routes live under a session:

```
/apps/{app_name}/users/{user_id}/sessions/{session_id}/artifacts
```

| Method | Path (relative to the prefix above) | Returns |
| --- | --- | --- |
| `GET` | `/artifacts` | `["chart.png", "user:profile.png"]` |
| `GET` | `/artifacts/{name}` | latest version as a `Part` (base64 body) |
| `GET` | `/artifacts/{name}?version=3` | pinned version |
| `GET` | `/artifacts/{name}/versions` | `[0, 1, 2, 3]` |
| `GET` | `/artifacts/{name}/versions/3` | that version as a `Part` (`latest` also accepted) |
| `GET` | `/artifacts/{name}/versions` + `/metadata` variants | `ArtifactVersion` metadata only |
| `POST` | `/artifacts` | save `{filename, artifact, customMetadata}` → `ArtifactVersion` |
| `DELETE` | `/artifacts/{name}` | removes every version |

A `GET` response body looks exactly like the upload shape used by `/run`:

```json
{
  "inlineData": {
    "mimeType": "image/png",
    "data": "iVBORw0KGgoAAAANSUhEUg..."
  }
}
```

### Decode and stream it back

Your app endpoint is a thin translate-and-forward:

```python
import base64

import httpx
from fastapi import FastAPI
from fastapi.responses import Response

app = FastAPI()
ADK = "http://127.0.0.1:8000"


@app.get("/files/{session_id}/{name:path}")
async def get_file(session_id: str, name: str, version: int | None = None):
    url = f"{ADK}/apps/my_app/users/me/sessions/{session_id}/artifacts/{name}"
    if version is not None:
        url += f"?version={version}"
    async with httpx.AsyncClient() as client:
        resp = await client.get(url)
        resp.raise_for_status()
        part = resp.json()["inlineData"]

    return Response(
        content=base64.b64decode(part["data"]),
        media_type=part["mimeType"],
    )
```

Two things this endpoint should do for you: authenticate the caller (the ADK server does not), and set `Cache-Control` — an artifact version is immutable, so `max-age` is safe and free.

### `/run` vs `/run_sse`: where the delta lands

The delta map travels on the content event, but the two transports shape it differently:

- **`POST /run`** — returns `list[Event]`; the content event keeps `actions.artifactDelta` attached.
- **`POST /run_sse`** — the server *splits* it: first a content event with the delta cleared, then a separate content-less "action-only" event carrying `actions.artifactDelta`. ADK Web renders artifacts from both frames during part processing *and* action processing.

If your SSE client only inspects events that have `content`, you will silently miss every artifact. Handle the content-less action event too.

### Gotchas

- **No authentication.** The API server's session and artifact endpoints are open to anyone who can reach the port. Bind to `127.0.0.1` and put your own auth layer in front — never expose it publicly as-is.
- **`user:` names still need a session in the URL.** `user:profile.png` resolves against app + user, but the route still requires the `/sessions/{session_id}/` segment. Any session id for that user works.
- **`{name:path}` swallows slashes.** Filenames with directories (`reports/2026/q1.pdf`) work, which is also why the route param is declared `:path`.
- **Metadata vs bytes.** `/versions` and `/versions/{v}/metadata` return `ArtifactVersion` (`version`, `canonicalUri`, `customMetadata`, `createTime`, `mimeType`) — cheap for building a file picker; only fetch the `Part` when the user asks for content.
- **Deletion is all-or-nothing.** `DELETE /artifacts/{name}` removes every version; there is no per-version delete over HTTP.

---

## 5. Way 3 — Choosing the right channel for tool outputs (the three-way decision)

Tools that produce binary are the highest-leverage place to apply artifacts. The decision depends on *who needs to consume the payload*:

| Pattern | Target consumer | Token cost | Max size | Best for |
|---|---|---|---|---|
| **Inline multimodal `Part`** | The Gemini model itself | High (vision/audio encoder tokens) | ~20 MB | Charts to interpret, screenshots to inspect |
| **ADK artifact service** | Session user, later stages, sub-agents | **Zero** (out-of-band; ID returned) | 100 MB+ | Generated PDF reports, ZIP archives |
| **Signed Cloud Storage URL** | The end-user's browser | Minimal (a text URL) | Gigabytes | Video exports, large raw datasets |

**Inline** when the model must actually look at the asset:

```python
return {
    "status": "success",
    "mime_type": "image/png",
    "data_base64": base64.b64encode(chart_png_bytes).decode("ascii"),
    "summary": f"Rendered quarterly performance chart for {quarter}.",
}
```

**Artifact** when the file is *for the user* or a downstream stage — the LLM gets a clean four-line dictionary instead of megabytes of CSV:

```python
csv_bytes = await audit_service.generate_csv(start_date, end_date)
filename = f"audit_{start_date}_to_{end_date}.csv"
version = await ctx.save_artifact(
    filename=filename,
    artifact=types.Part.from_bytes(data=csv_bytes, mime_type="text/csv"),
)
return {"status": "success", "filename": filename, "version": version,
        "size_bytes": len(csv_bytes),
        "summary": f"Generated audit export '{filename}' — ready for download."}
```

**Signed URL** for multi-gigabyte renders where neither the model nor your app server should touch the bytes.

If the LLM only needs to tell the user a PDF is ready, return a link. Never pass PDF bytes into the context window.

---

## 6. Way 4 — Cross-session user memory for files (`user:` artifacts)

Artifacts are not just per-conversation scratch. With a durable service, a `user:`-prefixed filename behaves like a small per-user file store: a profile image, a brand kit, a repeatedly edited contract template — written once in session A, read in session Z.

Combined with state prefixes this gives you a clean tiering:

| Need | Where |
|---|---|
| A flag for this conversation | state, no prefix |
| A preference across all of a user's sessions | state, `user:` prefix |
| A *file* the user owns | artifact, `user:` filename |
| A setting for every user of the app | state, `app:` prefix |
| Scratch for one invocation | state, `temp:` prefix |

Note that `list_artifact_keys()` returns session filenames *and* the user's `user:`-prefixed filenames together, so you can enumerate both classes in one call.

---

## 7. Way 5 — Backing agent file tools with artifacts

A file tool that writes to raw disk has to re-solve path confinement, traversal defense, quotas, and cleanup. Artifacts give you a store that is already namespaced by app, user, and session, already versioned, and already isolated per tenant:

```python
def list_files(ctx: ToolContext) -> dict:
    """List files saved for this session. Takes no arguments."""
    names = sorted(ctx.list_artifact_keys())
    return {"status": "success", "files": names,
            "summary": f"Workspace holds {len(names)} files."}

def read_file(name: str, ctx: ToolContext) -> dict:
    """Read a saved text artifact by name.

    Args:
        name (str): Relative filename, e.g. 'report.md'.
    """
    part = ctx.load_artifact(name)
    if part is None:
        return {"status": "error", "error_message": f"{name} not found.", "retryable": False}
    text = part.inline_data.data.decode("utf-8")
    return {"status": "success", "name": name, "content": text}
```

There is no path to traverse because the "path" is a key in a namespaced store, not a filesystem location. Keep scratch directories (files the agent edits and re-reads *within* a session) separate from artifacts (durable, versioned outputs) — mixing the two is how one session's data leaks into the next.

---

## 8. Way 6 — Versioning as workflow history

Because every save increments a version, artifacts double as an append-only draft history. A document-generation agent that revises `contract.pdf` three times in one conversation produces v0, v1, v2 — all readable:

```python
v2 = await ctx.load_artifact("contract.pdf", version=2)   # the earlier draft
latest = await ctx.load_artifact("contract.pdf")          # what the user last saw
```

That gives you **rewind and replay** semantics for free: after a bad turn, reload the previous version instead of recomputing it, and pin `version=` anywhere a stage must reproduce an exact historical input. Interactive flows deliberately read *latest*; pipelines pin explicitly.

---

## 9. Way 7 — Lifecycle, privacy, and the "forget me" flow

Artifacts are also long-lived personal data — which makes them part of any GDPR/CCPA erasure story. The good news: unlike ADK's `MemoryService` (which exposes ingestion and search but **no per-entry delete**), the artifact service exposes deletion including version history:

```python
async def erase_user_artifacts(artifact_service, app_name: str, user_id: str) -> dict:
    """Delete every user-scoped artifact for one user."""
    filenames = await artifact_service.list_artifact_keys(
        app_name=app_name, user_id=user_id,
    )
    deleted = []
    for name in filenames:
        if not name.startswith("user:"):
            continue
        await artifact_service.delete_artifact(
            app_name=app_name, user_id=user_id, filename=name,
        )
        deleted.append(name)
    return {"deleted": deleted, "count": len(deleted)}
```

Pair it with session deletion (`list_sessions` → `delete_session`) and `user:`-scoped state clearing, and return an honest per-store status rather than a single triumphant `{"ok": true}`. Also align bucket lifecycle/retention rules with your session retention policy so orphaned objects are cleaned up too — otherwise your storage quietly accumulates what your app believes it deleted.

---

## 10. Decision table: state or artifact?

| You need to… | Use |
| --- | --- |
| Track a step, flag, or small value for this conversation | **State**, unprefixed key |
| Share a preference across a user's conversations | **State**, `user:` prefix |
| Pass scratch data between calls in one request | **State**, `temp:` prefix |
| Store a file, image, PDF, or any bulk/binary payload | **Artifact** + reference in state |
| Move a value from one node to its successor | Node `output` (not state at all) |
| Survive an application restart | The *service* decides — not `InMemory*` |

State values must be serializable (strings, numbers, booleans, simple lists/dicts). The conversion discipline: **flatten** rich objects to primitives (`model_dump(mode="json")`, `asdict()`, `isoformat()`, `str(uuid)`), **reference** what you can't flatten (store the ID, rebuild on read), and **delegate** binary or large payloads to artifacts with only a filename/version pointer left behind.

---

## 11. Common failure modes

1. **Forgetting `artifact_service=` on the `Runner`.** Every save/load raises `ValueError` — often in production, at first use. Wire it at startup.
2. **Bytes in state.** Base64 blobs make the session document balloon, every future turn re-read them, and the `SessionService` may fail to serialize. State stays in kilobytes; artifacts carry the megabytes.
3. **Bytes echoed in tool returns.** Storing the artifact doesn't help if the tool's *response* also contains the payload — the model sees it immediately. Return envelopes with metadata and a one-line summary.
4. **Unpinned reads in pipelines.** "Latest" is a moving target; pin `version=` when the input must be reproducible.
5. **Binary injected into instructions.** `{artifact.chart.png}` on a PNG is noise, not context. Render text deliberately.
6. **In-memory service in production.** Everything vanishes on restart — swap to `GcsArtifactService` before deploy.
7. **Wrong MIME type.** The MIME type, not the extension, is what downstream consumers key off.
8. **Conversation history re-sending the world.** Stages that only need their inputs should run with `include_contents="none"`.

**A useful audit:** after a run, print `session.state` sizes and the artifact list. The healthy shape is state measured in kilobytes, artifacts carrying the megabytes, and any state value whose name ends in `_file` or `_version` being the only trace of a binary anywhere.

---

## 12. Checklist

- [ ] `artifact_service=` is passed to the `Runner` — otherwise every artifact call raises.
- [ ] 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.
- [ ] Producers return pointer metadata from tools, never the payload.
- [ ] Pipelines pin `version=` when reading; interactive flows deliberately use latest.
- [ ] Session-scoped filenames for per-run outputs; `user:` prefix for genuinely cross-session files.
- [ ] Client fetch paths (app endpoint or signed URL) enforce per-user authorization — including over `adk api_server`, which ships with none.
- [ ] Stages without conversation needs run with `include_contents="none"`.
- [ ] Deletion/lifecycle covers artifacts (versions included) alongside sessions and `user:` state.

---

## Conclusion

ADK artifacts are one small API — `save_artifact`, `load_artifact`, `list_artifact_keys`, `delete_artifact` — that unlock at least seven distinct application patterns: clean multi-agent handoffs, attachment storage, the right channel for binary tool outputs, per-user file stores, versioned agent file tools, draft/rewind history, and compliant erasure. It is also one REST surface: `adk api_server` serves the same store under `/apps/…/sessions/…/artifacts`, so a client that reads `actions.artifactDelta`, fetches the version, and decodes the base64 `Part` can render any of these files without your app writing a byte-moving endpoint of its own. The unifying idea is a *pipeline of references*: state says what exists and where, artifacts hold what it weighs, and prompts receive only the text a model can act on. Keep those three channels separate and you can add stages, files, and users without your token bill — or your context window — growing with every byte you produce.

---

## References

- [Passing Artifacts Between Pipeline Stages Without Polluting Prompts](https://blog.redlinesoft.net/posts/adk-artifacts-between-pipeline-stages)
- [Storing Conversation Attachments and Blobs: Cloud Storage Session Linking](https://blog.redlinesoft.net/posts/adk-session-attachments-blobs-cloud-storage)
- [Handling Binary Payloads: Returning Images, PDFs, and Audio from Tools](https://blog.redlinesoft.net/posts/binary-payloads-tools-images-pdfs-audio)
- [State vs Memory vs Sessions: Deconstructing Persistence in ADK](https://blog.redlinesoft.net/posts/adk-state-vs-memory-vs-sessions)
- [Serializing Complex Custom Objects into Session State](https://blog.redlinesoft.net/posts/adk-serializing-custom-objects-state)
- [File System and Disk I/O Tools: Safe Workspace Isolation for Agents](https://blog.redlinesoft.net/posts/file-system-tools-workspace-isolation)
- [Implementing a User Forget-Me Tool for GDPR/CCPA Compliance in ADK](https://blog.redlinesoft.net/posts/adk-forget-me-tool-gdpr-ccpa)
- [Google ADK Documentation — Artifacts](https://adk.dev/artifacts/)
- [Google ADK Documentation — API Server](https://adk.dev/runtime/api-server/)
