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

推荐订阅源

爱范儿
爱范儿
博客园 - 叶小钗
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
腾讯CDC
S
SegmentFault 最新的问题
D
DataBreaches.Net
Hugging Face - Blog
Hugging Face - Blog
L
LangChain Blog
Recent Announcements
Recent Announcements
阮一峰的网络日志
阮一峰的网络日志
N
Netflix TechBlog - Medium
大猫的无限游戏
大猫的无限游戏
M
MIT News - Artificial intelligence
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 三生石上(FineUI控件)
F
Fortinet All Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Martin Fowler
Martin Fowler
雷峰网
雷峰网
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
小众软件
小众软件
云风的 BLOG
云风的 BLOG
T
Tailwind CSS 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
My agent kept hitting context limits. This one function f...
Mukunda Rao · 2026-05-26 · via DEV Community

Mukunda Rao Katta

Hermes Agent Challenge Submission: Write About Hermes Agent

This is a submission for the Hermes Agent Challenge.

My Hermes research agent was failing after about 40 turns. The cause: conversation history growing past the context window. The fix everyone reaches for is "just drop old messages" — but if you drop a tool_use without its matching tool_result, Anthropic's API rejects the whole request.

I needed something smarter. That's agent-message-trim.

One call

from agent_message_trim import trim_messages

result = trim_messages(messages, max_tokens=4000)

# Send result.messages to the model — it's safe.
response = client.messages.create(
    model="claude-sonnet-4-5",
    messages=result.messages,
    ...
)

print(f"Dropped {result.dropped_count} messages to fit")

Enter fullscreen mode Exit fullscreen mode

Tool pair safety

This is the part that matters. If your history looks like this:

[
    {"role": "user", "content": "search for X"},
    {"role": "assistant", "content": [{"type": "tool_use", "id": "call_001", ...}]},
    {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "call_001", ...}]},
    {"role": "assistant", "content": "Here is what I found."},
]

Enter fullscreen mode Exit fullscreen mode

trim_messages never drops the tool_use without also dropping its tool_result. They move as a unit. The conversation you get back is always API-valid.

Keep your system prompt

result = trim_messages(messages, max_tokens=4000, keep_system=True)
# system-role messages are pinned — never dropped, not counted toward drop candidates

Enter fullscreen mode Exit fullscreen mode

Two strategies

# Default: drop from the front (oldest messages go first)
result = trim_messages(messages, max_tokens=4000, strategy="drop_oldest")

# Keep first + last, remove from the middle
result = trim_messages(messages, max_tokens=4000, strategy="drop_middle")

Enter fullscreen mode Exit fullscreen mode

drop_middle is useful when you want to keep the original task context AND the most recent exchange, but can sacrifice the middle of a long conversation.

Custom token counter

The built-in estimator is max(1, (len(text)+3)//4). Plug in your own:

import tiktoken
enc = tiktoken.encoding_for_model("gpt-4o")

result = trim_messages(
    messages,
    max_tokens=4000,
    count_tokens=lambda text: len(enc.encode(text)),
)

Enter fullscreen mode Exit fullscreen mode

TrimResult tells you what happened

result = trim_messages(messages, max_tokens=4000)
result.messages        # trimmed list
result.token_count     # estimated tokens used
result.original_count  # how many messages came in
result.dropped_count   # how many were removed
result.ok              # True if nothing was dropped
result.kept_count      # len(result.messages)

Enter fullscreen mode Exit fullscreen mode

Just want the list?

from agent_message_trim import trim_to_fit

trimmed = trim_to_fit(messages, max_tokens=4000)
# returns the list directly

Enter fullscreen mode Exit fullscreen mode

Zero dependencies

Standard library only: json, dataclasses. Nothing else.

pip install agent-message-trim

Enter fullscreen mode Exit fullscreen mode

Repo: https://github.com/MukundaKatta/agent-message-trim