adk-python icon indicating copy to clipboard operation
adk-python copied to clipboard

Add LocalFileArtifactService for local file system artifact storage

Open eduramirezh opened this issue 1 year ago • 4 comments

** Please make sure you read the contribution guide and file the issues in the right place. ** Contribution guide.

Is your feature request related to a problem? Please describe. Currently, ADK Python only provides two artifact storage options: InMemoryArtifactService (for development/testing) and GcsArtifactService (for cloud production). There's no option for local file system persistence, which creates a gap for:

  • Local development environments where developers want persistent artifact storage without cloud dependencies
  • Testing scenarios that need file persistence across test runs but don't require cloud storage
  • Self-hosted or air-gapped deployments where cloud storage isn't available or desired
  • CI/CD pipelines that need artifact persistence within build containers

Describe the solution you'd like A new LocalFileArtifactService that implements the BaseArtifactService interface and stores artifacts on the local file system. This service should:

  • Store artifacts in a configurable local directory structure
  • Maintain the same namespace patterns as existing services (user/session scoping)
  • Support all existing artifact operations (save, load, delete, list, versioning)
  • Preserve MIME types and handle different content types
  • Provide async operations using proper thread handling for file I/O
  • Handle error conditions gracefully (corrupted metadata, missing files, etc.)
  • Follow ADK coding standards and patterns

Describe alternatives you've considered

  • Using InMemoryArtifactService: Doesn't provide persistence across application restarts
  • Using GcsArtifactService: Requires cloud setup and credentials, not suitable for local development
  • External storage solutions: Would require additional dependencies and complexity
  • Custom implementations: Each user implementing their own defeats the purpose of having a standard artifact service

Additional context This feature would complete the artifact storage options by providing:

  1. InMemoryArtifactService - For ephemeral development/testing
  2. GcsArtifactService - For cloud production deployments
  3. LocalFileArtifactService - For local persistence needs

The implementation should be a drop-in replacement that maintains full API compatibility with existing artifact services, allowing developers to switch between storage backends easily based on their deployment needs.

Expected file structure:

  {base_path}/
  ├── {app_name}/
  │   └── {user_id}/
  │       ├── {session_id}/
  │       │   └── {filename}/
  │       │       ├── 0              # artifact data
  │       │       ├── 0.metadata.json # MIME type info
  │       │       ├── 1              # next version
  │       │       └── 1.metadata.json
  │       └── user/                   # user-namespaced files
  │           └── {user:filename}/
  │               ├── 0
  │               └── 0.metadata.json

This would enable developers to use ADK in a wider range of deployment scenarios while maintaining consistency with the existing artifact service architecture.

eduramirezh avatar Aug 07 '25 10:08 eduramirezh

a LocalFileArtifactService would be very useful. for my use case I made a quick DatabaseArtifactService that persists in a sqlite db. providing code as it may be helpful:

class DatabaseArtifactService(BaseArtifactService, BaseModel):
    """An implementation of the artifact service that uses a SQLite database for persistent storage."""

    db_url: str
    _db_path: str = PrivateAttr(default='')
    _USER_NAMESPACE_SESSION_ID: str = PrivateAttr(default='<user_namespace>')

    def model_post_init(self, __context: Any) -> None:  # noqa: PYI063
        """Parse the db_url to extract the database file path."""
        try:
            url = make_url(self.db_url)
        except Exception as e:
            raise ValueError(
                f'Invalid database URL format: {self.db_url}'
            ) from e
        if not url.database:
            raise ValueError(f'Database path is missing in URL: {self.db_url}')
        self._db_path = str(url.database).lstrip('/')

    def _get_db_session_id(self, session_id: str, filename: str) -> str:
        """Determine the session ID to use for the database query."""
        if filename.startswith('user:'):
            return self._USER_NAMESPACE_SESSION_ID
        return session_id

    async def _initialize_db(self, db: aiosqlite.Connection) -> None:
        """Ensure the database schema exists on the provided connection. This is stateless and idempotent."""
        await db.execute('PRAGMA journal_mode=WAL;')
        await db.execute('PRAGMA busy_timeout = 5000;')
        await db.execute(
            """
            CREATE TABLE IF NOT EXISTS artifacts (
                app_name TEXT NOT NULL,
                user_id TEXT NOT NULL,
                session_id TEXT NOT NULL,
                filename TEXT NOT NULL,
                version INTEGER NOT NULL,
                mime_type TEXT,
                data BLOB,
                PRIMARY KEY (app_name, user_id, session_id, filename, version)
            )
        """
        )
        await db.commit()

    @override
    async def save_artifact(
        self,
        *,
        app_name: str,
        user_id: str,
        session_id: str,
        filename: str,
        artifact: types.Part,
    ) -> int:
        db_session_id = self._get_db_session_id(session_id, filename)
        if not artifact.inline_data:
            raise ValueError(f"Artifact '{filename}' has no inline_data.")

        mime_type = artifact.inline_data.mime_type
        data = artifact.inline_data.data

        async with aiosqlite.connect(self._db_path, timeout=10) as db:
            await self._initialize_db(db)

            async with db.execute(
                'SELECT MAX(version) FROM artifacts WHERE app_name=? AND user_id=? AND session_id=? AND filename=?',
                (app_name, user_id, db_session_id, filename),
            ) as cursor:
                row = await cursor.fetchone()
                new_version = (
                    row[0] if row and row[0] is not None else -1
                ) + 1

            await db.execute(
                'INSERT INTO artifacts (app_name, user_id, session_id, filename, version, mime_type, data) VALUES (?, ?, ?, ?, ?, ?, ?)',
                (
                    app_name,
                    user_id,
                    db_session_id,
                    filename,
                    new_version,
                    mime_type,
                    data,
                ),
            )
            await db.commit()
            return new_version

    @override
    async def load_artifact(
        self,
        *,
        app_name: str,
        user_id: str,
        session_id: str,
        filename: str,
        version: int | None = None,
    ) -> types.Part | None:
        try:
            async with aiosqlite.connect(self._db_path, timeout=10) as db:
                await self._initialize_db(db)

                if version is None:
                    query = 'SELECT mime_type, data FROM artifacts WHERE app_name=? AND user_id=? AND session_id=? AND filename=? ORDER BY version DESC LIMIT 1'
                    params = (
                        app_name,
                        user_id,
                        self._get_db_session_id(session_id, filename),
                        filename,
                    )
                else:
                    query = 'SELECT mime_type, data FROM artifacts WHERE app_name=? AND user_id=? AND session_id=? AND filename=? AND version=?'
                    params = (
                        app_name,
                        user_id,
                        self._get_db_session_id(session_id, filename),
                        filename,
                        version,
                    )

                async with db.execute(query, params) as cursor:
                    row = await cursor.fetchone()
                    if not row:
                        return None
                    return types.Part(
                        inline_data=types.Blob(mime_type=row[0], data=row[1])
                    )
        except aiosqlite.OperationalError as e:
            if 'no such table' in str(e):
                logger.warning(
                    'Artifact table does not exist, returning None. This is expected if no artifacts have been saved yet.'
                )
                return None
            raise

    @override
    async def list_artifact_keys(
        self, *, app_name: str, user_id: str, session_id: str
    ) -> list[str]:
        async with aiosqlite.connect(self._db_path, timeout=10) as db:
            await self._initialize_db(db)

            query = 'SELECT DISTINCT filename FROM artifacts WHERE app_name=? AND user_id=? AND (session_id=? OR session_id=?)'
            params = (
                app_name,
                user_id,
                session_id,
                self._USER_NAMESPACE_SESSION_ID,
            )

            async with db.execute(query, params) as cursor:
                rows = await cursor.fetchall()
                return sorted([row[0] for row in rows])

    @override
    async def delete_artifact(
        self, *, app_name: str, user_id: str, session_id: str, filename: str
    ) -> None:
        async with aiosqlite.connect(self._db_path, timeout=10) as db:
            await self._initialize_db(db)

            db_session_id = self._get_db_session_id(session_id, filename)
            await db.execute(
                'DELETE FROM artifacts WHERE app_name=? AND user_id=? AND session_id=? AND filename=?',
                (app_name, user_id, db_session_id, filename),
            )
            await db.commit()

    @override
    async def list_versions(
        self, *, app_name: str, user_id: str, session_id: str, filename: str
    ) -> list[int]:
        async with aiosqlite.connect(self._db_path, timeout=10) as db:
            await self._initialize_db(db)

            db_session_id = self._get_db_session_id(session_id, filename)
            query = 'SELECT version FROM artifacts WHERE app_name=? AND user_id=? AND session_id=? AND filename=? ORDER BY version ASC'
            params = (app_name, user_id, db_session_id, filename)

            async with db.execute(query, params) as cursor:
                rows = await cursor.fetchall()
                return [row[0] for row in rows]

cschmidterNBTC avatar Aug 29 '25 13:08 cschmidterNBTC

Hi @eduramirezh , thanks a lot for this request and the PR, we recently started the community repo https://github.com/google/adk-python-community. I think it makes perfect sense for your PR to go into this repo. Would you mind contributing there, and our team member will create a new pypi target for that. Thanks again!

cc @hangfei

DeanChensj avatar Aug 30 '25 00:08 DeanChensj

@cschmidterNBTC how do you use it in project? where you set DatabaseArtifactService as artifact_service?

Keydol avatar Sep 11 '25 12:09 Keydol

Hi, thank you for this contribution, I am working on something similar!

GWeale avatar Nov 04 '25 21:11 GWeale