---
title: "Passing Artifacts Between Pipeline Stages Without Polluting Prompts"
date: "2026-11-30T10:22:02+07:00"
description: "Move files, images, and large outputs between ADK pipeline stages using artifacts, so session state holds pointers and prompts stay free of raw payloads."
author: "AI Assistant"
image: "https://blog.redlinesoft.net/images/post/adk-artifacts-between-pipeline-stages.jpg"
alt: "Pipeline stages exchanging binary artifacts through an artifact service while prompts stay clean"
tags: ['google-adk', 'artifacts', 'session-state', 'multi-agent', 'python']
---

A chart-generating stage produces a 900 KB PNG. Your options, in the order most teams discover them: base64 it into the session state, watch the state dict become a junk drawer and every serialized session balloon; paste it into the next stage's instruction and watch the model try to reason about a data URI; or improvise a file path and quietly lose versioning, scoping, and replayability.

ADK already has the right primitive for this, and it is not state — it is **Artifacts**: named, versioned binary blobs managed by an `ArtifactService`, referenced from state as plain strings. This tutorial shows how to pass real payloads between pipeline stages while keeping prompts small, state serializable, and every handoff inspectable.

---

## 1. Two Channels, Two Kinds of Data

ADK gives you two separate mechanisms, and conflating them is the root of 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     │
└───────────────────────┘      └──────────────────────────┘
```

- **Session 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. Never sent to a model unless a stage explicitly loads and needs them.

If a value would not survive being printed in a log, it belongs in an artifact, not in `session.state`.

---

## 2. What Artifacts Give You

From the ADK docs, the mechanics worth knowing before designing handoffs:

- **Storage is delegated.** A `BaseArtifactService` implementation does the actual persisting: `InMemoryArtifactService` for local development, `GcsArtifactService` for durable Google Cloud Storage. You hand one to the `Runner`; contexts inside that runner get access to it.
- **Payloads are `google.genai.types.Part` objects**, with bytes and MIME type in `inline_data`. The MIME type — not the 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` without a version returns the latest; with `version=N` it returns exactly that one. Re-saving `chart.png` in stage 2 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.

---

## 3. Wiring the Runner

No artifact service, no artifacts: calling `save_artifact` or `load_artifact` without one configured on the `Runner` raises. So the wiring step is non-negotiable:

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

APP_NAME = "report_pipeline"

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

runner = Runner(
    agent=root_agent,
    app_name=APP_NAME,
    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 GCS-backed storage for anything that must survive deploys, be shared across sessions with the `user:` prefix, or be audited later.

---

## 4. Saving From a Stage: Keep the Bytes Out of State

The producer stage renders its output inside a tool (or a callback) and saves it through the context. ADK records the save as an `artifact_delta` on the resulting event — `{filename: version}` — so the run itself documents what was written.

```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.
        tool_context: ADK tool context (injected automatically).

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

    # In Python, save through the context so ADK tracks the artifact_delta
    # on the event that follows this tool call. (Async in Python: await it.)
    version = tool_context.save_artifact("chart.png", part)

    # The pointer is what goes into session state — and what downstream sees.
    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."}
```

Three habits keep the prompt clean here:

1. **Return metadata from the tool, never the payload.** The model needs `{"filename": "chart.png", "version": 3}` to reason about what it did; it does not need 900 KB of base64.
2. **Put the pointer in state, not the content.** `chart_file` + `chart_version` is ~60 characters that survive every handoff.
3. **Size discipline for state.** State values must be serializable, and large ones corrupt the whole point of the split — keep state to identifiers, captions, and small structured summaries.

---

## 5. Consuming From the Next Stage

Downstream stages have three escalating options, and picking the cheapest one that works is the whole game.

### Option A — talk about it (usually enough)

The consumer stage only needs to *describe* or *reference* the artifact:

```python
narrative = LlmAgent(
    name="narrative",
    model="gemini-flash-latest",
    instruction="""
    You have a saved chart: {chart_file?} (version {chart_version?}).
    Write a 3-sentence interpretation of the trend it shows, based on the
    underlying numbers in {source_stats?}.
    Reference the chart by name; never attempt to reproduce its contents.
    """,
    output_key="narrative_text",
)
```

State pointers flow in through ordinary `{key}` templating. The bytes are not loaded at all.

### Option B — inject rendered text on purpose

ADK's instruction templating understands artifacts directly: `{artifact.chart.png}` inserts the artifact's *text* content into the instruction. That is appropriate for text-ish artifacts — a CSV, a JSON dump, a log excerpt — where the content genuinely is the input. It is the wrong tool for a PNG or PDF: you would be injecting noise the model cannot use, which is exactly the pollution we are avoiding. Prefer a deliberate text rendering (the caption, a summary table) over raw binary.

### Option C — load the bytes into a tool, not into prose

When a stage truly must process the file — a vision stage inspecting the chart, an extractor parsing the PDF — load it inside a tool where bytes stay in program memory:

```python
from google.adk.tools import ToolContext

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
    # Bytes live in this scope only. Return a compact textual finding.
    findings = my_vision_model.describe(blob.data, blob.mime_type)
    return {"status": "ok", "mime_type": blob.mime_type,
            "bytes": len(blob.data), "findings": findings}
```

Load, compute, discard, return a *finding*. ADK also ships a `LoadArtifactsTool` that lets a model list and pull artifacts on demand — useful when the choice of file isn't known until runtime, but the same discipline applies: what comes back should be text the model can use, not a dump it must wade through.

### Pinning versions matters

`load_artifact("chart.png")` with no version returns the **latest** — which is right for conversational "use the newest chart" flows and wrong for pipelines where stage 3 must read exactly the version stage 2 produced. Pin it: store `chart_version` in state and call `load_artifact(filename, version=state["chart_version"])`. Now a re-run that rewrites the artifact cannot silently change what the next stage analyzed, and you can reproduce any historical run byte-for-byte.

---

## 6. Stopping the Other Polluters

Artifacts solve payload size; three neighbors still sneak bytes into prompts:

- **Conversation history.** A stage that only needs its inputs should say so: `include_contents="none"` gives it its instruction and current-turn input, nothing more. Without it, every prior event — including the producer's tool traffic — is re-sent on every model call.
- **Event echo.** If your tool returns the payload as its response, the model sees it immediately regardless of what you stored. Return envelopes with metadata and a human-readable one-liner.
- **State creep.** Large intermediates that only matter *within* one run belong under the `temp:` namespace — they're available to sibling stages during the invocation and discarded when it completes, so nothing carries forward to poison the next turn.

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

---

## 7. Checklist

- [ ] An `artifact_service` is configured on the `Runner` — otherwise every save/load raises.
- [ ] Producers save `types.Part` payloads with an accurate `mime_type` and return only pointer metadata.
- [ ] State carries `filename` + `version` + a short caption; never bytes, never base64.
- [ ] Consumers either reference the pointer, inject rendered *text*, or load bytes inside a tool — never paste binary into instructions.
- [ ] Pipelines pin `version=` when reading; interactive flows deliberately use latest.
- [ ] Session-scoped filenames for per-run outputs; `user:` prefix for cross-session files.
- [ ] Stages without conversation needs run with `include_contents="none"`.
- [ ] In production, swap `InMemoryArtifactService` for durable storage so artifacts outlive a restart.

**Takeaway:** a clean multi-agent pipeline is a pipeline of *references*. State says what exists and where; artifacts hold what it weighs; prompts receive only the text a model can act on. Keep those three channels separate and you can add stages without your token bill — or your context window — growing with every byte you produce.

## Sources
- Google ADK Documentation: https://adk.dev/
- Artifacts: https://adk.dev/artifacts/
- State: The Session's Scratchpad: https://adk.dev/sessions/state/
