Conversation With History

Open in ColabOpen in GitHub

Overview

This tutorial covers how to create a multi-turn Chain that remembers previous conversations, using LangChain. It includes managing conversation history, defining a ChatPromptTemplate, and utilizing an LLM for chain creation. The conversation history is managed using chat_history.

Table of Contents

References


Environment Setup

Set up the environment. You may refer to Environment Setup for more details.

[Note]

  • langchain-opentutorial is a package that provides a set of easy-to-use environment setup, useful functions and utilities for tutorials.

  • You can checkout the langchain-opentutorial for more details.

Alternatively, environment variables can also be set using a .env file.

[Note]

  • This is not necessary if you've already set the environment variables in the previous step.

Creating a Chain that Remembers Previous Conversations

MessagesPlaceholder is a class in LangChain used to handle conversation history. It is primarily utilized in chatbots or multi-turn conversation systems to store and reuse previous conversation content.

Key Roles

Inserting Conversation History :

  • Used to insert prior conversations (e.g., question-and-answer history) into the prompt.

  • This allows the model to understand the context of the conversation and generate appropriate responses.

Managing Variables :

  • Manages conversation history within the prompt using a specific key (e.g., chat_history).

  • It is linked to a user-defined variable name.

Usage

MessagesPlaceholder(variable_name="chat_history")

  • Here, chat_history is the variable name where conversation history is stored.

  • As the conversation progresses, chat_history is continually updated with pairs of questions and responses.

Creating a Chain to Record Conversations (chain_with_history)

In this step, we create a system that manages session-based conversation history and generates an executable chain.

  • Conversation History Management : The store dictionary saves and retrieves conversation history (ChatMessageHistory) by session ID. If a session does not exist, a new one is created.

  • Chain Execution : RunnableWithMessageHistory combines conversation history and the chain to generate responses based on user questions and conversation history. This structure is designed to effectively manage multi-turn conversations.

Execute the first question.

Execute the next question.

Below is a case where a new session is created when the session_id is different.

Last updated