How to manage artifacts and persistent outputs in Google ADK?
#google-adk#artifacts#persistence#files#versioning
Answer
Artifacts in Google ADK
Artifacts are persistent outputs (files, reports, code, images) that agents produce during execution. They are versioned and stored alongside the session.
Artifact Lifecycle
Saving Artifacts
pythonfrom google.genai import types async def generate_report(query: str, tool_context) -> str: """Generate and save a report as an artifact. Args: query: The topic to report on. """ report = f"# Report: {query}\n\nFindings: ..." artifact = types.Part.from_data( data=report.encode(), mime_type="text/markdown" ) version = await tool_context.save_artifact("report.md", artifact) return f"Report saved (version {version})" async def save_chart(data: dict, tool_context) -> str: """Save a chart image as an artifact.""" import matplotlib.pyplot as plt import io fig, ax = plt.subplots() ax.bar(data.keys(), data.values()) buf = io.BytesIO() fig.savefig(buf, format="png") artifact = types.Part.from_data( data=buf.getvalue(), mime_type="image/png" ) version = await tool_context.save_artifact("chart.png", artifact) return f"Chart saved (version {version})"
Loading Artifacts
pythonasync def review_report(tool_context) -> str: """Load and review a previously saved report.""" artifact = await tool_context.load_artifact("report.md") if artifact is None: return "No report found." content = artifact.data.decode() return f"Report content:\n{content}"
Artifact Versioning
python# Each save creates a new version v1 = await tool_context.save_artifact("draft.md", draft_v1) # version 0 v2 = await tool_context.save_artifact("draft.md", draft_v2) # version 1 # Load latest version (default) latest = await tool_context.load_artifact("draft.md") # Load specific version v1_content = await tool_context.load_artifact("draft.md", version=0)
Common Artifact Types
| Type | MIME Type | Use Case |
|---|---|---|
| Text report | text | Analysis results |
| Markdown | text | Formatted reports |
| JSON data | text | Structured output |
| CSV | text | Data exports |
text | Generated documents | |
| PNG/JPG | text | Charts, diagrams |
| Python code | text | Generated scripts |
Learn more at Sessions & Artifacts.