Metadata-Version: 2.5
Name: history-guard
Version: 0.1.0
Summary: LangChain 1.x middleware that keeps agent message histories valid for Anthropic and Amazon Bedrock.
Project-URL: Repository, https://github.com/triguiahmed/history-guard
Project-URL: Issues, https://github.com/triguiahmed/history-guard/issues
Author: Ahmed Trigui
License-Expression: MIT
License-File: LICENSE
Keywords: agents,anthropic,bedrock,langchain,langgraph,middleware,tool-use
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: langchain-core<2,>=1.1
Requires-Dist: langchain<2,>=1.1
Description-Content-Type: text/markdown

# history-guard

[![CI](https://github.com/triguiahmed/history-guard/actions/workflows/ci.yml/badge.svg)](https://github.com/triguiahmed/history-guard/actions/workflows/ci.yml)
![Python](https://img.shields.io/badge/python-3.10%E2%80%933.13-blue)
![LangChain](https://img.shields.io/badge/langchain-%E2%89%A51.1-1c3c3c)
![Typed](https://img.shields.io/badge/typing-mypy%20strict-informational)

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.
```

```python
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/`](tests/) that shows the failure first and then
the fix. See [How it's tested](#how-its-tested).

## Install

```bash
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

```python
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

```python
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

```python
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

```bash
uv sync && uv run pytest
```

- **A wire-level oracle** ([`tests/_wire.py`](tests/_wire.py)) serializes histories with the
  real `langchain-anthropic` and `langchain-aws` serializers 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`](tests/test_middleware.py)) run
  `create_agent` with 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`](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`](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
