ConsecutiveSystemMessagesMiddleware (src/anthropic_compat.py)

OpenIntelligentUI · apps/agent/src/anthropic_compat.py · python · MIT
ai, AI / Agents

Middleware normalizes Anthropic messages to ensure system messages are consecutive and valid.

# Source: https://github.com/CopilotKit/OpenIntelligentUI | License: MIT | Copyright Atai Barkai
# Provided via justclaw.it.com; keep this notice with the code.
"""Anthropic-specific message normalization, applied at model-call time so
graph state stays untouched.

1. Anthropic requires all system messages to be consecutive at the head of the
   conversation. CopilotKitMiddleware injects its "App Context" SystemMessage
   via the add_messages reducer, which appends it after the human turn — valid
   for OpenAI, rejected by langchain-anthropic.
2. Streaming a zero-length thinking block accumulates {type, signature} with
   no "thinking" key; Anthropic 400s on replay in the tool loop unless the
   empty text field is restored."""

from langchain.agents.middleware import AgentMiddleware, Mode

... (truncated -- full source via MCP)

See the full source, get the GitHub permalink, and search for more like it.

Get a free API key