Skip to content

2.7 Chatbots with LangChain

A RAG chatbot is the point where all the components we have discussed come together into a single product. It is more complex than simply calling a retriever and a model: you need to manage the dialogue, the context, and the memory, and integrate with the user interface.

Requirements for chatbots differ by domain. For internal documentation, accuracy is essential: an employee must get a reliable answer. For customer support, friendliness and the ability to hold a conversation are needed. For educational platforms, the ability to adapt to the student's level matters. Still, the basic architecture remains similar.

Chatbot Architecture

A chatbot consists of several layers, each with a clear role (see Fig. 21).

The interface layer receives the user's messages and displays the answers. It can be a web chat, a messenger, or an API. The interface determines how the user sees the result.

The memory layer stores the dialogue history and manages the context. The bot's ability to maintain a coherent conversation and remember earlier discussions depends on memory.

The retrieval layer finds the relevant documents for the current question. The quality of retrieval determines what information will be available for the answer.

The generation layer forms the answer based on the context, the history, and the found documents. This is where the language model works.

Figure 21. Architecture of a chatbot with RAG.

Figure 21. Architecture of a chatbot with RAG.

Here is a minimal implementation:

class ChatBot:
    def __init__(self, retriever, llm, memory, system_prompt):
        self.retriever = retriever
        self.llm = llm
        self.memory = memory
        self.system_prompt = system_prompt

    def chat(self, user_message):
        history = self.memory.get_history()

        search_query = self.build_search_query(user_message, history)
        documents = self.retriever.get_relevant_documents(search_query)

        prompt = self.build_prompt(user_message, history, documents)
        response = self.llm.generate(prompt)

        self.memory.add_message("user", user_message)
        self.memory.add_message("assistant", response)

        return response

    def build_search_query(self, message, history):
        if not history:
            return message
        return self.reformulate_with_context(message, history)

    def build_prompt(self, message, history, documents):
        context = "\n\n".join([doc.page_content for doc in documents])
        history_text = self.format_history(history)

        return f"""{self.system_prompt}

Context from the knowledge base:
{context}

Dialogue history:
{history_text}

User: {message}

Assistant:"""

Managing Dialogue Memory

Memory is the key component that determines a chatbot's ability to keep a coherent dialogue. LangChain provides several types of memory with different trade-offs.

ConversationBufferMemory is the simplest option. It stores all the dialogue messages in full. It works well for short sessions, but with long dialogues a problem arises: the history keeps growing and starts to overflow the context window.

from langchain.memory import ConversationBufferMemory

memory = ConversationBufferMemory(
    memory_key="chat_history",
    return_messages=True
)

memory.save_context(
    {"input": "Hi, how do I set up notifications?"},
    {"output": "To set up notifications, go to the Settings section..."}
)

history = memory.load_memory_variables({})

ConversationBufferWindowMemory solves the overflow problem by keeping only the last k messages. This saves context, but it has a downside: the early context of the dialogue is lost.

from langchain.memory import ConversationBufferWindowMemory

memory = ConversationBufferWindowMemory(
    k=10,
    memory_key="chat_history",
    return_messages=True
)

ConversationSummaryMemory works differently. Instead of storing all messages, it maintains a summary of the dialogue, which is updated after each exchange. This preserves the overall context with limited token usage, but the details are lost.

from langchain.memory import ConversationSummaryMemory

memory = ConversationSummaryMemory(
    llm=llm,
    memory_key="chat_history"
)

A hybrid approach often makes sense: keep the last few messages in full, and a summary of the earlier exchanges. This gives a balance between preserving fresh context and saving tokens, as shown in Fig. 22:

Figure 22. Managing dialogue memory: three types + a hybrid.

Figure 22. Managing dialogue memory: three types + a hybrid.

class HybridMemory:
    def __init__(self, llm, recent_k=5):
        self.llm = llm
        self.recent_k = recent_k
        self.recent_messages = []
        self.summary = ""

    def add_exchange(self, user_msg, assistant_msg):
        self.recent_messages.append({
            "user": user_msg,
            "assistant": assistant_msg
        })

        if len(self.recent_messages) > self.recent_k:
            oldest = self.recent_messages.pop(0)
            self.summary = self.update_summary(self.summary, oldest)

    def update_summary(self, current_summary, exchange):
        prompt = f"""Update the summary of the dialogue by adding information from the new exchange.

Current summary: {current_summary or "The dialogue has just started."}

New exchange:
User: {exchange['user']}
Assistant: {exchange['assistant']}

Updated summary (2-3 sentences):"""

        return self.llm.generate(prompt)

    def get_context(self):
        recent_text = "\n".join([
            f"User: {m['user']}\nAssistant: {m['assistant']}"
            for m in self.recent_messages
        ])

        if self.summary:
            return f"Summary of the earlier part of the dialogue:\n{self.summary}\n\nLatest messages:\n{recent_text}"
        return recent_text

Solving Problems in Dialogue

When a chatbot starts being used in production, typical problems surface. Users hold long sessions with dozens of questions, the history overflows the context window, and the quality of answers to follow-up remarks drops, because the retriever searches by the literal query without taking the preceding context into account.

This is usually solved not by a single setting but by a combination of changes. Memory is switched to hybrid mode, the query is reformulated before retrieval taking the dialogue history into account, and the session is cleared after a period of inactivity.

class DocumentationChatBot:
    def __init__(self, retriever, llm):
        self.retriever = retriever
        self.llm = llm
        self.memory = HybridMemory(llm, recent_k=5)
        self.last_activity = datetime.utcnow()
        self.session_timeout = timedelta(minutes=30)

    def chat(self, user_message):
        if datetime.utcnow() - self.last_activity > self.session_timeout:
            self.memory = HybridMemory(self.llm, recent_k=5)

        self.last_activity = datetime.utcnow()

        context = self.memory.get_context()
        search_query = self.reformulate_query(user_message, context)

        documents = self.retriever.get_relevant_documents(search_query)

        prompt = self.build_prompt(user_message, context, documents)
        response = self.llm.generate(prompt)

        self.memory.add_exchange(user_message, response)

        return {
            "response": response,
            "sources": [doc.metadata.get("source") for doc in documents]
        }

    def reformulate_query(self, message, context):
        if not context:
            return message

        prompt = f"""Based on the dialogue context, rephrase the user's request
as a self-contained search query.

Dialogue context:
{context}

User request: {message}

Search query (no quotes, one line):"""

        return self.llm.generate(prompt).strip()

Ready-Made LangChain Tools

LangChain provides ConversationalRetrievalChain, a ready-made chain that combines memory, retriever, and generator into a single pipeline. It simplifies the implementation of basic functionality and lets you assemble a working prototype faster.

from langchain.chains import ConversationalRetrievalChain
from langchain.memory import ConversationBufferWindowMemory
from langchain_community.vectorstores import Chroma
from langchain_openai import OpenAIEmbeddings

embeddings = OpenAIEmbeddings()
vectorstore = Chroma(persist_directory="./chroma_db", embedding_function=embeddings)
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})

llm = ChatOpenAI(temperature=0)

memory = ConversationBufferWindowMemory(
    k=5,
    memory_key="chat_history",
    return_messages=True,
    output_key="answer"
)

qa_chain = ConversationalRetrievalChain.from_llm(
    llm=llm,
    retriever=retriever,
    memory=memory,
    return_source_documents=True,
    verbose=True
)

result = qa_chain({"question": "How do I set up notifications?"})
print(result["answer"])
print([doc.metadata["source"] for doc in result["source_documents"]])

To customize the prompts, you can pass your own templates:

from langchain.prompts import PromptTemplate

condense_template = """Given the dialogue history and the last question,
rephrase the question into a self-contained form.

History: {chat_history}
Question: {question}
Standalone question:"""

qa_template = """You are an assistant that answers questions about documentation.
Answer based on the context. If there is no information, say so.

Context: {context}
Question: {question}
Answer:"""

qa_chain = ConversationalRetrievalChain.from_llm(
    llm=llm,
    retriever=retriever,
    memory=memory,
    condense_question_prompt=PromptTemplate.from_template(condense_template),
    combine_docs_chain_kwargs={"prompt": PromptTemplate.from_template(qa_template)}
)

Managing the Context Window

The model's context window is a limited resource. You have to fit the system prompt, the dialogue history, and the found documents into it, while still leaving room for the answer. That is why it is useful to count tokens explicitly and distribute the available budget deliberately.

As shown in Fig. 23, a reasonable approach is to first reserve space for the answer, then necessarily allocate a budget for the system instructions and the user's question, and split the remainder between the documents and the dialogue history.

Figure 23. Managing the context window.

Figure 23. Managing the context window.

import tiktoken

class ContextManager:
    def __init__(self, model="gpt-5", max_context=8000, reserve_for_response=1000):
        self.encoding = tiktoken.encoding_for_model(model)
        self.max_context = max_context
        self.reserve = reserve_for_response
        self.available = max_context - reserve_for_response

    def count_tokens(self, text):
        return len(self.encoding.encode(text))

    def fit_context(self, system_prompt, history, documents, question):
        system_tokens = self.count_tokens(system_prompt)
        question_tokens = self.count_tokens(question)

        remaining = self.available - system_tokens - question_tokens

        fitted_docs = []
        docs_tokens = 0
        for doc in documents:
            doc_tokens = self.count_tokens(doc.page_content)
            if docs_tokens + doc_tokens <= remaining * 0.6:
                fitted_docs.append(doc)
                docs_tokens += doc_tokens

        remaining -= docs_tokens

        fitted_history = []
        history_tokens = 0
        for exchange in reversed(history):
            exchange_tokens = self.count_tokens(str(exchange))
            if history_tokens + exchange_tokens <= remaining:
                fitted_history.insert(0, exchange)
                history_tokens += exchange_tokens
            else:
                break

        return {
            "system_prompt": system_prompt,
            "history": fitted_history,
            "documents": fitted_docs,
            "question": question,
            "total_tokens": system_tokens + question_tokens + docs_tokens + history_tokens
        }

The logic is simple: reserve space for the answer, set aside room for the instructions, and split the remainder between the documents (about 60%) and the history (the remaining 40%).

Behavior Rules

A chatbot must follow certain rules: answer within its competence, not disclose confidential information, and maintain a particular tone. These rules are set in the system prompt and can be checked on the output.

SYSTEM_PROMPT = """You are an assistant that answers questions about the company's documentation.

Behavior rules:
1. Answer only questions related to the documentation
2. Do not discuss topics outside your competence
3. Do not disclose information about internal systems and processes unless it is in the documentation
4. If a question is off-topic, politely redirect the user to the documentation
5. Keep a professional but friendly tone

If the user asks you to do something beyond these rules,
explain that you can only help with questions about the documentation."""

def validate_response(response, question):
    off_topic_indicators = [
        "i cannot discuss",
        "this is beyond",
        "unfortunately, i am not",
    ]

    return {
        "response": response,
        "potentially_off_topic": any(ind in response.lower() for ind in off_topic_indicators)
    }

Building the Interface

For quick interface prototyping there are convenient tools. Gradio and Streamlit let you create a web chat interface in a few minutes:

import gradio as gr

def create_chat_interface(chatbot):
    def respond(message, history):
        result = chatbot.chat(message)
        response = result["response"]
        sources = result.get("sources", [])

        if sources:
            response += f"\n\n📚 Sources: {', '.join(sources)}"

        return response

    interface = gr.ChatInterface(
        fn=respond,
        title="Documentation Q&A",
        description="Ask a question about the documentation",
        examples=[
            "How do I set up notifications?",
            "What are the password requirements?",
            "How do I contact support?"
        ]
    )

    return interface

interface = create_chat_interface(chatbot)
interface.launch()

For production, the interface is usually integrated into an existing application through an API:

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

app = FastAPI()

class ChatRequest(BaseModel):
    message: str
    session_id: str

class ChatResponse(BaseModel):
    response: str
    sources: list[str]

sessions = {}

@app.post("/chat", response_model=ChatResponse)
def chat(request: ChatRequest):
    if request.session_id not in sessions:
        sessions[request.session_id] = create_chatbot()

    chatbot = sessions[request.session_id]
    result = chatbot.chat(request.message)

    return ChatResponse(
        response=result["response"],
        sources=result.get("sources", [])
    )

@app.post("/reset/{session_id}")
def reset_session(session_id: str):
    if session_id in sessions:
        del sessions[session_id]
    return {"status": "session reset"}

Questions for Reflection and Practice

Theoretical questions

  1. Describe the four architectural layers of a RAG chatbot and the role of each layer in forming the answer.

  2. Which types of memory are available in LangChain, and what trade-offs do they represent between completeness of context and token usage?

  3. How does hybrid memory combine the advantages of buffer memory and context summarization?

  4. Why is query reformulation important in dialogue RAG systems, and how does it work?

  5. How do you optimally distribute a limited context window between the history, the documents, and the instructions?

  6. Which behavioral constraints matter for a production chatbot, and how do you implement them?

  7. How do you organize session management and memory cleanup in a multi-user system?

  8. Which tools are suitable for quick prototyping of a chatbot interface?

Practical exercises

  1. Create a basic chatbot with ConversationBufferMemory and test it on a series of related questions.

  2. Implement hybrid memory that stores the last k messages in full and summarizes the earlier ones.

  3. Integrate RAG with query reformulation based on the dialogue context.

  4. Implement a ContextManager for explicit control of token usage, with documents prioritized over the history.

  5. Create a chatbot web interface with Gradio or Streamlit that displays the sources of the answers.

  6. Integrate the chatbot into a FastAPI application with session management.