Understanding LangChain Fundamentals: Messages, Chat Models, and My First Chatbot

2026-12-01来源 dev.toEnglish

My LangChain learning journey continues. After setting up Python and connecting Google Gemini, it was time to understand how LangChain actually communicates with AI models.

Introduction

In my previous article, I completed the initial setup of my LangChain learning environment.

I installed Python, configured a virtual environment, installed the required dependencies, connected Google Gemini, and successfully made my first API call through LangChain.

That was a good starting point, but I wanted to understand what was happening behind the scenes.

How does LangChain communicate with an AI model?

What exactly is a chat model?

What are SystemMessage, HumanMessage, and AIMessage?

And how can I use these components to build an actual chatbot?

These were some of the questions I wanted to answer in Phase 2.

Rather than jumping into advanced concepts, I decided to understand the fundamentals first.

1. Understanding LLMs and Chat Models

Before writing more code, I wanted to understand two important terms: LLM and Chat Model.

What is an LLM?

LLM stands for Large Language Model.

It is an AI model trained on large amounts of text data to understand and generate human language.

An LLM can perform tasks such as:

  • Answering questions.
  • Generating content.
  • Summarizing documents.
  • Explaining programming concepts.
  • Generating and understanding code.

For example, I could ask Gemini:

Explain Angular dependency injection in simple terms. 

The model processes the input and generates a response.

What is a Chat Model?

A chat model provides an interface for interacting with an AI model through conversational messages.

Instead of treating everything as a single plain-text prompt, chat models support structured messages with different roles.

For example:

  • System: Defines how the AI should behave.
  • Human: Contains the user's input.
  • AI: Contains the model's response.

This structure becomes particularly useful when building conversational applications.

In LangChain, I used ChatGoogleGenerativeAI to communicate with Gemini.

from langchain_google_genai import ChatGoogleGenerativeAI llm = ChatGoogleGenerativeAI( model="gemini-3.5-flash-lite" ) 

Here, llm represents my chat model instance.

I could now use this instance to send messages and receive responses.

2. Understanding LangChain Messages

One of the first important concepts I learned was how LangChain represents conversations.

LangChain provides different message classes for different roles.

The three main message types I explored were:

Message Purpose
SystemMessage Defines the assistant's behavior and instructions.
HumanMessage Represents input from the user.
AIMessage Represents the response generated by the AI model.

Let's understand each one.

SystemMessage

A system message provides instructions to the AI model.

For example, I wanted my assistant to behave like a senior Angular developer.

from langchain_core.messages import SystemMessage system_message = SystemMessage( content="You are a senior Angular developer. Explain concepts clearly." ) 

This instruction establishes the assistant's role and communication style.

HumanMessage

A human message represents what the user wants to ask.

from langchain_core.messages import HumanMessage human_message = HumanMessage( content="What are Angular Signals?" ) 

This is the actual question sent by the user.

AIMessage

An AI message represents the response generated by the model.

I don't normally create this message manually when interacting with Gemini. The model returns it after processing the input.

For example:

response = llm.invoke([ SystemMessage( content="You are a senior Angular developer." ), HumanMessage( content="What are Angular Signals?" ) ]) 

The returned object is an AIMessage.

I can access its content using:

print(response.content) 

This was an important distinction for me: invoke() returns a message object, not simply a string.

3. Making My First Chat Model Invocation

After understanding the message types, I combined them in a practical example.

I created a new exercise file:

excercise/ simple_chatbot.py 

I wanted to send a user question to Gemini with a system instruction.

Here's the implementation:

from dotenv import load_dotenv from langchain_google_genai import ChatGoogleGenerativeAI from langchain_core.messages import ( SystemMessage, HumanMessage ) load_dotenv() llm = ChatGoogleGenerativeAI( model="gemini-3.5-flash-lite" ) messages = [ SystemMessage( content="You are a senior Angular developer." ), HumanMessage( content="Explain Angular dependency injection." ) ] response = llm.invoke(messages) print(response.content) 

Let's understand the execution flow.

  1. I initialized the Gemini chat model.
  2. I created a system message defining the assistant's role.
  3. I created a human message containing my question.
  4. I passed both messages to llm.invoke().
  5. Gemini processed the conversation and returned an AI message.
  6. I printed the generated response.

The important thing here is that I was no longer sending just a plain-text question.

I was sending a structured conversation.

This gave me more control over how the model interpreted the request.

4. Understanding the Model Response

Another important thing I discovered was that the model response is not always a simple Python string.

When I executed:

response = llm.invoke(messages) print(response) 

I received an AIMessage object.

To access the generated text, I used:

print(response.content) 

However, depending on the model integration and response format, response.content can be either:

  • A regular string.
  • A list of content blocks.

For example, a structured response might look like:

[ { "type": "text", "text": "Angular Signals provide..." } ] 

I encountered this behavior while working with Gemini.

To handle both possibilities, I created a small helper function:

def extract_text(response): content = response.content if isinstance(content, str): return content return "\n".join( block["text"] for block in content if isinstance(block, dict) and block.get("type") == "text" ) 

Now I could safely extract the textual response:

assistant_response = extract_text(response) print(assistant_response) 

This was a useful practical lesson because I didn't want my application to depend on only one response format.

5. Understanding Token Usage

While exploring model responses, I also learned that LangChain provides usage metadata.

For example:

response = llm.invoke(messages) print(response.usage_metadata) 

This can provide information about token usage, such as:

  • Input tokens.
  • Output tokens.
  • Total tokens.

Why is this useful?

When building AI applications, token usage matters because it can affect API costs, response limits, and application performance.

I didn't need to optimize token usage at this stage, but I wanted to understand where this information was available.

6. Building an Interactive Terminal Chatbot

After understanding messages and chat model invocation, I wanted to build something more practical.

Instead of hardcoding a question, I wanted to interact with the chatbot through the terminal.

I modified my exercise to accept user input continuously.

from dotenv import load_dotenv from langchain_google_genai import ChatGoogleGenerativeAI from langchain_core.messages import ( SystemMessage, HumanMessage ) load_dotenv() llm = ChatGoogleGenerativeAI( model="gemini-3.5-flash-lite" ) print("Angular Chatbot") print("Type 'exit' to quit.\n") while True: user_input = input("You: ") if user_input.lower() == "exit": print("Goodbye!") break if not user_input.strip(): continue messages = [ SystemMessage( content="You are a senior Angular developer. " "Answer Angular questions clearly." ), HumanMessage(content=user_input) ] response = llm.invoke(messages) print("\nAssistant:") print(extract_text(response)) print() 

Now I could ask questions directly from the terminal.

For example:

You: What are Angular Signals? Assistant: Angular Signals are a reactive primitive... 

I could ask another question, and the chatbot would generate another response.

At this point, I had successfully built a basic interactive chatbot.

But during testing, I noticed something interesting.

7. An Important Discovery: My Chatbot Couldn't Remember Previous Questions

I tried a simple conversation.

You: My name is Alex. Assistant: Nice to meet you, Alex! You: What is my name? Assistant: I don't know your name. 

Initially, this confused me.

I had just told the chatbot my name. Why couldn't it remember it?

The reason was in my implementation.

Every time the user entered a new question, I was creating a new messages list:

messages = [ SystemMessage( content="You are a senior Angular developer." ), HumanMessage(content=user_input) ] 

This meant that every invocation contained only:

  1. The system instruction.
  2. The latest user question.

The previous conversation was never sent to Gemini.

This helped me understand an important concept:

An LLM does not automatically remember previous interactions just because I am using it through a chatbot interface.

If I want the model to understand previous messages, I need to include that conversation history in subsequent requests.

For example, I could maintain a list of messages:

conversation_history = [ SystemMessage( content="You are a senior Angular developer." ) ] while True: user_input = input("You: ") if user_input.lower() == "exit": break if not user_input.strip(): continue conversation_history.append( HumanMessage(content=user_input) ) response = llm.invoke(conversation_history) conversation_history.append(response) print("\nAssistant:") print(extract_text(response)) print() 

Now the conversation history is preserved in the Python application's memory.

Whenever the user asks a new question, the application sends the previous messages along with it.

This allows Gemini to understand the context of the conversation.

I would explore this concept properly in a later phase dedicated to conversation history and memory.

For now, understanding why my first chatbot couldn't remember previous questions was an important learning milestone.

8. What I Learned in Phase 2

Phase 2 helped me understand the fundamental interaction between LangChain and an AI model.

Here's a summary of what I covered:

Concept What I Learned
LLM A model capable of understanding and generating language.
Chat Model An interface for interacting with models through conversational messages.
SystemMessage Defines the assistant's behavior.
HumanMessage Represents user input.
AIMessage Represents the model's response.
invoke() Sends input to the model and returns its response.
response.content Provides the content of the AI response.
Usage Metadata Provides information about token consumption.
Conversation History Previous messages must be included to preserve context.

I also completed practical exercises involving:

  • Sending structured messages to Gemini.
  • Creating an Angular-focused chatbot.
  • Accepting continuous terminal input.
  • Extracting text from different response formats.
  • Maintaining conversation history manually.

9. Challenges and Important Takeaways

The biggest takeaway from this phase was understanding the difference between a chatbot interface and an actual conversational system.

A terminal loop alone doesn't provide memory.

The application must maintain and pass conversation history to the model.

I also learned not to assume that every model integration returns content in exactly the same format.

Understanding these details early helped me avoid unnecessary complexity later.

Final Thoughts

Phase 2 was complete.

I now understood how LangChain communicates with Gemini, how messages are structured, how to invoke a chat model, and how to build a basic interactive chatbot.

More importantly, I understood why my first chatbot couldn't remember previous questions and what was needed to preserve conversation context.

The next step in my learning journey was to understand how to communicate more effectively with AI models.

Instead of writing prompts directly inside my application, I wanted to learn how to create reusable prompts and dynamically inject information into them.

That brings me to Phase 3: Prompt Engineering with LangChain.

What's Next?

In the next article:

Learning Prompt Engineering with LangChain: PromptTemplate and ChatPromptTemplate

I'll explore:

  • What is prompt engineering?
  • Why reusable prompt templates are useful.
  • Understanding PromptTemplate.
  • Understanding ChatPromptTemplate.
  • Working with dynamic variables.
  • Building Angular-focused prompts.

The journey continues!

Series: My LangChain Learning Journey: From Beginner to Building an AI Agent

Phase: 2 of 9 — LangChain Fundamentals

原文:https://www.a8q9.cn/en/article/understanding-langchain-fundamentals-messages-chat-models-and-my-first-chatbot-b30c4d.html

相关文章