Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions DICT_ARTIFACTS_FIX.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Fix for Issue #3622: Accept dict-shaped artifacts in InMemoryArtifactService

## Summary
Fixed the artifact services to accept dict-shaped (serialized) artifacts in addition to `types.Part` objects. This allows users to pass artifacts as dictionaries, which are automatically converted to `types.Part` objects internally.

## Changes Made

### 1. Base Artifact Service (`base_artifact_service.py`)
- Updated the `save_artifact()` method signature to accept `types.Part | dict[str, Any]`
- Updated the docstring to clarify that dict-shaped artifacts are now supported

### 2. InMemoryArtifactService (`in_memory_artifact_service.py`)
- Updated the `save_artifact()` method to:
- Accept `types.Part | dict[str, Any]` parameter type
- Added conversion logic: `if isinstance(artifact, dict): artifact = types.Part.model_validate(artifact)`
- This deserialization happens before any artifact processing

### 3. GcsArtifactService (`gcs_artifact_service.py`)
- Updated the async `save_artifact()` method to:
- Accept `types.Part | dict[str, Any]` parameter type
- Added conversion logic before threading to sync method
- The internal `_save_artifact()` method processes the already-converted `types.Part` object

### 4. FileArtifactService (`file_artifact_service.py`)
- Updated the async `save_artifact()` method to:
- Accept `types.Part | dict[str, Any]` parameter type
- Added conversion logic before threading to sync method
- The internal `_save_artifact_sync()` method processes the already-converted `types.Part` object

### 5. ForwardingArtifactService (`_forwarding_artifact_service.py`)
- Updated the `save_artifact()` method to:
- Accept `types.Part | dict[str, Any]` parameter type
- Added conversion logic before forwarding to the parent tool context

### 6. Test Suite (`test_artifact_service.py`)
- Added `test_save_load_dict_shaped_artifact()` test to verify dict-shaped artifacts can be saved and loaded across all service types (IN_MEMORY, GCS, FILE)
- Added `test_save_text_dict_shaped_artifact()` test to verify text-based dict-shaped artifacts work correctly in InMemoryArtifactService

## How It Works

When a dictionary is passed to `save_artifact()`:
1. The method checks if the artifact is a dictionary using `isinstance(artifact, dict)`
2. If it is, it converts it to a `types.Part` object using `types.Part.model_validate(artifact)`
3. The rest of the method processes the converted `types.Part` object as usual

## Example Usage

```python
# Before (still supported)
artifact = types.Part(text="Hello, World!")
await service.save_artifact(..., artifact=artifact)

# After (now also supported)
artifact_dict = {"text": "Hello, World!"}
await service.save_artifact(..., artifact=artifact_dict)

# Also works with inline data
artifact_dict = {
"inline_data": {
"data": "dGVzdF9kYXRh", # base64 encoded
"mime_type": "text/plain",
}
}
await service.save_artifact(..., artifact=artifact_dict)
```

## Backward Compatibility

✅ **Fully backward compatible** - All existing code using `types.Part` objects will continue to work exactly as before.
5 changes: 3 additions & 2 deletions src/google/adk/agents/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,14 +136,15 @@ async def load_artifact(
async def save_artifact(
self,
filename: str,
artifact: types.Part,
artifact: types.Part | dict[str, Any],
custom_metadata: dict[str, Any] | None = None,
) -> int:
"""Saves an artifact and records it as delta for the current session.
Args:
filename: The filename of the artifact.
artifact: The artifact to save.
artifact: The artifact to save. Can be a types.Part object or a
dict-shaped (serialized) artifact.
custom_metadata: Custom metadata to associate with the artifact.
Returns:
Expand Down
11 changes: 6 additions & 5 deletions src/google/adk/artifacts/base_artifact_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async def save_artifact(
app_name: str,
user_id: str,
filename: str,
artifact: types.Part,
artifact: types.Part | dict[str, Any],
session_id: Optional[str] = None,
custom_metadata: Optional[dict[str, Any]] = None,
) -> int:
Expand All @@ -84,10 +84,11 @@ async def save_artifact(
app_name: The app name.
user_id: The user ID.
filename: The filename of the artifact.
artifact: The artifact to save. If the artifact consists of `file_data`,
the artifact service assumes its content has been uploaded separately,
and this method will associate the `file_data` with the artifact if
necessary.
artifact: The artifact to save. Can be a types.Part object or a
dict-shaped (serialized) artifact that will be converted to types.Part.
If the artifact consists of `file_data`, the artifact service assumes
its content has been uploaded separately, and this method will associate
the `file_data` with the artifact if necessary.
session_id: The session ID. If `None`, the artifact is user-scoped.
custom_metadata: custom metadata to associate with the artifact.

Expand Down
6 changes: 5 additions & 1 deletion src/google/adk/artifacts/file_artifact_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ async def save_artifact(
app_name: str,
user_id: str,
filename: str,
artifact: types.Part,
artifact: types.Part | dict[str, Any],
session_id: Optional[str] = None,
custom_metadata: Optional[dict[str, Any]] = None,
) -> int:
Expand All @@ -326,6 +326,10 @@ async def save_artifact(
computed scope root; absolute paths or inputs that traverse outside that
root (for example ``"../../secret.txt"``) raise ``ValueError``.
"""
# Convert dict-shaped artifact to types.Part if necessary
if isinstance(artifact, dict):
artifact = types.Part.model_validate(artifact)

return await asyncio.to_thread(
self._save_artifact_sync,
user_id,
Expand Down
6 changes: 5 additions & 1 deletion src/google/adk/artifacts/gcs_artifact_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,14 @@ async def save_artifact(
app_name: str,
user_id: str,
filename: str,
artifact: types.Part,
artifact: types.Part | dict[str, Any],
session_id: Optional[str] = None,
custom_metadata: Optional[dict[str, Any]] = None,
) -> int:
# Convert dict-shaped artifact to types.Part if necessary
if isinstance(artifact, dict):
artifact = types.Part.model_validate(artifact)

return await asyncio.to_thread(
self._save_artifact,
app_name,
Expand Down
6 changes: 5 additions & 1 deletion src/google/adk/artifacts/in_memory_artifact_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,10 +99,14 @@ async def save_artifact(
app_name: str,
user_id: str,
filename: str,
artifact: types.Part,
artifact: types.Part | dict[str, Any],
session_id: Optional[str] = None,
custom_metadata: Optional[dict[str, Any]] = None,
) -> int:
# Convert dict-shaped artifact to types.Part if necessary
if isinstance(artifact, dict):
artifact = types.Part.model_validate(artifact)

path = self._artifact_path(app_name, user_id, filename, session_id)
if path not in self.artifacts:
self.artifacts[path] = []
Expand Down
4 changes: 2 additions & 2 deletions src/google/adk/cli/adk_web_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,8 @@ class SaveArtifactRequest(common.BaseModel):
"""Request payload for saving a new artifact."""

filename: str = Field(description="Artifact filename.")
artifact: types.Part = Field(
description="Artifact payload encoded as google.genai.types.Part."
artifact: types.Part | dict[str, Any] = Field(
description="Artifact payload encoded as google.genai.types.Part or as a dict-shaped artifact."
)
custom_metadata: Optional[dict[str, Any]] = Field(
default=None,
Expand Down
6 changes: 5 additions & 1 deletion src/google/adk/tools/_forwarding_artifact_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,14 @@ async def save_artifact(
app_name: str,
user_id: str,
filename: str,
artifact: types.Part,
artifact: types.Part | dict[str, Any],
session_id: Optional[str] = None,
custom_metadata: Optional[dict[str, Any]] = None,
) -> int:
# Convert dict-shaped artifact to types.Part if necessary
if isinstance(artifact, dict):
artifact = types.Part.model_validate(artifact)

return await self.tool_context.save_artifact(
filename=filename,
artifact=artifact,
Expand Down
99 changes: 99 additions & 0 deletions tests/unittests/artifacts/test_artifact_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -766,3 +766,102 @@ async def test_file_save_artifact_rejects_absolute_path_within_scope(tmp_path):
filename=str(absolute_in_scope),
artifact=part,
)

@pytest.mark.asyncio
@pytest.mark.parametrize(
"service_type",
[
ArtifactServiceType.IN_MEMORY,
ArtifactServiceType.GCS,
ArtifactServiceType.FILE,
],
)
async def test_save_load_dict_shaped_artifact(
service_type, artifact_service_factory
):
"""Tests saving and loading dict-shaped artifacts.

This tests the fix for accepting dict-shaped (serialized) artifacts
in the save_artifact method. Dict-shaped artifacts are commonly used
when artifacts are stored/retrieved from JSON or other serialization formats.
"""
artifact_service = artifact_service_factory(service_type)
# Create a dict-shaped artifact by serializing a real Part instance
part = types.Part.from_bytes(data=b"test_data", mime_type="text/plain")
dict_artifact = part.model_dump(exclude_none=True)

app_name = "app0"
user_id = "user0"
session_id = "123"
filename = "dict_file.txt"

# Save the dict-shaped artifact
version = await artifact_service.save_artifact(
app_name=app_name,
user_id=user_id,
session_id=session_id,
filename=filename,
artifact=dict_artifact,
)
assert version == 0

# Load and verify the artifact
loaded = await artifact_service.load_artifact(
app_name=app_name,
user_id=user_id,
session_id=session_id,
filename=filename,
)
assert loaded is not None
assert loaded.inline_data is not None
assert loaded.inline_data.mime_type == "text/plain"


@pytest.mark.asyncio
@pytest.mark.parametrize(
"service_type",
[
ArtifactServiceType.IN_MEMORY,
ArtifactServiceType.GCS,
ArtifactServiceType.FILE,
],
)
async def test_save_text_dict_shaped_artifact(
service_type, artifact_service_factory
):
"""Tests saving and loading dict-shaped artifacts with text content."""
artifact_service = artifact_service_factory(service_type)
# Create a dict-shaped artifact by serializing a real Part instance
part = types.Part(text="Hello, World!")
dict_artifact = part.model_dump(exclude_none=True)

app_name = "app0"
user_id = "user0"
session_id = "123"
filename = "text_file.txt"

# Save the dict-shaped artifact
await artifact_service.save_artifact(
app_name=app_name,
user_id=user_id,
session_id=session_id,
filename=filename,
artifact=dict_artifact,
)

# Load and verify the artifact
loaded = await artifact_service.load_artifact(
app_name=app_name,
user_id=user_id,
session_id=session_id,
filename=filename,
)
assert loaded is not None
# GCS/File services may return text as inline_data bytes; accept either form.
if loaded.text is not None:
assert loaded.text == "Hello, World!"
else:
assert (
loaded.inline_data is not None
and loaded.inline_data.data == b"Hello, World!"
)
Comment on lines +860 to +867
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The comment on line 860 is not entirely accurate. The FileArtifactService preserves text artifacts as text, while GcsArtifactService converts them to inline_data with bytes. InMemoryArtifactService also preserves text.

The current assertion is a bit too general and could mask incorrect behavior in one of the services. To make the test more robust and clear about the expected behavior of each service, I suggest adding specific assertions for each service_type.

Suggested change
# GCS/File services may return text as inline_data bytes; accept either form.
if loaded.text is not None:
assert loaded.text == "Hello, World!"
else:
assert (
loaded.inline_data is not None
and loaded.inline_data.data == b"Hello, World!"
)
# GCS service converts text to inline_data bytes, while File and InMemory
# services preserve text content.
if service_type is ArtifactServiceType.GCS:
assert loaded.text is None
assert loaded.inline_data is not None
assert loaded.inline_data.data == b"Hello, World!"
assert loaded.inline_data.mime_type == "text/plain"
else:
assert loaded.inline_data is None
assert loaded.text == "Hello, World!"