How to See Every Message in a LangChain Agent Run in Python
An agent's answer hides how it got there. Did the model call your tool, with which arguments, and what did the tool return? A LangChain agent keeps every message of its run, and each one says who wrote it and what it holds. This guide prints them all for a small Python agent that counts letters.
Syntax
<result> = <agent>.invoke({"messages": [{"role": "user", "content": "<question>"}]})
for <message> in <result>["messages"]:
<message>.pretty_print()
| Part | What it is |
|---|---|
<agent>.invoke(...) | Runs the agent on one question and returns when the run is over. LangChain's agents guide: invoke returns the final response at the end of a run |
<result>["messages"] | Every message of the run, in order: your question first, then what the model and the tools added |
<message>.pretty_print() | Prints one message: a header with its type, then what it holds |
The messages are of three types here. LangChain's messages guide describes them:
| Type | What it is |
|---|---|
HumanMessage | Represents user input and interactions with the model: your question |
AIMessage | Responses generated by the model, including text content, tool calls, and metadata |
ToolMessage | Represents the outputs of tool calls |
The Example
An agent on Claude Opus 5.5 with one tool, count_letter, which counts how many times a letter appears in a word. It's asked: How many times does the letter r appear in strawberry?
Prerequisites
- A Claude API key, with credit on your Anthropic account. The Claude API has no free tier. Claude Opus 5.5 costs $4 per million input tokens and $20 per million output tokens, and one run of this guide's agent used 885 input and 119 output tokens: about $0.006.
- uv. This guide uses uv 0.13.10 with Python 3.14.10.
Step 1: Create the Project
In a terminal, in the folder where you keep your projects, create a project, move into it and add three packages:
uv init --python 3.14 --no-package letter-counter
cd letter-counter
uv add langchain langchain-anthropic python-dotenv
Initialized project `letter-counter` at `/Users/you/source/letter-counter`
Using CPython 3.14.10
Creating virtual environment at: .venv
Resolved 47 packages in 30ms
Installed 45 packages in 217ms
+ langchain==1.5.2
+ langchain-anthropic==1.7.13
+ python-dotenv==1.2.4
The shortened output keeps the three packages you asked for. uv also installed the 42 packages they need, such as langchain-core 1.8.5, langgraph 1.2.25 and anthropic 2.16.0.
| Package | What it gives the project |
|---|---|
langchain | create_agent, which builds an agent from a model and tools |
langchain-anthropic | The Claude integration, used for any model name that starts with anthropic: |
python-dotenv | load_dotenv(), which reads your API key from a .env file |
--python 3.14 gives the project Python 3.14, the newest version LangChain 1.5 lists as supported. --no-package makes a plain project with main.py at the top: without it, uv 0.13.10 created a packaged project with a src/ folder instead.
Step 2: Add Your Claude API Key
Create a file called .env in the letter-counter folder, with this line:
ANTHROPIC_API_KEY=your-api-key
Replace your-api-key with your key. How to Get a Claude API Key shows where to create one. LangChain's Claude integration reads the key from the ANTHROPIC_API_KEY environment variable, and load_dotenv() puts it there when the script starts.
The key is a secret, so add a line with .env to the project's .gitignore, the file uv init created.
Step 3: Run the Agent and Print Its Answer
Replace everything in main.py with:
from dotenv import load_dotenv
from langchain.agents import create_agent
load_dotenv()
def count_letter(word: str, letter: str) -> int:
"""Count how many times a letter appears in a word."""
return word.count(letter)
agent = create_agent(model="anthropic:claude-opus-5-5", tools=[count_letter])
result = agent.invoke(
{"messages": [{"role": "user", "content": "How many times does the letter r appear in strawberry?"}]}
)
print(result["messages"][-1].text)
count_letteris the tool, a plain Python function, andcreate_agentturns it into a tool the model can call. LangChain's tools guide explains the defaults: the tool's name comes from the function name, its description from the docstring, and the type hints define the tool's input schema.create_agentbuilds the agent."anthropic:claude-opus-5-5"is a model identifier in LangChain's"provider:model"form: the provider, then Claude's model ID.result["messages"][-1].textis the text of the last message: the answer.
Run it:
uv run main.py
The letter "r" shows up **3** times in "strawberry": once in "st**r**aw" and twice in "be**rr**y."

The asterisks are Markdown that makes the letters bold. The answer is right, but did the model call count_letter, or count the letters itself? The answer alone can't tell you.
Step 4: Print Every Message of the Run
Replace the line print(result["messages"][-1].text) with:
for message in result["messages"]:
message.pretty_print()
Run it again:
uv run main.py
================================ Human Message =================================
How many times does the letter r appear in strawberry?
================================== Ai Message ==================================
[{'id': 'toolu_01SJ1bC6y5qyCMWprYSocNy3', 'caller': {'type': 'direct'}, 'input': {'word': 'strawberry', 'letter': 'r'}, 'name': 'count_letter', 'type': 'tool_use', 'toolset_name': None}]
Tool Calls:
count_letter (toolu_01SJ1bC6y5qyCMWprYSocNy3)
Call ID: toolu_01SJ1bC6y5qyCMWprYSocNy3
Args:
word: strawberry
letter: r
================================= Tool Message =================================
Name: count_letter
3
================================== Ai Message ==================================
The letter "r" shows up **3** times in "strawberry": once in "st**r**aw" and twice in "be**rr**y."

Now the whole run is visible, in four messages:
- Your question. The
Human Messageis the question you passed toinvoke. The result includes it, as the first message. - The model asked for the tool. The first
Ai Messageholds a tool call:count_letterwithwordset tostrawberryandletterset tor. The line in square brackets is the message's raw content, atool_useblock in Claude's own format. Under it,Tool Callsshows the same call in LangChain's standard form, with the call's ID. - The tool answered. The
Tool Messageholds whatcount_letterreturned,3. The agent ran your function in between; you didn't write that step. - The model answered. The last
Ai Messageholds the text, written from the tool's result.
The wording of the answer changes from run to run. In two more runs it said The letter **r** shows up **3 times** in "strawberry", followed by the same explanation, but the tool call, its arguments and its result were the same each time.
The Complete File
from dotenv import load_dotenv
from langchain.agents import create_agent
load_dotenv()
def count_letter(word: str, letter: str) -> int:
"""Count how many times a letter appears in a word."""
return word.count(letter)
agent = create_agent(model="anthropic:claude-opus-5-5", tools=[count_letter])
result = agent.invoke(
{"messages": [{"role": "user", "content": "How many times does the letter r appear in strawberry?"}]}
)
for message in result["messages"]:
message.pretty_print()

Other Content You May See
This agent's run was short. Runs of a slightly different agent, with a system prompt and a question that made Claude think, showed three more things:
- A thinking block. Claude Opus 5.5 sometimes thinks before it answers. Then the answer's
contentis a list of two blocks: athinkingblock with empty text and a longsignature, then atextblock. The thinking text is empty: Anthropic's thinking guide says thatdisplay: "omitted", the default on many models, returns thinking blocks with an emptythinkingfield.pretty_print()prints the whole list, signature included. - Content as a string or as a list. In this guide's run, the answer's content was a plain string, while the tool call's message held a list. LangChain's messages guide calls the
contentattribute loosely-typed, supporting strings and lists of untyped objects.message.texthandles both: langchain-core's own description of it says it only extracts blocks withtype: 'text'; other block types are ignored. - No system prompt in the list. A
system_promptgiven tocreate_agentdoesn't appear inresult["messages"]. The list still started with theHuman Message.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
| Checking only the answer to see whether a tool ran | The last message holds only the answer's text | Loop over all of result["messages"] |
Printing message.content as the answer | When Claude thinks, content is a list of blocks, not text | Use message.text |
Calling message.text() as a method | It's deprecated: langchain-core says to use .text as a property, and the method form goes away in 2.0.0 | Write message.text, without brackets |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Only two messages: your question and one Ai Message with text | The model answered without the tool. That's right when the question doesn't need it: asked where basil comes from, an agent whose only tool read a plant's soil moisture answered straight away | If the question does need the tool, say in the tool's docstring when to use it |
FAQ
Why is the tool's result a separate message?
Because the model sees the conversation as messages, and a tool's result is one of them. LangChain's messages guide: Tool messages are used to pass the results of a single tool execution back to the model. The agent sends it back to the model in a second call, and the model writes its answer from it.
Can I see the messages while the agent is still running?
Yes, with streaming. The agents guide says to use streaming to surface intermediate messages and tool activity as they happen, instead of waiting for invoke to return.
Do I need this in a real app?
To check that the agent uses its tools the way you meant, yes. It's the quickest way to spot a wrong argument, a missed tool call, or a tool result the model misread.
Conclusion
result["messages"] holds everything a LangChain agent run involved: your question, the model's tool calls with their arguments, the tools' results and the final answer, each in a message that says what it is. Loop over the messages and call pretty_print() on each, to see exactly what happened between the question and the answer.
Additional Resources
- Agents —
create_agent,invokeand the agent loop. - Messages — message types, content and content blocks.
- BaseMessage — the reference for
pretty_print()andtext.
