A tool-calling conversation includes both an assistant's request and the tool's response. LangGraph reports INVALID_CHAT_HISTORY when an AIMessage contains a tool call without a matching ToolMessage, preventing the conversation from continuing until the missing response is resolved.
The same mismatch can come from a hand-built message list or from sending a new user message while a saved thread is waiting for tools. Matching the tool name is insufficient; each response must carry the original tool_call_id and follow the assistant's tool calls before the next user or assistant turn.
Recovery depends on whether the tool still needs to run or its result already exists. A tool that has not finished can resume from the checkpoint where it was pending, but replaying a completed payment, email, or other external action can duplicate its effects. A saved result allows the conversation to be repaired without executing that action again.
The sample thread runs in a Python project with LangGraph installed and needs no API key, because a scripted test model stands in for the provider. Tested with LangGraph 1.2.20 and its prebuilt create_react_agent. That API is deprecated in favor of LangChain's create_agent; a provider may report malformed history differently with the newer API.
Steps to fix invalid chat history in LangGraph:
- Create broken_thread.py in your project using your text editor, starting with a scripted test model.
- broken_thread.py
from langchain_core.language_models.fake_chat_models import ( FakeMessagesListChatModel, ) from langchain_core.messages import AIMessage, HumanMessage from langchain_core.tools import tool from langgraph.checkpoint.memory import InMemorySaver from langgraph.prebuilt import create_react_agent class ScriptedModel(FakeMessagesListChatModel): def bind_tools(self, tools, **kwargs): return self model = ScriptedModel(responses=[ AIMessage(content="", tool_calls=[{ "name": "add", "args": {"a": 2, "b": 3}, "id": "call_add_1", }]), AIMessage(content="Scripted reply: sum is 5"), AIMessage(content="Scripted reply: it was 5"), ])
The model returns these three fixed messages in order and never reads the conversation. A real model decides on its own tool calls and words its own replies.
- Append the add tool and the checkpointed agent to broken_thread.py.
saved_sums = [] @tool def add(a: int, b: int) -> int: """Add two integers and save the sum.""" saved_sums.append(a + b) if len(saved_sums) == 1: raise ConnectionError("Connection lost") return a + b graph = create_react_agent( model, [add], checkpointer=InMemorySaver(), )
On its first call, add saves the sum and then raises, so the work is done but no ToolMessage reaches the conversation.
- Append the failed tool turn and the follow-up user message to broken_thread.py.
config = {"configurable": {"thread_id": "failed-thread"}} try: graph.invoke( {"messages": [HumanMessage(content="Add 2 and 3.")]}, config, ) except ConnectionError as error: print(f"Tool failed: {error}") try: graph.invoke( {"messages": [ HumanMessage(content="What was the result?"), ]}, config, ) except ValueError as error: print(f"ValueError: {error}")
- Save broken_thread.py.
- Run broken_thread.py to reproduce the missing-tool-response error.
$ python broken_thread.py ##### snipped ##### Tool failed: Connection lost ValueError: Found AIMessages with tool_calls that do not have a corresponding ToolMessage. ##### snipped ##### For troubleshooting, visit: https://docs.langchain.com/oss/python/langgraph/errors/INVALID_CHAT_HISTORY
The first omitted lines are a harmless deprecation warning for create_react_agent. The error identifies an unanswered tool request, rather than an invalid tool name or malformed tool arguments.
- Create repair_history.py in the same folder with this thread inspection, replacing the broken_thread import with your own graph and config when repairing an application.
- repair_history.py
from langchain_core.messages import AIMessage, ToolMessage from broken_thread import config, graph def unanswered(messages): answered = { message.tool_call_id for message in messages if isinstance(message, ToolMessage) } return [ call for message in messages if isinstance(message, AIMessage) for call in message.tool_calls if call["id"] not in answered ] snapshot = graph.get_state(config) messages = snapshot.values["messages"] print(snapshot.next) for state in graph.get_state_history(config): for task in state.tasks: if task.name == "tools" and task.error: print(task.name, task.error) for call in unanswered(messages): print(call["id"], call["name"], call["args"])
An application's repair script needs the graph compiled against the same persistent checkpointer and a config with the failed thread_id. An InMemorySaver thread ends with its process, so the sample import replays the failure on every run, and a thread lost that way cannot be repaired.
- Save repair_history.py.
- Run repair_history.py to read the pending node, the tool failure, and the unanswered call.
$ python repair_history.py ##### snipped ##### ('agent',) tools ConnectionError('Connection lost') call_add_1 add {'a': 2, 'b': 3}('agent',) means a new message reached the unanswered call, and ('tools',) means the thread is still waiting for the tools node. If no calls are listed, the error may belong to a different thread or an earlier checkpoint; an empty result is not a reason to erase history.
One section finishes the fix. Correct a hand-built message list applies to a list built in code, including a graph whose get_state() raises No checkpointer set, Resume a tool that can safely run applies when the tool has not finished and may run again, and Repair a thread with a recorded tool result applies when the tool finished and its result is recorded.
Correct a hand-built message list
- Create corrected_input.py with your message list, placing each ToolMessage directly after the AIMessage that requested it.
- corrected_input.py
from langchain_core.messages import ( AIMessage, HumanMessage, ToolMessage, ) from broken_thread import graph messages = [ HumanMessage(content="Add 2 and 3."), AIMessage(content="", tool_calls=[{ "name": "add", "args": {"a": 2, "b": 3}, "id": "call_add_1", }]), ToolMessage( content="5", tool_call_id="call_add_1", name="add", ), ] config = {"configurable": {"thread_id": "corrected-input"}} result = graph.invoke({"messages": messages}, config) print(*[message.type for message in result["messages"]]) print(result["messages"][-1].content)
Each tool_call_id must equal the id in the assistant's tool call. A graph with no checkpointer takes the input alone, without config. A checkpointed thread keeps a malformed list it has already saved, so the corrected input needs a new thread_id.
- Save corrected_input.py.
- Run corrected_input.py to confirm that the corrected input completes.
$ python corrected_input.py ##### snipped ##### human ai tool ai Scripted reply: sum is 5
The tool entry directly after ai shows the corrected order, and the last line is the scripted model's fixed reply.
Resume a tool that can safely run
- Open repair_history.py in your text editor.
- Append a resume from the newest checkpoint that still has the tools node pending.
This runs the tool again. A failed tool needs its underlying cause resolved first, and a tool that may already have charged, sent, or changed something belongs in the recorded-result section instead. The sample's add only writes to an in-memory list, so repeating it is harmless.
from langchain_core.messages import HumanMessage pending = next( state for state in graph.get_state_history(config) if state.next == ("tools",) ) result = graph.invoke(None, pending.config)
A new user message makes graph.invoke(None, config) and Command(resume=...) repeat the same error on the latest checkpoint, so the resume targets the earlier one, as in replaying a checkpoint. For a dynamic interrupt(), pass Command(resume=...) with its requested input in place of None. The user message sent too early stays out of the new history and remains only in older checkpoints.
- Append the history checks and the resent user message to repair_history.py.
print(*[message.type for message in result["messages"]]) print(unanswered(result["messages"])) print(graph.get_state(config).next) print(result["messages"][-1].content) follow_up = graph.invoke( {"messages": [HumanMessage(content="What was the result?")]}, config, ) print(follow_up["messages"][-1].content)
- Save repair_history.py.
- Run repair_history.py to confirm that the resumed thread finished and accepts the resent message.
$ python repair_history.py ##### snipped ##### human ai tool ai [] () Scripted reply: sum is 5 Scripted reply: it was 5
The empty list means no tool call remains unanswered, and the empty tuple means the thread has no scheduled work. The two Scripted reply lines are the test model's fixed text, so a real model words them differently. A new interrupt, another unanswered call, or an exception requires further diagnosis.
Repair a thread with a recorded tool result
- Open repair_history.py in your text editor.
- Append a private backup of the thread's messages before changing its checkpoint.
Checkpoint edits change the conversation seen by the model. The affected thread must have no other active writer during recovery. The backup contains conversation data and checkpoint identifiers; it belongs in private local storage. An existing backup causes this code to stop instead of overwriting it. The retained snapshot.config identifies the original checkpoint.
import json from pathlib import Path from langchain_core.messages import messages_to_dict backup_path = Path("chat-history-before-repair.json") backup_path.touch(mode=0o600, exist_ok=False) backup_path.write_text(json.dumps({ "config": snapshot.config, "next": list(snapshot.next), "messages": messages_to_dict(messages), }, indent=2), encoding="utf-8")
- Append the recorded responses to repair_history.py, replacing the call ID and value with your own thread's.
results = { "call_add_1": "5", }
The value 5 is the sum the sample's add saved before losing its connection. For another conversation, the keys and values must come from its actual tool execution or external operation record. A made-up success response hides the failure. If an operation's outcome is unknown, recovery must stop until it is reconciled; retrying it may repeat a side effect.
- Append the code that inserts each response directly after its assistant message.
missing = {call["id"] for call in unanswered(messages)} if set(results) != missing: raise ValueError("Every missing call needs a result") repaired = [] for message in messages: repaired.append(message) if isinstance(message, AIMessage): for call in message.tool_calls: if call["id"] in results: repaired.append(ToolMessage( content=results[call["id"]], tool_call_id=call["id"], name=call["name"], ))
This preserves the original messages, including a user turn submitted too early, while placing the missing tool results before that turn. Existing tool responses remain in the list. Every call from the assistant must have its response before conversation turns continue.
- Append the checkpoint update that saves the repaired order as a completed tools step.
The removal marker resets the messages channel before inserting the complete repaired list. It is appropriate for the prebuilt agent's add_messages reducer, not an arbitrary custom state reducer. Omitting *repaired would clear the conversation. The as_node="tools" setting schedules the model after the supplied results rather than rerunning the tools.
from langchain_core.messages import RemoveMessage from langgraph.graph.message import REMOVE_ALL_MESSAGES repair_config = graph.update_state( config, {"messages": [ RemoveMessage(id=REMOVE_ALL_MESSAGES), *repaired, ]}, as_node="tools", )
A plain update_state with a reordered list would merge messages by ID instead of moving existing messages. Sending a ToolMessage to graph.invoke appends it and starts from START, so it cannot move a response ahead of an intervening user turn.
Related: Message deletion and history validity - Append the resume, the history checks, and a follow-up user message to repair_history.py.
from langchain_core.messages import HumanMessage result = graph.invoke(None, repair_config) print(*[message.type for message in result["messages"]]) print(unanswered(result["messages"])) print(graph.get_state(config).next) print(result["messages"][-1].content) follow_up = graph.invoke( {"messages": [ HumanMessage(content="Please repeat the result."), ]}, config, ) print(follow_up["messages"][-1].content)
Passing None resumes without adding another user message. The original thread_id stays unchanged, because a new thread ID would start another conversation and would not repair the affected one.
- Save repair_history.py.
- Run repair_history.py to confirm that the repaired thread has matched tool results and accepts a new turn.
$ python repair_history.py ##### snipped ##### human ai tool human ai [] () Scripted reply: sum is 5 Scripted reply: it was 5
The tool entry now sits before the second human entry, the empty list means no tool call remains unanswered, and the empty tuple means the thread has no scheduled work. The two Scripted reply lines are the test model's fixed text, so a real model words them differently. A new interrupt, another unanswered call, or an exception requires further diagnosis.
Related: LangGraph INVALID_CHAT_HISTORY troubleshooting