|
| 1 | +# Copyright 2026 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""ADK Web demo agent for RFC #93 — model-authored typed Workflows. |
| 16 | +
|
| 17 | +`root_agent` is a `Workflow` whose single node: |
| 18 | + 1. asks a planner `LlmAgent(output_schema=WorkflowSpec)` to author a plan, |
| 19 | + 2. validates it (`WorkflowSpecValidator`) against a capability registry, |
| 20 | + 3. persists the frozen spec + hash to session state, |
| 21 | + 4. executes it on the real ADK engine via the #92 supervisor, |
| 22 | +surfacing each step as a chat message so the ADK Web UI shows the authored |
| 23 | +plan, validation, capabilities, frozen hash, and final output. Run with: |
| 24 | +
|
| 25 | + adk web contributing/samples/workflows/authored_workflow_demo |
| 26 | +
|
| 27 | +Configure a model first (no hardcoded project): |
| 28 | + export GOOGLE_GENAI_USE_VERTEXAI=1 GOOGLE_CLOUD_PROJECT=<project> |
| 29 | + export GOOGLE_CLOUD_LOCATION=global SPIKE_GEMINI_MODEL=gemini-3.5-flash |
| 30 | +""" |
| 31 | + |
| 32 | +from __future__ import annotations |
| 33 | + |
| 34 | +import hashlib |
| 35 | +import json |
| 36 | +import os |
| 37 | +import sys |
| 38 | +from typing import Literal |
| 39 | + |
| 40 | +from google.adk import Agent |
| 41 | +from google.adk import Context |
| 42 | +from google.adk import Event |
| 43 | +from google.adk import Workflow |
| 44 | +from google.adk.workflow import node |
| 45 | +from google.genai import types |
| 46 | +from pydantic import BaseModel |
| 47 | + |
| 48 | +# Reuse the committed #93 authoring stack (sibling sample dir). |
| 49 | +sys.path.insert( |
| 50 | + 0, |
| 51 | + os.path.join( |
| 52 | + os.path.dirname(os.path.abspath(__file__)), |
| 53 | + "..", |
| 54 | + "..", |
| 55 | + "authored_workflow_spike", |
| 56 | + ), |
| 57 | +) |
| 58 | +from authoring import Capability # noqa: E402 |
| 59 | +from authoring import CapabilityRegistry # noqa: E402 |
| 60 | +from authoring import SpecInterpreter # noqa: E402 |
| 61 | +from authoring import WorkflowSpec # noqa: E402 |
| 62 | +from authoring import WorkflowSpecValidator # noqa: E402 |
| 63 | + |
| 64 | +MODEL = os.environ.get("SPIKE_GEMINI_MODEL", "gemini-2.5-flash") |
| 65 | +DET = types.GenerateContentConfig(temperature=0) |
| 66 | + |
| 67 | +# A small, deliberately-mixed codebase to audit (3 vulnerable, 1 safe). |
| 68 | +FILES = [ |
| 69 | + { |
| 70 | + "path": "auth.py", |
| 71 | + "code": "def login(pw): return pw == 'admin123' # hardcoded", |
| 72 | + }, |
| 73 | + { |
| 74 | + "path": "db.py", |
| 75 | + "code": "q = 'SELECT * FROM users WHERE id=' + request.args['id']", |
| 76 | + }, |
| 77 | + {"path": "net.py", "code": "os.system('ping ' + user_supplied_host)"}, |
| 78 | + {"path": "math.py", "code": "def mean(xs):\n return sum(xs) / len(xs)"}, |
| 79 | +] |
| 80 | + |
| 81 | + |
| 82 | +class Finding(BaseModel): |
| 83 | + path: str |
| 84 | + severity: Literal["CRITICAL", "HIGH", "MEDIUM", "LOW", "NONE"] |
| 85 | + issue: str |
| 86 | + |
| 87 | + |
| 88 | +class ReportFixed(BaseModel): |
| 89 | + total: int |
| 90 | + critical: int |
| 91 | + high: int |
| 92 | + medium: int |
| 93 | + low: int |
| 94 | + none: int |
| 95 | + summary: str |
| 96 | + |
| 97 | + |
| 98 | +class Note(BaseModel): |
| 99 | + note: str |
| 100 | + |
| 101 | + |
| 102 | +def _registry() -> CapabilityRegistry: |
| 103 | + return CapabilityRegistry([ |
| 104 | + Capability( |
| 105 | + name="reviewer", |
| 106 | + input_kind="item", |
| 107 | + output_model=Finding, |
| 108 | + serialize_input=True, |
| 109 | + max_fan_out=50, |
| 110 | + build=lambda: Agent( |
| 111 | + name="reviewer", |
| 112 | + model=MODEL, |
| 113 | + output_schema=Finding, |
| 114 | + generate_content_config=DET, |
| 115 | + instruction=( |
| 116 | + "Input JSON with keys path and code. Output a Finding" |
| 117 | + " (echo the path)." |
| 118 | + ), |
| 119 | + ), |
| 120 | + ), |
| 121 | + Capability( |
| 122 | + name="triager", |
| 123 | + input_kind="list", |
| 124 | + output_model=ReportFixed, |
| 125 | + serialize_input=True, |
| 126 | + build=lambda: Agent( |
| 127 | + name="triager", |
| 128 | + model=MODEL, |
| 129 | + output_schema=ReportFixed, |
| 130 | + generate_content_config=DET, |
| 131 | + instruction=( |
| 132 | + "Input: a JSON list of Findings. Output ReportFixed:" |
| 133 | + " total, per-severity counts (must sum to total), and" |
| 134 | + " a one-line summary." |
| 135 | + ), |
| 136 | + ), |
| 137 | + ), |
| 138 | + Capability( |
| 139 | + name="formatter", |
| 140 | + input_kind="item", |
| 141 | + output_model=Note, |
| 142 | + serialize_input=True, |
| 143 | + build=lambda: Agent( |
| 144 | + name="formatter", |
| 145 | + model=MODEL, |
| 146 | + output_schema=Note, |
| 147 | + generate_content_config=DET, |
| 148 | + instruction=( |
| 149 | + "Input: a ReportFixed JSON. Output a Note: a one-line" |
| 150 | + " markdown bullet summarizing the audit." |
| 151 | + ), |
| 152 | + ), |
| 153 | + ), |
| 154 | + ]) |
| 155 | + |
| 156 | + |
| 157 | +_REGISTRY_DESC = ( |
| 158 | + "reviewer (item: a file with path and code -> Finding), triager (LIST of" |
| 159 | + " Findings -> ReportFixed), formatter (item: a ReportFixed -> Note)." |
| 160 | +) |
| 161 | +_PLANNER_INSTR = ( |
| 162 | + "Author a WorkflowSpec using ONLY these capabilities: " |
| 163 | + + _REGISTRY_DESC |
| 164 | + + " The task input has a 'files' list of objects with path and code." |
| 165 | + " Author:" |
| 166 | + " a fan_out of reviewer over task.files, then a step running triager on the" |
| 167 | + " findings, then a step running formatter on the report. Use" |
| 168 | + " Binding(source='task', path='files') and Binding(source='step'," |
| 169 | + " step=<id>) to chain. Set output to the formatter step." |
| 170 | +) |
| 171 | + |
| 172 | + |
| 173 | +def _msg(text: str) -> Event: |
| 174 | + return Event( |
| 175 | + content=types.Content(role="model", parts=[types.Part(text=text)]) |
| 176 | + ) |
| 177 | + |
| 178 | + |
| 179 | +def _hash(spec: WorkflowSpec) -> str: |
| 180 | + return hashlib.sha256( |
| 181 | + json.dumps(spec.model_dump(), sort_keys=True).encode() |
| 182 | + ).hexdigest()[:12] |
| 183 | + |
| 184 | + |
| 185 | +@node(rerun_on_resume=True) |
| 186 | +async def author_validate_execute(ctx: Context, node_input): |
| 187 | + reg = _registry() |
| 188 | + |
| 189 | + # 1. LOAD-OR-AUTHOR. If a frozen spec exists in this session, REUSE it (do not |
| 190 | + # re-author) — this is the resume/reproducibility claim. Otherwise the model |
| 191 | + # authors a fresh typed WorkflowSpec (data, not code). |
| 192 | + existing = ctx.state.get("authored_workflow:frozen_spec") |
| 193 | + if existing: |
| 194 | + spec = WorkflowSpec.model_validate(existing) |
| 195 | + spec_hash = ctx.state.get("authored_workflow:frozen_spec_hash") or _hash( |
| 196 | + spec |
| 197 | + ) |
| 198 | + reused = True |
| 199 | + yield _msg( |
| 200 | + f"♻️ **Reusing frozen plan** from session state — hash `{spec_hash}`. " |
| 201 | + "The model is NOT re-invoked; the exact prior plan is replayed." |
| 202 | + ) |
| 203 | + else: |
| 204 | + reused = False |
| 205 | + yield _msg( |
| 206 | + "🧭 **Model-authored Workflow** — planning a security audit over " |
| 207 | + f"{len(FILES)} files using only registered capabilities " |
| 208 | + "(`reviewer`, `triager`, `formatter`)." |
| 209 | + ) |
| 210 | + planner = Agent( |
| 211 | + name="planner", |
| 212 | + model=MODEL, |
| 213 | + output_schema=WorkflowSpec, |
| 214 | + generate_content_config=DET, |
| 215 | + instruction=_PLANNER_INSTR, |
| 216 | + ) |
| 217 | + raw = await ctx.run_node( |
| 218 | + planner, |
| 219 | + node_input=f"Audit these files: {[f['path'] for f in FILES]}.", |
| 220 | + run_id="plan", |
| 221 | + ) |
| 222 | + spec = WorkflowSpec.model_validate(raw) |
| 223 | + spec_hash = _hash(spec) |
| 224 | + steps = " → ".join(s.kind for s in spec.steps) |
| 225 | + yield _msg( |
| 226 | + f"📋 **Authored plan** (`{steps}`):\n```json\n" |
| 227 | + f"{json.dumps(spec.model_dump(), indent=1)}\n```" |
| 228 | + ) |
| 229 | + |
| 230 | + # 2. VALIDATE — semantic validation against the registry (always). |
| 231 | + warnings = WorkflowSpecValidator(reg).validate(spec) # raises on hard error |
| 232 | + caps = sorted({getattr(s, "capability", None) for s in spec.steps} - {None}) |
| 233 | + yield _msg( |
| 234 | + "✅ **Validation passed.** Capabilities referenced (all registered): " |
| 235 | + f"`{caps}`." |
| 236 | + + (f"\n⚠️ warnings: {warnings}" if warnings else "") |
| 237 | + ) |
| 238 | + |
| 239 | + # 3. FREEZE — persist spec + hash to session state on first author only |
| 240 | + # (visible in the State tab; reused runs already have it). |
| 241 | + if not reused: |
| 242 | + ctx.state["authored_workflow:frozen_spec"] = spec.model_dump() |
| 243 | + ctx.state["authored_workflow:frozen_spec_hash"] = spec_hash |
| 244 | + yield _msg( |
| 245 | + f"🔒 **Frozen spec** persisted to session state — hash `{spec_hash}`. " |
| 246 | + "Re-send the prompt: it replays this exact plan, not a new one." |
| 247 | + ) |
| 248 | + |
| 249 | + # 4. EXECUTE — run the validated plan on the real ADK engine (#92 supervisor). |
| 250 | + result = await SpecInterpreter(reg, ctx).execute(spec, {"files": FILES}) |
| 251 | + yield _msg( |
| 252 | + "📄 **Audit result:**" |
| 253 | + f" {result.get('note') if isinstance(result, dict) else result}" |
| 254 | + ) |
| 255 | + yield Event( |
| 256 | + output={ |
| 257 | + "hash": spec_hash, |
| 258 | + "result": result, |
| 259 | + "capabilities": caps, |
| 260 | + "reused": reused, |
| 261 | + } |
| 262 | + ) |
| 263 | + |
| 264 | + |
| 265 | +root_agent = Workflow( |
| 266 | + name="security_audit_planner", |
| 267 | + edges=[("START", author_validate_execute)], |
| 268 | +) |
0 commit comments