Skip to main content

Command Palette

Search for a command to run...

LangChain Series: Understanding Messages

Updated
4 min read
LangChain Series: Understanding Messages

So far in this series, we have covered:

LangChain Basics

Agents

Tools

Models and Model Integration

Streaming and Batch Processing

Now, we move to an important concept in LangChain:

Messages

What are Messages?

Messages are the fundamental units of context in LangChain that represent the input and output of a model.

Instead of passing plain text, LangChain uses structured message objects. This helps the model better understand:

Who is speaking

What is being said

The context of the conversation

Structure of a Message

Each message consists of three main components:

Role

Defines who the message is coming from:

User (Human)

AI (Model)

System

Content

The actual text or data of the message.

Example:

"What is LangChain?"

Metadata (Optional)

Additional information such as:

Token usage

Message ID

User name

Any custom data

This helps in tracking conversations and improving context handling.

Why Messages are Important

Messages allow LangChain to:

  1. Maintain conversation history

  2. Enable multi-turn conversations

  3. Provide better context to LLMs

  4. Support advanced features like agents and tools

Think of messages as a structured chat history rather than plain text.

Types of Messages in LangChain

LangChain provides different message types:

1. System Message

Defines how the model should behave.

SystemMessage("You are a helpful assistant") 

2. Human Message

Represents input from the user.

HumanMessage("Explain Artificial Intelligence")

3. AI Message

Represents the response generated by the model.

AIMessage("Sure I can help you with anything")

4. Tool Message

Represents output from external tools (APIs, databases, etc.) that the model uses.

Text Prompts vs Message Prompts

  1. Text Prompts

These are simple strings.

Use when:

  1. You have a single question

  2. No conversation history is needed

Example:

response = model.invoke("What is LangChain?") 
print(response) 
  1. Message Prompts

These use a list of structured messages.

Use when:

  1. You need conversation context

  2. Building chatbots or agents

  3. Multi-step reasoning is required

Basic Example of Messages

from langchain.messages import SystemMessage, HumanMessage

messages = [ 
             SystemMessage(content="You are a senior software developer."),                                                     
             HumanMessage(content="What is the Software Development Lifecycle?")
           ]

response = model.invoke(messages)

print(response.content)

Explanation:

  1. The system sets the role of the model

  2. The human asks a question

  3. The model responds based on both

Simulating a Conversation

You can also predefine messages to simulate a conversation:

from langchain.messages import SystemMessage, HumanMessage, AIMessage

messages = [
            SystemMessage(content="You are a senior software developer."),         

            HumanMessage(content="Can you help me with software development?"),   

            AIMessage(content="Yes, I can help you with software development."), 

            HumanMessage(content="Explain the basic process of software development.")
             ]

response = model.invoke(messages)

print(response.content) 

Why this is useful:

  1. Provides prior context to the model

  2. Makes responses more accurate

  3. Useful for testing and demos

Using Metadata in Messages

You can attach additional information to messages:

from langchain.messages import HumanMessage

message = HumanMessage(
            content="What is artificial intelligence?", 
            name="prathmesh", 
            id="123" 
            )

response = model.invoke([message])

print(response.usage_metadata)

Why metadata matters:

  1. Helps track users

  2. Useful in multi-user systems

  3. Improves debugging and logging

Advanced Concept: ChatPromptTemplate (Important)

LangChain also provides a way to create dynamic prompts.

from langchain.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([ 
        ("system", "You are a helpful assistant."), 
        ("human", "Explain {topic} in simple terms.") 
        ])

messages = prompt.format_messages(topic="Machine Learning")

response = model.invoke(messages)

print(response.content)

Benefits:

  1. Dynamic input handling

  2. Reusable prompt templates

  3. Cleaner and scalable code

How Messages Enable Memory

Messages play a key role in:

  1. Chatbots

  2. Conversational AI

  3. Agents

By passing previous messages, the model can:

  1. Remember past interactions

  2. Maintain context

  3. Give more relevant answers

Summary

Messages are structured units of communication in LangChain They include role, content, and optional metadata They help maintain context and enable conversations Message-based prompts are more powerful than simple text prompts They are essential for building chatbots, agents, and AI systems