DEV Community

FIORELA MILADY
FIORELA MILADY

Posted on

Creating a Generative AI Chatbot with Python and Streamlit

Introduction
In the current era of artificial intelligence (AI), chatbots have revolutionized digital interaction by enabling natural conversations through natural language processing (NLP) and advanced language models. In this article, we will explore how to create a generative chatbot using Python and Streamlit.

Development Step by Step

****Environment Setup:

  • We will install the necessary libraries and configure the connection with the OpenAI API.
pip install openai streamlit
Enter fullscreen mode Exit fullscreen mode
import openai
from dotenv import load_dotenv
import os
import streamlit as st
import time

load_dotenv()

api_key = os.getenv("OPENAI_API_KEY")

if not api_key:
    raise ValueError("No API key provided for OpenAI")

openai.api_key = api_key
Enter fullscreen mode Exit fullscreen mode

User Interface with Streamlit: We will develop a simple web interface where users can interact with the generative chatbot.

# Set the title for the Streamlit web app
st.title("My ChatGPT")

# Initialize session state for storing chat messages
if "messages" not in st.session_state:
    st.session_state["messages"] = [{"role": "assistant", "content": "Hello, I'm ChatGPT, how can I assist you today?"}]

# Display existing chat messages
for msg in st.session_state["messages"]:
    st.chat_message(msg["role"]).write(msg["content"])

# Check for user input and handle interaction with ChatGPT
if user_input := st.chat_input():
    # Add user input to session state as a message
    st.session_state["messages"].append({"role": "user", "content": user_input})

    # Attempt to call OpenAI's ChatCompletion API with error handling
    retries = 3
    success = False

    for attempt in range(retries):
        try:
            # Call the OpenAI ChatCompletion API with the current session messages
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                messages=st.session_state["messages"]
            )
            # Get the response message from the API and add it to session state
            response_message = response['choices'][0]['message']['content']
            st.session_state["messages"].append({"role": "assistant", "content": response_message})
            # Display the assistant's response in the chat interface
            st.chat_message("assistant").write(response_message)
            success = True  # Mark the request as successful
            break  # Exit the retry loop if successful
        except openai.error.RateLimitError as e:
            # Handle rate limit errors by warning and retrying after 5 seconds
            st.warning(f"RateLimitError: {e}. Retrying in 5 seconds...")
            time.sleep(5)
        except Exception as e:
            # Handle other exceptions by displaying an error message
            st.error(f"Error calling OpenAI API: {e}")
            break

    # Display an error message if the request was not successful after retries
    if not success:
        st.error("Could not complete request due to rate limit errors.")
Enter fullscreen mode Exit fullscreen mode

Result

The Visual Studio Code editor displaying a Python file (app.py).

The web interface generated by Streamlit for the chatbot

Conclusion

Creating a generative chatbot with Python and Streamlit is an endeavor that not only delves into natural language processing and machine learning but also showcases the potential of artificial intelligence to revolutionize digital interaction.

Top comments (0)