How to create your own chatGPT using Streamlit and ChatGPT API

Anirudh Rawat
3 min readNov 12, 2024

--

In today’s tech-driven world, the power of generative AI is at everyone’s fingertips, thanks to large language models like ChatGPT. While OpenAI’s ChatGPT interface is well-known, building your own customizable version can be even more exciting. In this guide, we’ll walk through creating a simple yet powerful ChatGPT clone using Streamlit for the web interface and the OpenAI API for language processing.

Prerequisites

Before we dive into the code, ensure you have the following:

  • Python installed (version 3.7 or higher).
  • An OpenAI API key (you can obtain this by signing up on OpenAI’s platform).
  • Streamlit and openai Python packages installed. You can install them using:

pip install streamlit openai

Setting Up Your ChatGPT Clone

Below, we’ll break down the steps to create a fully functional ChatGPT-like application.

The Code

Here’s the full Python script:

from openai import OpenAI
import streamlit as st

# Set the title for the Streamlit web app
st.title("ChatGPT-like clone")

# Initialize the OpenAI client with your API key
client = OpenAI(api_key="your-openai-api-key")

# Check for an existing model in the session state or set a default one
if "openai_model" not in st.session_state:
st.session_state["openai_model"] = "gpt-3.5-turbo"

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

# Display past messages in the chat
for message in st.session_state.messages:
with st.chat_message(message["role"]):
st.markdown(message["content"])

# Capture new user input
if prompt := st.chat_input("What is up?"):
# Append user input to the session state
st.session_state.messages.append({"role": "user", "content": prompt})
with st.chat_message("user"):
st.markdown(prompt)

# Generate a response from the ChatGPT API
with st.chat_message("assistant"):
stream = client.chat.completions.create(
model=st.session_state["openai_model"],
messages=[
{"role": m["role"], "content": m["content"]}
for m in st.session_state.messages
],
stream=True,
)
response = st.write_stream(stream)

# Store the assistant's response in the session state
st.session_state.messages.append({"role": "assistant", "content": response})

Explanation of the Code

  1. Library Imports: We import the OpenAI class from the openai library and streamlit for building the web interface.

2. Streamlit Title: st.title("ChatGPT-like clone") sets the app's title.

3. OpenAI Client Initialization: The OpenAI client is initialized with your API key. Be sure to replace "your-openai-api-key" with your actual API key or store it securely using environment variables or a secrets manager.

4. Session State Management:

  • st.session_state["openai_model"] sets the default model to gpt-3.5-turbo.
  • st.session_state.messages stores the conversation history to maintain context.

5. Displaying Conversation History: The code iterates over st.session_state.messages to show past user and assistant messages.

6. User Input Handling:

  • st.chat_input("What is up?") captures new user input.
  • The user’s message is appended to the session state and displayed.

7. Generating Responses:

  • The script sends a request to the OpenAI API with the conversation history.
  • The response is streamed in real-time using st.write_stream() for an interactive experience.

8. Storing Responses: The assistant’s response is added to the session state to maintain the conversation history.

Running the App

  1. Save the script to a file, such as chat_gpt_clone.py.

2. Run the app using Streamlit:

streamlit run chat_gpt_clone.py

3. Open the provided local URL in your web browser to start chatting!

Customizing Your Clone

  • API Model: You can change st.session_state["openai_model"] to use other models like gpt-4 if your API key supports it.
  • Features: Enhance your app by adding buttons, speech-to-text, or different conversation themes.
  • Security: Always keep your API key secure. Use environment variables or st.secrets to manage sensitive information.

Final Thoughts

With just a few lines of Python code, you’ve created your own ChatGPT-like application. This simple app can be further customized to suit your needs, from personal projects to professional applications.

Creating your AI-driven app doesn’t need to be complicated. Streamlit’s simplicity combined with the power of OpenAI’s language models makes it easy to develop and deploy conversational AI solutions that fit your unique requirements.

Try building your own AI-powered tools and explore the potential of generative models today!

--

--

Anirudh Rawat
Anirudh Rawat

No responses yet