This content originally appeared on DEV Community and was authored by Tapoban Ray
Meaning of Context-Retaining Chatbot
A Context-Retaining chatbot is a chatbot that can remember its previous conversation and respond to the user considering the conversation history.
In this article, we are going to build an AI chatbot using Streamlit as the front-end and the free Gemini API that remembers all its previous conversations, and also host it on Streamlit Community Cloud.
Let’s start building the chatbot:
- Generate a free Gemini API key.
2.Install the following Python libraries:
langchain
langchain-core
langchain-google-genai
streamlit
watchdog
python-dotenv
3.Save the Google Gemini API key in a .env file.
GEMINI_API_KEY="your-api-key-here"
4.Then we need to use the API key from the .env file in our Python file.
import os
from dotenv import load_dotenv
load_dotenv()
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
5.Now, let’s implement the AI functionality.
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
def generate_output(
prompt: str,
):
"""Send the prompt to the LLM and return the response."""
llm = ChatGoogleGenerativeAI(
model="gemini-2.0-flash-001",
api_key=GEMINI_API_KEY,
max_output_tokens=10000,
)
output = llm.invoke(prompt)
return output.content
def get_prompt(human_message: str, system_message: str, chat_history: list):
"""Creates a structured prompt for the LLM."""
prompt_template = ChatPromptTemplate(
[
("system", system_message),
(MessagesPlaceholder(variable_name="chat_history")),
("human", "{query}"),
]
)
return prompt_template.invoke(
{"chat_history": chat_history, "query": human_message}
)
6.With that, our AI methods are ready. Now we need to build the UI with Streamlit and use these methods in there.
import streamlit as st
CHAT_HISTORY = "chat_history"
SYSTEM_MESSAGE = "system_message"
session_variables = {
CHAT_HISTORY: [],
SYSTEM_MESSAGE: "You are a helpful assistant.",
}
for var in session_variables.keys():
if var not in st.session_state:
st.session_state[var] = session_variables.get(var)
st.set_page_config(page_title="AI Chatbot")
st.title("AI Chatbot")
st.chat_message("ai").markdown(
generate_output(
prompt="Say hi to user in order to initiate conversation in a warm and polite way."
)
)
def append_to_chat_history(prompt: str):
"""Add every message to the chat_history."""
final_prompt = get_prompt(
human_message=prompt,
chat_history=st.session_state[CHAT_HISTORY],
system_message=st.session_state[SYSTEM_MESSAGE],
)
ai_message = generate_output(
prompt=final_prompt,
)
st.session_state[CHAT_HISTORY].append(("human", prompt))
st.session_state[CHAT_HISTORY].append(("ai", ai_message))
st.chat_message("ai").markdown(ai_message)
# Displaying chat history
for chat in st.session_state[CHAT_HISTORY]:
st.chat_message(chat[0]).write(chat[1])
user_prompt = st.chat_input(
placeholder="Enter your message...",
)
if user_prompt:
st.chat_message("human").write(user_prompt)
append_to_chat_history(prompt=user_prompt)
Done!!! Our AI chatbot is ready. Now, we will host it on Streamlit Community Cloud so that we can share our chatbot with others.
Before doing that, it’s better to upload our project to a GitHub repository. For that, we need to run the following commands:
# Initialise git with default branch as 'main'
git init -b main
# Create a new public repository in your GitHub account and then,
# Connect your local git repo with your remote repository.
git remote add origin <url_to_your_remote_repo>
# Move your code to the staging area
git add .
# Commit the code locally on your machine with a commit message.
git commit -m "Built an AI chatbot."
# Upload the code to your remote GitHub repository.
git push origin main
Once your code has been uploaded to the remote GitHub repository, we can now easily host the chatbot via Streamlit Cloud.
- Sign up to Streamlit Community Cloud.
- Click on
Create App
in the upper-right corner of the page. - Click on
Deploy a public app from GitHub
. - Go to
Paste GitHub URL
and paste the URL of your main.py file from GitHub. - Edit the branch name to
main
, since that is our default branch name. - Finally, click on
Deploy
.
Streamlit will take some time to download the required packages and start running.
Our AI chatbot is now fully up and running on Streamlit Community Cloud!
You can now share the URL of your chatbot on your resume or with your friends and family.
This content originally appeared on DEV Community and was authored by Tapoban Ray