Building a Chat Engine with Conversation History
Building a Chat Engine with Conversation History in TypeScript
Welcome to the second unit of our course on building a RAG-powered chatbot! In the previous lesson, we built a type-safe document processor that forms the retrieval component of our RAG system. Today, we'll focus on the conversational aspect by creating a chat engine that can maintain conversation history, all implemented in TypeScript.
While our document processor is excellent at finding relevant information, a complete RAG system needs a way to interact with users in a natural, conversational manner. This is where our chat engine comes in. The chat engine is responsible for managing the conversation flow, formatting prompts with relevant context, and maintaining a history of the interaction.
Understanding the Chat Engine
The chat engine we'll build today will:
- Manage interactions with the language model
- Optionally maintain a history of the conversation for display or logging
- Format prompts with relevant context from our document processor
- Provide methods to reset the conversation history when needed
By the end of this lesson, you'll have a fully functional, type-safe chat engine that can be integrated with the document processor we built previously to create a complete RAG system.
Creating the ChatEngine Class Structure
Let's begin by setting up the basic structure of our ChatEngine class in TypeScript. We'll use type annotations and access modifiers to ensure type safety and encapsulation.
Key points in this initialization:
- Chat Model: We initialize
this.chatModelusingnew ChatOpenAI()to create an instance of the OpenAI chat model for generating responses. - System Message: We define strict instructions that guide the AI's behavior, telling it to answer questions only based on the provided context and to politely decline if no relevant context is available.
- Prompt Template: We use
ChatPromptTemplate.fromMessages()to explicitly define both the system and human message templates. The system message sets the assistant's behavior, and the human message template includes placeholders for context and question. - Conversation History: We initialize an empty array to optionally keep track of the conversation for display or logging purposes. This history is not sent to the model in this implementation.
This structure ensures our chat engine can properly communicate with the language model while optionally maintaining a record of the conversation.
