chore: import upstream snapshot with attribution
Continuous Integration / Pre-commit Linter (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.10) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.11) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.12) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.13) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.10) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.11) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.12) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.13) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.14) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Waiting to run
Copybara PR Handler / close-imported-pr (push) Waiting to run
Continuous Integration / Pre-commit Linter (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.10) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.11) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.12) (push) Waiting to run
Continuous Integration / Mypy Check (Python 3.13) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.10) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.11) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.12) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.13) (push) Waiting to run
Continuous Integration / Unit Tests (Python 3.14) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.10) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.11) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.12) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.13) (push) Waiting to run
Continuous Integration / A2A v0.3 Tests (Python 3.14) (push) Waiting to run
Copybara PR Handler / close-imported-pr (push) Waiting to run
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
# OAuth Sample
|
||||
|
||||
## Introduction
|
||||
|
||||
This sample data science agent uses Agent Engine Code Execution Sandbox to execute LLM generated code.
|
||||
|
||||
|
||||
## How to use
|
||||
|
||||
* 1. Follow https://docs.cloud.google.com/agent-builder/agent-engine/code-execution/quickstart#create-an-agent-engine-instance to create an agent engine instance. Replace the AGENT_ENGINE_RESOURCE_NAME with the one you just created. A new sandbox environment under this agent engine instance will be created for each session with TTL of 1 year. But sandbox can only main its state for up to 14 days. This is the recommended usage for production environments.
|
||||
|
||||
* 2. For testing or protyping purposes, create a sandbox environment by following this guide: https://docs.cloud.google.com/agent-builder/agent-engine/code-execution/quickstart#create_a_sandbox. Replace the SANDBOX_RESOURCE_NAME with the one you just created. This will be used as the default sandbox environment for all the code executions throughout the lifetime of the agent. As the sandbox is re-used across sessions, all sessions will share the same Python environment and variable values."
|
||||
|
||||
|
||||
## Sample prompt
|
||||
|
||||
* Can you write a function that calculates the sum from 1 to 100.
|
||||
* The dataset is given as below. Store,Date,Weekly_Sales,Holiday_Flag,Temperature,Fuel_Price,CPI,Unemployment Store 1,2023-06-01,1000,0,70,3.0,200,5 Store 2,2023-06-02,1200,1,80,3.5,210,6 Store 3,2023-06-03,1400,0,90,4.0,220,7 Store 4,2023-06-04,1600,1,70,4.5,230,8 Store 5,2023-06-05,1800,0,80,5.0,240,9 Store 6,2023-06-06,2000,1,90,5.5,250,10 Store 7,2023-06-07,2200,0,90,6.0,260,11 Plot a scatter plot showcasing the relationship between Weekly Sales and Temperature for each store, distinguishing stores with a Holiday Flag.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,93 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Data science agent."""
|
||||
|
||||
from google.adk.agents.llm_agent import Agent
|
||||
from google.adk.code_executors.agent_engine_sandbox_code_executor import AgentEngineSandboxCodeExecutor
|
||||
|
||||
|
||||
def base_system_instruction():
|
||||
"""Returns: data science agent system instruction."""
|
||||
|
||||
return """
|
||||
# Guidelines
|
||||
|
||||
**Objective:** Assist the user in achieving their data analysis goals within the context of a Python Colab notebook, **with emphasis on avoiding assumptions and ensuring accuracy.** Reaching that goal can involve multiple steps. When you need to generate code, you **don't** need to solve the goal in one go. Only generate the next step at a time.
|
||||
|
||||
**Code Execution:** All code snippets provided will be executed within the Colab environment.
|
||||
|
||||
**Statefulness:** All code snippets are executed and the variables stays in the environment. You NEVER need to re-initialize variables. You NEVER need to reload files. You NEVER need to re-import libraries.
|
||||
|
||||
**Output Visibility:** Always print the output of code execution to visualize results, especially for data exploration and analysis. For example:
|
||||
- To look at the shape of a pandas.DataFrame do:
|
||||
```tool_code
|
||||
print(df.shape)
|
||||
```
|
||||
The output will be presented to you as:
|
||||
```tool_outputs
|
||||
(49, 7)
|
||||
|
||||
```
|
||||
- To display the result of a numerical computation:
|
||||
```tool_code
|
||||
x = 10 ** 9 - 12 ** 5
|
||||
print(f'{{x=}}')
|
||||
```
|
||||
The output will be presented to you as:
|
||||
```tool_outputs
|
||||
x=999751168
|
||||
|
||||
```
|
||||
- You **never** generate ```tool_outputs yourself.
|
||||
- You can then use this output to decide on next steps.
|
||||
- Print just variables (e.g., `print(f'{{variable=}}')`.
|
||||
|
||||
**No Assumptions:** **Crucially, avoid making assumptions about the nature of the data or column names.** Base findings solely on the data itself. Always use the information obtained from `explore_df` to guide your analysis.
|
||||
|
||||
**Available files:** Only use the files that are available as specified in the list of available files.
|
||||
|
||||
**Data in prompt:** Some queries contain the input data directly in the prompt. You have to parse that data into a pandas DataFrame. ALWAYS parse all the data. NEVER edit the data that are given to you.
|
||||
|
||||
**Answerability:** Some queries may not be answerable with the available data. In those cases, inform the user why you cannot process their query and suggest what type of data would be needed to fulfill their request.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name="agent_engine_code_execution_agent",
|
||||
instruction=base_system_instruction() + """
|
||||
|
||||
|
||||
You need to assist the user with their queries by looking at the data and the context in the conversation.
|
||||
You final answer should summarize the code and code execution relevant to the user query.
|
||||
|
||||
You should include all pieces of data to answer the user query, such as the table from code execution results.
|
||||
If you cannot answer the question directly, you should follow the guidelines above to generate the next step.
|
||||
If the question can be answered directly with writing any code, you should do that.
|
||||
If you doesn't have enough data to answer the question, you should ask for clarification from the user.
|
||||
|
||||
You should NEVER install any package on your own like `pip install ...`.
|
||||
When plotting trends, you should make sure to sort and order the data by the x-axis.
|
||||
|
||||
|
||||
""",
|
||||
code_executor=AgentEngineSandboxCodeExecutor(
|
||||
# Replace with your sandbox resource name if you already have one. Only use it for testing or prototyping purposes, because this will use the same sandbox for all requests.
|
||||
# "projects/vertex-agent-loadtest/locations/us-central1/reasoningEngines/6842889780301135872/sandboxEnvironments/6545148628569161728",
|
||||
sandbox_resource_name=None,
|
||||
# Replace with agent engine resource name used for creating sandbox environment.
|
||||
agent_engine_resource_name=None,
|
||||
),
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,99 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Data science agent."""
|
||||
|
||||
from google.adk.agents.llm_agent import Agent
|
||||
from google.adk.code_executors.built_in_code_executor import BuiltInCodeExecutor
|
||||
|
||||
|
||||
def base_system_instruction():
|
||||
"""Returns: data science agent system instruction."""
|
||||
|
||||
return """
|
||||
# Guidelines
|
||||
|
||||
**Objective:** Assist the user in achieving their data analysis goals within the context of a Python Colab notebook, **with emphasis on avoiding assumptions and ensuring accuracy.** Reaching that goal can involve multiple steps. When you need to generate code, you **don't** need to solve the goal in one go. Only generate the next step at a time.
|
||||
|
||||
**Code Execution:** All code snippets provided will be executed within the Colab environment.
|
||||
|
||||
**Statefulness:** All code snippets are executed and the variables stays in the environment. You NEVER need to re-initialize variables. You NEVER need to reload files. You NEVER need to re-import libraries.
|
||||
|
||||
**Imported Libraries:** The following libraries are ALREADY imported and should NEVER be imported again:
|
||||
|
||||
```tool_code
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import scipy
|
||||
```
|
||||
|
||||
**Output Visibility:** Always print the output of code execution to visualize results, especially for data exploration and analysis. For example:
|
||||
- To look at the shape of a pandas.DataFrame do:
|
||||
```tool_code
|
||||
print(df.shape)
|
||||
```
|
||||
The output will be presented to you as:
|
||||
```tool_outputs
|
||||
(49, 7)
|
||||
|
||||
```
|
||||
- To display the result of a numerical computation:
|
||||
```tool_code
|
||||
x = 10 ** 9 - 12 ** 5
|
||||
print(f'{{x=}}')
|
||||
```
|
||||
The output will be presented to you as:
|
||||
```tool_outputs
|
||||
x=999751168
|
||||
|
||||
```
|
||||
- You **never** generate ```tool_outputs yourself.
|
||||
- You can then use this output to decide on next steps.
|
||||
- Print just variables (e.g., `print(f'{{variable=}}')`.
|
||||
|
||||
**No Assumptions:** **Crucially, avoid making assumptions about the nature of the data or column names.** Base findings solely on the data itself. Always use the information obtained from `explore_df` to guide your analysis.
|
||||
|
||||
**Available files:** Only use the files that are available as specified in the list of available files.
|
||||
|
||||
**Data in prompt:** Some queries contain the input data directly in the prompt. You have to parse that data into a pandas DataFrame. ALWAYS parse all the data. NEVER edit the data that are given to you.
|
||||
|
||||
**Answerability:** Some queries may not be answerable with the available data. In those cases, inform the user why you cannot process their query and suggest what type of data would be needed to fulfill their request.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name="data_science_agent",
|
||||
instruction=base_system_instruction() + """
|
||||
|
||||
|
||||
You need to assist the user with their queries by looking at the data and the context in the conversation.
|
||||
You final answer should summarize the code and code execution relevant to the user query.
|
||||
|
||||
You should include all pieces of data to answer the user query, such as the table from code execution results.
|
||||
If you cannot answer the question directly, you should follow the guidelines above to generate the next step.
|
||||
If the question can be answered directly with writing any code, you should do that.
|
||||
If you doesn't have enough data to answer the question, you should ask for clarification from the user.
|
||||
|
||||
You should NEVER install any package on your own like `pip install ...`.
|
||||
When plotting trends, you should make sure to sort and order the data by the x-axis.
|
||||
|
||||
|
||||
""",
|
||||
code_executor=BuiltInCodeExecutor(),
|
||||
)
|
||||
@@ -0,0 +1,48 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""A Python coding agent using the GkeCodeExecutor for secure execution."""
|
||||
|
||||
from google.adk.agents import LlmAgent
|
||||
from google.adk.code_executors import GkeCodeExecutor
|
||||
|
||||
|
||||
def gke_agent_system_instruction():
|
||||
"""Returns: The system instruction for the GKE-based coding agent."""
|
||||
return """You are a helpful and capable AI agent that can write and execute Python code to answer questions and perform tasks.
|
||||
|
||||
When a user asks a question, follow these steps:
|
||||
1. Analyze the request.
|
||||
2. Write a complete, self-contained Python script to accomplish the task.
|
||||
3. Your code will be executed in a secure, sandboxed environment.
|
||||
4. Return the full and complete output from the code execution, including any text, results, or error messages."""
|
||||
|
||||
|
||||
gke_executor = GkeCodeExecutor(
|
||||
# This must match the namespace in your deployment_rbac.yaml where the
|
||||
# agent's ServiceAccount and Role have permissions.
|
||||
namespace="agent-sandbox",
|
||||
# Setting an explicit timeout prevents a stuck job from running forever.
|
||||
timeout_seconds=600,
|
||||
)
|
||||
|
||||
root_agent = LlmAgent(
|
||||
name="gke_coding_agent",
|
||||
description=(
|
||||
"A general-purpose agent that executes Python code in a secure GKE"
|
||||
" Sandbox."
|
||||
),
|
||||
instruction=gke_agent_system_instruction(),
|
||||
code_executor=gke_executor,
|
||||
)
|
||||
@@ -0,0 +1,71 @@
|
||||
# Custom Code Executor Agent Sample
|
||||
|
||||
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`.
|
||||
|
||||
## Overview
|
||||
|
||||
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.
|
||||
|
||||
## Key Concept: `CodeExecutor` Customization
|
||||
|
||||
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.
|
||||
|
||||
## Example: Adding Japanese Font Support
|
||||
|
||||
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.
|
||||
|
||||
## How to use
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Ensure you have configured your environment for using
|
||||
[Google Cloud Vertex AI](https://google.github.io/adk-docs/get-started/quickstart/#gemini---google-cloud-vertex-ai).
|
||||
You will need to have a Google Cloud Project with the Vertex AI API enabled.
|
||||
|
||||
### Running the agent
|
||||
|
||||
You can run this agent using the ADK CLI.
|
||||
|
||||
To interact with the agent through the command line:
|
||||
|
||||
```bash
|
||||
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:
|
||||
|
||||
```bash
|
||||
adk web contributing/samples/
|
||||
```
|
||||
|
||||
Then select `custom_code_execution` from the list of agents and interact with
|
||||
it.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,165 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Data science agent, with a custom code executor that enables Japanese fonts."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
from typing import Optional
|
||||
import urllib.request
|
||||
|
||||
from google.adk.agents.invocation_context import InvocationContext
|
||||
from google.adk.agents.llm_agent import Agent
|
||||
from google.adk.code_executors.code_execution_utils import CodeExecutionInput
|
||||
from google.adk.code_executors.code_execution_utils import CodeExecutionResult
|
||||
from google.adk.code_executors.code_execution_utils import File
|
||||
from google.adk.code_executors.vertex_ai_code_executor import VertexAiCodeExecutor
|
||||
from typing_extensions import override
|
||||
|
||||
# The Python code snippet to be prepended to the user's code.
|
||||
# This will register the Japanese font with matplotlib.
|
||||
_FONT_SETUP_CODE = """
|
||||
import matplotlib.font_manager as fm
|
||||
|
||||
font_path = "NotoSerifJP[wght].ttf"
|
||||
try:
|
||||
fm.fontManager.addfont(font_path)
|
||||
prop = fm.FontProperties(fname=font_path)
|
||||
plt.rcParams['font.family'] = prop.get_name()
|
||||
print("Japanese font enabled for matplotlib.")
|
||||
except Exception as e:
|
||||
print(f"Failed to set Japanese font: {e}")
|
||||
"""
|
||||
|
||||
|
||||
def _load_font_file(font_url: str, font_filename: str) -> Optional[File]:
|
||||
"""Downloads a font file and returns it as a File object."""
|
||||
try:
|
||||
with urllib.request.urlopen(font_url) as response:
|
||||
font_bytes = response.read()
|
||||
except Exception as e:
|
||||
print(f"Failed to download font: {e}")
|
||||
return None
|
||||
|
||||
# Base64-encode the font content.
|
||||
font_content = base64.b64encode(font_bytes).decode("utf-8")
|
||||
return File(name=font_filename, content=font_content)
|
||||
|
||||
|
||||
class CustomCodeExecutor(VertexAiCodeExecutor):
|
||||
"""A Vertex AI code executor that automatically enables Japanese fonts."""
|
||||
|
||||
@override
|
||||
def execute_code(
|
||||
self,
|
||||
invocation_context: InvocationContext,
|
||||
code_execution_input: CodeExecutionInput,
|
||||
) -> CodeExecutionResult:
|
||||
font_url = "https://github.com/notofonts/noto-cjk/raw/refs/heads/main/google-fonts/NotoSerifJP%5Bwght%5D.ttf"
|
||||
font_filename = "NotoSerifJP[wght].ttf"
|
||||
font_file = _load_font_file(font_url, font_filename)
|
||||
# If the font download fails, execute the original code without it.
|
||||
if font_file is not None:
|
||||
# Add the font file to the input files.
|
||||
code_execution_input.input_files.append(font_file)
|
||||
|
||||
# Prepend the font setup code to the user's code.
|
||||
code_execution_input.code = (
|
||||
f"{_FONT_SETUP_CODE}\n\n{code_execution_input.code}"
|
||||
)
|
||||
|
||||
# Execute the modified code.
|
||||
return super().execute_code(invocation_context, code_execution_input)
|
||||
|
||||
|
||||
def base_system_instruction():
|
||||
"""Returns: data science agent system instruction."""
|
||||
|
||||
return """
|
||||
# Guidelines
|
||||
|
||||
**Objective:** Assist the user in achieving their data analysis goals within the context of a Python Colab notebook, **with emphasis on avoiding assumptions and ensuring accuracy.** Reaching that goal can involve multiple steps. When you need to generate code, you **don't** need to solve the goal in one go. Only generate the next step at a time.
|
||||
|
||||
**Code Execution:** All code snippets provided will be executed within the Colab environment.
|
||||
|
||||
**Statefulness:** All code snippets are executed and the variables stays in the environment. You NEVER need to re-initialize variables. You NEVER need to reload files. You NEVER need to re-import libraries.
|
||||
|
||||
**Imported Libraries:** The following libraries are ALREADY imported and should NEVER be imported again:
|
||||
|
||||
```tool_code
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import scipy
|
||||
```
|
||||
|
||||
**Output Visibility:** Always print the output of code execution to visualize results, especially for data exploration and analysis. For example:
|
||||
- To look at the shape of a pandas.DataFrame do:
|
||||
```tool_code
|
||||
print(df.shape)
|
||||
```
|
||||
The output will be presented to you as:
|
||||
```tool_outputs
|
||||
(49, 7)
|
||||
|
||||
```
|
||||
- To display the result of a numerical computation:
|
||||
```tool_code
|
||||
x = 10 ** 9 - 12 ** 5
|
||||
print(f'{{x=}}')
|
||||
```
|
||||
The output will be presented to you as:
|
||||
```tool_outputs
|
||||
x=999751168
|
||||
|
||||
```
|
||||
- You **never** generate ```tool_outputs yourself.
|
||||
- You can then use this output to decide on next steps.
|
||||
- Print just variables (e.g., `print(f'{{variable=}}')`.
|
||||
|
||||
**No Assumptions:** **Crucially, avoid making assumptions about the nature of the data or column names.** Base findings solely on the data itself. Always use the information obtained from `explore_df` to guide your analysis.
|
||||
|
||||
**Available files:** Only use the files that are available as specified in the list of available files.
|
||||
|
||||
**Data in prompt:** Some queries contain the input data directly in the prompt. You have to parse that data into a pandas DataFrame. ALWAYS parse all the data. NEVER edit the data that are given to you.
|
||||
|
||||
**Answerability:** Some queries may not be answerable with the available data. In those cases, inform the user why you cannot process their query and suggest what type of data would be needed to fulfill their request.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name="data_science_agent",
|
||||
instruction=base_system_instruction() + """
|
||||
|
||||
|
||||
You need to assist the user with their queries by looking at the data and the context in the conversation.
|
||||
You final answer should summarize the code and code execution relevant to the user query.
|
||||
|
||||
You should include all pieces of data to answer the user query, such as the table from code execution results.
|
||||
If you cannot answer the question directly, you should follow the guidelines above to generate the next step.
|
||||
If the question can be answered directly with writing any code, you should do that.
|
||||
If you doesn't have enough data to answer the question, you should ask for clarification from the user.
|
||||
|
||||
You should NEVER install any package on your own like `pip install ...`.
|
||||
When plotting trends, you should make sure to sort and order the data by the x-axis.
|
||||
|
||||
|
||||
""",
|
||||
code_executor=CustomCodeExecutor(),
|
||||
)
|
||||
@@ -0,0 +1,59 @@
|
||||
# Vertex AI Code Execution Agent Sample
|
||||
|
||||
This directory contains a sample agent that demonstrates how to use the
|
||||
`VertexAiCodeExecutor` for data science tasks.
|
||||
|
||||
## Overview
|
||||
|
||||
The agent is designed to assist with data analysis in a Python environment. It
|
||||
can execute Python code to perform tasks like data manipulation, analysis, and
|
||||
visualization. This agent is particularly useful for tasks that require a secure
|
||||
and sandboxed code execution environment with common data science libraries
|
||||
pre-installed.
|
||||
|
||||
This sample is a direct counterpart to the
|
||||
[code execution sample](../code_execution/) which uses the
|
||||
`BuiltInCodeExecutor`. The key difference in this sample is the use of
|
||||
`VertexAiCodeExecutor`.
|
||||
|
||||
## `VertexAiCodeExecutor`
|
||||
|
||||
The `VertexAiCodeExecutor` leverages the
|
||||
[Vertex AI Code Interpreter Extension](https://cloud.google.com/vertex-ai/generative-ai/docs/extensions/code-interpreter)
|
||||
to run Python code. This provides several advantages:
|
||||
|
||||
- **Security**: Code is executed in a sandboxed environment on Google Cloud,
|
||||
isolating it from your local system.
|
||||
- **Pre-installed Libraries**: The environment comes with many common Python
|
||||
data science libraries pre-installed, such as `pandas`, `numpy`, and
|
||||
`matplotlib`.
|
||||
- **Stateful Execution**: The execution environment is stateful, meaning
|
||||
variables and data from one code execution are available in subsequent
|
||||
executions within the same session.
|
||||
|
||||
## How to use
|
||||
|
||||
### Prerequisites
|
||||
|
||||
Ensure you have configured your environment for using
|
||||
[Google Cloud Vertex AI](https://google.github.io/adk-docs/get-started/quickstart/#gemini---google-cloud-vertex-ai).
|
||||
You will need to have a Google Cloud Project with the Vertex AI API enabled.
|
||||
|
||||
### Running the agent
|
||||
|
||||
You can run this agent using the ADK CLI from the root of the repository.
|
||||
|
||||
To interact with the agent through the command line:
|
||||
|
||||
```bash
|
||||
adk run contributing/samples/vertex_code_execution "Plot a sine wave from 0 to 10"
|
||||
```
|
||||
|
||||
To use the web interface:
|
||||
|
||||
```bash
|
||||
adk web contributing/samples/
|
||||
```
|
||||
|
||||
Then select `vertex_code_execution` from the list of agents and interact with
|
||||
it.
|
||||
@@ -0,0 +1,15 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
from . import agent
|
||||
@@ -0,0 +1,99 @@
|
||||
# Copyright 2026 Google LLC
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Data science agent that uses Vertex AI code interpreter."""
|
||||
|
||||
from google.adk.agents.llm_agent import Agent
|
||||
from google.adk.code_executors.vertex_ai_code_executor import VertexAiCodeExecutor
|
||||
|
||||
|
||||
def base_system_instruction():
|
||||
"""Returns: data science agent system instruction."""
|
||||
|
||||
return """
|
||||
# Guidelines
|
||||
|
||||
**Objective:** Assist the user in achieving their data analysis goals within the context of a Python Colab notebook, **with emphasis on avoiding assumptions and ensuring accuracy.** Reaching that goal can involve multiple steps. When you need to generate code, you **don't** need to solve the goal in one go. Only generate the next step at a time.
|
||||
|
||||
**Code Execution:** All code snippets provided will be executed within the Colab environment.
|
||||
|
||||
**Statefulness:** All code snippets are executed and the variables stays in the environment. You NEVER need to re-initialize variables. You NEVER need to reload files. You NEVER need to re-import libraries.
|
||||
|
||||
**Imported Libraries:** The following libraries are ALREADY imported and should NEVER be imported again:
|
||||
|
||||
```tool_code
|
||||
import io
|
||||
import math
|
||||
import re
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import scipy
|
||||
```
|
||||
|
||||
**Output Visibility:** Always print the output of code execution to visualize results, especially for data exploration and analysis. For example:
|
||||
- To look at the shape of a pandas.DataFrame do:
|
||||
```tool_code
|
||||
print(df.shape)
|
||||
```
|
||||
The output will be presented to you as:
|
||||
```tool_outputs
|
||||
(49, 7)
|
||||
|
||||
```
|
||||
- To display the result of a numerical computation:
|
||||
```tool_code
|
||||
x = 10 ** 9 - 12 ** 5
|
||||
print(f'{{x=}}')
|
||||
```
|
||||
The output will be presented to you as:
|
||||
```tool_outputs
|
||||
x=999751168
|
||||
|
||||
```
|
||||
- You **never** generate ```tool_outputs yourself.
|
||||
- You can then use this output to decide on next steps.
|
||||
- Print just variables (e.g., `print(f'{{variable=}}')`.
|
||||
|
||||
**No Assumptions:** **Crucially, avoid making assumptions about the nature of the data or column names.** Base findings solely on the data itself. Always use the information obtained from `explore_df` to guide your analysis.
|
||||
|
||||
**Available files:** Only use the files that are available as specified in the list of available files.
|
||||
|
||||
**Data in prompt:** Some queries contain the input data directly in the prompt. You have to parse that data into a pandas DataFrame. ALWAYS parse all the data. NEVER edit the data that are given to you.
|
||||
|
||||
**Answerability:** Some queries may not be answerable with the available data. In those cases, inform the user why you cannot process their query and suggest what type of data would be needed to fulfill their request.
|
||||
|
||||
"""
|
||||
|
||||
|
||||
root_agent = Agent(
|
||||
name="data_science_agent",
|
||||
instruction=base_system_instruction() + """
|
||||
|
||||
|
||||
You need to assist the user with their queries by looking at the data and the context in the conversation.
|
||||
You final answer should summarize the code and code execution relevant to the user query.
|
||||
|
||||
You should include all pieces of data to answer the user query, such as the table from code execution results.
|
||||
If you cannot answer the question directly, you should follow the guidelines above to generate the next step.
|
||||
If the question can be answered directly with writing any code, you should do that.
|
||||
If you doesn't have enough data to answer the question, you should ask for clarification from the user.
|
||||
|
||||
You should NEVER install any package on your own like `pip install ...`.
|
||||
When plotting trends, you should make sure to sort and order the data by the x-axis.
|
||||
|
||||
|
||||
""",
|
||||
code_executor=VertexAiCodeExecutor(),
|
||||
)
|
||||
Reference in New Issue
Block a user