This directory contains a sample agent that demonstrates how to customize a
CodeExecutor to perform environment setup before executing code. The specific
example shows how to add support for Japanese fonts in matplotlib plots by
subclassing VertexAiCodeExecutor.
This sample showcases a powerful pattern for customizing code execution
environments. By extending a base CodeExecutor, you can inject setup code to
prepare the environment before a user's code is run. This enables advanced use
cases that require specific configurations, in this case, adding custom fonts.
The Agent Development Kit (ADK) allows for powerful customization of code
execution by extending existing CodeExecutor classes. By subclassing an
executor (e.g., VertexAiCodeExecutor) and overriding its execute_code
method, you can inject custom logic to:
- Modify the code before it's executed.
- Add files to the execution environment.
- Process the results after execution.
The CustomCodeExecutor in this sample solves a common issue where non-Latin
characters do not render correctly in plots generated by matplotlib due to
missing fonts in the execution environment.
It achieves this by: 1. Subclassing VertexAiCodeExecutor: It inherits all
the functionality of the standard Vertex AI code executor. 2. Overriding
execute_code: Before calling the parent's execute_code method, it performs
the following steps: a. Downloads a Japanese font file (NotoSerifJP). b. Adds
the font file to the list of files to be uploaded to the execution environment.
c. Prepends a Python code snippet to the user's code. This snippet uses
matplotlib.font_manager to register the newly available font file, making it
available for plotting. 3. Executing the modified code: The combined code
(setup snippet + original code) is then executed in the Vertex AI environment,
which now has the Japanese font available for matplotlib.
This ensures that any plots generated during the agent's session can correctly display Japanese characters.
Ensure you have configured your environment for using Google Cloud Vertex AI. You will need to have a Google Cloud Project with the Vertex AI API enabled.
You can run this agent using the ADK CLI.
To interact with the agent through the command line:
adk run contributing/samples/custom_code_execution "Plot a bar chart with these categories and values: {'リンゴ': 10, 'バナナ': 15, 'オレンジ': 8}. Title the chart '果物の在庫' (Fruit Stock)."To use the web interface:
adk web contributing/samples/Then select custom_code_execution from the list of agents and interact with
it.