From 48a580fc7ba6f3767f4829194e284e7d35b37de5 Mon Sep 17 00:00:00 2001 From: Ferran Pons Serra Date: Sun, 15 Nov 2026 20:42:31 +0000 Subject: [PATCH] feat(labs): add adaptive team orchestration Add an experimental workflow helper that plans a task, selects one specialist at a time, replans when progress stalls, and can pause for a person to accept the plan. The loop is an original ADK workflow on top of ctx.run_node, structured output, and RequestInput. It is inspired by the publicly described Magentic-One pattern (google/adk-python#8167). Co-authored-by: Ferran Pons Serra --- .../samples/workflows/adaptive_team/README.md | 66 ++ .../workflows/adaptive_team/__init__.py | 15 + .../samples/workflows/adaptive_team/agent.py | 53 ++ docs/guides/README.md | 1 + docs/guides/labs/adaptive_team/team/index.md | 194 +++++ src/google/adk/features/_feature_registry.py | 4 + src/google/adk/labs/adaptive_team/__init__.py | 41 ++ .../adk/labs/adaptive_team/_constants.py | 41 ++ src/google/adk/labs/adaptive_team/_prompts.py | 266 +++++++ src/google/adk/labs/adaptive_team/_team.py | 660 ++++++++++++++++++ src/google/adk/labs/adaptive_team/_types.py | 168 +++++ .../unittests/labs/adaptive_team/__init__.py | 13 + .../labs/adaptive_team/test_adaptive_team.py | 566 +++++++++++++++ 13 files changed, 2088 insertions(+) create mode 100644 contributing/samples/workflows/adaptive_team/README.md create mode 100644 contributing/samples/workflows/adaptive_team/__init__.py create mode 100644 contributing/samples/workflows/adaptive_team/agent.py create mode 100644 docs/guides/labs/adaptive_team/team/index.md create mode 100644 src/google/adk/labs/adaptive_team/__init__.py create mode 100644 src/google/adk/labs/adaptive_team/_constants.py create mode 100644 src/google/adk/labs/adaptive_team/_prompts.py create mode 100644 src/google/adk/labs/adaptive_team/_team.py create mode 100644 src/google/adk/labs/adaptive_team/_types.py create mode 100644 tests/unittests/labs/adaptive_team/__init__.py create mode 100644 tests/unittests/labs/adaptive_team/test_adaptive_team.py diff --git a/contributing/samples/workflows/adaptive_team/README.md b/contributing/samples/workflows/adaptive_team/README.md new file mode 100644 index 00000000000..4bf0d3dcf42 --- /dev/null +++ b/contributing/samples/workflows/adaptive_team/README.md @@ -0,0 +1,66 @@ +# ADK Adaptive Team Sample + +## Overview + +This sample coordinates two specialists from a shared plan. A coordinator +writes the plan, picks who should work next, and replaces the plan when two +rounds in a row do not move the task forward. The workflow stops with one +answer. + +The helper is `adaptive_team` in `google.adk.labs.adaptive_team`. It is +experimental. + +## Sample Inputs + +- `Compare the energy use of electric and gas heating for a small apartment, and name the bigger uncertainty.` + + The researcher gathers facts. The analyst compares them. The coordinator + answers after the progress check says the task is covered, or after the + round and replan limits. + +- `What would change that comparison if the apartment were heated only on weekends?` + + A follow-up in the same session starts a new plan. The previous ledger is + left behind with the previous invocation. + +## Graph + +```mermaid +graph TD + START --> driver[driver
PYTHON FUNCTION] + driver -.->|ctx.run_node| coordinator + driver -.->|ctx.run_node| researcher + driver -.->|ctx.run_node| analyst +``` + +## How To + +Build the workflow from a coordinator and the specialists. The coordinator's +instruction is extra guidance. The helper writes the planning, progress, and +final-answer instructions, and it does not call the coordinator's tools. + +```python +root_agent = adaptive_team( + name="energy_brief", + manager=coordinator, + participants=[researcher, analyst], + max_rounds=6, + stall_limit=2, + replan_limit=1, +) +``` + +Set `review_plan=True` to pause for a yes or no on each plan. The reply is a +`PlanDecision`. Pass `approved` and, when rejecting, `notes` describing the +change. A rejection spends one entry from `replan_limit`. + +Read the ledger from session state with `team_state_key("energy_brief")`. +Coordinator events set `custom_metadata["adaptive_team"]["kind"]` to `plan`, +`replan`, `progress`, or `answer`. Specialist events keep the specialist as +the author. + +## Related Guides + +- [adaptive_team](../../../../docs/guides/labs/adaptive_team/team/index.md) - Building a workflow that plans, selects specialists, and replans when work stalls. +- [Dynamic nodes](../../../../docs/guides/workflow/dynamic_nodes/index.md) - Running a node from inside another node with `ctx.run_node`. +- [Workflow](../../../../docs/guides/workflow/workflow/index.md) - The graph the helper returns. diff --git a/contributing/samples/workflows/adaptive_team/__init__.py b/contributing/samples/workflows/adaptive_team/__init__.py new file mode 100644 index 00000000000..4015e47d6e4 --- /dev/null +++ b/contributing/samples/workflows/adaptive_team/__init__.py @@ -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 diff --git a/contributing/samples/workflows/adaptive_team/agent.py b/contributing/samples/workflows/adaptive_team/agent.py new file mode 100644 index 00000000000..6b6002d4b71 --- /dev/null +++ b/contributing/samples/workflows/adaptive_team/agent.py @@ -0,0 +1,53 @@ +# 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 coordinator that plans, picks a specialist, and replans if work stalls.""" + +from google.adk import Agent +from google.adk.labs.adaptive_team import adaptive_team + +researcher = Agent( + name='researcher', + description='Collects qualitative facts and cites where they come from.', + instruction=( + 'Gather the facts the assignment asks for. Do not compute totals' + ' or give the final recommendation.' + ), +) + +analyst = Agent( + name='analyst', + description='Compares figures and states the main uncertainty.', + instruction=( + 'Use the facts you are given. Show the comparison in words and' + ' name the largest uncertainty.' + ), +) + +coordinator = Agent( + name='coordinator', + description='Turns an open question into a plan and a final answer.', + instruction=( + 'Prefer sources a reader can check. Say when a number is an estimate.' + ), +) + +root_agent = adaptive_team( + name='energy_brief', + manager=coordinator, + participants=[researcher, analyst], + max_rounds=6, + stall_limit=2, + replan_limit=1, +) diff --git a/docs/guides/README.md b/docs/guides/README.md index 6481543c87d..c2e7056f767 100644 --- a/docs/guides/README.md +++ b/docs/guides/README.md @@ -88,6 +88,7 @@ This directory contains specific developer guides for the ADK Python implementat * [TypesafeClassifier](integrations/typesafe/typesafe_classifier/index.md) - Answering `Choice`, `Binary`, and `Score` questions with TypeSafe's Jev decision models instead of a model turn. ### Labs +* [adaptive_team](labs/adaptive_team/team/index.md) - Coordinating specialists from a shared plan, with stall detection, replanning, and an optional pause to accept the plan. * [AntigravityAgent](labs/antigravity/index.md) - Runs a Google Antigravity SDK agent as an ADK agent node. * [ClassifierNode](labs/classifiers/classifier_node/index.md) - Routing a workflow on a classifier's answer to one `Choice` or `Binary` question. * [LlmClassifier](labs/classifiers/llm_classifier/index.md) - Answering `Choice`, `Binary`, and `Score` questions with any model, in one structured-output call. diff --git a/docs/guides/labs/adaptive_team/team/index.md b/docs/guides/labs/adaptive_team/team/index.md new file mode 100644 index 00000000000..c1e1dc67bbd --- /dev/null +++ b/docs/guides/labs/adaptive_team/team/index.md @@ -0,0 +1,194 @@ +# adaptive_team + +`adaptive_team` builds a workflow that answers an open task by planning it, +choosing one specialist at a time, and replacing the plan when the work +stalls. + +## Introduction + +Some tasks do not have a fixed path. A research brief, a comparison, or a +draft that needs both reading and calculation can start with a plan and then +change that plan when a step repeats itself. `Workflow` can already run a +Python function that calls `ctx.run_node`. What each application would +otherwise rebuild is the plan, the record of each turn, the stall limit, the +optional pause for a person to accept the plan, and the final answer. + +`adaptive_team` returns that workflow. The caller supplies a coordinator +`LlmAgent` and the specialist agents. The helper supplies the instructions +for the plan, the progress check, and the final answer. The coordinator's +own instruction is appended as extra guidance. Specialist tools stay on the +specialists. The coordinator's tools are not called during those three +phases, because each phase has to return one structured object or one final +reply. + +The package is experimental. `ADAPTIVE_TEAM` is enabled by default and logs a +warning the first time the helper is used. Set `ADK_DISABLE_ADAPTIVE_TEAM=1` +to turn it off. + +## Get started + +The workflow below compares two heating fuels. The researcher collects facts. +The analyst compares them. The coordinator's instruction only adds guidance +about sources and estimates. + +```python +from google.adk import Agent +from google.adk.labs.adaptive_team import adaptive_team + +researcher = Agent( + name="researcher", + description="Collects qualitative facts and cites where they come from.", + instruction="Gather the facts the assignment asks for.", +) +analyst = Agent( + name="analyst", + description="Compares figures and states the main uncertainty.", + instruction="Compare the facts you are given.", +) +coordinator = Agent( + name="coordinator", + description="Turns an open question into a plan and a final answer.", + instruction="Prefer sources a reader can check.", +) + +root_agent = adaptive_team( + name="energy_brief", + manager=coordinator, + participants=[researcher, analyst], + max_rounds=6, + stall_limit=2, + replan_limit=1, +) +``` + +Run it the same way as any other workflow. The workflow's output is the final +answer text. + +## How it works + +One driver node inside the workflow owns the loop. + +1. The coordinator writes a `TaskPlan`: a goal, facts already known, open + questions, and ordered steps. Each step is supposed to name a specialist + from the roster. +1. When `review_plan` is true, the workflow pauses with `RequestInput` and a + `PlanDecision` schema. Approving the plan continues it. Rejecting it, and + sending notes, spends one replacement and asks for a new plan. With no + replacements left, the current plan continues. +1. Each round, the coordinator returns a `RoundAssessment`. `satisfied` ends + the loop. Otherwise `participant` must be a roster name and `assignment` + is the user message for that specialist. +1. The specialist runs through `ctx.run_node` and the turn is appended to the + ledger. A turn is stalled when the assessment says so, when that + specialist was just given the same assignment, or when the name is not on + the roster or the assignment is empty. +1. `stall_limit` stalled turns in a row replace the plan, up to + `replan_limit` replacements. The new plan is shown the previous plan and + the reason the team stalled. After the last allowed stall, the coordinator + writes a best-effort answer instead. +1. `max_rounds` counts specialist turns across every attempt. Reaching it + also writes the answer. + +The ledger is a `TeamSnapshot` in session state, under +`team_state_key(name)`. It stores the task, the plan, every round, the stall +window, and the final answer. The snapshot is tied to the current invocation. +A pause for review stays in that invocation, so the run continues from the +saved ledger and does not repeat model calls that already finished. A new +user message is a new invocation and starts a new ledger. + +Coordinator events set `custom_metadata["adaptive_team"]` to a dict whose +`kind` is a `TeamNotice`: `plan`, `replan`, `progress`, or `answer`. The +`answer` event's output is the final text. Specialist events keep the +specialist's author, so a caller can show those turns without treating them +as the answer. + +`stop_reason` on the snapshot is one of `satisfied`, `round_limit`, +`replan_limit`, or `empty_task`. + +## Configuration options + +| Option | Type | Default | Description | +| :------------- | :---------------------- | :--------------- | :----------------------------------------------------------------------------------------------------------------------------------- | +| `name` | `str` | | Workflow name. Also the suffix of the session-state key. | +| `manager` | `LlmAgent` | | Coordinator. Its instruction is extra guidance. Its tools are not used for the plan, the progress check, or the answer. | +| `participants` | sequence of `BaseAgent` | | Specialists the coordinator may call. Names must be unique Python identifiers and must not match the coordinator or its phase names. | +| `max_rounds` | `int` | `8` | Maximum specialist turns across all attempts. | +| `stall_limit` | `int` | `2` | Consecutive stalled turns before the plan is replaced. | +| `replan_limit` | `int` | `1` | How many replacement plans are allowed. Zero keeps the first plan only. | +| `review_plan` | `bool` | `False` | Pause for a `PlanDecision` before each plan is executed. | +| `description` | `str` | a short sentence | Description stored on the workflow. | + +Give every specialist a `description`. The roster the coordinator sees is the +name plus that description. The specialist's own `instruction` still applies +when that agent runs. + +`stall_limit` counts consecutive stalled turns, not every turn. A turn that +the coordinator marks as progress resets the streak. Replacing the plan also +resets the streak. Earlier turns stay in the transcript so the new plan and +the final answer can use them. + +A rejection during review spends the same budget as a stall replacement. The +notes on the rejection are the reason the next plan has to address. + +## Advanced applications + +Pause for a person to edit the plan before any specialist runs: + +```python +root_agent = adaptive_team( + name="energy_brief", + manager=coordinator, + participants=[researcher, analyst], + review_plan=True, + replan_limit=2, +) +``` + +The pause is a normal `adk_request_input` function call. Resume it with a +`PlanDecision`, for example `{"approved": false, "notes": "focus on cost"}`. +The interrupt id is `review-v` plus the plan version, starting at +`review-v0`. + +Read the ledger after the run: + +```python +from google.adk.labs.adaptive_team import TeamSnapshot +from google.adk.labs.adaptive_team import team_state_key + +snapshot = TeamSnapshot.model_validate( + session.state[team_state_key("energy_brief")] +) +``` + +Filter the event stream by kind when the caller wants the plan and the answer +without assembling them from specialist text: + +```python +from google.adk.labs.adaptive_team import TEAM_EVENT_METADATA_KEY +from google.adk.labs.adaptive_team import TeamNotice + +kind = (event.custom_metadata or {}).get(TEAM_EVENT_METADATA_KEY, {}) +if kind.get("kind") == TeamNotice.ANSWER: + final_answer = event.output +``` + +## Limitations + +The coordinator phases do not see session history and do not call the +manager's tools. Everything they should know has to fit in the task, the +plan, and the transcript. A specialist keeps the tools and the mode +configured on that agent. + +Participant names are matched exactly, after stripping surrounding space. +Descriptions are the only roster text the coordinator is given, so a missing +description makes the roster less useful. + +The ledger lives in session state for the invocation. It is not a memory +service, and a new user message does not continue the previous plan. + +The feature is experimental. Field names on `TaskPlan`, `RoundAssessment`, +`PlanDecision`, and `TeamSnapshot` can still change. + +## Related samples + +- [Adaptive team](../../../../../contributing/samples/workflows/adaptive_team/agent.py) - Two specialists and a coordinator with a stall limit of two rounds. diff --git a/src/google/adk/features/_feature_registry.py b/src/google/adk/features/_feature_registry.py index 396b998d373..d0879bba4f9 100644 --- a/src/google/adk/features/_feature_registry.py +++ b/src/google/adk/features/_feature_registry.py @@ -27,6 +27,7 @@ class FeatureName(str, Enum): """Feature names.""" + ADAPTIVE_TEAM = "ADAPTIVE_TEAM" AGENT_CONFIG = "AGENT_CONFIG" AGENT_ENGINE_SANDBOX_ENVIRONMENT = "AGENT_ENGINE_SANDBOX_ENVIRONMENT" AGENT_STATE = "AGENT_STATE" @@ -121,6 +122,9 @@ class FeatureConfig: # Central registry: FeatureName -> FeatureConfig _FEATURE_REGISTRY: dict[FeatureName, FeatureConfig] = { + FeatureName.ADAPTIVE_TEAM: FeatureConfig( + FeatureStage.EXPERIMENTAL, default_on=True + ), FeatureName.AGENT_CONFIG: FeatureConfig( FeatureStage.STABLE, default_on=True ), diff --git a/src/google/adk/labs/adaptive_team/__init__.py b/src/google/adk/labs/adaptive_team/__init__.py new file mode 100644 index 00000000000..5542915cf1f --- /dev/null +++ b/src/google/adk/labs/adaptive_team/__init__.py @@ -0,0 +1,41 @@ +# 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. + +"""Coordinate specialists with a shared plan and a stall limit. + +Experimental. The helper returns an ordinary workflow, and the shape of +the ledger may change. +""" + +from ._constants import TEAM_EVENT_METADATA_KEY +from ._constants import team_state_key +from ._team import adaptive_team +from ._types import PlanDecision +from ._types import RoundAssessment +from ._types import RoundNote +from ._types import TaskPlan +from ._types import TeamNotice +from ._types import TeamSnapshot + +__all__ = [ + 'PlanDecision', + 'RoundAssessment', + 'RoundNote', + 'TEAM_EVENT_METADATA_KEY', + 'TaskPlan', + 'TeamNotice', + 'TeamSnapshot', + 'adaptive_team', + 'team_state_key', +] diff --git a/src/google/adk/labs/adaptive_team/_constants.py b/src/google/adk/labs/adaptive_team/_constants.py new file mode 100644 index 00000000000..efbead0789f --- /dev/null +++ b/src/google/adk/labs/adaptive_team/_constants.py @@ -0,0 +1,41 @@ +# 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. + +"""Names and stop reasons for adaptive team orchestration.""" + +from __future__ import annotations + +TEAM_EVENT_METADATA_KEY = 'adaptive_team' +"""``Event.custom_metadata`` key for coordinator notices. + +The value is a dict whose ``kind`` is a :class:`TeamNotice` value. +""" + +STOP_SATISFIED = 'satisfied' +STOP_ROUND_LIMIT = 'round_limit' +STOP_REPLAN_LIMIT = 'replan_limit' +STOP_EMPTY_TASK = 'empty_task' + + +def team_state_key(name: str) -> str: + """Returns the session-state key for one adaptive team's snapshot. + + Args: + name: The workflow name passed to :func:`adaptive_team`. + + Returns: + A session-scoped state key. The value is a dict that validates as + :class:`TeamSnapshot`. + """ + return f'adaptive_team:{name}' diff --git a/src/google/adk/labs/adaptive_team/_prompts.py b/src/google/adk/labs/adaptive_team/_prompts.py new file mode 100644 index 00000000000..626abd34fbd --- /dev/null +++ b/src/google/adk/labs/adaptive_team/_prompts.py @@ -0,0 +1,266 @@ +# 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. + +"""Prompts for adaptive team orchestration. + +The instructions stay free of curly braces so ADK's state injection does +not treat them as session placeholders. The task, the plan, and the +transcript travel in the user message instead. +""" + +from __future__ import annotations + +from ._types import RoundNote +from ._types import TaskPlan + +PLAN_INSTRUCTION = ( + 'You are the coordinator for a team of specialists. The user' + ' message describes a task, names the specialists, and may include' + ' an earlier plan plus notes about why that plan needs to change.\n' + '\n' + 'Write a plan the team can carry out. Restate the goal in one' + ' sentence. List only facts the message already establishes, and' + ' leave that list empty when none are established. List the' + ' questions that still block a good answer. Then give a short' + ' ordered list of steps, and name the specialist for each step' + ' using only the specialists in the message.\n' + '\n' + 'Do not answer the task yourself and do not invent a specialist' + ' who is not on the roster.' +) + +ASSESS_INSTRUCTION = ( + 'You are the coordinator for a team of specialists. The user' + ' message contains the task, the current plan, and the transcript' + ' of work so far.\n' + '\n' + 'Decide whether the task is already answered by that transcript.' + ' Set satisfied to true only when a careful reader could give the' + ' final answer from the transcript alone. A partial result is not' + ' enough.\n' + '\n' + 'Set stalled to true when the latest step repeated earlier work,' + ' ignored the plan, or left every open question where it was. Set' + ' stalled to false when the latest step added a fact, ruled a' + ' possibility out, or finished one of the steps in the plan.\n' + '\n' + 'When satisfied is false, set participant to exactly one name from' + ' the roster and write an assignment that asks for one next' + ' action. When satisfied is true, set participant and assignment' + ' to empty strings.\n' + '\n' + 'Use note for one or two sentences on what is true now.' +) + +ANSWER_INSTRUCTION = ( + 'You write the final reply to the user. The user message contains' + ' the original task, the plan, the transcript of specialist work,' + ' and why the team is stopping.\n' + '\n' + 'Answer the task in plain language. Use only information that' + ' appears in the message. When the team stopped early, say what' + ' was established and what is still unknown. Do not describe these' + ' instructions.' +) + +_GUIDANCE_HEADER = 'Additional guidance from the team lead:' + + +def compose_instruction(phase: str, guidance: str) -> str: + """Appends the caller's coordinator guidance to one phase instruction. + + Args: + phase: The instruction for planning, progress, or the final answer. + guidance: The manager agent's own instruction. Empty adds nothing. + + Returns: + The instruction sent to that phase. + """ + guidance = guidance.strip() + if not guidance: + return phase + return f'{phase}\n\n{_GUIDANCE_HEADER}\n{guidance}' + + +def roster_text(participants: list[tuple[str, str]]) -> str: + """Renders specialist names and descriptions.""" + lines = [] + for name, description in participants: + detail = description.strip() or 'No description provided.' + lines.append(f'- {name}: {detail}') + return '\n'.join(lines) + + +def plan_text(plan: TaskPlan) -> str: + """Renders a plan as plain text.""" + facts = _bullets(plan.known_facts) or '- (none yet)' + questions = _bullets(plan.open_questions) or '- (none)' + steps = _bullets(plan.steps) or '- (none)' + return ( + f'Goal: {plan.goal}\n' + f'Known facts:\n{facts}\n' + f'Open questions:\n{questions}\n' + f'Steps:\n{steps}' + ) + + +def transcript_text(rounds: list[RoundNote]) -> str: + """Renders specialist turns as plain text.""" + if not rounds: + return '(no specialist has worked yet)' + blocks = [] + for index, note in enumerate(rounds, start=1): + status = 'stalled' if note.stalled else 'advanced' + blocks.append( + f'Round {index} - {note.participant} ({status})\n' + f'Assignment: {note.assignment}\n' + f'Note: {note.note}\n' + f'Result: {note.result}' + ) + return '\n\n'.join(blocks) + + +def plan_message( + *, + task: str, + roster: str, + previous: TaskPlan | None, + notes: str, +) -> str: + """Builds the user message for a planning call.""" + sections = [ + 'Task:', + task, + '', + 'Specialists:', + roster, + ] + if previous is not None: + sections.extend(['', 'Previous plan:', plan_text(previous)]) + if notes.strip(): + sections.extend(['', 'Why a new plan is needed:', notes.strip()]) + return '\n'.join(sections) + + +def assess_message( + *, + task: str, + plan: TaskPlan, + rounds: list[RoundNote], + roster: str, + completed: int, + max_rounds: int, + notes: str, +) -> str: + """Builds the user message for a progress check.""" + sections = [ + 'Task:', + task, + '', + 'Specialists:', + roster, + '', + 'Current plan:', + plan_text(plan), + '', + f'Rounds completed: {completed} of {max_rounds}.', + '', + 'Transcript:', + transcript_text(rounds), + ] + if notes.strip(): + sections.extend(['', 'Notes to keep in mind:', notes.strip()]) + return '\n'.join(sections) + + +def specialist_message( + *, + name: str, + description: str, + task: str, + plan: TaskPlan, + rounds: list[RoundNote], + assignment: str, +) -> str: + """Builds the user message for one specialist turn.""" + role = description.strip() or 'No description provided.' + return '\n'.join([ + f'You are {name}.', + role, + '', + 'Task:', + task, + '', + 'Plan:', + plan_text(plan), + '', + 'Earlier results:', + transcript_text(rounds), + '', + 'Your assignment:', + assignment, + ]) + + +def answer_message( + *, + task: str, + plan: TaskPlan | None, + rounds: list[RoundNote], + stop_reason: str, +) -> str: + """Builds the user message for the final answer.""" + plan_body = plan_text(plan) if plan is not None else '(no plan)' + return '\n'.join([ + 'Task:', + task, + '', + f'Stopping because: {stop_reason}.', + '', + 'Plan:', + plan_body, + '', + 'Transcript:', + transcript_text(rounds), + ]) + + +def plan_notice(plan: TaskPlan, version: int) -> str: + """Short text for a plan event.""" + steps = _bullets(plan.steps) or '- (none)' + return f'Plan {version}: {plan.goal}\n{steps}' + + +def review_message(plan: TaskPlan, version: int) -> str: + """Text shown when a person is asked to accept a plan.""" + summary = plan_notice(plan, version) + return ( + f'{summary}\n' + '\n' + 'Reply with approved set to true to start this plan, or' + ' approved set to false and notes describing what to change.' + ) + + +def progress_notice(note: RoundNote) -> str: + """Short text for a progress event.""" + status = 'stalled' if note.stalled else 'advanced' + preview = ' '.join(note.result.split()) + if len(preview) > 240: + preview = preview[:237] + '...' + return f'{note.participant} ({status}): {preview}' + + +def _bullets(items: list[str]) -> str: + return '\n'.join(f'- {item}' for item in items if item.strip()) diff --git a/src/google/adk/labs/adaptive_team/_team.py b/src/google/adk/labs/adaptive_team/_team.py new file mode 100644 index 00000000000..d73724dd22d --- /dev/null +++ b/src/google/adk/labs/adaptive_team/_team.py @@ -0,0 +1,660 @@ +# 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. + +"""Build a workflow that coordinates specialists from a shared plan.""" + +from __future__ import annotations + +from collections.abc import AsyncGenerator +from collections.abc import Awaitable +from collections.abc import Callable +from collections.abc import Sequence +import inspect +import json +import logging +from typing import TypeVar + +from pydantic import BaseModel + +from ...agents.base_agent import BaseAgent +from ...agents.context import Context +from ...agents.llm_agent import LlmAgent +from ...agents.readonly_context import ReadonlyContext +from ...events.event import Event +from ...events.request_input import RequestInput +from ...features._feature_decorator import experimental +from ...features._feature_registry import FeatureName +from ...workflow._node import node +from ...workflow._workflow import Workflow +from ._constants import STOP_EMPTY_TASK +from ._constants import STOP_REPLAN_LIMIT +from ._constants import STOP_ROUND_LIMIT +from ._constants import STOP_SATISFIED +from ._constants import TEAM_EVENT_METADATA_KEY +from ._constants import team_state_key +from ._prompts import ANSWER_INSTRUCTION +from ._prompts import answer_message +from ._prompts import ASSESS_INSTRUCTION +from ._prompts import assess_message +from ._prompts import compose_instruction +from ._prompts import PLAN_INSTRUCTION +from ._prompts import plan_message +from ._prompts import plan_notice +from ._prompts import progress_notice +from ._prompts import review_message +from ._prompts import roster_text +from ._prompts import specialist_message +from ._types import PlanDecision +from ._types import RoundAssessment +from ._types import RoundNote +from ._types import TaskPlan +from ._types import TeamNotice +from ._types import TeamSnapshot + +logger = logging.getLogger('google_adk.' + __name__) + +_Instruction = str | Callable[[ReadonlyContext], str | Awaitable[str]] +_PlanModel = TypeVar('_PlanModel', TaskPlan, RoundAssessment) +_APPROVALS = frozenset({ + 'approve', + 'approved', + 'yes', + 'y', + 'ok', + 'lgtm', + 'accept', + 'accepted', +}) + + +@experimental(FeatureName.ADAPTIVE_TEAM) +def adaptive_team( + *, + name: str, + manager: LlmAgent, + participants: Sequence[BaseAgent], + max_rounds: int = 8, + stall_limit: int = 2, + replan_limit: int = 1, + review_plan: bool = False, + description: str = '', +) -> Workflow: + """Builds a workflow that coordinates specialists one turn at a time. + + The workflow asks ``manager`` for a plan, then repeatedly asks it who + should work next. Each specialist runs through ``ctx.run_node``. A + round counts as stalled when the coordinator says so, when the same + specialist is handed the same assignment again, or when the chosen + name is not on the roster. ``stall_limit`` stalled rounds in a row + replace the plan, up to ``replan_limit`` replacements. The manager's + own instruction is extra guidance. This helper supplies the planning, + progress, and final-answer instructions, and it does not call the + manager's tools. + + The plan, the rounds, and the stall window are saved in session state + under :func:`team_state_key`. A pause for plan review resumes in the + same invocation. A later user message starts a fresh ledger. Coordinator + events carry ``custom_metadata[TEAM_EVENT_METADATA_KEY]`` with a + ``kind`` of :class:`TeamNotice`. Specialist events keep their own + author, so a caller can stream them apart from the final answer. + + Args: + name: Workflow name. Must be a Python identifier. + manager: Coordinator model. Its instruction is appended as guidance. + Its tools are not used for planning, progress checks, or the answer. + participants: Specialists the coordinator may call. Names must be + unique, different from the manager and from the coordinator's + internal phase names, and each value must be a :class:`BaseAgent`. + Descriptions are shown to the coordinator. + max_rounds: Maximum specialist turns across every plan attempt. + stall_limit: Consecutive stalled turns before the plan is replaced. + replan_limit: How many replacement plans are allowed. Zero keeps the + first plan only. + review_plan: When true, pause for a :class:`PlanDecision` before + executing a plan and again after each replacement. A rejection + spends one replacement. With none left, the current plan proceeds. + description: Workflow description. A short default is used when empty. + + Returns: + A workflow whose output is the final answer text. + + Raises: + TypeError: If ``manager`` is not an ``LlmAgent`` or a participant is + not an agent. + ValueError: If a limit is out of range or a name collides. + + Example: + ```python + from google.adk.agents.llm_agent import LlmAgent + from google.adk.labs.adaptive_team import adaptive_team + + team = adaptive_team( + name='briefing', + manager=LlmAgent( + name='lead', + instruction='Prefer sources a reader can check.', + ), + participants=[ + LlmAgent( + name='researcher', + description='Collects qualitative facts.', + instruction='Gather facts. Do not recommend.', + ), + ], + max_rounds=6, + stall_limit=2, + replan_limit=1, + ) + ``` + """ + roster = _validate( + manager=manager, + participants=participants, + max_rounds=max_rounds, + stall_limit=stall_limit, + replan_limit=replan_limit, + ) + guidance = manager.instruction + planner = _phase_agent( + manager, + role='plan', + instruction=_phase_instruction(PLAN_INSTRUCTION, guidance), + output_schema=TaskPlan, + ) + assessor = _phase_agent( + manager, + role='assess', + instruction=_phase_instruction(ASSESS_INSTRUCTION, guidance), + output_schema=RoundAssessment, + ) + writer = _phase_agent( + manager, + role='answer', + instruction=_phase_instruction(ANSWER_INSTRUCTION, guidance), + output_schema=None, + ) + by_name = {agent.name: agent for agent in roster} + roster_block = roster_text( + [(agent.name, agent.description) for agent in roster] + ) + state_key = team_state_key(name) + step_budget = (replan_limit + 1) * (max_rounds + 3) + 4 + + @node(name='driver', rerun_on_resume=True) + async def driver( + ctx: Context, node_input: str + ) -> AsyncGenerator[Event | RequestInput, None]: + # Stable run ids let a resumed driver replay model calls. The snapshot + # is keyed by invocation so a new user message does not reuse a ledger + # that belongs to an earlier turn. + snapshot = _snapshot_for_turn(ctx, state_key, node_input) + if snapshot.final_answer: + yield _answer_event(snapshot) + return + if not snapshot.task: + _finish_without_model(ctx, state_key, snapshot) + yield _answer_event(snapshot) + return + + for _ in range(step_budget): + if snapshot.plan is None: + raw_plan = await ctx.run_node( + planner, + node_input=plan_message( + task=snapshot.task, + roster=roster_block, + previous=snapshot.replaced_plan, + notes=snapshot.revision_notes, + ), + run_id=f'plan-v{snapshot.plan_version}', + use_sub_branch=True, + ) + snapshot.plan = _as_model(raw_plan, TaskPlan) + snapshot.replaced_plan = None + snapshot.revision_notes = '' + snapshot.plan_accepted = not review_plan + _save(ctx, state_key, snapshot) + logger.info( + 'Adaptive team %s wrote plan version %s.', + name, + snapshot.plan_version, + ) + yield _notice( + TeamNotice.PLAN + if snapshot.plan_version == 0 + else TeamNotice.REPLAN, + plan_notice(snapshot.plan, snapshot.plan_version), + snapshot, + ) + continue + + if review_plan and not snapshot.plan_accepted: + decision = _parse_decision(ctx.resume_inputs.get(_review_id(snapshot))) + if decision is None: + _save(ctx, state_key, snapshot) + yield RequestInput( + interrupt_id=_review_id(snapshot), + message=review_message(snapshot.plan, snapshot.plan_version), + payload=snapshot.plan.model_dump(mode='json'), + response_schema=PlanDecision, + ) + return + if decision.approved or snapshot.plan_version >= replan_limit: + snapshot.plan_accepted = True + snapshot.revision_notes = '' if decision.approved else decision.notes + _save(ctx, state_key, snapshot) + continue + _begin_replan(snapshot, decision.notes) + _save(ctx, state_key, snapshot) + continue + + if len(snapshot.rounds) >= max_rounds: + await _write_answer( + ctx, + state_key, + snapshot, + writer, + STOP_ROUND_LIMIT, + name, + ) + yield _answer_event(snapshot) + return + + if _stall_streak(snapshot) >= stall_limit: + if snapshot.plan_version >= replan_limit: + await _write_answer( + ctx, + state_key, + snapshot, + writer, + STOP_REPLAN_LIMIT, + name, + ) + yield _answer_event(snapshot) + return + _begin_replan(snapshot, _stall_reason(snapshot)) + _save(ctx, state_key, snapshot) + continue + + round_index = len(snapshot.rounds) + raw_assessment = await ctx.run_node( + assessor, + node_input=assess_message( + task=snapshot.task, + plan=snapshot.plan, + rounds=snapshot.rounds, + roster=roster_block, + completed=round_index, + max_rounds=max_rounds, + notes=snapshot.revision_notes, + ), + run_id=f'assess-p{snapshot.plan_version}-r{round_index}', + use_sub_branch=True, + ) + assessment = _as_model(raw_assessment, RoundAssessment) + if assessment.satisfied: + await _write_answer( + ctx, + state_key, + snapshot, + writer, + STOP_SATISFIED, + name, + ) + yield _answer_event(snapshot) + return + + note = await _run_round( + ctx, + snapshot, + assessment, + by_name, + ) + snapshot.rounds.append(note) + _save(ctx, state_key, snapshot) + yield _notice( + TeamNotice.PROGRESS, + progress_notice(note), + snapshot, + ) + raise RuntimeError( + f'Adaptive team {name!r} did not finish within its step budget.' + ) + + text = description or ( + 'Coordinates specialists from a shared plan, checks progress' + ' each round, and replaces the plan when the work stalls.' + ) + return Workflow(name=name, description=text, edges=[('START', driver)]) + + +def _validate( + *, + manager: LlmAgent, + participants: Sequence[BaseAgent], + max_rounds: int, + stall_limit: int, + replan_limit: int, +) -> list[BaseAgent]: + """Checks constructor arguments and returns a concrete roster.""" + if not isinstance(manager, LlmAgent): + raise TypeError( + f'manager must be an LlmAgent, got {type(manager).__name__}.' + ) + if max_rounds < 1: + raise ValueError('max_rounds must be at least 1.') + if stall_limit < 1: + raise ValueError('stall_limit must be at least 1.') + if replan_limit < 0: + raise ValueError('replan_limit must be at least 0.') + roster = list(participants) + if not roster: + raise ValueError('participants must contain at least one agent.') + + phase_names = { + f'{manager.name}_plan', + f'{manager.name}_assess', + f'{manager.name}_answer', + } + seen: set[str] = set() + for agent in roster: + if not isinstance(agent, BaseAgent): + raise TypeError( + f'participants must be agents, got {type(agent).__name__}.' + ) + if not agent.name.isidentifier(): + raise ValueError( + f'Participant name {agent.name!r} must be a valid Python identifier.' + ) + if agent.name in seen: + raise ValueError(f'Duplicate participant name {agent.name!r}.') + if agent.name == manager.name or agent.name in phase_names: + raise ValueError( + f'Participant name {agent.name!r} collides with the coordinator.' + ) + seen.add(agent.name) + return roster + + +def _phase_instruction(phase: str, guidance: _Instruction) -> _Instruction: + """Joins a phase instruction with the manager's guidance.""" + if isinstance(guidance, str): + return compose_instruction(phase, guidance) + + async def _provider(ctx: ReadonlyContext) -> str: + resolved = guidance(ctx) + if inspect.isawaitable(resolved): + resolved = await resolved + return compose_instruction(phase, resolved) + + return _provider + + +def _phase_agent( + manager: LlmAgent, + *, + role: str, + instruction: _Instruction, + output_schema: type[BaseModel] | None, +) -> LlmAgent: + """Clones the manager for one structured phase. + + The clone drops tools and sub-agents. Structured phases need a single + JSON object, and the specialists are the ones who act. + """ + return manager.clone( + update={ + 'name': f'{manager.name}_{role}', + 'instruction': instruction, + 'output_schema': output_schema, + 'tools': [], + 'sub_agents': [], + 'mode': 'single_turn', + 'include_contents': 'none', + 'output_key': None, + 'planner': None, + } + ) + + +def _snapshot_for_turn(ctx: Context, state_key: str, task: str) -> TeamSnapshot: + """Loads this invocation's ledger, or starts one.""" + invocation_id = ctx.get_invocation_context().invocation_id + current = _load(ctx, state_key) + if current is not None and current.invocation_id == invocation_id: + return current + return TeamSnapshot(invocation_id=invocation_id, task=task.strip()) + + +def _load(ctx: Context, state_key: str) -> TeamSnapshot | None: + raw = ctx.state.get(state_key) + if isinstance(raw, TeamSnapshot): + return raw + if isinstance(raw, dict): + return TeamSnapshot.model_validate(raw) + return None + + +def _save(ctx: Context, state_key: str, snapshot: TeamSnapshot) -> None: + ctx.state[state_key] = snapshot.model_dump(mode='json') + + +def _finish_without_model( + ctx: Context, state_key: str, snapshot: TeamSnapshot +) -> None: + snapshot.final_answer = 'No task was provided.' + snapshot.stop_reason = STOP_EMPTY_TASK + _save(ctx, state_key, snapshot) + + +def _begin_replan(snapshot: TeamSnapshot, notes: str) -> None: + snapshot.replaced_plan = snapshot.plan + snapshot.plan_version += 1 + snapshot.plan = None + snapshot.plan_accepted = False + snapshot.streak_from = len(snapshot.rounds) + snapshot.revision_notes = notes + + +def _stall_streak(snapshot: TeamSnapshot) -> int: + streak = 0 + window = snapshot.rounds[snapshot.streak_from :] + for note in reversed(window): + if not note.stalled: + break + streak += 1 + return streak + + +def _stall_reason(snapshot: TeamSnapshot) -> str: + window = snapshot.rounds[snapshot.streak_from :] + stalled = [note for note in window if note.stalled] + if not stalled: + return 'The team stopped making progress.' + last = stalled[-1] + return ( + f'{last.participant} did not move the task forward.' + f' Assignment: {last.assignment}' + ) + + +def _repeats_previous( + snapshot: TeamSnapshot, assessment: RoundAssessment +) -> bool: + if not snapshot.rounds: + return False + previous = snapshot.rounds[-1] + return previous.participant == assessment.participant.strip() and _norm( + previous.assignment + ) == _norm(assessment.assignment) + + +def _norm(text: str) -> str: + return ' '.join(text.split()).casefold() + + +def _review_id(snapshot: TeamSnapshot) -> str: + return f'review-v{snapshot.plan_version}' + + +def _parse_decision(raw: object) -> PlanDecision | None: + """Reads a plan-review answer from ``ctx.resume_inputs``.""" + if raw is None: + return None + if isinstance(raw, PlanDecision): + return raw + if isinstance(raw, BaseModel): + raw = raw.model_dump() + if isinstance(raw, dict): + if set(raw) == {'result'}: + return _parse_decision(raw['result']) + if 'approved' in raw: + return PlanDecision.model_validate(raw) + return None + if isinstance(raw, bool): + return PlanDecision(approved=raw, notes='') + if isinstance(raw, str): + text = raw.strip() + if text.casefold() in _APPROVALS: + return PlanDecision(approved=True, notes='') + if text: + return PlanDecision(approved=False, notes=text) + return None + + +def _as_model(raw: object, model: type[_PlanModel]) -> _PlanModel: + if isinstance(raw, model): + return raw + if isinstance(raw, dict): + return model.model_validate(raw) + raise ValueError( + f'Coordinator returned {type(raw).__name__}, expected {model.__name__}.' + ) + + +def _result_text(value: object) -> str: + if value is None: + return '' + if isinstance(value, str): + return value.strip() + if isinstance(value, BaseModel): + return value.model_dump_json() + if isinstance(value, (dict, list)): + return json.dumps(value, ensure_ascii=False) + return str(value).strip() + + +async def _run_round( + ctx: Context, + snapshot: TeamSnapshot, + assessment: RoundAssessment, + by_name: dict[str, BaseAgent], +) -> RoundNote: + """Runs the chosen specialist, or records that the name was unusable.""" + participant_name = assessment.participant.strip() + assignment = assessment.assignment.strip() + stalled = assessment.stalled or _repeats_previous(snapshot, assessment) + agent = by_name.get(participant_name) + plan = snapshot.plan + if agent is None or plan is None or not assignment: + allowed = ', '.join(by_name) + reason = ( + f'No specialist named {participant_name!r} is on the roster' + f' ({allowed}).' + if agent is None + else 'The coordinator did not give an assignment.' + ) + return RoundNote( + participant=participant_name or '(none)', + assignment=assignment, + result=reason, + stalled=True, + note=assessment.note, + ) + + result = await ctx.run_node( + agent, + node_input=specialist_message( + name=agent.name, + description=agent.description, + task=snapshot.task, + plan=plan, + rounds=snapshot.rounds, + assignment=assignment, + ), + run_id=f'work-p{snapshot.plan_version}-r{len(snapshot.rounds)}', + use_sub_branch=True, + ) + text = _result_text(result) + if not text: + stalled = True + text = f'{agent.name} returned no result.' + return RoundNote( + participant=agent.name, + assignment=assignment, + result=text, + stalled=stalled, + note=assessment.note, + ) + + +async def _write_answer( + ctx: Context, + state_key: str, + snapshot: TeamSnapshot, + writer: LlmAgent, + reason: str, + team_name: str, +) -> None: + """Asks the coordinator for the final answer and stores it.""" + plan = snapshot.plan + raw = await ctx.run_node( + writer, + node_input=answer_message( + task=snapshot.task, + plan=plan, + rounds=snapshot.rounds, + stop_reason=reason, + ), + run_id=( + f'answer-p{snapshot.plan_version}-r{len(snapshot.rounds)}-{reason}' + ), + use_sub_branch=True, + ) + text = _result_text(raw) + snapshot.final_answer = text or 'The team did not produce an answer.' + snapshot.stop_reason = reason + _save(ctx, state_key, snapshot) + log = logger.info if reason == STOP_SATISFIED else logger.warning + log('Adaptive team %s is stopping: %s.', team_name, reason) + + +def _notice(kind: TeamNotice, text: str, snapshot: TeamSnapshot) -> Event: + return Event( + message=text, + custom_metadata={ + TEAM_EVENT_METADATA_KEY: { + 'kind': kind.value, + 'plan_version': snapshot.plan_version, + 'rounds': len(snapshot.rounds), + 'stop_reason': snapshot.stop_reason, + } + }, + ) + + +def _answer_event(snapshot: TeamSnapshot) -> Event: + event = _notice(TeamNotice.ANSWER, snapshot.final_answer or '', snapshot) + event.output = snapshot.final_answer + return event diff --git a/src/google/adk/labs/adaptive_team/_types.py b/src/google/adk/labs/adaptive_team/_types.py new file mode 100644 index 00000000000..630c52c63af --- /dev/null +++ b/src/google/adk/labs/adaptive_team/_types.py @@ -0,0 +1,168 @@ +# 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. + +"""Structured records for adaptive team orchestration.""" + +from __future__ import annotations + +from enum import Enum + +from pydantic import BaseModel +from pydantic import ConfigDict +from pydantic import Field + + +class TeamNotice(str, Enum): + """Kind of a coordinator event. + + Stored at ``event.custom_metadata['adaptive_team']['kind']``. Specialist + events are not tagged, so a caller can stream them separately from the + coordinator's plan, progress, and final answer. + """ + + PLAN = 'plan' + REPLAN = 'replan' + PROGRESS = 'progress' + ANSWER = 'answer' + + +class TaskPlan(BaseModel): + """The coordinator's plan for the current attempt.""" + + model_config = ConfigDict( + extra='ignore', + use_attribute_docstrings=True, + ) + + goal: str + """One sentence stating what the team should deliver.""" + + known_facts: list[str] = Field(default_factory=list) + """Facts the task already establishes. Empty when none are established.""" + + open_questions: list[str] = Field(default_factory=list) + """Questions that still need an answer before the task is done.""" + + steps: list[str] = Field(default_factory=list) + """Ordered steps. Each step names one specialist from the roster.""" + + +class RoundAssessment(BaseModel): + """The coordinator's reading of the work so far.""" + + model_config = ConfigDict( + extra='ignore', + use_attribute_docstrings=True, + ) + + satisfied: bool + """True only when the transcript is enough to answer the task.""" + + stalled: bool = False + """True when the latest step did not move the task forward.""" + + participant: str = '' + """Specialist name for the next step. Empty when the task is satisfied.""" + + assignment: str = '' + """The single next action for that specialist. Empty when satisfied.""" + + note: str = '' + """One or two sentences on what is true now.""" + + +class PlanDecision(BaseModel): + """A person's decision about a plan that is waiting for review.""" + + model_config = ConfigDict( + extra='ignore', + use_attribute_docstrings=True, + ) + + approved: bool + """True to accept the plan and let the specialists start.""" + + notes: str = '' + """What to change when approved is false. Empty when the plan is accepted.""" + + +class RoundNote(BaseModel): + """One specialist turn, as stored in the session.""" + + model_config = ConfigDict(extra='ignore') + + participant: str + """Specialist who was asked to work, or the name the coordinator invented.""" + + assignment: str + """What that specialist was asked to do.""" + + result: str + """What the specialist returned, or why nobody was called.""" + + stalled: bool + """Whether this turn counted as a lack of progress.""" + + note: str = '' + """The coordinator's short reading of the turn.""" + + +class TeamSnapshot(BaseModel): + """Ledger stored in session state for one invocation of a team. + + A new user message starts a new invocation, and the team ignores a snapshot + whose invocation id does not match. A pause for plan review stays in the + same invocation, so the snapshot is what lets the run continue. + """ + + model_config = ConfigDict(extra='ignore') + + version: int = 1 + """Schema version of this snapshot.""" + + invocation_id: str = '' + """Invocation that owns this snapshot.""" + + task: str = '' + """The user task text for this invocation.""" + + plan: TaskPlan | None = None + """Current plan. None while a replacement plan is being written.""" + + replaced_plan: TaskPlan | None = None + """The plan a replacement is rewriting. Cleared once the new plan exists.""" + + plan_version: int = 0 + """How many times the plan has been replaced. The first plan is version 0.""" + + plan_accepted: bool = False + """Whether the current plan may be executed.""" + + rounds: list[RoundNote] = Field(default_factory=list) + """Specialist turns for every attempt, oldest first.""" + + streak_from: int = 0 + """Index into ``rounds`` where the current stall streak starts.""" + + revision_notes: str = '' + """Notes the next plan should address. Cleared once that plan is written.""" + + final_answer: str | None = None + """The answer returned to the caller, once the team has stopped.""" + + stop_reason: str | None = None + """Why the team stopped. + + One of satisfied, round_limit, replan_limit, or empty_task. + """ diff --git a/tests/unittests/labs/adaptive_team/__init__.py b/tests/unittests/labs/adaptive_team/__init__.py new file mode 100644 index 00000000000..58d482ea386 --- /dev/null +++ b/tests/unittests/labs/adaptive_team/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/tests/unittests/labs/adaptive_team/test_adaptive_team.py b/tests/unittests/labs/adaptive_team/test_adaptive_team.py new file mode 100644 index 00000000000..c2e5d9560d6 --- /dev/null +++ b/tests/unittests/labs/adaptive_team/test_adaptive_team.py @@ -0,0 +1,566 @@ +# 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. + +"""Behavior tests for adaptive team orchestration.""" + +from __future__ import annotations + +import json +from typing import Any + +from google.adk.agents.llm_agent import LlmAgent +from google.adk.apps.app import App +from google.adk.apps.app import ResumabilityConfig +from google.adk.events.event import Event +from google.adk.features._feature_registry import FeatureName +from google.adk.features._feature_registry import temporary_feature_override +from google.adk.labs.adaptive_team import adaptive_team +from google.adk.labs.adaptive_team import TEAM_EVENT_METADATA_KEY +from google.adk.labs.adaptive_team import team_state_key +from google.adk.labs.adaptive_team import TeamNotice +from google.adk.models.llm_request import LlmRequest +from google.adk.workflow import Workflow +from google.adk.workflow.utils._workflow_hitl_utils import create_request_input_response +import pytest + +from ... import testing_utils + +_TASK = 'Compare electric and gas heating for a small apartment.' +_FINDING = 'Water boils at 100 C at sea level.' + + +def _plan(goal: str) -> str: + return json.dumps({ + 'goal': goal, + 'known_facts': ['The apartment is small.'], + 'open_questions': ['Which fuel uses more energy?'], + 'steps': ['researcher gathers the comparison points'], + }) + + +def _assess( + *, + satisfied: bool, + stalled: bool = False, + participant: str = '', + assignment: str = '', + note: str = 'Checked the transcript.', +) -> str: + return json.dumps({ + 'satisfied': satisfied, + 'stalled': stalled, + 'participant': participant, + 'assignment': assignment, + 'note': note, + }) + + +def _team( + manager_responses: list[str], + researcher_responses: list[str] | None = None, + **kwargs: Any, +) -> tuple[Workflow, testing_utils.MockModel, testing_utils.MockModel]: + manager_model = testing_utils.MockModel.create(responses=manager_responses) + researcher_model = testing_utils.MockModel.create( + responses=researcher_responses or [_FINDING] + ) + workflow = adaptive_team( + name='briefing', + manager=LlmAgent( + name='lead', + model=manager_model, + instruction='Prefer sources a reader can check.', + ), + participants=[ + LlmAgent( + name='researcher', + description='Collects qualitative facts.', + instruction='Gather facts. Do not recommend.', + model=researcher_model, + ), + ], + **kwargs, + ) + return workflow, manager_model, researcher_model + + +async def _run( + workflow: Workflow, + message: str = _TASK, + *, + resumable: bool = False, +) -> tuple[testing_utils.InMemoryRunner, list[Event]]: + if resumable: + app = App( + name='briefing_app', + root_agent=workflow, + resumability_config=ResumabilityConfig(is_resumable=True), + ) + runner = testing_utils.InMemoryRunner(app=app) + else: + runner = testing_utils.InMemoryRunner(node=workflow) + events = await runner.run_async(message) + return runner, events + + +def _notices(events: list[Event]) -> list[dict[str, Any]]: + notices = [] + for event in events: + metadata = event.custom_metadata or {} + body = metadata.get(TEAM_EVENT_METADATA_KEY) + if isinstance(body, dict) and 'kind' in body: + notices.append(body) + return notices + + +def _request_text(request: LlmRequest) -> str: + chunks: list[str] = [] + instruction = request.config.system_instruction + if isinstance(instruction, str): + chunks.append(instruction) + for content in request.contents: + if not content.parts: + continue + for part in content.parts: + if part.text: + chunks.append(part.text) + return '\n'.join(chunks) + + +def _snapshot(runner: testing_utils.InMemoryRunner) -> dict[str, Any]: + stored = runner.session.state[team_state_key('briefing')] + assert isinstance(stored, dict) + return stored + + +def _answer(events: list[Event]) -> str: + answers = [ + event.output + for event in events + if isinstance(event.output, str) + and (event.custom_metadata or {}) + .get(TEAM_EVENT_METADATA_KEY, {}) + .get('kind') + == TeamNotice.ANSWER.value + ] + assert answers + return answers[-1] + + +@pytest.mark.asyncio +async def test_delegates_then_returns_the_final_answer(): + """One specialist turn, then a satisfied check, returns the answer. + + The specialist's text stays on that specialist's events. The coordinator's + final event is the only answer, and the session stores the ledger. + """ + workflow, manager_model, researcher_model = _team([ + _plan('Compare the two heating fuels.'), + _assess( + satisfied=False, + participant='researcher', + assignment='List the main comparison points.', + ), + _assess(satisfied=True, note='The comparison is complete.'), + 'Electric heating is simpler to meter in this apartment.', + ]) + + runner, events = await _run(workflow) + + assert _answer(events) == ( + 'Electric heating is simpler to meter in this apartment.' + ) + assert [notice['kind'] for notice in _notices(events)] == [ + 'plan', + 'progress', + 'answer', + ] + authors = {event.author for event in events} + assert 'researcher' in authors + finding_events = [ + event + for event in events + if event.author == 'researcher' + and event.content + and event.content.parts + and any(_FINDING in (part.text or '') for part in event.content.parts) + ] + assert finding_events + assert len(researcher_model.requests) == 1 + assert 'List the main comparison points.' in _request_text( + researcher_model.requests[0] + ) + assert _TASK in _request_text(manager_model.requests[0]) + assert 'researcher' in _request_text(manager_model.requests[0]) + assert 'Prefer sources a reader can check.' in _request_text( + manager_model.requests[0] + ) + assert _FINDING in _request_text(manager_model.requests[2]) + assert _FINDING in _request_text(manager_model.requests[3]) + + stored = _snapshot(runner) + assert stored['stop_reason'] == 'satisfied' + assert stored['plan']['goal'] == 'Compare the two heating fuels.' + assert stored['rounds'][0]['result'] == _FINDING + assert stored['rounds'][0]['participant'] == 'researcher' + assert stored['final_answer'] == _answer(events) + + +@pytest.mark.asyncio +async def test_second_user_message_starts_a_new_ledger(): + """A later turn in the same session does not reuse the previous answer.""" + workflow, manager_model, _ = _team([ + _plan('First goal.'), + _assess(satisfied=True), + 'Answer one.', + _plan('Second goal.'), + _assess(satisfied=True), + 'Answer two.', + ]) + runner = testing_utils.InMemoryRunner(node=workflow) + + first = await runner.run_async('First task.') + second = await runner.run_async('Second task.') + + assert _answer(first) == 'Answer one.' + assert _answer(second) == 'Answer two.' + assert len(manager_model.requests) == 6 + assert _snapshot(runner)['task'] == 'Second task.' + assert _snapshot(runner)['plan']['goal'] == 'Second goal.' + + +@pytest.mark.asyncio +async def test_stall_replaces_the_plan_once(): + """One stalled turn replaces the plan, and the new plan sees that turn.""" + workflow, manager_model, researcher_model = _team( + [ + _plan('First attempt.'), + _assess( + satisfied=False, + stalled=True, + participant='researcher', + assignment='Repeat the same search.', + ), + _plan('Second attempt.'), + _assess(satisfied=True), + 'The second plan was enough.', + ], + stall_limit=1, + replan_limit=1, + max_rounds=4, + ) + + runner, events = await _run(workflow) + + assert _answer(events) == 'The second plan was enough.' + assert [notice['kind'] for notice in _notices(events)] == [ + 'plan', + 'progress', + 'replan', + 'answer', + ] + assert len(researcher_model.requests) == 1 + second_plan = _request_text(manager_model.requests[2]) + assert 'First attempt.' in second_plan + assert 'did not move the task forward' in second_plan + stored = _snapshot(runner) + assert stored['plan_version'] == 1 + assert stored['stop_reason'] == 'satisfied' + assert len(stored['rounds']) == 1 + assert stored['rounds'][0]['stalled'] is True + + +@pytest.mark.asyncio +async def test_replan_budget_stops_with_a_best_effort_answer(): + """A stall with no replacements left synthesizes instead of planning again.""" + workflow, manager_model, _ = _team( + [ + _plan('Only plan.'), + _assess( + satisfied=False, + stalled=True, + participant='researcher', + assignment='Look again.', + ), + 'Partial notes only.', + ], + stall_limit=1, + replan_limit=0, + ) + + runner, events = await _run(workflow) + + assert _answer(events) == 'Partial notes only.' + assert _snapshot(runner)['stop_reason'] == 'replan_limit' + assert _snapshot(runner)['plan_version'] == 0 + assert len(manager_model.requests) == 3 + assert 'Stopping because: replan_limit.' in _request_text( + manager_model.requests[-1] + ) + + +@pytest.mark.asyncio +async def test_round_limit_stops_before_another_progress_check(): + """Filling max_rounds stops before another progress check.""" + workflow, manager_model, researcher_model = _team( + [ + _plan('Bounded plan.'), + _assess( + satisfied=False, + participant='researcher', + assignment='Collect one fact.', + ), + 'Stopped at the round limit.', + ], + max_rounds=1, + stall_limit=3, + ) + + runner, events = await _run(workflow) + + assert _answer(events) == 'Stopped at the round limit.' + assert len(researcher_model.requests) == 1 + assert len(manager_model.requests) == 3 + assert _snapshot(runner)['stop_reason'] == 'round_limit' + assert len(_snapshot(runner)['rounds']) == 1 + assert [notice['kind'] for notice in _notices(events)] == [ + 'plan', + 'progress', + 'answer', + ] + + +@pytest.mark.asyncio +async def test_unknown_specialist_is_a_stalled_round(): + """A name that is not on the roster is recorded and does not call anyone.""" + workflow, _, researcher_model = _team( + [ + _plan('Need a real specialist.'), + _assess( + satisfied=False, + participant='ghost', + assignment='Invent a source.', + ), + 'Nobody by that name was available.', + ], + max_rounds=1, + stall_limit=4, + ) + + runner, _ = await _run(workflow) + + assert not researcher_model.requests + note = _snapshot(runner)['rounds'][0] + assert note['participant'] == 'ghost' + assert note['stalled'] is True + assert 'ghost' in note['result'] + + +@pytest.mark.asyncio +async def test_repeated_assignment_counts_as_stalled(): + """Repeating the same assignment stalls even if the model disagrees.""" + workflow, _, researcher_model = _team( + [ + _plan('Measure once.'), + _assess( + satisfied=False, + stalled=False, + participant='researcher', + assignment='Measure the boiler.', + ), + _assess( + satisfied=False, + stalled=False, + participant='researcher', + assignment='Measure the boiler.', + ), + _plan('Try a different measurement.'), + _assess(satisfied=True), + 'The repeat was discarded.', + ], + researcher_responses=['first reading', 'same reading'], + stall_limit=1, + replan_limit=1, + max_rounds=4, + ) + + runner, events = await _run(workflow) + + assert len(researcher_model.requests) == 2 + notes = _snapshot(runner)['rounds'] + assert notes[0]['stalled'] is False + assert notes[1]['stalled'] is True + assert _snapshot(runner)['plan_version'] == 1 + assert 'replan' in [notice['kind'] for notice in _notices(events)] + + +@pytest.mark.asyncio +async def test_empty_task_does_not_call_the_model(): + """A blank user message finishes with an explanation and no model call.""" + workflow, manager_model, researcher_model = _team(['unused']) + + runner, events = await _run(workflow, ' ') + + assert _answer(events) == 'No task was provided.' + assert not manager_model.requests + assert not researcher_model.requests + assert _snapshot(runner)['stop_reason'] == 'empty_task' + + +@pytest.mark.parametrize('resumable', [False, True]) +@pytest.mark.asyncio +async def test_plan_review_pauses_and_resume_skips_a_second_plan( + resumable: bool, +): + """Approval resumes the same plan. The planner model is not called again.""" + workflow, manager_model, _ = _team( + [ + _plan('Review this plan.'), + _assess(satisfied=True), + 'Approved and answered.', + ], + review_plan=True, + ) + + runner, paused = await _run(workflow, resumable=resumable) + + assert any( + event.get_function_calls() + and event.get_function_calls()[0].name == 'adk_request_input' + for event in paused + ) + assert len(manager_model.requests) == 1 + assert _snapshot(runner)['plan_accepted'] is False + + resumed = await runner.run_async( + new_message=testing_utils.UserContent( + create_request_input_response( + 'review-v0', + {'approved': True, 'notes': ''}, + ) + ), + invocation_id=paused[0].invocation_id, + ) + + assert _answer(resumed) == 'Approved and answered.' + assert len(manager_model.requests) == 3 + assert _snapshot(runner)['plan_version'] == 0 + assert _snapshot(runner)['plan_accepted'] is True + assert _snapshot(runner)['rounds'] == [] + + +@pytest.mark.asyncio +async def test_rejected_plan_is_rewritten_with_the_notes(): + """A rejection spends one replacement and the notes reach the next plan.""" + workflow, manager_model, _ = _team( + [ + _plan('Draft plan.'), + _plan('Cost-focused plan.'), + _assess(satisfied=True), + 'Rewritten answer.', + ], + review_plan=True, + replan_limit=1, + ) + runner, paused = await _run(workflow) + assert len(manager_model.requests) == 1 + + revised = await runner.run_async( + new_message=testing_utils.UserContent( + create_request_input_response( + 'review-v0', + {'approved': False, 'notes': 'focus on cost'}, + ) + ), + invocation_id=paused[0].invocation_id, + ) + assert any(event.get_function_calls() for event in revised) + assert len(manager_model.requests) == 2 + rewrite = _request_text(manager_model.requests[1]) + assert 'focus on cost' in rewrite + assert 'Draft plan.' in rewrite + + finished = await runner.run_async( + new_message=testing_utils.UserContent( + create_request_input_response( + 'review-v1', + {'approved': True, 'notes': ''}, + ) + ), + invocation_id=paused[0].invocation_id, + ) + + assert _answer(finished) == 'Rewritten answer.' + assert len(manager_model.requests) == 4 + assert _snapshot(runner)['plan_version'] == 1 + assert _snapshot(runner)['plan']['goal'] == 'Cost-focused plan.' + + +def test_rejects_invalid_configuration(): + """Limits and roster names are checked before a workflow is returned.""" + lead = LlmAgent(name='lead', instruction='Coordinate.') + researcher = LlmAgent(name='researcher', description='Finds facts.') + + with pytest.raises(ValueError, match='at least one'): + adaptive_team(name='briefing', manager=lead, participants=[]) + with pytest.raises(ValueError, match='Duplicate'): + adaptive_team( + name='briefing', + manager=lead, + participants=[researcher, LlmAgent(name='researcher')], + ) + with pytest.raises(ValueError, match='collides'): + adaptive_team( + name='briefing', + manager=lead, + participants=[LlmAgent(name='lead_plan')], + ) + with pytest.raises(ValueError, match='max_rounds'): + adaptive_team( + name='briefing', + manager=lead, + participants=[researcher], + max_rounds=0, + ) + with pytest.raises(ValueError, match='stall_limit'): + adaptive_team( + name='briefing', + manager=lead, + participants=[researcher], + stall_limit=0, + ) + with pytest.raises(ValueError, match='replan_limit'): + adaptive_team( + name='briefing', + manager=lead, + participants=[researcher], + replan_limit=-1, + ) + with pytest.raises(TypeError, match='LlmAgent'): + adaptive_team( + name='briefing', + manager=object(), # type: ignore[arg-type] + participants=[researcher], + ) + + +def test_disabled_feature_refuses_to_build(): + """Turning the feature off fails at construction.""" + with temporary_feature_override(FeatureName.ADAPTIVE_TEAM, False): + with pytest.raises(RuntimeError, match='ADAPTIVE_TEAM'): + adaptive_team( + name='briefing', + manager=LlmAgent(name='lead'), + participants=[LlmAgent(name='researcher')], + )