|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import logging |
| 18 | +from typing import Optional |
| 19 | + |
| 20 | +from google.genai import types |
| 21 | + |
| 22 | +from ..agents.invocation_context import InvocationContext |
| 23 | +from .base_plugin import BasePlugin |
| 24 | + |
| 25 | +logger = logging.getLogger('google_adk.' + __name__) |
| 26 | + |
| 27 | + |
| 28 | +class SaveFilesAsArtifactsPlugin(BasePlugin): |
| 29 | + """A plugin that saves files embedded in user messages as artifacts. |
| 30 | +
|
| 31 | + This is useful to allow users to upload files in the chat experience and have |
| 32 | + those files available to the agent. |
| 33 | +
|
| 34 | + We use Blob.display_name to determine |
| 35 | + the file name. Artifacts with the same name will be overwritten. A placeholder |
| 36 | + with the artifact name will be put in place of the embedded file in the user |
| 37 | + message so the model knows where to find the file. You may want to add |
| 38 | + load_artifacts tool to the agent, or load the artifacts in your own tool to |
| 39 | + use the files. |
| 40 | + """ |
| 41 | + |
| 42 | + def __init__(self, name: str = 'save_files_as_artifacts_plugin'): |
| 43 | + """Initialize the save files as artifacts plugin. |
| 44 | +
|
| 45 | + Args: |
| 46 | + name: The name of the plugin instance. |
| 47 | + """ |
| 48 | + super().__init__(name) |
| 49 | + |
| 50 | + async def on_user_message_callback( |
| 51 | + self, |
| 52 | + *, |
| 53 | + invocation_context: InvocationContext, |
| 54 | + user_message: types.Content, |
| 55 | + ) -> Optional[types.Content]: |
| 56 | + """Process user message and save any attached files as artifacts.""" |
| 57 | + if not invocation_context.artifact_service: |
| 58 | + logger.warning( |
| 59 | + 'Artifact service is not set. SaveFilesAsArtifactsPlugin' |
| 60 | + ' will not be enabled.' |
| 61 | + ) |
| 62 | + return user_message |
| 63 | + |
| 64 | + if not user_message.parts: |
| 65 | + return user_message |
| 66 | + |
| 67 | + for i, part in enumerate(user_message.parts): |
| 68 | + if part.inline_data is None: |
| 69 | + continue |
| 70 | + |
| 71 | + try: |
| 72 | + # Use display_name if available, otherwise generate a filename |
| 73 | + file_name = part.inline_data.display_name |
| 74 | + if not file_name: |
| 75 | + file_name = f'artifact_{invocation_context.invocation_id}_{i}' |
| 76 | + logger.info( |
| 77 | + f'No display_name found, using generated filename: {file_name}' |
| 78 | + ) |
| 79 | + |
| 80 | + await invocation_context.artifact_service.save_artifact( |
| 81 | + app_name=invocation_context.app_name, |
| 82 | + user_id=invocation_context.user_id, |
| 83 | + session_id=invocation_context.session.id, |
| 84 | + filename=file_name, |
| 85 | + artifact=part, |
| 86 | + ) |
| 87 | + |
| 88 | + # Replace the inline data with a placeholder text |
| 89 | + user_message.parts[i] = types.Part( |
| 90 | + text=f'[Uploaded Artifact: "{file_name}"]' |
| 91 | + ) |
| 92 | + logger.info(f'Successfully saved artifact: {file_name}') |
| 93 | + |
| 94 | + except Exception as e: |
| 95 | + logger.error(f'Failed to save artifact for part {i}: {e}') |
| 96 | + # Keep the original part if saving fails |
| 97 | + continue |
| 98 | + |
| 99 | + return user_message |
0 commit comments