Skip to main content
In this section, you will learn how to structure multi-turn conversations using LangChain’s message schemas.

Objectives

  1. Structure conversations with SystemMessage, HumanMessage, and AIMessage.
  2. Prime model behavior with System messages.
  3. Simulate multi-turn dialogue memory.

Understanding Chat Message Roles

When building multi-turn conversations, LLMs require messages to be structured with specific roles. LangChain provides specialized API classes under langchain_core.messages to handle these roles:
  • SystemMessage: Sets the persona, behavior, constraints, and instructions for the AI model (e.g., “You are a helpful French translation assistant”).
  • HumanMessage: Represents the queries or prompts sent directly by the user.
  • AIMessage: Represents the responses returned by the AI model. In multi-turn chat logs, previous AI responses are passed back to the model as AIMessage instances to simulate context memory.

Conversation Structure

Goal

Instruct the model to act as a math solver and provide the history of a previous calculation.

Sample Input

Sequential messages:
  1. SystemMessage(content="Solve the following math problems")
  2. HumanMessage(content="What is 81 divided by 9?")
  3. AIMessage(content="81 divided by 9 is 9.")
  4. HumanMessage(content="What is 10 times 5?")

Sample Output

Plan

  1. Import SystemMessage, HumanMessage, and AIMessage.
  2. Package messages in a list representing the chat conversation history.
  3. Pass the list to model.invoke() and print the response.

Code Implementation

1. Setup and Invoke

Exercise: Translation Memory 🌍

Goal

Build a conversation history list where the user instructs the model to translate words to French, translates one word, and then queries a second word.

Sample Input

  1. System message: “Translate words to French.”
  2. Human message: “Cat” -> AI: “Chat”
  3. Human message: “Dog”

Sample Output

Plan

  1. Form a conversation list using SystemMessage, HumanMessage, and AIMessage.
  2. Call model.invoke() with the list using a Groq-provided model (llama-3.3-70b-versatile) initialized via core abstractions and print the output.

Practice & Exercises

To practice, open the interactive notebook:

Practice & Exercises

Practice structuring conversational message flows.💻 VS Code | 🚀 Colab | 📥 Download