Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 32 ยท Getting Started

Messages and Your First Chat

Understand LangChain chat messages (system, human, AI, tool), build a conversation as a list, read content and metadata from replies, and practice with a stand-in.

Modern LLM APIs are chat APIs: instead of one string you send a list of messages, each with a role, and the model answers with one more message. LangChain wraps those roles in classes, so the same list works with every provider. Understanding messages is the key to prompts, memory and agents later, so it is worth getting precise now.

The four message roles

Class Role Who writes it Purpose
SystemMessage system You, the developer Standing instructions: persona, rules, output style
HumanMessage human (user) The end user The question or request
AIMessage ai (assistant) The model A reply; may include tool-call requests
ToolMessage tool Your code The result of running a tool the model asked for

All of them live in langchain_core.messages. Each has a .content (usually text, sometimes a list of parts for images or other media) and optional extras such as .id, .name and .additional_kwargs.

Python
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage

history = [
    SystemMessage("You answer in one sentence."),
    HumanMessage("What is a vector database?"),
]
reply = model.invoke(history)      # an AIMessage
print(reply.content)

This is read-only here because model needs a provider, but note the shape: a list in, one message out. To continue the conversation you append the reply and the next question, then call again.

Python
history.append(reply)
history.append(HumanMessage("Give me an example."))
reply2 = model.invoke(history)

The model has no memory of its own. It sees only what you send in each call, which is why memory in LangChain is really about managing that list.

Shortcuts you will see

LangChain accepts several equivalent spellings, which confuses beginners:

Python
model.invoke("Hello")                                   # a str becomes one HumanMessage
model.invoke([("system", "Be brief."), ("human", "Hi")])   # (role, text) tuples
model.invoke([{"role": "user", "content": "Hi"}])          # OpenAI-style dicts
model.invoke([HumanMessage("Hi")])                         # message objects

All four are converted to message objects before the call. Use objects when you need metadata and tuples for short, readable templates.

Inside an AIMessage

A reply carries more than text. These fields appear in practice:

  • content: the reply text.
  • usage_metadata: input, output and total token counts, handy for cost tracking.
  • response_metadata: provider details such as the model name and finish reason.
  • tool_calls: structured requests to run tools (see the agents chapter).
  • id: a unique message id, used by LangGraph to update or delete messages.
Python
reply = model.invoke("Name one planet.")
print(reply.content)             # "Mars."
print(reply.usage_metadata)      # {'input_tokens': 12, 'output_tokens': 3, 'total_tokens': 15}

The numbers above only illustrate the structure; real counts depend on the provider.

A stand-in message system (runnable)

To practice without a network, here is a plain-Python imitation of the message classes and of a chat model that "answers" by echoing the last human message. The point is the data flow, not the answer.

Python Stand-in: messages as a growing list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the second call sends everything: the system rule, both questions and the first answer. Longer conversations cost more tokens and eventually hit the context-window limit. The chapter on memory shows how to trim and summarize.

Converting between message styles (runnable)

LangChain normalizes tuples and dicts into message objects. This stand-in does the same, which shows why all four spellings are interchangeable.

Python Stand-in: normalizing tuples, dicts and strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Tool messages in one picture

When an agent uses a tool, four message types meet in one conversation. The model's AIMessage asks for a tool; your code runs it and replies with a ToolMessage; the model then answers.

sequenceDiagram
    participant U as HumanMessage
    participant M as Model
    participant T as Your tool
    U->>M: "What is 12 * 7?"
    M->>T: AIMessage with tool_calls
    T->>M: ToolMessage "84"
    M->>U: AIMessage "12 times 7 is 84."

The conversation list grows with every step, and the model sees all of it each time.

Common mistakes

  • Forgetting the system message position. Put it first; some providers require that.
  • Sending a ToolMessage without the matching tool call in an earlier AIMessage. Providers reject orphaned tool results.
  • Assuming the model remembers. It does not; resend the history.
  • Printing the whole object and wondering what to use. Take .content for text.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does model.invoke('Hello') send to a chat model?

    A plain string is converted to one human message before the call.
  2. 2. Why does a chatbot resend the whole message list on every turn?

    Chat models are stateless. Conversation memory is your list of messages.
  3. 3. Which field of an AIMessage holds token counts?

    usage_metadata carries input, output and total token counts when the provider reports them.
  4. 4. Who creates a ToolMessage?

    Your program executes the tool and returns its result as a ToolMessage.

Summary

  • Chat models take a list of messages and return one AIMessage.
  • Roles: system (rules), human (user), AI (model), tool (tool results).
  • Strings, tuples and dicts are all converted to message objects.
  • Models are stateless: memory means resending (and managing) the list.
  • Replies carry usage_metadata, response_metadata and tool_calls besides content.

Next: The Runnable Interface