Contents Menu Expand Light mode Dark mode Auto light/dark, in light mode Auto light/dark, in dark mode Skip to content
adk-fluent v0.13.5 is out — Install from PyPI or star on GitHub
adk-fluent
Light Logo Dark Logo
adk-fluent

Getting Started

  • Getting Started
  • AI Coding Agent & Editor Setup
    • Claude Code Setup
    • Cursor Setup
    • VS Code (Copilot) Setup
    • Windsurf Setup
    • Cline Setup
    • Zed Setup
    • Agent Skills

User Guide

  • User Guide
    • Architecture & Core Concepts
    • Best Practices & Anti-Patterns
    • Framework Comparison
    • Builders
    • Expression Language
    • Data Flow Between Agents
    • Prompt Builder
    • One-Shot Execution
    • Callbacks
    • Presets
    • State Transforms
    • Structured Data
    • Context Engineering
    • Composition Patterns
    • Visibility
    • Transfer Control
    • Memory
    • IR and Backends
    • Execution Backends
    • Temporal Guide
    • Middleware
    • Guards (G Module)
    • Evaluation
    • Testing
    • A2A – Agent-to-Agent Communication
    • A2UI – Agent-to-UI Composition
    • Skills – Composable Agent Packages
    • Building Harnesses – From Agent to Autonomous Runtime
    • Error Reference
    • ADK Samples — Fluent API Ports
      • LLM Auditor
      • Financial Advisor
      • Short Movie Agents
      • Deep Search
      • Brand Search Optimization
      • Travel Concierge

API Reference

  • API Reference
    • Module: agent
    • Module: config
    • Module: executor
    • Module: planner
    • Module: plugin
    • Module: runtime
    • Module: service
    • Module: tool
    • Module: workflow
    • Module: prompt
    • Module: context
    • Module: transforms
    • Module: artifacts
    • Module: middleware
    • Module: tools
    • Module: contracts
    • Module: eval
    • Module: visibility

Cookbook

  • Cookbook — Zero to Symphony
    • Hero Workflows
      • Deep Research Agent — Gemini Deep Research in 20 Lines
      • Customer Support Triage — Multi-Tier Routing with Escalation
      • Code Review Agent — Parallel Analysis with Structured Verdicts
      • Investment Analysis Pipeline — Route, Loop, and Conditional Delivery
      • E-Commerce Order Pipeline — Every Primitive in One System
      • Multi-Tool Task Agent — Tools, Guards, and Dependency Injection
      • Dispatch & Join — Fire-and-Continue Background Execution
    • Deep Research Agent — Gemini Deep Research in 20 Lines
    • Customer Support Triage — Multi-Tier Routing with Escalation
    • Code Review Agent — Parallel Analysis with Structured Verdicts
    • Investment Analysis Pipeline — Route, Loop, and Conditional Delivery
    • E-Commerce Order Pipeline — Every Primitive in One System
    • Multi-Tool Task Agent — Tools, Guards, and Dependency Injection
    • Dispatch & Join — Fire-and-Continue Background Execution

All Recipes (Auto-Generated)

  • Cookbook
    • Email Classifier Agent – Simple Agent Creation
    • Travel Planner with Weather and Flight Lookup – Agent with Tools
    • Content Moderation with Logging – Additive Callbacks
    • Document Processing Pipeline – Sequential Pipeline
    • Market Research Fan-Out – Parallel FanOut
    • Essay Refinement Loop – Loop Agent
    • Product Launch Coordinator – Team Coordinator Pattern
    • Quick Code Review – One-Shot Execution with .ask()
    • Live Translation Pipeline – Streaming with .stream()
    • A/B Testing Agent Variants – Agent Cloning with .clone()
    • Smoke-Testing a Customer Support Bot – Inline Testing with .test()
    • Medical Advice Safety Guardrails – Guardrails with .guard()
    • Customer Support Chat Session with .session()
    • Medical Advice Safety Guards – Guards with .guard()
    • Multi-Department Ticket Routing via Dynamic Field Forwarding
    • Production Deployment – to_app() with Middleware Stack
    • News Analysis Pipeline with Operator Composition: >>, |, *
    • E-Commerce Order Routing with Deterministic Branching
    • Multi-Language Support Routing with Dict >> Shorthand
    • Fraud Detection Pipeline with Conditional Gating
    • Resume Refinement Loop with Conditional Exit
    • Order Processing with Typed State Keys
    • Enterprise Agent with Shared Compliance Preset
    • A/B Prompt Testing for Marketing Copy with .with_()
    • Domain Expert Agent via @agent Decorator
    • Introspection & Debugging – validate(), explain(), inspect()
    • Deployment Pipeline: Serialize Agent Configs with to_dict and to_yaml
    • Senior Architect Delegates to Junior Specialists (LLM-Driven Routing)
    • Investment Analysis Pipeline: Full Expression Language in Production
    • ETL Pipeline: Plain Functions as Data Cleaning Steps (>> fn)
    • Customer Onboarding: Conditional Loops with * until(pred) Operator
    • Structured Invoice Parsing: Typed Output Contracts with @ Operator
    • Knowledge Retrieval: Primary API + Fallback Search with // Operator
    • Research Data Pipeline: State Transforms with S Factories
    • Code Review Pipeline – Expression Algebra in Practice
    • ML Inference Monitoring: Performance Tap for Pure Observation
    • Analytics Data Quality: State Contract Assertions with expect()
    • Mock Testing: Customer Onboarding Pipeline with Deterministic Mocks
    • Retry If: API Integration Agent That Retries on Transient Failures
    • Map Over: Batch Processing Customer Feedback with Iteration
    • Timeout: Real-Time Trading Agent with Strict Execution Deadline
    • Gate: Legal Document Review with Human Approval
    • Race: Fastest-Response Search Across Multiple Providers
    • Primitives Showcase: E-Commerce Order Pipeline Using All Primitives
    • Senior Architect Delegates to Junior Specialists (LLM-Driven Routing)
    • Retry If: API Integration Agent That Retries on Transient Failures
    • Pipeline Optimization with IR – Inspecting, Compiling, and Selecting Backends
    • Middleware: Production Middleware Stack for a Healthcare API Agent
    • Contracts and Testing: Medical Imaging Pipeline with Strict Data Contracts
    • Dependency Injection: Multi-Environment Deployment (Dev/Staging/Prod)
    • Architecture Documentation – Mermaid Diagrams from Live Code
    • Context Engineering: Customer Support Pipeline
    • Capture and Route: IT Helpdesk Triage
    • Visibility: Content Review Pipeline
    • Contract Checking: Catch Data Flow Bugs Before Runtime
    • Insurance Claim Processing: Structured Data Pipelines
    • Customer Service Hub: Agent Transfer Control
    • Deep Research Agent – Gemini Deep Research / Perplexity Clone
    • Customer Support Triage – ADK-Samples Inspired Multi-Tier Support
    • Code Review Agent – Gemini CLI / GitHub Copilot Inspired
    • Multi-Tool Task Agent – Manus / OpenAI Agents SDK Inspired
    • Dispatch & Join: Fire-and-Continue Background Execution
    • StreamRunner: Continuous Userless Agent Execution
    • Dispatch-Aware Middleware: Observability for Background Execution
    • M Module: Fluent Middleware Composition
    • TraceContext and Topology Hooks: Cross-Cutting Observability
    • MiddlewareSchema: Typed Middleware State Declarations
    • Built-in Middleware: CostTracker, LatencyMiddleware, TopologyLogMiddleware
    • T Module: Fluent Tool Composition and Dynamic Loading
    • G Module: Declarative Guard Composition
    • Engine Selection – Backend-Selectable Agent Execution
    • Asyncio Backend – Zero-Dependency IR Interpreter
    • A2UI Basics: Declarative Agent-to-UI Composition
    • Temporal Backend – Durable Execution for Agent Pipelines
    • A2UI Agent Integration: Wiring UI to Agents
    • Compute Layer – Pluggable Model, State, Tool, and Artifact Providers
    • A2UI Operators: UI Composition with |, >>, +
    • A2UI LLM-Guided Mode: Let the LLM Design the UI
    • A2UI Pipeline: UI in Multi-Agent Pipelines
    • Prefect Backend – Flow Orchestration for Agent Pipelines
    • DBOS Backend – Durable Functions for Agent Pipelines
    • Skill-Based Agents – Composable Skills from SKILL.md Files
    • Agent Collaboration Mechanisms — Six Ways Agents Work Together
    • Skill-Powered Harness – Building a CodAct Coding Agent
    • Gemini CLI / Claude Code Clone – Production Coding Agent Harness
    • Recipes by Use Case

Examples

  • Runnable Examples

Guides

  • Decision Guide
  • Migration Guide: Native ADK to adk-fluent

Contributing

  • Contributing
    • Codegen Pipeline
    • Upstream ADK Impact Analysis & Generator Architecture
    • Namespace Robustness: Uniformization & Partial Generation
    • Adding Builders

Project

  • Changelog

Research

  • Skill-Based Agents in adk-fluent: Research & 100x Vision
  • Missing Verbs & Idioms: The Next DX Frontier
  • New Structural Types: Beyond Pipeline, FanOut, Loop
Back to top
View this page
Edit this page

Gate: Legal Document Review with Human Approval¶

Tip

What you’ll learn How to use gate: legal document review with human approval with the fluent API.

Source: 41_gate_approval.py

from adk_fluent import Agent, Pipeline, gate

# Scenario: A legal document review pipeline where AI drafts contracts,
# but high-risk clauses require human attorney sign-off before finalization.

# gate(): pause pipeline when condition is met, wait for human approval
contract_pipeline = (
    Agent("clause_analyzer")
    .model("gemini-2.5-flash")
    .instruct("Analyze the contract clauses and assess liability risk level.")
    .writes("liability_risk")
    >> gate(
        lambda s: s.get("liability_risk") == "high",
        message="High liability risk detected. Senior counsel approval required before proceeding.",
    )
    >> Agent("contract_finalizer").model("gemini-2.5-flash").instruct("Finalize the contract with approved terms.")
)

# Custom gate key for tracking specific approval states
compliance_review = (
    Agent("compliance_checker").model("gemini-2.5-flash").instruct("Check regulatory compliance of the proposed terms.")
    >> gate(
        lambda s: True,
        message="Compliance officer must review before filing.",
        gate_key="_compliance_gate",
    )
    >> Agent("filing_agent")
    .model("gemini-2.5-flash")
    .instruct("File the approved documents with the regulatory authority.")
)

# Multiple gates in a pipeline -- multi-stage legal review
multi_stage_review = (
    Agent("contract_drafter").model("gemini-2.5-flash").instruct("Draft the merger agreement based on term sheet.")
    >> gate(
        lambda s: s.get("deal_value_usd", 0) > 10_000_000,
        message="Deal exceeds $10M threshold. Board approval required.",
    )
    >> Agent("risk_disclosures")
    .model("gemini-2.5-flash")
    .instruct("Generate required risk disclosures for the agreement.")
    >> gate(
        lambda s: s.get("cross_border") == "yes",
        message="Cross-border deal requires international counsel sign-off.",
    )
)
# Native ADK requires a custom BaseAgent with EventActions(escalate=True)
# to pause a pipeline for human approval:
#
#   from google.adk.agents.base_agent import BaseAgent
#   from google.adk.events.event import Event
#   from google.adk.events.event_actions import EventActions
#   from google.genai import types
#
#   class LegalApprovalGate(BaseAgent):
#       async def _run_async_impl(self, ctx):
#           if ctx.session.state.get("liability_risk") == "high":
#               if not ctx.session.state.get("_gate_approved"):
#                   ctx.session.state["_gate_pending"] = True
#                   yield Event(
#                       invocation_id=ctx.invocation_id,
#                       author=self.name, branch=ctx.branch,
#                       content=types.Content(role="model",
#                           parts=[types.Part(text="Senior counsel approval required.")]),
#                       actions=EventActions(escalate=True),
#                   )
#
# This is ~25 lines of boilerplate per approval gate.
        graph TD
    n1[["contract_drafter_then_gate_3_then_risk_disclosures_then_gate_4 (sequence)"]]
    n2["contract_drafter"]
    n3{{"gate_3 (gate)"}}
    n4["risk_disclosures"]
    n5{{"gate_4 (gate)"}}
    n2 --> n3
    n3 --> n4
    n4 --> n5
    

Equivalence¶

from adk_fluent._primitive_builders import _GateBuilder
from adk_fluent._base import BuilderBase

# gate() creates a _GateBuilder
g = gate(lambda s: True, message="Test")
assert isinstance(g, _GateBuilder)
assert isinstance(g, BuilderBase)

# Stores predicate and message
assert g._message == "Test"

# Default message when none specified
g_default = gate(lambda s: True)
assert g_default._message == "Approval required"

# Custom gate key
g_custom = gate(lambda s: True, gate_key="_compliance_gate")
assert g_custom._gate_key == "_compliance_gate"

# Auto-generated gate key
g_auto = gate(lambda s: True)
assert g_auto._gate_key.startswith("_gate_")

# Builds as BaseAgent (implements _run_async_impl)
built = g.build()
assert hasattr(built, "_run_async_impl")

# Composable in pipeline
assert isinstance(contract_pipeline, Pipeline)
built_pipeline = contract_pipeline.build()
assert len(built_pipeline.sub_agents) == 3
Next
Race: Fastest-Response Search Across Multiple Providers
Previous
Timeout: Real-Time Trading Agent with Strict Execution Deadline
Copyright © 2025–2026, adk-fluent contributors
Made with Sphinx and @pradyunsg's Furo
On this page
  • Gate: Legal Document Review with Human Approval
    • Equivalence