Loading

Quipoin Menu

Learn • Practice • Grow

generative-ai / Project: Custom Chatbot with Memory
tutorial

Project: Custom Chatbot with Memory

In this project, you will build a custom chatbot that remembers the conversation history. It will use OpenAI's GPT API and a simple web interface with Streamlit.

A chatbot with memory can answer follow‑up questions correctly because it keeps track of previous messages.

What You Will Build

  • A web page where users type messages.
  • The chatbot responds using GPT‑3.5 or GPT‑4.
  • It remembers the conversation so you can ask follow‑ups like "What did I just ask?"

Prerequisites

  • Python installed (3.8+).
  • OpenAI API key (get it here).
  • Basic Python knowledge (functions, lists, dictionaries).

Step 1: Install Required Libraries

Open a terminal and run:
pip install openai streamlit

Step 2: Write the Chatbot Code

Create a file named chatbot.py and copy the code below. Replace your-api-key with your actual OpenAI API key.
import openai
import streamlit as st

# Set your OpenAI API key
openai.api_key = "your-api-key"

st.title("🤖 My Chatbot")

# Initialize session state to store conversation history
if "messages" not in st.session_state:
st.session_state.messages = []

# Display previous messages
for msg in st.session_state.messages:
with st.chat_message(msg["role"]):
st.markdown(msg["content"])

# Get user input
if prompt := st.chat_input("Say something..."):
# Add user message to history
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)

# Call OpenAI API
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=st.session_state.messages
)
reply = response.choices[0].message.content

# Add assistant reply to history
st.session_state.messages.append({"role": "assistant", "content": reply})
with st.chat_message("assistant"):
st.markdown(reply)

Step 3: Run the Chatbot

In the terminal, run:
streamlit run chatbot.py
Your browser will open with the chatbot interface. Type a message and press Enter. The bot will respond and remember the whole conversation.

How It Works

  • st.session_state.messages stores the entire chat history.
  • Each new user message is appended to the list.
  • The entire list is sent to OpenAI’s API – the model sees the whole conversation so far.
  • The assistant’s reply is also stored, enabling follow‑ups.

Try It Yourself

Ask: "What is the capital of France?" Then ask: "What about Germany?" The bot should understand you are still asking for capitals because it remembers the context.


Two Minute Drill
  • Streamlit provides an easy web interface.
  • Store conversation in st.session_state.
  • Send the full message history to OpenAI API each time.
  • The model uses the history to answer follow‑ups.

Need more clarification?

Drop us an email at career@quipoinfotech.com