Objectives
- Structure conversations with
SystemMessage,HumanMessage, andAIMessage. - Prime model behavior with System messages.
- 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 underlangchain_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 asAIMessageinstances 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:SystemMessage(content="Solve the following math problems")HumanMessage(content="What is 81 divided by 9?")AIMessage(content="81 divided by 9 is 9.")HumanMessage(content="What is 10 times 5?")
Sample Output
Plan
- Import
SystemMessage,HumanMessage, andAIMessage. - Package messages in a list representing the chat conversation history.
- 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
- System message: “Translate words to French.”
- Human message: “Cat” -> AI: “Chat”
- Human message: “Dog”
Sample Output
Plan
- Form a conversation list using
SystemMessage,HumanMessage, andAIMessage. - Call
model.invoke()with the list using a Groq-provided model (llama-3.3-70b-versatile) initialized via core abstractions and print the output.
Solution
Solution
Practice & Exercises
To practice, open the interactive notebook:Practice & Exercises
Practice structuring conversational message flows.💻 VS Code | 🚀 Colab | 📥 Download