history-guard
A LangChain 1.x AgentMiddleware that keeps agent message histories valid for
Anthropic and Amazon Bedrock (Converse), so long-running LangGraph agents stop
failing with errors like:
messages.1: `tool_use` ids were found without `tool_result` blocks immediately after: call_1.
Each `tool_use` block must have a corresponding `tool_result` block in the next message.
ValidationException: The number of toolResult blocks at messages.2.content exceeds
the number of toolUse blocks of previous turn.
ValueError: Received multiple non-consecutive system messages.
from langchain.agents import create_agent
from history_guard import HistoryGuardMiddleware
agent = create_agent(
model,
tools,
middleware=[..., HistoryGuardMiddleware()], # keep it last
checkpointer=checkpointer,
)
Why this exists
Anthropic's Messages API and Bedrock's Converse API are strict about history shape: every tool call must be answered by exactly one tool result in the very next turn, the conversation must open with a user turn, and no content may be blank. A single agent turn keeps to these rules. Long-lived, checkpointed, interruptible threads often don't:
| How it happens in a LangGraph agent | Rejected by | Repair |
|---|---|---|
| A human-in-the-loop interrupt is abandoned: the user sends a new message instead of resuming | both | add an error ToolMessage for the unanswered call |
| A trimming / windowing step cuts between a tool call and its result | both | drop the orphaned result; add a user turn if the window opens on the assistant |
| A retry or replay writes a second result for the same call | both | keep the first result |
| A user message is appended between a call and its result (concurrent input) | Anthropic | move the result back next to its call |
A model from another provider (e.g. via fallback) truncates a tool call; create_agent answers it, but langchain-aws never sends the call |
Bedrock | remove the unparseable call, note it in text |
A SystemMessage is appended mid-thread (policy reminder, mode switch) |
Anthropic serializer raises; otherwise both silently drop it | fold it into the system prompt |
| Whitespace-only content | Anthropic | strip it; drop messages left empty |
Every row is a test in tests/ that shows the failure first and then
the fix. See How it's tested.
Install
pip install "history-guard @ git+https://github.com/triguiahmed/history-guard"
Requires Python 3.10+ and langchain>=1.1. No dependency on any provider package.
Usage
As agent middleware
import logging
from history_guard import HistoryGuardMiddleware
guard = HistoryGuardMiddleware(
mode="repair", # or "observe" / "strict"
on_repair=lambda r: metrics.incr("history_guard.repair", tags=[r.summary()]),
)
logging.getLogger("history_guard").setLevel(logging.WARNING)
| Mode | Sends to the model | Use it for |
|---|---|---|
repair (default) |
the repaired history | production |
observe |
the original history; logs and calls on_repair |
measuring impact before turning repair on |
strict |
nothing: raises ProtocolViolationError |
tests and CI, where a violation is a bug to fix upstream |
Put it last. wrap_model_call hooks nest in list order, so the last middleware sits
closest to the model and sees the request after every other middleware has changed it.
State is not rewritten. The guard repairs the outgoing request, not the checkpoint. The stored thread stays an exact record of what happened, and you can remove or reconfigure the guard without migrating old threads.
Without an agent
from history_guard import sanitize_messages, find_violations
result = sanitize_messages(messages) # also: sanitize_conversation(messages, system_message=...)
result.messages # safe to send
result.repairs # (Repair(kind=RepairKind.DANGLING_TOOL_CALL, index=4, ...), ...)
find_violations(messages) # dry run: what would change, without changing anything
Configuration
from history_guard import GuardConfig, HistoryGuardMiddleware
HistoryGuardMiddleware(
config=GuardConfig(
interrupted_tool_result="Cancelled by the user before it ran.",
leading_user_placeholder="(Earlier conversation summarized above.)",
inline_system="keep", # if your model uses mid_conversation_system_messages
)
)
Synthetic messages carry response_metadata["history_guard"], so they're easy to
spot in traces.
What it deliberately doesn't do
The rules come from probing what langchain-anthropic and langchain-aws actually
send, not from the API docs alone. Where the serializers already make a history
valid, the guard leaves it alone, so it adds no log noise:
- Consecutive same-role messages: both serializers merge them.
- Empty assistant messages (
"", common from Claude): Anthropic drops them, Bedrock substitutes a placeholder. - Trailing whitespace on the final assistant turn: stripped by both.
Out of scope: extended-thinking block ordering and signatures, tool schema validation,
context-window limits (use SummarizationMiddleware or ContextEditingMiddleware),
and prompt-cache breakpoints (preserved, never moved).
Upstream handles some of this. SummarizationMiddleware picks cut points that
don't split tool pairs, and recent create_agent versions (1.4.x+) answer invalid tool
calls. Other paths still let broken histories through. For example,
trim_messages(strategy="last") returns an orphaned ToolMessage unless you pass
start_on="human" (checked with langchain-core 1.8.5; there's a test for it). This guard
is the last line of defence at the model boundary, whatever route the history took:
interrupts, custom middleware, imported threads, or provider fallbacks.
How it's tested
uv sync && uv run pytest
- A wire-level oracle (
tests/_wire.py) serializes histories with the reallangchain-anthropicandlangchain-awsserializers and checks the payload against the documented rules. Every scenario first asserts that the provider rejects the input, so no rule is made up. - End-to-end agents (
tests/test_middleware.py) runcreate_agentwith a scripted model that raises like the real API on an invalid request. That covers interrupts with a checkpointer, a trimming middleware, async, and all three modes. - Property tests (
tests/test_properties.py, Hypothesis) generate random broken histories and check four properties: the output is accepted by both providers, repair is idempotent, user text is never lost, and well-formed histories are never touched. - CI covers Python 3.10–3.13, the oldest supported versions (
langchain==1.1.0), and a weekly run against the newest upstream releases, because serializer behaviour can change in any upstream release.
Overhead is about 0.4 ms for a 200-message history and about 6 ms for 2,000 (pure Python, no I/O).
Design notes
See docs/design.md for the decisions and trade-offs: why it
repairs the request instead of the state, why an unanswered call gets an error
result instead of being deleted, and why validation is defined as a dry run of repair.
License
MIT
Metadata
Release files for history-guard 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| history_guard-0.1.0.tar.gz | 245.4 kB | With provenance | Details for history_guard-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| history_guard-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for history_guard-0.1.0-py3-none-any.whl |
Total release size: 260.0 kB
Release files / history_guard-0.1.0.tar.gz
| Download URL | history_guard-0.1.0.tar.gz |
|---|---|
| Size | 245.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a931bc70a3cdb0698832bf3c8515d43c8d9e6472130d6f3f0587d012c502c16e
|
|
BLAKE2b-256 checksum How to use checksums |
9b55594acc5afc429f6e0ddca4a2fc54f64413c076d69bae57eeadfc4d487021
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.
Transparency logRelease files / history_guard-0.1.0-py3-none-any.whl
| Download URL | history_guard-0.1.0-py3-none-any.whl |
|---|---|
| Size | 14.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
97aa788a6fa142dd9ee03c63a1700be4c8e19bd7bb9e7e2f2545ef24afd32c66
|
|
BLAKE2b-256 checksum How to use checksums |
7b3ce977d699b41e3a5c90bceaa8cecf21676c0019a57276040f76ac18132174
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.
Transparency logSecurity for history-guard 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for history_guard-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 3, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.