惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
SegmentFault 最新的问题
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
量子位
月光博客
月光博客
阮一峰的网络日志
阮一峰的网络日志
T
Tailwind CSS Blog
GbyAI
GbyAI
爱范儿
爱范儿
Y
Y Combinator Blog
宝玉的分享
宝玉的分享
有赞技术团队
有赞技术团队
罗磊的独立博客
Recent Announcements
Recent Announcements
博客园 - 司徒正美
M
MIT News - Artificial intelligence
小众软件
小众软件
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
B
Blog RSS Feed
A
About on SuperTechFans
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research
雷峰网
雷峰网

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
How to Build Long-Running AI Agents with Google Gen AI SDK
Gate of AI · 2026-06-01 · via DEV Community

🚀 Technical Briefing: This tutorial is part of our deep-dive series on Agentic Workflows at Gate of AI. For the full technical breakdown, interactive code sandbox, and the native Arabic translation, visit the original article here.

<span>Tutorial</span>
<span>Advanced</span>
<span>⏱ 45 min read</span>
<span>© Gate of AI 2026-05-31</span>

Step away from standard chat APIs. Learn the foundational architecture for building long-running, stateful autonomous agents inspired by the new Gemini Enterprise Unified Inbox.

Prerequisites


  • Python 3.10 or higher
  • Access to the Google Gen AI SDK (Gemini 1.5 Pro or higher)
  • A Google Cloud Project with Billing Enabled
  • Advanced understanding of asynchronous Python (asyncio) and state management

What We're Building

With Google Cloud's announcement of Long-Running Agents in Gemini Enterprise, the development paradigm has officially shifted. In this tutorial, we will construct the foundational "pause-and-resume" architecture required to build these agents.

We won't just build a chatbot. We will build a stateful, asynchronous Python worker that executes a multi-step task, intentionally "pauses" when it requires simulated human approval (mimicking the Unified Inbox), and resumes upon confirmation.

Setup and Installation

We will use the official Google Gen AI SDK and python-dotenv for our environment variables.


pip install google-genai python-dotenv asyncio

Secure your API credentials in a .env file.



# .env file
GEMINI_API_KEY=your_gemini_api_key_here

Step 1: Architecting the Stateful Client

Unlike a standard chatbot that forgets data between queries, a long-running agent must maintain a rigid state dictionary. We initialize the official genai.Client and set up our state manager.



import os
import asyncio
from google import genai
from dotenv import load_dotenv

load_dotenv()

class LongRunningAgent:
def init(self):
# Initialize the official Google Gen AI Client
self.client = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
self.model = "gemini-1.5-pro"

    # This dictionary mimics the persistent state stored in a database
    self.state = {
        "status": "idle", # idle, running, awaiting_approval, completed
        "workflow_history": [],
        "pending_approval_request": None
    }

def log_action(self, action):
    print(f"[AGENT LOG]: {action}")
    self.state["workflow_history"].append(action)

Step 2: Building the "Pause-and-Resume" HITL Logic

The core innovation of Gemini's new update is the Human-in-the-Loop (HITL) Inbox. Here, we build the asynchronous logic that allows the agent to pause execution when it hits a restricted action.



async def request_human_approval(self, task_description):
"""Simulates pushing a task to the Unified Inbox"""
self.state["status"] = "awaiting_approval"
self.state["pending_approval_request"] = task_description
    self.log_action(f"PAUSED: Awaiting human approval for: {task_description}")

    # Simulate waiting for the manager to click "Approve" in the Inbox
    while self.state["status"] == "awaiting_approval":
        await asyncio.sleep(2) # Check database/state every 2 seconds

    self.log_action("RESUMED: Human approval granted.")
    return True

def simulate_manager_approval(self):
    """External function called by your UI/Inbox when a user clicks approve"""
    if self.state["status"] == "awaiting_approval":
        self.state["status"] = "running"
        self.state["pending_approval_request"] = None
        print("\n✅ [INBOX]: Manager approved the action.\n")

Step 3: Executing the Asynchronous Workflow

Now, we tie it together. We will use the client.models.generate_content method to process data, but wrap it in our async execution loop.



async def run_multi_day_workflow(self, initial_prompt):
self.state["status"] = "running"
self.log_action("Starting long-running workflow...")
    # Phase 1: Autonomous Processing
    self.log_action("Analyzing request via Gemini API...")
    response = self.client.models.generate_content(
        model=self.model,
        contents=f"Analyze this task and propose a 3-step execution plan: {initial_prompt}"
    )
    self.log_action(f"Plan generated: {response.text[:100]}...")

    # Phase 2: Hitting a permission wall (Mimicking the Unified Inbox feature)
    await asyncio.sleep(1) # Simulating heavy compute time

    # The agent realizes it needs access to a restricted system (e.g., Google Drive)
    await self.request_human_approval("Access restricted Drive Folder: 'Q3 Financials'")

    # Phase 3: Post-Approval Execution
    self.log_action("Finalizing workflow with approved access...")
    final_response = self.client.models.generate_content(
        model=self.model,
        contents="The human approved access. Generate the final summary report."
    )

    self.state["status"] = "completed"
    self.log_action("Workflow Completed.")
    return final_response.text

⚠️ Expert Tip: In a production environment, do not use asyncio.sleep to hold state. You must serialize the self.state dictionary to a persistent database (like Redis or PostgreSQL). When the webhook from your Inbox arrives, you retrieve the state and re-initialize the agent.

Testing the Unified Inbox Architecture

To run this, we will use Python's asyncio.gather to run the agent in the background while simulating a human checking their inbox.



async def main():
agent = LongRunningAgent()
# Start the agent as a background task
agent_task = asyncio.create_task(
    agent.run_multi_day_workflow("Audit the Q3 Marketing Spend")
)

# Simulate the human manager checking their inbox after 5 seconds
await asyncio.sleep(5)
agent.simulate_manager_approval()

# Wait for the agent to finish
result = await agent_task
print(f"\n[FINAL OUTPUT]:\n{result}")

if name == 'main':
asyncio.run(main())

What to Build Next


  • Replace the simulated wait loop by saving the agent's state to a PostgreSQL database.
  • Build a frontend React/Next.js "Unified Inbox" UI that triggers the webhook to resume the agent.
  • Implement the official genai.types.Tool configurations to let the agent actually execute the actions post-approval.