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

推荐订阅源

让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MyScale Blog
MyScale Blog
U
Unit 42
M
MIT News - Artificial intelligence
小众软件
小众软件
P
Proofpoint News Feed
雷峰网
雷峰网
L
LangChain Blog
S
SegmentFault 最新的问题
腾讯CDC
F
Fortinet All Blogs
A
About on SuperTechFans
WordPress大学
WordPress大学
Vercel News
Vercel News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
G
Google Developers Blog
大猫的无限游戏
大猫的无限游戏
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
D
Docker
N
Netflix TechBlog - Medium
Apple Machine Learning Research
Apple Machine Learning Research
Recent Announcements
Recent Announcements
D
DataBreaches.Net
Stack Overflow Blog
Stack Overflow Blog

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
hermes-stack: four governance layers for Hermes Agent in ...
Mukunda Rao · 2026-05-22 · via DEV Community

This is a submission for the Hermes Agent Challenge.

What I Built

hermes-stack is a tiny Python harness that wraps a Hermes Agent call with four governance layers:

  1. A budget cap that stops the agent when it would spend past a dollar amount or a call count.
  2. An egress allowlist that blocks any outbound HTTP fetch the agent did not declare up front.
  3. An audit trace that writes every call, denial, and exception to a JSONL file.
  4. A structured output check that pulls JSON out of the model reply, validates it against a schema, and retries once if the first reply does not parse.

Each layer fails closed. The audit trail captures the failure before it propagates. The whole thing is a single HermesAgent you wrap around a Hermes call.

I wrote a companion piece for the Write prompt: Wrapping Hermes Agent with agent-stack. This post is the working repo version, with the layers actually wired up, the demo running, and the tests green.

Demo

A 60-second demo lives at examples/url_summarizer.py. It does three things in order, so each layer gets a chance to prove itself.

git clone https://github.com/MukundaKatta/hermes-stack.git
cd hermes-stack
python3 -m pip install -e ".[dev,schema]"
python3 -m pytest tests/ -v
python3 examples/url_summarizer.py

Enter fullscreen mode Exit fullscreen mode

The demo runs offline by default with HermesStub. Set OPENROUTER_API_KEY and it switches to the real nousresearch/hermes-3-llama-3.1-405b free tier on OpenRouter.

Output, trimmed:

[hermes-stack] OPENROUTER_API_KEY not set; using HermesStub (offline).

STEP 1 / 3   Egress allowlist denies an unlisted host
egress denied: host=evil.example.com url=https://evil.example.com/steal-secrets

STEP 2 / 3   Hermes call returns structured JSON
fetched 528 chars from https://example.com/
tokens: prompt=120 completion=140
call cost: $0.000196
budget snapshot: {'spent_usd': 0.000196, 'usd_cap': 0.5, 'calls': 1, 'call_cap': 5}
structured output:
{
  "title": "Stub Summary",
  "key_points": [
    "The hermes-stack wraps Hermes Agent calls with four governance layers.",
    "Each layer fails closed and writes to the audit trail.",
    "The structured-output check rejects model JSON that misses a required key."
  ],
  "sentiment": "neutral",
  "confidence": 0.82
}

STEP 3 / 3   Budget cap fires when spend pushes over
budget caught at call 2: kind=usd requested=$0.000392 cap=$0.000200

DONE
mode: stub
trace saved to /Users/ubl/hermes-stack/traces/run.jsonl
trace lines: 12

Enter fullscreen mode Exit fullscreen mode

The trace JSONL has one line per event:

run.start
egress.denied
egress.allowed
tool.fetch.ok
hermes.call
hermes.ok
cast.ok
hermes.call
hermes.ok
hermes.call
budget.exceeded
run.end

Enter fullscreen mode Exit fullscreen mode

That ordering is the whole point. The egress check fires before any network call. The budget check sits between the model call and the next one. The cast check sits between the model reply and your code. The trace sits across all of them.

Code

Repository: github.com/MukundaKatta/hermes-stack

The interesting part is the agent class. Every Hermes call goes through the same path: reserve a call slot, emit a pre-event, call the model, record the spend, cast the output, emit a post-event. Any step can raise and the audit trail catches it.

class HermesAgent:
    def chat(self, messages):
        self.budget.reserve_call()
        self._trace("hermes.call", {...})
        try:
            resp = self.client.complete(messages)
        except Exception as exc:
            self._trace("hermes.error", {...})
            raise
        try:
            self.budget.record_spend(resp.usd_cost)
        except BudgetExceeded as exc:
            self._trace("budget.exceeded", {...})
            raise
        self._trace("hermes.ok", {...})
        return resp

Enter fullscreen mode Exit fullscreen mode

run_structured is the cast layer on top of chat. It tries to parse JSON out of the reply, and if the parse or schema check fails, it sends one repair prompt and tries again. Mirrors the pattern in agentcast-py.

def run_structured(self, messages, schema=None):
    resp = self.chat(messages)
    try:
        structured = cast_json(resp.text, schema)
    except OutputInvalid as exc:
        self._trace("cast.invalid", {"reason": exc.reason})
        repair = messages + [
            ChatMessage(role="assistant", content=resp.text),
            ChatMessage(role="user", content=(
                "Reply again with ONLY a JSON object in a fenced block. "
                f"reason={exc.reason}"
            )),
        ]
        resp = self.chat(repair)
        structured = cast_json(resp.text, schema)
    return HermesResult(structured=structured, response=resp, ...)

Enter fullscreen mode Exit fullscreen mode

The repair call counts against the cap. There is no infinite retry. One repair, then up.

The budget layer is the smallest piece worth showing. It is a dataclass with a lock, a USD ceiling, and a call count.

@dataclass
class BudgetCap:
    usd_cap: float = 1.00
    call_cap: int = 50
    ...
    def record_spend(self, usd):
        with self._lock:
            new_total = self._spent_usd + usd
            if new_total > self.usd_cap:
                raise BudgetExceeded(
                    f"USD cap reached: ${new_total:.4f} > ${self.usd_cap:.4f}",
                    kind="usd",
                    requested=new_total,
                    cap=self.usd_cap,
                )
            self._spent_usd = new_total

Enter fullscreen mode Exit fullscreen mode

The lock matters when an agent kicks off two tool calls in parallel. Without it, both threads can read the current spend, both think there is room, and you blow past the cap by one call.

My Tech Stack

  • Python 3.10+ with requests and an optional jsonschema extra.
  • Hermes-3-Llama-3.1-405B via the OpenRouter free tier. Hosted on openrouter.ai.
  • A deterministic offline HermesStub so the demo runs without a key.
  • Pytest for the 23-test suite.

The full stack is intentionally tiny. The four governance modules together are about 300 lines, including type hints and docstrings. The harness should be small enough that you read the whole thing before depending on it.

How I Used Hermes Agent

Hermes-3-Llama-3.1-405B is the agentic model the challenge is built around. It is instruction-following enough that you can ask for JSON and usually get JSON. It does well on multi-step prompting where you walk it through a structured task.

What it is not is governed. Out of the box, a Hermes call has no per-session budget, no allowlist on tool fetches, no audit trail, and no contract on the reply shape. None of those are model problems. They are wrapper problems. So I wrote a wrapper.

The agentic capability I leaned on most is structured output with tool use. The summarize_url flow asks Hermes to act as a summarizer over a fetched document and return a JSON object with title, key_points, sentiment, and confidence. The structured output layer catches the cases where Hermes drifts into prose or skips a required key, and the repair prompt walks it back.

I picked Hermes for two reasons. First, the free tier on OpenRouter is enough to test the full path end-to-end, including the budget cap, without a paid key. Second, it runs locally if you want it to. The same wrapper works against vllm or llama.cpp serving the same Hermes-3 checkpoint. You only swap the URL inside HermesClient.

What I learned

Per-call cost matters more than total cost. A cap of one dollar is easy to think about. A cap of $0.000196 per call is the number that actually catches a runaway loop.

Repair prompts cost more than first prompts. The cap has to leave room for the repair call. Size it to exactly one call's worth and the repair will never fire because the budget catches it first.

Egress allowlists are smaller than people expect. For the URL summarizer demo, the whole allowlist is {example.com, openrouter.ai}. Two hosts is the entire attack surface for outbound HTTP.

The repo is public and MIT-licensed: github.com/MukundaKatta/hermes-stack. Issues and PRs welcome.


Thanks to the DEV team and Nous Research for running the challenge. The four-layer pattern was waiting for an excuse to land in one place, and Hermes was a good excuse.