Skip to main content

How to See Every Message in a LangChain Agent Run in Python

· 10 min read
Jagdish Kumawat
Founder @ Dewiride

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​

Syntax
<result> = <agent>.invoke({"messages": [{"role": "user", "content": "<question>"}]})

for <message> in <result>["messages"]:
<message>.pretty_print()
PartWhat 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:

TypeWhat it is
HumanMessageRepresents user input and interactions with the model: your question
AIMessageResponses generated by the model, including text content, tool calls, and metadata
ToolMessageRepresents 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:

Terminal
uv init --python 3.14 --no-package letter-counter
cd letter-counter
uv add langchain langchain-anthropic python-dotenv
Output (shortened)
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.

PackageWhat it gives the project
langchaincreate_agent, which builds an agent from a model and tools
langchain-anthropicThe Claude integration, used for any model name that starts with anthropic:
python-dotenvload_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:

.env
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:

main.py
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_letter is the tool, a plain Python function, and create_agent turns 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_agent builds 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].text is the text of the last message: the answer.

Run it:

Terminal
uv run main.py
Output
The letter "r" shows up **3** times in "strawberry": once in "st**r**aw" and twice in "be**rr**y."

The terminal after uv run main.py: the agent answers that the letter r shows up 3 times in strawberry, once in straw and twice in berry, with Markdown asterisks around the 3 and the r letters.

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:

main.py (replace the print line)
for message in result["messages"]:
message.pretty_print()

Run it again:

Terminal
uv run main.py
Output
================================ 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."

The terminal after uv run main.py with pretty_print: a Human Message with the question, an Ai Message with a tool_use block and a Tool Calls section calling count_letter with word strawberry and letter r, a Tool Message from count_letter with 3, and a last Ai Message with the answer.

Now the whole run is visible, in four messages:

  1. Your question. The Human Message is the question you passed to invoke. The result includes it, as the first message.
  2. The model asked for the tool. The first Ai Message holds a tool call: count_letter with word set to strawberry and letter set to r. The line in square brackets is the message's raw content, a tool_use block in Claude's own format. Under it, Tool Calls shows the same call in LangChain's standard form, with the call's ID.
  3. The tool answered. The Tool Message holds what count_letter returned, 3. The agent ran your function in between; you didn't write that step.
  4. The model answered. The last Ai Message holds 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​

main.py
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()

The complete main.py in a macOS-style code window: it loads the .env file, defines the count_letter tool, creates an agent on anthropic with that tool, asks how many times the letter r appears in strawberry, and pretty-prints every message of the result.

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 content is a list of two blocks: a thinking block with empty text and a long signature, then a text block. The thinking text is empty: Anthropic's thinking guide says that display: "omitted", the default on many models, returns thinking blocks with an empty thinking field. 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 content attribute loosely-typed, supporting strings and lists of untyped objects. message.text handles both: langchain-core's own description of it says it only extracts blocks with type: 'text'; other block types are ignored.
  • No system prompt in the list. A system_prompt given to create_agent doesn't appear in result["messages"]. The list still started with the Human Message.

Common Mistakes​

MistakeWhat happensDo this instead
Checking only the answer to see whether a tool ranThe last message holds only the answer's textLoop over all of result["messages"]
Printing message.content as the answerWhen Claude thinks, content is a list of blocks, not textUse message.text
Calling message.text() as a methodIt's deprecated: langchain-core says to use .text as a property, and the method form goes away in 2.0.0Write message.text, without brackets

Troubleshooting​

SymptomLikely causeFix
Only two messages: your question and one Ai Message with textThe 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 awayIf 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, invoke and the agent loop.
  • Messages — message types, content and content blocks.
  • BaseMessage — the reference for pretty_print() and text.