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

推荐订阅源

博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
aimingoo的专栏
aimingoo的专栏
腾讯CDC
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
F
Fortinet All Blogs
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园_首页
B
Blog RSS Feed
D
Docker
M
MIT News - Artificial intelligence
爱范儿
爱范儿
I
InfoQ

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
I replaced 200 lines of ad-hoc state management in my Her...
Mukunda Rao · 2026-05-26 · via DEV Community

This is a submission for the Hermes Agent Challenge.

My Hermes research agent was tracking state across 20+ variables. Turn counter. Running cost. Message history. Sub-tasks done. Sub-tasks pending. Errors per tool. Each was a standalone variable at the top of the loop, updated individually, saved separately, and restored manually after a crash.

By turn 47, the state management was 200 lines of ad-hoc code spread across the loop. I replaced it with one object.

One object for all agent state

from agent_state_bag import StateBag

state = StateBag({
    "turn": 0,
    "cost_usd": 0.0,
    "messages": [],
    "sub_tasks_done": [],
    "errors": 0,
})

for turn in range(1, 50):
    state["turn"] = turn
    state.increment("cost_usd", 0.05)
    state.increment("errors") if tool_failed else None

    response = call_llm(state["messages"])
    state["messages"].append({"role": "assistant", "content": response.text})

Enter fullscreen mode Exit fullscreen mode

StateBag is a dict wrapper with extra features. It passes through all the dict methods you expect, plus the things a long-running agent actually needs.

Snapshot before each turn

state.push_turn()   # saves current state to history

# If the turn fails badly, restore to before this turn
state.reset_to(state.last_snapshot())

Enter fullscreen mode Exit fullscreen mode

At the start of each turn, push a snapshot. If something goes catastrophically wrong mid-turn, you can roll back to the clean state before that turn started.

Diff what changed

snap = state.snapshot()

# ... agent does stuff ...

changes = state.diff(snap)
# {"cost_usd": (0.15, 0.20), "messages": (old_list, new_list), "sub_tasks_done": ([], ["task1"])}

Enter fullscreen mode Exit fullscreen mode

I log the diff to my trace file at the end of each turn. When reviewing a run, I can see exactly what each turn changed — without comparing full state snapshots manually.

Numeric helpers

state.increment("turn")               # += 1
state.increment("cost_usd", 0.05)     # += 0.05
state.decrement("retries_left")       # -= 1

Enter fullscreen mode Exit fullscreen mode

Returns the new value. Initializes to 0 if the key is missing.

Persist to disk

state.save("state.json")

Enter fullscreen mode Exit fullscreen mode

state = StateBag.load("state.json")

Enter fullscreen mode Exit fullscreen mode

Plain JSON. Grep-able, inspectable, resumable. I save state after every successful turn. On crash, StateBag.load restores exactly where I was.

Turn history

state.push_turn()    # checkpoint this turn
# ...10 more turns...
state.history        # list of all saved snapshots
state.turn_count     # 11
state.last_snapshot() # most recent snapshot

Enter fullscreen mode Exit fullscreen mode

The history grows across the run. After the run, I can replay it to see how state evolved turn by turn.

Merge from another source

# Worker agent's output state
state.merge(worker_output)   # other wins on conflict; deep-copied

Enter fullscreen mode Exit fullscreen mode

In my multi-agent setup, workers return their results as dicts. The supervisor merges them into its own state.

Zero dependencies

Standard library only: json, copy, dataclasses, typing. No third-party packages.

pip install agent-state-bag

Enter fullscreen mode Exit fullscreen mode

Repo: https://github.com/MukundaKatta/agent-state-bag