This Python application creates a basic ChatGPT-style chatbot using Streamlit for the user interface and the OpenAI API for generating AI responses. Users can enter their own OpenAI API key, ask questions, and receive real-time AI-generated answers.
What This Application Does
- Creates a web-based chatbot interface using Streamlit.
- Allows users to securely enter their OpenAI API key.
- Stores conversation history during the session.
- Sends user messages to the OpenAI model.
- Streams AI responses in real time for a smooth chat experience.
- Maintains the conversation context so the AI can respond intelligently to follow-up questions.
Here I give the chatbot code, show how to deploy this on local machine, and then on cloud.
The full code is given below. The explanation of the code is provided below the code
# app.py
# To run: python -m streamlit run app.py
# Open URL: http://localhost:8501
from openai import OpenAI
import streamlit as st
st.title("ChatGPT-like Clone")
# Sidebar API Key
api_key = st.sidebar.text_input(
"Enter OpenAI API Key",
type="password"
)
if not api_key:
st.info("Please enter your OpenAI API Key in the sidebar.")
st.stop()
client = OpenAI(api_key=api_key)
# Model
if "openai_model" not in st.session_state:
st.session_state["openai_model"] = "gpt-4o-mini"
# Chat history
if "messages" not in st.session_state:
st.session_state.messages = []
# Display chat history
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])
# User input
if prompt := st.chat_input("What is up?"):
st.session_state.messages.append(
{"role": "user", "content": prompt}
)
with st.chat_message("user"):
st.markdown(prompt)
with st.chat_message("assistant"):
stream = client.chat.completions.create(
model=st.session_state["openai_model"],
messages=st.session_state.messages,
stream=True,
)
response = st.write_stream(stream)
st.session_state.messages.append(
{"role": "assistant", "content": response}
)
Code Breakdown
1. Import Required Libraries
from openai import OpenAI
import streamlit as st
These libraries provide access to the OpenAI API and Streamlit web components.
2. Create the Application Title
st.title("ChatGPT-like Clone")
Displays the title at the top of the web page.
3. Accept OpenAI API Key
api_key = st.sidebar.text_input(
"Enter OpenAI API Key",
type="password"
)
Creates a password-protected input field in the sidebar where users enter their OpenAI API key.
4. Validate API Key
if not api_key:
st.info("Please enter your OpenAI API Key in the sidebar.")
st.stop()
Stops the application until a valid API key is provided.
5. Initialize OpenAI Client
client = OpenAI(api_key=api_key)
Creates a connection to OpenAI using the user-provided API key.
6. Set the AI Model
st.session_state["openai_model"] = "gpt-4o-mini"
Specifies the OpenAI model that will generate responses.
7. Store Chat History
st.session_state.messages = []
Keeps track of all user and assistant messages during the session.
8. Display Previous Messages
for message in st.session_state.messages:
Shows the conversation history whenever the page refreshes.
9. Accept User Input
prompt = st.chat_input("What is up?")
Provides a chat input box where users can ask questions.
10. Generate AI Responses
stream = client.chat.completions.create(
model=st.session_state["openai_model"],
messages=st.session_state.messages,
stream=True,
)
Sends the conversation history to OpenAI and requests a streamed response.
1. Display Streaming Output
response = st.write_stream(stream)
Shows the AI response as it is being generated, creating a real-time chat experience.
12. Save the AI Response
st.session_state.messages.append(
{"role": "assistant", "content": response}
)
Stores the assistant’s response so it becomes part of future conversations.
How to run this code
Step 1: Install Python
Download and install Python from: Python Official Website
Step 2: Create a Project Folder
Create a new folder and save your code as app.py.
Example:
chatgpt-clone/
│
└── app.py
Step 3: Create a Virtual Environment (Recommended)
Open a terminal in the project folder and run:
python -m venv venv
Activate it:
Windows
venv\Scripts\activate
Mac/Linux
source venv/bin/activate
Step 4: Install Required Packages
Install Streamlit and OpenAI:
pip install streamlit openai
Verify installation:
pip list
You should see both streamlit and openai in the package list.
Step 5: Run the Application
Execute:
streamlit run app.py
or
python -m streamlit run app.py
Step 6: Open the Application
After the command runs successfully, Streamlit will display a URL similar to:
Local URL: http://localhost:8501
Open that URL in your web browser.
Step 7: Enter Your OpenAI API Key
- Obtain an API key from: OpenAI Platform
- Paste the key into the sidebar input field.
- Start chatting with the AI assistant.
Steps To deploy this application on cloud
Step 1: Create a GitHub Repository
- Log in to GitHub
- Click New Repository.
- Give your repository a name (for example,
chatgpt-clone). - Make it Public.
- Click Create Repository.
Step 2: Upload Your Files
Your repository should contain at least:
chatgpt-clone/
│
├── app.py
└── requirements.txt
Create a requirements.txt file containing:
streamlit
openai
Upload both files to GitHub.
Step 3: Sign in to Streamlit Community Cloud
Go to:
Sign in using your GitHub account.
Step 4: Create a New App
- Click Create App.
- Select your GitHub repository.
- Choose the branch (usually
main). - Set the main file path:
app.py
- Click Deploy.
Step 5: Wait for Deployment
Streamlit will:
- Clone your GitHub repository
- Install dependencies from
requirements.txt - Launch your application
This usually takes 1–2 minutes.
Step 6: Access Your App
After deployment, Streamlit will provide a public URL similar to:
https://your-app-name.streamlit.app
Anyone with this URL can access your application.
