Skip to content
Merged
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
2 changes: 2 additions & 0 deletions .github/workflows/release-update-adk-web.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v6
with:
persist-credentials: false

- name: Fetch and unzip frontend assets
run: |
Expand Down
2 changes: 1 addition & 1 deletion contributing/samples/integrations/gepa/rater_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def __call__(self, messages: list[dict[str, Any]]) -> dict[str, Any]:
Returns:
A dictionary containing rating information including score.
"""
env = jinja2.Environment()
env = jinja2.Environment(autoescape=True)
env.globals['user_input'] = (
messages[0].get('parts', [{}])[0].get('text', '') if messages else ''
)
Expand Down
79 changes: 79 additions & 0 deletions contributing/samples/integrations/gepa/rater_lib_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# 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.
import sys
from unittest import mock

# Mock the retry module before importing rater_lib
mock_retry_module = mock.MagicMock()


def mock_retry_decorator(*args, **kwargs):
def decorator(func):
return func

return decorator


mock_retry_module.retry = mock_retry_decorator
sys.modules["retry"] = mock_retry_module

from gepa import rater_lib


def test_rater_escapes_html_inputs_to_prevent_xss():
"""Rater escapes HTML tags in user and model inputs to prevent XSS.

Setup: Mock genai.Client to return a dummy rating response.
Act: Call Rater with messages containing HTML tags.
Assert: Verify that the rendered prompt template contains escaped HTML.
"""
# Arrange
with mock.patch("google.genai.Client") as mock_client_cls:
mock_client = mock_client_cls.return_value
mock_generate = mock_client.models.generate_content
mock_generate.return_value.text = (
"Property: The agent fulfilled the user's primary request.\n"
"Evidence: mock evidence\n"
"Rationale: mock rationale\n"
"Verdict: yes"
)

template_path = (
"contributing/samples/integrations/gepa/rubric_validation_template.txt"
)
rater = rater_lib.Rater(
tool_declarations="[]", validation_template_path=template_path
)

messages = [
{
"role": "user",
"parts": [{"text": "<script>alert('XSS')</script>"}],
},
{
"role": "model",
"parts": [{"text": "Hello <img src=x onerror=alert(1)>"}],
},
]

# Act
rater(messages)

# Assert
assert mock_generate.called
call_args = mock_generate.call_args
contents = call_args.kwargs["contents"]

assert "&lt;script&gt;alert(&#39;XSS&#39;)&lt;/script&gt;" in contents
assert "Hello &lt;img src=x onerror=alert(1)&gt;" in contents
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,12 @@ Verdict: no
</available_tools>

<main_prompt>
{{user_input}}
{{user_input|e}}
</main_prompt>
</user_prompt>

<responses>
{{model_response}}
{{model_response|e}}
</responses>

<properties>
Expand Down
47 changes: 47 additions & 0 deletions contributing/samples/managed_agent/basic/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Managed Agent

## Overview

This sample runs a `ManagedAgent` configured with the built-in `google_search`
tool. Given an open-ended request, the server-side harness autonomously issues
many searches and synthesizes the result in a single turn.

## Sample Inputs

- `Compare the current flagship smartphones from Apple, Samsung, and Google. For each, find its launch price, display size, and main rear camera resolution, then recommend the best value for someone who mostly takes photos.`

The showcase input. A single question the harness answers by fanning out into a
dozen-odd searches. It does broad discovery first, then targeted per-model spec
and price lookups, self-correcting when it hits a stale model, before composing
a comparison table and a reasoned recommendation.

- `Which of those would you pick for shooting video instead?`

A follow-up turn that reuses the recovered remote sandbox and the previous
interaction, continuing the same research thread. This demonstrates multi-turn
chaining.

## Graph

```mermaid
graph LR
User -->|message| ManagedAgent
ManagedAgent -->|interactions.create| ManagedAgentsAPI
ManagedAgentsAPI -->|server-side research loop: google_search ×N| ManagedAgentsAPI
ManagedAgentsAPI -->|streamed events| ManagedAgent
ManagedAgent -->|answer| User
```

## How To

- **Create the agent**: instantiate `ManagedAgent` with an `agent_id`, an
`environment` spec, and a list of server-side `tools`. No `model` is set; the
model is part of the managed agent on the server.
- **Provision a sandbox**: `environment={'type': 'remote'}` requests a fresh
remote sandbox. The resulting environment id is stored on emitted events, so
subsequent turns automatically recover and reuse it.
- **Multi-turn chaining**: the agent recovers the `previous_interaction_id` from
the session events, so follow-up turns continue the same interaction without
any extra wiring.
- **Drive it**: a `ManagedAgent` is a `BaseAgent`, so a standard `Runner` runs
it just like any other agent.
15 changes: 15 additions & 0 deletions contributing/samples/managed_agent/basic/__init__.py
Original file line number Diff line number Diff line change
@@ -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
49 changes: 49 additions & 0 deletions contributing/samples/managed_agent/basic/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# 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 ManagedAgent backed by the Managed Agents API (interactions.create).

``ManagedAgent`` calls the Managed Agents API directly from its run loop instead
of running a local model loop. It currently supports server-side tools only
(ADK built-in tools and raw ``google.genai.types.Tool`` configs); here we wire
up ``google_search``, which runs entirely on the server.

A fresh remote sandbox is provisioned via ``environment={'type': 'remote'}``;
the environment id is recovered from prior events so multi-turn conversations
reuse the same sandbox.

Run with ``adk web`` / ``adk run contributing/samples/managed_agent/basic``. See
the README for the required environment / auth setup.
"""

import os

from google.adk.agents import ManagedAgent
from google.adk.tools import google_search

# The Managed Agent id served by the Managed Agents API. Override with the
# MANAGED_AGENT_ID environment variable if your project has access to a
# different agent.
_DEFAULT_AGENT_ID = 'antigravity-preview-05-2026'

root_agent = ManagedAgent(
name='managed_search_agent',
agent_id=os.environ.get('MANAGED_AGENT_ID', _DEFAULT_AGENT_ID),
# Provision a remote sandbox for the agent. The environment id is recovered
# from prior events, so follow-up turns reuse the same sandbox.
environment={'type': 'remote'},
# Only server-side tools are supported today. google_search is an ADK
# built-in tool that executes on the server.
tools=[google_search],
)
54 changes: 54 additions & 0 deletions contributing/samples/managed_agent/code_execution/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Managed Agent - Code Execution

## Overview

This sample runs a `ManagedAgent` configured with the built-in **code execution**
tool so it can write and run code server-side to compute answers.

Unlike a regular `LlmAgent` (which enables code execution via
`code_executor=BuiltInCodeExecutor()`), `ManagedAgent` has no `code_executor`
field. Instead you pass the raw built-in tool config
`types.Tool(code_execution=types.ToolCodeExecution())` in `tools` -- the same
config `BuiltInCodeExecutor` produces under the hood. This makes the sample a
demonstration of the raw `types.Tool` server-side tool path.

## Sample Inputs

- `What is the sum of the first 50 prime numbers? Use code to compute it.`

The model writes and runs code server-side; the answer (5117) comes from the
executed code rather than the model guessing.

- `Now do the same for the first 100 primes.`

A follow-up turn that reuses the recovered remote sandbox and the previous
interaction (answer: 24133), demonstrating multi-turn chaining.

## Graph

```mermaid
graph LR
User -->|message| ManagedAgent
ManagedAgent -->|interactions.create| ManagedAgentsAPI
ManagedAgentsAPI -->|server-side code execution| ManagedAgentsAPI
ManagedAgentsAPI -->|streamed events| ManagedAgent
ManagedAgent -->|answer| User
```

## How To

- **Create the agent**: instantiate `ManagedAgent` with an `agent_id`, an
`environment` spec, and
`tools=[types.Tool(code_execution=types.ToolCodeExecution())]`. No `model` is
set -- the model is part of the managed agent on the server.
- **Enable code execution**: `ManagedAgent` has no `code_executor` field, so the
raw `types.Tool(code_execution=...)` config is passed in `tools`. The
interactions converter turns it into the server-side `code_execution` tool.
- **Provision a sandbox**: `environment={'type': 'remote'}` requests a fresh
remote sandbox. The resulting environment id is stored on emitted events, so
subsequent turns automatically recover and reuse it.
- **Multi-turn chaining**: the agent recovers the `previous_interaction_id` from
the session events, so follow-up turns continue the same interaction without
any extra wiring.
- **Drive it**: a `ManagedAgent` is a `BaseAgent`, so a standard `Runner` runs
it just like any other agent.
15 changes: 15 additions & 0 deletions contributing/samples/managed_agent/code_execution/__init__.py
Original file line number Diff line number Diff line change
@@ -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
55 changes: 55 additions & 0 deletions contributing/samples/managed_agent/code_execution/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# 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 ManagedAgent that runs server-side code execution.

``ManagedAgent`` calls the Managed Agents API directly from its run loop instead
of running a local model loop. It currently supports server-side tools only.

Unlike ``LlmAgent``, ``ManagedAgent`` has no ``code_executor`` field, so code
execution is enabled by passing the raw built-in tool config
``types.Tool(code_execution=types.ToolCodeExecution())`` in ``tools`` -- the
same config ``BuiltInCodeExecutor`` produces under the hood. The model writes
and runs code on the server to compute answers.

A fresh remote sandbox is provisioned via ``environment={'type': 'remote'}``;
the environment id is recovered from prior events so multi-turn conversations
reuse the same sandbox.

Run with ``adk web`` /
``adk run contributing/samples/managed_agent/code_execution``. See the README
for the required environment / auth setup.
"""

import os

from google.adk.agents import ManagedAgent
from google.genai import types

# The Managed Agent id served by the Managed Agents API. Override with the
# MANAGED_AGENT_ID environment variable if your project has access to a
# different agent.
_DEFAULT_AGENT_ID = 'antigravity-preview-05-2026'

root_agent = ManagedAgent(
name='managed_code_execution_agent',
agent_id=os.environ.get('MANAGED_AGENT_ID', _DEFAULT_AGENT_ID),
# Provision a remote sandbox for the agent. The environment id is recovered
# from prior events, so follow-up turns reuse the same sandbox.
environment={'type': 'remote'},
# ManagedAgent has no `code_executor` field; enable server-side code
# execution by passing the raw built-in tool config. This is the same config
# BuiltInCodeExecutor appends for a regular LlmAgent.
tools=[types.Tool(code_execution=types.ToolCodeExecution())],
)
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,9 @@ python_version = "3.11"
disable_error_code = [ "import-not-found", "import-untyped", "unused-ignore" ]
strict = true
plugins = [ "pydantic.mypy" ]
overrides = [ { module = [
"google.auth.*",
], ignore_missing_imports = true, follow_imports = "skip" } ]

[tool.pytest]
ini_options.testpaths = [ "tests" ]
Expand Down
8 changes: 4 additions & 4 deletions src/google/adk/agents/loop_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ class LoopAgentState(BaseAgentState):


@deprecated(
'LoopAgent is deprecated and will be removed in future versions.'
' Please use Workflow instead.'
'LoopAgent is deprecated in favor of Workflow and will be removed in a'
' future version. Workflow cannot yet be used as an LlmAgent sub-agent.'
)
class LoopAgent(BaseAgent):
"""A shell agent that run its sub-agents in a loop.
Expand All @@ -61,8 +61,8 @@ class LoopAgent(BaseAgent):
reached, the loop agent will stop.

.. deprecated::
LoopAgent is deprecated and will be removed in future versions.
Please use Workflow instead.
LoopAgent is deprecated in favor of Workflow and will be removed in a
future version. Workflow cannot yet be used as an LlmAgent sub-agent.
"""

config_type: ClassVar[type[BaseAgentConfig]] = LoopAgentConfig
Expand Down
Loading