# Artifacts

<div class="language-support-tag">
  <span class="lst-supported">Supported in ADK</span><span class="lst-python">Python v0.1.0</span><span class="lst-typescript">TypeScript v0.6.1</span><span class="lst-go">Go v0.1.0</span><span class="lst-java">Java v0.1.0</span><span class="lst-kotlin">Kotlin v0.1.0</span>
</div>

In ADK, **Artifacts** represent a crucial mechanism for managing named, versioned binary data associated either with a specific user interaction session or persistently with a user across multiple sessions. They allow your agents and tools to handle data beyond simple text strings, enabling richer interactions involving files, images, audio, and other binary formats.

!!! Note
    The specific parameters or method names for the primitives may vary slightly by SDK language (e.g., `save_artifact` in Python, `saveArtifact` in Java). Refer to the language-specific API documentation for details.

## What are Artifacts?

*   **Definition:** An Artifact is essentially a piece of binary data (like the content of a file) identified by a unique `filename` string within a specific scope (session or user). Each time you save an artifact with the same filename, a new version is created.

*   **Representation:** Artifacts are consistently represented using the standard `google.genai.types.Part` object. The core data is typically stored within an inline data structure of the `Part` (accessed via `inline_data`), which itself contains:
    *   `data`: The raw binary content as bytes.
    *   `mime_type`: A string indicating the type of the data (e.g., `"image/png"`, `"application/pdf"`). This is essential for correctly interpreting the data later.


=== "Python"

    ```py
    # Example of how an artifact might be represented as a types.Part
    import google.genai.types as types

    # Assume 'image_bytes' contains the binary data of a PNG image
    image_bytes = b'\x89PNG\r\n\x1a\n...' # Placeholder for actual image bytes

    image_artifact = types.Part(
        inline_data=types.Blob(
            mime_type="image/png",
            data=image_bytes
        )
    )

    # You can also use the convenience constructor:
    # image_artifact_alt = types.Part.from_bytes(data=image_bytes, mime_type="image/png")

    print(f"Artifact MIME Type: {image_artifact.inline_data.mime_type}")
    print(f"Artifact Data (first 10 bytes): {image_artifact.inline_data.data[:10]}...")
    ```

=== "Typescript"

    ```typescript
    import {createPartFromBase64, type Part} from '@google/genai';

    // Assume 'imageBytes' contains the binary data of a PNG image.
    const imageBytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);

    // Using Buffer.from(bytes).toString('base64') for Node.js environments.
    const imageArtifact: Part = createPartFromBase64(
      Buffer.from(imageBytes).toString('base64'),
      'image/png',
    );

    console.log(`Artifact MIME Type: ${imageArtifact.inlineData?.mimeType}`);
    // Note: Accessing raw bytes would require decoding from base64.
    ```

=== "Go"

    ```go
    import (
      "log"

      "google.golang.org/genai"
    )

    --8<-- "examples/go/snippets/artifacts/main.go:representation"
    ```

=== "Java"

    ```java
    import com.google.genai.types.Part;
    import java.nio.charset.StandardCharsets;

    public class ArtifactExample {
        public static void main(String[] args) {
            // Assume 'imageBytes' contains the binary data of a PNG image
            byte[] imageBytes = {(byte) 0x89, (byte) 0x50, (byte) 0x4E, (byte) 0x47, (byte) 0x0D, (byte) 0x0A, (byte) 0x1A, (byte) 0x0A, (byte) 0x01, (byte) 0x02}; // Placeholder for actual image bytes

            // Create an image artifact using Part.fromBytes
            Part imageArtifact = Part.fromBytes(imageBytes, "image/png");

            System.out.println("Artifact MIME Type: " + imageArtifact.inlineData().get().mimeType().get());
            System.out.println(
                "Artifact Data (first 10 bytes): "
                    + new String(imageArtifact.inlineData().get().data().get(), 0, 10, StandardCharsets.UTF_8)
                    + "...");
        }
    }
    ```

=== "Kotlin"

    ```kotlin
    --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:representation"
    ```

*   **Persistence & Management:** Artifacts are not stored directly within the agent or session state. Their storage and retrieval are managed by a dedicated **Artifact Service** (an implementation of `BaseArtifactService`, defined in `google.adk.artifacts`. ADK provides various implementations, such as:
    *   An in-memory service for testing or temporary storage (e.g., `InMemoryArtifactService` in Python, defined in `google.adk.artifacts.in_memory_artifact_service.py`).
    *   A service for persistent storage using Google Cloud Storage (GCS) (e.g., `GcsArtifactService` in Python, defined in `google.adk.artifacts.gcs_artifact_service.py`).
    The chosen service implementation handles versioning automatically when you save data.

## Why Use Artifacts?

While session `state` is suitable for storing small pieces of configuration or conversational context (like strings, numbers, booleans, or small dictionaries/lists), Artifacts are designed for scenarios involving binary or large data:

1. **Handling Non-Textual Data:** Easily store and retrieve images, audio clips, video snippets, PDFs, spreadsheets, or any other file format relevant to your agent's function.
2. **Persisting Large Data:** Session state is generally not optimized for storing large amounts of data. Artifacts provide a dedicated mechanism for persisting larger blobs without cluttering the session state.
3. **User File Management:** Provide capabilities for users to upload files (which can be saved as artifacts) and retrieve or download files generated by the agent (loaded from artifacts).
4. **Sharing Outputs:** Enable tools or agents to generate binary outputs (like a PDF report or a generated image) that can be saved via `save_artifact` and later accessed by other parts of the application or even in subsequent sessions (if using user namespacing).
5. **Caching Binary Data:** Store the results of computationally expensive operations that produce binary data (e.g., rendering a complex chart image) as artifacts to avoid regenerating them on subsequent requests.

In essence, whenever your agent needs to work with file-like binary data that needs to be persisted, versioned, or shared, Artifacts managed by an `ArtifactService` are the appropriate mechanism within ADK.


## Common Use Cases

Artifacts provide a flexible way to handle binary data within your ADK applications.

Here are some typical scenarios where they prove valuable:

* **Generated Reports/Files:**
    * A tool or agent generates a report (e.g., a PDF analysis, a CSV data export, an image chart).

* **Handling User Uploads:**

    * A user uploads a file (e.g., an image for analysis, a document for summarization) through a front-end interface.

* **Storing Intermediate Binary Results:**

    * An agent performs a complex multi-step process where one step generates intermediate binary data (e.g., audio synthesis, simulation results).

* **Persistent User Data:**

    * Storing user-specific configuration or data that isn't a simple key-value state.

* **Caching Generated Binary Content:**

    * An agent frequently generates the same binary output based on certain inputs (e.g., a company logo image, a standard audio greeting).



## Core Concepts

Understanding artifacts involves grasping a few key components: the service that manages them, the data structure used to hold them, and how they are identified and versioned.

### Artifact Service (`BaseArtifactService`)

* **Role:** The central component responsible for the actual storage and retrieval logic for artifacts. It defines *how* and *where* artifacts are persisted.

* **Interface:** Defined by the abstract base class `BaseArtifactService`. Any concrete implementation must provide methods for:

    * `Save Artifact`: Stores the artifact data and returns its assigned version number.
    * `Load Artifact`: Retrieves a specific version (or the latest) of an artifact.
    * `List Artifact keys`: Lists the unique filenames of artifacts within a given scope.
    * `Delete Artifact`: Removes an artifact (and potentially all its versions, depending on implementation).
    * `List versions`: Lists all available version numbers for a specific artifact filename.

* **Configuration:** You provide an instance of an artifact service (e.g., `InMemoryArtifactService`, `GcsArtifactService`) when initializing the `Runner`. The `Runner` then makes this service available to agents and tools via the `InvocationContext`.

=== "Python"

    ```py
    from google.adk.runners import Runner
    from google.adk.artifacts import InMemoryArtifactService # Or GcsArtifactService
    from google.adk.agents import LlmAgent # Any agent
    from google.adk.sessions import InMemorySessionService

    # Example: Configuring the Runner with an Artifact Service
    my_agent = LlmAgent(name="artifact_user_agent", model="gemini-flash-latest")
    artifact_service = InMemoryArtifactService() # Choose an implementation
    session_service = InMemorySessionService()

    runner = Runner(
        agent=my_agent,
        app_name="my_artifact_app",
        session_service=session_service,
        artifact_service=artifact_service # Provide the service instance here
    )
    # Now, contexts within runs managed by this runner can use artifact methods
    ```

=== "Typescript"

    ```typescript
    import {
      InMemoryArtifactService,
      InMemorySessionService,
      LlmAgent,
      Runner,
    } from '@google/adk';

    // Example: Configuring the Runner with an Artifact Service
    const myAgent = new LlmAgent({
      name: 'artifact_user_agent',
      model: 'gemini-flash-latest',
    });
    const artifactService = new InMemoryArtifactService();
    const sessionService = new InMemorySessionService();

    const runner = new Runner({
      agent: myAgent,
      appName: 'my_artifact_app',
      sessionService: sessionService,
      artifactService: artifactService,
    });
    // Now, contexts within runs managed by this runner can use artifact methods.
    ```

=== "Go"

    ```go
    import (
      "context"
      "log"

      "google.golang.org/adk/agent/llmagent"
      "google.golang.org/adk/artifactservice"
      "google.golang.org/adk/llm/gemini"
      "google.golang.org/adk/runner"
      "google.golang.org/adk/sessionservice"
      "google.golang.org/genai"
	)

	--8<-- "examples/go/snippets/artifacts/main.go:configure-runner"
    ```

=== "Java"

    ```java
    import com.google.adk.agents.LlmAgent;
    import com.google.adk.runner.Runner;
    import com.google.adk.sessions.InMemorySessionService;
    import com.google.adk.artifacts.InMemoryArtifactService;

    // Example: Configuring the Runner with an Artifact Service
    LlmAgent myAgent =  LlmAgent.builder()
      .name("artifact_user_agent")
      .model("gemini-flash-latest")
      .build();
    InMemoryArtifactService artifactService = new InMemoryArtifactService(); // Choose an implementation
    InMemorySessionService sessionService = new InMemorySessionService();

    Runner runner = new Runner(myAgent, "my_artifact_app", artifactService, sessionService); // Provide the service instance here
    // Now, contexts within runs managed by this runner can use artifact methods
    ```

=== "Kotlin"

    ```kotlin
    --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:configure_runner"
    ```

### Artifact Data

* **Standard Representation:** Artifact content is universally represented using the `google.genai.types.Part` object, the same structure used for parts of LLM messages.

* **Key Attribute (`inline_data`):** For artifacts, the most relevant attribute is `inline_data`, which is a `google.genai.types.Blob` object containing:

    * `data` (`bytes`): The raw binary content of the artifact.
    * `mime_type` (`str`): A standard MIME type string (e.g., `'application/pdf'`, `'image/png'`, `'audio/mpeg'`) describing the nature of the binary data. **This is crucial for correct interpretation when loading the artifact.**

=== "Python"

    ```python
    import google.genai.types as types

    # Example: Creating an artifact Part from raw bytes
    pdf_bytes = b'%PDF-1.4...' # Your raw PDF data
    pdf_mime_type = "application/pdf"

    # Using the constructor
    pdf_artifact_py = types.Part(
        inline_data=types.Blob(data=pdf_bytes, mime_type=pdf_mime_type)
    )

    # Using the convenience class method (equivalent)
    pdf_artifact_alt_py = types.Part.from_bytes(data=pdf_bytes, mime_type=pdf_mime_type)

    print(f"Created Python artifact with MIME type: {pdf_artifact_py.inline_data.mime_type}")
    ```

=== "Typescript"

    ```typescript
    import {createPartFromBase64, type Part} from '@google/genai';

    // Example: Creating an artifact Part from raw bytes.
    const pdfBytes = new Uint8Array([0x25, 0x50, 0x44, 0x46, 0x2d, 0x31, 0x2e, 0x34]);
    const pdfMimeType = 'application/pdf';

    // Using Buffer.from(bytes).toString('base64') for Node.js environments.
    const pdfArtifact: Part = createPartFromBase64(
      Buffer.from(pdfBytes).toString('base64'),
      pdfMimeType,
    );
    console.log(`Created TypeScript artifact with MIME Type: ${pdfArtifact.inlineData?.mimeType}`);
    ```

=== "Go"

    ```go
    import (
      "log"
      "os"

      "google.golang.org/genai"
    )

    --8<-- "examples/go/snippets/artifacts/main.go:artifact-data"
    ```

=== "Java"

    ```java
    --8<-- "examples/java/snippets/src/main/java/artifacts/ArtifactDataExample.java:full_code"
    ```

=== "Kotlin"

    ```kotlin
    --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:artifact_data"
    ```

### Filename

* **Identifier:** A simple string used to name and retrieve an artifact within its specific namespace.
* **Uniqueness:** Filenames must be unique within their scope (either the session or the user namespace).
* **Best Practice:** Use descriptive names, potentially including file extensions (e.g., `"monthly_report.pdf"`, `"user_avatar.jpg"`), although the extension itself doesn't dictate behavior – the `mime_type` does.

### Versioning

* **Automatic Versioning:** The artifact service automatically handles versioning. When you call `save_artifact`, the service determines the next available version number (typically starting from 0 and incrementing) for that specific filename and scope.
* **Returned by `save_artifact`:** The `save_artifact` method returns the integer version number that was assigned to the newly saved artifact.
* **Retrieval:**
  * `load_artifact(..., version=None)` (default): Retrieves the *latest* available version of the artifact.
  * `load_artifact(..., version=N)`: Retrieves the specific version `N`.
* **Listing Versions:** The `list_versions` method (on the service, not context) can be used to find all existing version numbers for an artifact.

### Namespacing (Session vs. User)

* **Concept:** Artifacts can be scoped either to a specific session or more broadly to a user across all their sessions within the application. This scoping is determined by the `filename` format and handled internally by the `ArtifactService`.

* **Default (Session Scope):** If you use a plain filename like `"report.pdf"`, the artifact is associated with the specific `app_name`, `user_id`, *and* `session_id`. It's only accessible within that exact session context.


* **User Scope (`"user:"` prefix):** If you prefix the filename with `"user:"`, like `"user:profile.png"`, the artifact is associated only with the `app_name` and `user_id`. It can be accessed or updated from *any* session belonging to that user within the app.


=== "Python"

    ```python
    # Example illustrating namespace difference (conceptual)

    # Session-specific artifact filename
    session_report_filename = "summary.txt"

    # User-specific artifact filename
    user_config_filename = "user:settings.json"

    # When saving 'summary.txt' via context.save_artifact,
    # it's tied to the current app_name, user_id, and session_id.

    # When saving 'user:settings.json' via context.save_artifact,
    # the ArtifactService implementation should recognize the "user:" prefix
    # and scope it to app_name and user_id, making it accessible across sessions for that user.
    ```

=== "Typescript"

    ```typescript
    // Example illustrating namespace difference (conceptual)

    // Session-specific artifact filename
    const sessionReportFilename = "summary.txt";

    // User-specific artifact filename
    const userConfigFilename = "user:settings.json";

    // When saving 'summary.txt' via context.saveArtifact, it's tied to the current appName, userId, and sessionId.
    // When saving 'user:settings.json' via context.saveArtifact, the ArtifactService implementation recognizes the "user:" prefix and scopes it to appName and userId, making it accessible across sessions for that user.
    ```

=== "Go"

    ```go
    import (
      "log"
    )

    --8<-- "examples/go/snippets/artifacts/main.go:namespacing"
    ```

=== "Java"

    ```java
    // Example illustrating namespace difference (conceptual)

    // Session-specific artifact filename
    String sessionReportFilename = "summary.txt";

    // User-specific artifact filename
    String userConfigFilename = "user:settings.json"; // The "user:" prefix is key

    // When saving 'summary.txt' via context.save_artifact,
    // it's tied to the current app_name, user_id, and session_id.
    // artifactService.saveArtifact(appName, userId, sessionId1, sessionReportFilename, someData);

    // When saving 'user:settings.json' via context.save_artifact,
    // the ArtifactService implementation should recognize the "user:" prefix
    // and scope it to app_name and user_id, making it accessible across sessions for that user.
    // artifactService.saveArtifact(appName, userId, sessionId1, userConfigFilename, someData);
    ```

=== "Kotlin"

    ```kotlin
    --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:namespacing"
    ```

These core concepts work together to provide a flexible system for managing binary data within the ADK framework.

## Interacting with Artifacts (via Context Objects)

The primary way you interact with artifacts within your agent's logic (specifically within callbacks or tools) is through methods provided by the `CallbackContext` and `ToolContext` objects. These methods abstract away the underlying storage details managed by the `ArtifactService`.

*(Note: In TypeScript, `CallbackContext` and `ToolContext` are unified into a single `Context` type.)*

### Prerequisite: Configuring the `ArtifactService`

Before you can use any artifact methods via the context objects, you **must** provide an instance of a [`BaseArtifactService` implementation](#available-implementations) (like [`InMemoryArtifactService`](#inmemoryartifactservice) or [`GcsArtifactService`](#gcsartifactservice)) when initializing your `Runner`.

=== "Python"

    In Python, you provide this instance when initializing your `Runner`.

    ```python
    from google.adk.runners import Runner
    from google.adk.artifacts import InMemoryArtifactService # Or GcsArtifactService
    from google.adk.agents import LlmAgent
    from google.adk.sessions import InMemorySessionService

    # Your agent definition
    agent = LlmAgent(name="my_agent", model="gemini-flash-latest")

    # Instantiate the desired artifact service
    artifact_service = InMemoryArtifactService()

    # Provide it to the Runner
    runner = Runner(
        agent=agent,
        app_name="artifact_app",
        session_service=InMemorySessionService(),
        artifact_service=artifact_service # Service must be provided here
    )
    ```
    If no `artifact_service` is configured in the `InvocationContext` (which happens if it's not passed to the `Runner`), calling `save_artifact`, `load_artifact`, or `list_artifacts` on the context objects will raise a `ValueError`.

=== "Typescript"

    ```typescript
    import {
      InMemoryArtifactService,
      InMemorySessionService,
      LlmAgent,
      Runner,
    } from '@google/adk';

    // Your agent definition.
    const agent = new LlmAgent({
      name: 'my_agent',
      model: 'gemini-flash-latest',
    });

    // Instantiate the desired artifact service.
    const artifactService = new InMemoryArtifactService();

    // Provide it to the Runner.
    const runner = new Runner({
      agent: agent,
      appName: 'artifact_app',
      sessionService: new InMemorySessionService(),
      artifactService: artifactService,
    });
    // If no artifactService is configured, calling artifact methods on context objects will throw an error.
    ```
    In Java, if an `ArtifactService` instance is not available (e.g., `null`) when artifact operations are attempted, it would typically result in a `NullPointerException` or a custom error, depending on how your application is structured. Robust applications often use dependency injection frameworks to manage service lifecycles and ensure availability.

=== "Go"

    ```go
    import (
      "context"
      "log"

      "google.golang.org/adk/agent/llmagent"
      "google.golang.org/adk/artifactservice"
      "google.golang.org/adk/llm/gemini"
      "google.golang.org/adk/runner"
      "google.golang.org/adk/sessionservice"
      "google.golang.org/genai"
    )

    --8<-- "examples/go/snippets/artifacts/main.go:prerequisite"
    ```

=== "Java"

    In Java, you would instantiate a `BaseArtifactService` implementation and then ensure it's accessible to the parts of your application that manage artifacts. This is often done through dependency injection or by explicitly passing the service instance.

    ```java
    import com.google.adk.agents.LlmAgent;
    import com.google.adk.artifacts.InMemoryArtifactService; // Or GcsArtifactService
    import com.google.adk.runner.Runner;
    import com.google.adk.sessions.InMemorySessionService;

    public class SampleArtifactAgent {

      public static void main(String[] args) {

        // Your agent definition
        LlmAgent agent = LlmAgent.builder()
            .name("my_agent")
            .model("gemini-flash-latest")
            .build();

        // Instantiate the desired artifact service
        InMemoryArtifactService artifactService = new InMemoryArtifactService();

        // Provide it to the Runner
        Runner runner = new Runner(agent,
            "APP_NAME",
            artifactService, // Service must be provided here
            new InMemorySessionService());

      }
    }
    ```

=== "Kotlin"

    In Kotlin, you provide this instance when initializing your `Runner`.

    ```kotlin
    --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:configure_runner"
    ```
    If no `artifactService` is configured, calling `saveArtifact`, `loadArtifact`, or `listArtifacts` on the context objects will throw an exception.

### Accessing Methods

The artifact interaction methods are available directly on instances of `CallbackContext` (passed to agent and model callbacks) and `ToolContext` (passed to tool callbacks) in Python, Go, and Java and available on the unified `Context` in TypeScript.

#### Saving Artifacts

*   **Code Example:**

    === "Python"

        ```python
        import google.genai.types as types
        from google.adk.agents.callback_context import CallbackContext # Or ToolContext

        async def save_generated_report_py(context: CallbackContext, report_bytes: bytes):
            """Saves generated PDF report bytes as an artifact."""
            report_artifact = types.Part.from_bytes(
                data=report_bytes,
                mime_type="application/pdf"
            )
            filename = "generated_report.pdf"

            try:
                version = await context.save_artifact(filename=filename, artifact=report_artifact)
                print(f"Successfully saved Python artifact '{filename}' as version {version}.")
                # The event generated after this callback will contain:
                # event.actions.artifact_delta == {"generated_report.pdf": version}
            except ValueError as e:
                print(f"Error saving Python artifact: {e}. Is ArtifactService configured in Runner?")
            except Exception as e:
                # Handle potential storage errors (e.g., GCS permissions)
                print(f"An unexpected error occurred during Python artifact save: {e}")

        # --- Example Usage Concept (Python) ---
        # async def main_py():
        #   callback_context: CallbackContext = ... # obtain context
        #   report_data = b'...' # Assume this holds the PDF bytes
        #   await save_generated_report_py(callback_context, report_data)
        ```

    === "Typescript"

        ```typescript
        import {Context} from '@google/adk';
        import {createPartFromBase64, type Part} from '@google/genai';

        async function saveGeneratedReport(context: Context, reportBytes: Uint8Array): Promise<void> {
          /** Saves generated PDF report bytes as an artifact. */
          const reportArtifact: Part = createPartFromBase64(
            Buffer.from(reportBytes).toString('base64'),
            'application/pdf',
          );

          const filename = 'generated_report.pdf';

          try {
            const version = await context.saveArtifact(filename, reportArtifact);
            console.log(`Successfully saved TypeScript artifact '${filename}' as version ${version}.`);
          } catch (e: any) {
            console.error(
              `Error saving TypeScript artifact: ${e.message}. Is ArtifactService configured in Runner?`,
            );
          }
        }
        ```
    === "Go"

        ```go
        import (
          "log"

          "google.golang.org/adk/agent"
          "google.golang.org/adk/llm"
          "google.golang.org/genai"
        )

        --8<-- "examples/go/snippets/artifacts/main.go:saving-artifacts"
        ```

    === "Java"

        ```java
        import com.google.adk.agents.CallbackContext;
        import com.google.adk.artifacts.BaseArtifactService;
        import com.google.adk.artifacts.InMemoryArtifactService;
        import com.google.genai.types.Part;
        import java.nio.charset.StandardCharsets;

        public class SaveArtifactExample {

        public void saveGeneratedReport(CallbackContext callbackContext, byte[] reportBytes) {
        // Saves generated PDF report bytes as an artifact.
        Part reportArtifact = Part.fromBytes(reportBytes, "application/pdf");
        String filename = "generatedReport.pdf";

            callbackContext.saveArtifact(filename, reportArtifact);
            System.out.println("Successfully saved Java artifact '" + filename);
            // The event generated after this callback will contain:
            // event().actions().artifactDelta == {"generated_report.pdf": version}
        }

        // --- Example Usage Concept (Java) ---
        public static void main(String[] args) {
            BaseArtifactService service = new InMemoryArtifactService(); // Or GcsArtifactService
            SaveArtifactExample myTool = new SaveArtifactExample();
            byte[] reportData = "...".getBytes(StandardCharsets.UTF_8); // PDF bytes
            CallbackContext callbackContext; // ... obtain callback context from your app
            myTool.saveGeneratedReport(callbackContext, reportData);
            // Due to async nature, in a real app, ensure program waits or handles completion.
          }
        }
        ```

    === "Kotlin"

        In Kotlin, you access the `ArtifactService` from the `ToolContext` (or `CallbackContext` via `invocationContext`) to save an artifact.

        ```kotlin
        --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:interaction_save"
        ```

#### Loading Artifacts

*   **Code Example:**

    === "Python"

        ```python
        import google.genai.types as types
        from google.adk.agents.callback_context import CallbackContext # Or ToolContext

        async def process_latest_report_py(context: CallbackContext):
            """Loads the latest report artifact and processes its data."""
            filename = "generated_report.pdf"
            try:
                # Load the latest version
                report_artifact = await context.load_artifact(filename=filename)

                if report_artifact and report_artifact.inline_data:
                    print(f"Successfully loaded latest Python artifact '{filename}'.")
                    print(f"MIME Type: {report_artifact.inline_data.mime_type}")
                    # Process the report_artifact.inline_data.data (bytes)
                    pdf_bytes = report_artifact.inline_data.data
                    print(f"Report size: {len(pdf_bytes)} bytes.")
                    # ... further processing ...
                else:
                    print(f"Python artifact '{filename}' not found.")

                # Example: Load a specific version (if version 0 exists)
                # specific_version_artifact = await context.load_artifact(filename=filename, version=0)
                # if specific_version_artifact:
                #     print(f"Loaded version 0 of '{filename}'.")

            except ValueError as e:
                print(f"Error loading Python artifact: {e}. Is ArtifactService configured?")
            except Exception as e:
                # Handle potential storage errors
                print(f"An unexpected error occurred during Python artifact load: {e}")

        # --- Example Usage Concept (Python) ---
        # async def main_py():
        #   callback_context: CallbackContext = ... # obtain context
        #   await process_latest_report_py(callback_context)
        ```

    === "Typescript"

        ```typescript
        import {Context} from '@google/adk';

        async function processLatestReport(context: Context): Promise<void> {
          /** Loads the latest report artifact and processes its data. */
          const filename = 'generated_report.pdf';
          try {
            // Load the latest version
            const reportArtifact = await context.loadArtifact(filename);

            if (reportArtifact?.inlineData) {
              console.log(`Successfully loaded latest TypeScript artifact '${filename}'.`);
              console.log(`MIME Type: ${reportArtifact.inlineData.mimeType}`);
              // Process the reportArtifact.inlineData.data (base64 string)
              const pdfData = Buffer.from(reportArtifact.inlineData.data || '', 'base64');
              console.log(`Report size: ${pdfData.length} bytes.`);
              // ... further processing ...
            } else {
              console.log(`TypeScript artifact '${filename}' not found.`);
            }
          } catch (e: any) {
            console.error(
              `Error loading TypeScript artifact: ${e.message}. Is ArtifactService configured?`,
            );
          }
        }
        ```

    === "Go"

        ```go
        import (
          "log"

          "google.golang.org/adk/agent"
          "google.golang.org/adk/llm"
        )

        --8<-- "examples/go/snippets/artifacts/main.go:loading-artifacts"
        ```

    === "Java"

        ```java
        import com.google.adk.artifacts.BaseArtifactService;
        import com.google.genai.types.Part;
        import io.reactivex.rxjava3.core.MaybeObserver;
        import io.reactivex.rxjava3.disposables.Disposable;
        import java.util.Optional;

        public class MyArtifactLoaderService {

            private final BaseArtifactService artifactService;
            private final String appName;

            public MyArtifactLoaderService(BaseArtifactService artifactService, String appName) {
                this.artifactService = artifactService;
                this.appName = appName;
            }

            public void processLatestReportJava(String userId, String sessionId, String filename) {
                // Load the latest version by passing Optional.empty() for the version
                artifactService
                        .loadArtifact(appName, userId, sessionId, filename, Optional.empty())
                        .subscribe(
                                new MaybeObserver<Part>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {
                                        // Optional: handle subscription
                                    }

                                    @Override
                                    public void onSuccess(Part reportArtifact) {
                                        System.out.println(
                                                "Successfully loaded latest Java artifact '" + filename + "'.");
                                        reportArtifact
                                                .inlineData()
                                                .ifPresent(
                                                        blob -> {
                                                            System.out.println(
                                                                    "MIME Type: " + blob.mimeType().orElse("N/A"));
                                                            byte[] pdfBytes = blob.data().orElse(new byte[0]);
                                                            System.out.println("Report size: " + pdfBytes.length + " bytes.");
                                                            // ... further processing of pdfBytes ...
                                                        });
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        // Handle potential storage errors or other exceptions
                                        System.err.println(
                                                "An error occurred during Java artifact load for '"
                                                        + filename
                                                        + "': "
                                                        + e.getMessage());
                                    }

                                    @Override
                                    public void onComplete() {
                                        // Called if the artifact (latest version) is not found
                                        System.out.println("Java artifact '" + filename + "' not found.");
                                    }
                                });

                // Example: Load a specific version (e.g., version 0)
                /*
                artifactService.loadArtifact(appName, userId, sessionId, filename, Optional.of(0))
                    .subscribe(part -> {
                        System.out.println("Loaded version 0 of Java artifact '" + filename + "'.");
                    }, throwable -> {
                        System.err.println("Error loading version 0 of '" + filename + "': " + throwable.getMessage());
                    }, () -> {
                        System.out.println("Version 0 of Java artifact '" + filename + "' not found.");
                    });
                */
            }

            // --- Example Usage Concept (Java) ---
            public static void main(String[] args) {
                // BaseArtifactService service = new InMemoryArtifactService(); // Or GcsArtifactService
                // MyArtifactLoaderService loader = new MyArtifactLoaderService(service, "myJavaApp");
                // loader.processLatestReportJava("user123", "sessionABC", "java_report.pdf");
                // Due to async nature, in a real app, ensure program waits or handles completion.
            }
        }
        ```

    === "Kotlin"

        In Kotlin, you can load an artifact directly from the `ToolContext` (or `CallbackContext`) using `context.loadArtifact(name)`.

        ```kotlin
        --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:interaction_load"
        ```

#### Using `LoadArtifactsTool`

You can add `LoadArtifactsTool` when the model should decide which available
artifacts to load before answering. This is useful when users ask follow-up
questions about uploaded files or large generated outputs that are stored as
artifacts instead of kept in the conversation context.

`LoadArtifactsTool` lists available artifacts in the model instructions. When
the model calls the `load_artifacts` tool, ADK temporarily appends the selected
artifact contents to that request so the model can answer with the file content
in context. The loaded artifact content is not permanently saved back into the
session history, so the model should call the tool again when it needs the same
artifact in a later turn.

=== "Python"

    ```python
    from google.adk.agents import LlmAgent
    from google.adk.tools.load_artifacts_tool import LoadArtifactsTool

    root_agent = LlmAgent(
        name="artifact_reader",
        model="gemini-flash-latest",
        instruction=(
            "Answer questions about available user files. "
            "Call load_artifacts before answering when you need file contents."
        ),
        tools=[
            LoadArtifactsTool(),
        ],
    )
    ```

    Make sure the `Runner` for this agent is configured with an
    `artifact_service`; otherwise artifact listing and loading will fail. If
    your artifacts need human-readable summaries, subclass `LoadArtifactsTool`
    and customize its request instructions before loading the selected artifact
    contents.

=== "Go"

    ```go
    import (
      "google.golang.org/adk/agent/llmagent"
      "google.golang.org/adk/tool"
      "google.golang.org/adk/tool/loadartifactstool"
    )

    agent, err := llmagent.New(llmagent.Config{
        Name:        "artifact_reader",
        Model:       model,
        Instruction: "Answer questions about available user files. " +
            "When user asks about artifacts, load them and describe them.",
        Tools: []tool.Tool{
            loadartifactstool.New(),
        },
    })
    ```

    Make sure the `runner.Config` for this agent includes an
    `ArtifactService`; otherwise artifact listing and loading will fail.

=== "Kotlin"

    ```kotlin
    --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:load_artifacts_tool"
    ```

    Make sure the `Runner` for this agent is configured with an
    `artifactService`; otherwise artifact listing and loading will fail.

#### Listing Artifact Filenames

*   **Code Example:**

    === "Python"

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

        def list_user_files_py(tool_context: ToolContext) -> str:
            """Tool to list available artifacts for the user."""
            try:
                available_files = await tool_context.list_artifacts()
                if not available_files:
                    return "You have no saved artifacts."
                else:
                    # Format the list for the user/LLM
                    file_list_str = "\n".join([f"- {fname}" for fname in available_files])
                    return f"Here are your available Python artifacts:\n{file_list_str}"
            except ValueError as e:
                print(f"Error listing Python artifacts: {e}. Is ArtifactService configured?")
                return "Error: Could not list Python artifacts."
            except Exception as e:
                print(f"An unexpected error occurred during Python artifact list: {e}")
                return "Error: An unexpected error occurred while listing Python artifacts."

        # This function would typically be wrapped in a FunctionTool
        # from google.adk.tools import FunctionTool
        # list_files_tool = FunctionTool(func=list_user_files_py)
        ```

    === "Typescript"

        ```typescript
        import {Context} from '@google/adk';

        async function listUserFiles(context: Context): Promise<string> {
          /** Tool to list available artifacts for the user. */
          try {
            const availableFiles = await context.listArtifacts();
            if (!availableFiles || availableFiles.length === 0) {
              return 'You have no saved artifacts.';
            } else {
              // Format the list for the user/LLM
              const fileListStr = availableFiles.map((fname) => `- ${fname}`).join('\n');
              return `Here are your available TypeScript artifacts:\n${fileListStr}`;
            }
          } catch (e: any) {
            console.error(
              `Error listing TypeScript artifacts: ${e.message}. Is ArtifactService configured?`,
            );
            return 'Error: Could not list TypeScript artifacts.';
          }
        }
        ```

    === "Go"

        ```go
        import (
          "fmt"
          "log"
          "strings"

          "google.golang.org/adk/agent"
          "google.golang.org/adk/llm"
          "google.golang.org/genai"
        )

        --8<-- "examples/go/snippets/artifacts/main.go:listing-artifacts"
        ```

    === "Java"

        ```java
        import com.google.adk.artifacts.BaseArtifactService;
        import com.google.adk.artifacts.ListArtifactsResponse;
        import com.google.common.collect.ImmutableList;
        import io.reactivex.rxjava3.core.SingleObserver;
        import io.reactivex.rxjava3.disposables.Disposable;

        public class MyArtifactListerService {

            private final BaseArtifactService artifactService;
            private final String appName;

            public MyArtifactListerService(BaseArtifactService artifactService, String appName) {
                this.artifactService = artifactService;
                this.appName = appName;
            }

            // Example method that might be called by a tool or agent logic
            public void listUserFilesJava(String userId, String sessionId) {
                artifactService
                        .listArtifactKeys(appName, userId, sessionId)
                        .subscribe(
                                new SingleObserver<ListArtifactsResponse>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {
                                        // Optional: handle subscription
                                    }

                                    @Override
                                    public void onSuccess(ListArtifactsResponse response) {
                                        ImmutableList<String> availableFiles = response.filenames();
                                        if (availableFiles.isEmpty()) {
                                            System.out.println(
                                                    "User "
                                                            + userId
                                                            + " in session "
                                                            + sessionId
                                                            + " has no saved Java artifacts.");
                                        } else {
                                            StringBuilder fileListStr =
                                                    new StringBuilder(
                                                            "Here are the available Java artifacts for user "
                                                                    + userId
                                                                    + " in session "
                                                                    + sessionId
                                                                    + ":\n");
                                            for (String fname : availableFiles) {
                                                fileListStr.append("- ").append(fname).append("\n");
                                            }
                                            System.out.println(fileListStr.toString());
                                        }
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        System.err.println(
                                                "Error listing Java artifacts for user "
                                                        + userId
                                                        + " in session "
                                                        + sessionId
                                                        + ": "
                                                        + e.getMessage());
                                        // In a real application, you might return an error message to the user/LLM
                                    }
                                });
            }

            // --- Example Usage Concept (Java) ---
            public static void main(String[] args) {
                // BaseArtifactService service = new InMemoryArtifactService(); // Or GcsArtifactService
                // MyArtifactListerService lister = new MyArtifactListerService(service, "myJavaApp");
                // lister.listUserFilesJava("user123", "sessionABC");
                // Due to async nature, in a real app, ensure program waits or handles completion.
            }
        }
        ```

=== "Kotlin"

    ```kotlin
    --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:listing_artifacts"
    ```

These methods for saving, loading, and listing provide a convenient and consistent way to manage binary data persistence within ADK, whether using Python's context objects or directly interacting with the `BaseArtifactService` in Java, regardless of the chosen backend storage implementation.

## Available Implementations

ADK provides concrete implementations of the `BaseArtifactService` interface, offering different storage backends suitable for various development stages and deployment needs. These implementations handle the details of storing, versioning, and retrieving artifact data based on the `app_name`, `user_id`, `session_id`, and `filename` (including the `user:` namespace prefix).

### InMemoryArtifactService

*   **Storage Mechanism:**
    *   Python: Uses a Python dictionary (`self.artifacts`) held in the application's memory. The dictionary keys represent the artifact path, and the values are lists of `types.Part`, where each list element is a version.
    *   Java: Uses nested `HashMap` instances (`private final Map<String, Map<String, Map<String, Map<String, List<Part>>>>> artifacts;`) held in memory. The keys at each level are `appName`, `userId`, `sessionId`, and `filename` respectively. The innermost `List<Part>` stores the versions of the artifact, where the list index corresponds to the version number.
*   **Key Features:**
    *   **Simplicity:** Requires no external setup or dependencies beyond the core ADK library.
    *   **Speed:** Operations are typically very fast as they involve in-memory map/dictionary lookups and list manipulations.
    *   **Ephemeral:** All stored artifacts are **lost** when the application process terminates. Data does not persist between application restarts.
*   **Use Cases:**
    *   Ideal for local development and testing where persistence is not required.
    *   Suitable for short-lived demonstrations or scenarios where artifact data is purely temporary within a single run of the application.
*   **Instantiation:**

    === "Python"

        ```python
        from google.adk.artifacts import InMemoryArtifactService

        # Simply instantiate the class
        in_memory_service_py = InMemoryArtifactService()

        # Then pass it to the Runner
        # runner = Runner(..., artifact_service=in_memory_service_py)
        ```

    === "Typescript"

        ```typescript
        import {InMemoryArtifactService} from '@google/adk';

        // Simply instantiate the class
        const inMemoryService = new InMemoryArtifactService();

        // This instance would then be provided to your Runner.
        // const runner = new Runner({
        //   /* other services */,
        //   artifactService: inMemoryService
        // });
        ```

    === "Go"

        ```go
        import (
          "google.golang.org/adk/artifactservice"
        )

        --8<-- "examples/go/snippets/artifacts/main.go:in-memory-service"
        ```

    === "Java"

        ```java
        import com.google.adk.artifacts.BaseArtifactService;
        import com.google.adk.artifacts.InMemoryArtifactService;

        public class InMemoryServiceSetup {
            public static void main(String[] args) {
                // Simply instantiate the class
                BaseArtifactService inMemoryServiceJava = new InMemoryArtifactService();

                System.out.println("InMemoryArtifactService (Java) instantiated: " + inMemoryServiceJava.getClass().getName());

                // This instance would then be provided to your Runner.
                // Runner runner = new Runner(
                //     /* other services */,
                //     inMemoryServiceJava
                // );
            }
        }
        ```

    === "Kotlin"

        ```kotlin
        --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:in_memory_service"
        ```
### GcsArtifactService


*   **Storage Mechanism:** Leverages Google Cloud Storage (GCS) for persistent artifact storage. Each version of an artifact is stored as a separate object (blob) within a specified GCS bucket.
*   **Object Naming Convention:** It constructs GCS object names (blob names) using a hierarchical path structure.
*   **Key Features:**
    *   **Persistence:** Artifacts stored in GCS persist across application restarts and deployments.
    *   **Scalability:** Leverages the scalability and durability of Google Cloud Storage.
    *   **Versioning:** Explicitly stores each version as a distinct GCS object. The `saveArtifact` method in `GcsArtifactService`.
    *   **Permissions Required:** The application environment needs appropriate credentials (e.g., Application Default Credentials) and IAM permissions to read from and write to the specified GCS bucket.
*   **Use Cases:**
    *   Production environments requiring persistent artifact storage.
    *   Scenarios where artifacts need to be shared across different application instances or services (by accessing the same GCS bucket).
    *   Applications needing long-term storage and retrieval of user or session data.
*   **Instantiation:**

    === "Python"

        ```python
        from google.adk.artifacts import GcsArtifactService

        # Specify the GCS bucket name
        gcs_bucket_name_py = "your-gcs-bucket-for-adk-artifacts" # Replace with your bucket name

        try:
            gcs_service_py = GcsArtifactService(bucket_name=gcs_bucket_name_py)
            print(f"Python GcsArtifactService initialized for bucket: {gcs_bucket_name_py}")
            # Ensure your environment has credentials to access this bucket.
            # e.g., via Application Default Credentials (ADC)

            # Then pass it to the Runner
            # runner = Runner(..., artifact_service=gcs_service_py)

        except Exception as e:
            # Catch potential errors during GCS client initialization (e.g., auth issues)
            print(f"Error initializing Python GcsArtifactService: {e}")
            # Handle the error appropriately - maybe fall back to InMemory or raise
        ```

    === "Typescript"

        ```typescript
        import {GcsArtifactService} from '@google/adk';

        // Specify the GCS bucket name.
        const gcsBucketName = 'your-gcs-bucket-for-adk-artifacts';

        try {
          const gcsService = new GcsArtifactService(gcsBucketName);
          console.log(`TypeScript GcsArtifactService initialized for bucket: ${gcsBucketName}`);
          // Ensure your environment has credentials to access this bucket.
          // e.g., via Application Default Credentials (ADC).

          // Then pass it to the Runner.
          // const runner = new Runner({..., artifactService: gcsService});
        } catch (e: any) {
          // Catch potential errors during GCS client initialization (e.g., auth issues).
          console.error(`Error initializing TypeScript GcsArtifactService: ${e.message}`);
        }
        ```

    === "Java"

        ```java
        --8<-- "examples/java/snippets/src/main/java/artifacts/GcsServiceSetup.java:full_code"
        ```

    === "Kotlin"

        ```kotlin
        --8<-- "examples/kotlin/snippets/artifacts/ArtifactExamples.kt:gcs_service"
        ```
Choosing the appropriate `ArtifactService` implementation depends on your application's requirements for data persistence, scalability, and operational environment.

## Best Practices

To use artifacts effectively and maintainably:

* **Choose the Right Service:** Use `InMemoryArtifactService` for rapid prototyping, testing, and scenarios where persistence isn't needed. Use `GcsArtifactService` (or implement your own `BaseArtifactService` for other backends) for production environments requiring data persistence and scalability.
* **Meaningful Filenames:** Use clear, descriptive filenames. Including relevant extensions (`.pdf`, `.png`, `.wav`) helps humans understand the content, even though the `mime_type` dictates programmatic handling. Establish conventions for temporary vs. persistent artifact names.
* **Specify Correct MIME Types:** Always provide an accurate `mime_type` when creating the `types.Part` for `save_artifact`. This is critical for applications or tools that later `load_artifact` to interpret the `bytes` data correctly. Use standard IANA MIME types where possible.
* **Understand Versioning:** Remember that `load_artifact()` without a specific `version` argument retrieves the *latest* version. If your logic depends on a specific historical version of an artifact, be sure to provide the integer version number when loading.
* **Use Namespacing (`user:`) Deliberately:** Only use the `"user:"` prefix for filenames when the data truly belongs to the user and should be accessible across all their sessions. For data specific to a single conversation or session, use regular filenames without the prefix.
* **Error Handling:**
    * Always check if an `artifact_service` is actually configured before calling context methods (`save_artifact`, `load_artifact`, `list_artifacts`) – they will raise a `ValueError` if the service is `None`.
    * Check the return value of `load_artifact`, as it will be `None` if the artifact or version doesn't exist. Don't assume it always returns a `Part`.
    * Be prepared to handle exceptions from the underlying storage service, especially with `GcsArtifactService` (e.g., `google.api_core.exceptions.Forbidden` for permission issues, `NotFound` if the bucket doesn't exist, network errors).
* **Size Considerations:** Artifacts are suitable for typical file sizes, but be mindful of potential costs and performance impacts with extremely large files, especially with cloud storage. `InMemoryArtifactService` can consume significant memory if storing many large artifacts. Evaluate if very large data might be better handled through direct GCS links or other specialized storage solutions rather than passing entire byte arrays in-memory.
* **Cleanup Strategy:** For persistent storage like `GcsArtifactService`, artifacts remain until explicitly deleted. If artifacts represent temporary data or have a limited lifespan, implement a strategy for cleanup. This might involve:
    * Using GCS lifecycle policies on the bucket.
    * Building specific tools or administrative functions that utilize the `artifact_service.delete_artifact` method (note: delete is *not* exposed via context objects for safety).
    * Carefully managing filenames to allow pattern-based deletion if needed.
