top of page

Integrating ChatGPT into the streamlit user experience

Updated: Mar 7

In this article, I'll be explaining what I did to build a custom GPT with all the right prompts to help guide a learning professional through building their pathway, and then what I had to do to integrate it into my Streamlit app.


Building a Digital Assistant that helps learning professionals assess their learning pathways was always going to deliver value, but to make it really sing, I had to integrate a GPT module that would assist with the next part of the journey—building learning pathways.



Prototype - High Level Architecture
Prototype - High Level Architecture


What is ChatGPT?


"ChatGPT is a variant of the GPT (Generative Pre-trained Transformer) models, designed to generate human-like text based on the input it receives. It can understand and generate language in a way that mimics human conversation, making it suitable for a wide range of applications"


Building a custom GPT


Creating productive GPTs means knowing how to ask the right questions and anticipating all the ways in which your user will need to answer to achieve the objective.


Please note: You'll need to purchase a subscription to access ChatGPT 4. This will allow you to create custom GPTs that can be queried via your OpenAPI key.


WARNING: You'll be charged based on the number of times your API key is queried. Be mindful of 1) where you share the key and your app. I suggest you use Streamlit's secret manager to store your API keys.


In this case, I built a Learning Pathway GPT that invites the user to share a topic or skill and then guides them through completing other requirements before generating a result based on the pre-defined outputs I had instructed the ChatGPT to use.


Integrating ChatGPT into Streamlit


I searched the streamlit community and found someone who had already embedded at ChatGPT into their code.


After you have created your custom Chat GPT you will need to retrieve your API key and also the ID of the Custom GPT you have created. You can do this from your playground > assistants. This is where you will find the id of your custom ChatGPT.


The below code is what you need to add to your streamlit app.


Digital Assistant Page

openaiKey = 'insert-your-api-key-here'

os.environ["OPENAI_API_KEY"] = openaiKey
openai.api_key = openaiKey
client = openai.OpenAI()

# Set the page layout width to 1000 pixels
st.set_page_config(
    layout="wide",
    initial_sidebar_state="auto",
    page_title="Curators Workbench - Plan a Pathway",
    page_icon="📊",
)
add_logo("content/CW1_Logo.png")
    
id_assistente = 'insert-your-custom_ChatGPT_ID-here'

inference(id_assistente)

Digital Assistant msg_bot


Then you will need to add a inference_assistant.py file that contains the following:

import streamlit as st
import openai
import time
from exportChat import export_chat

def inference(id_assistente):
    if "msg_bot" not in st.session_state:
        st.session_state.msg_bot = []
        st.session_state.msg_bot.append("Hi, I'm your Pathway Planner. What skill would you like to build your pathway for?")
        st.session_state.msg = []
        
        try :
            #create a thread
            thread = openai.beta.threads.create()
            my_thread_id = thread.id
        
            st.session_state.thread_id = my_thread_id
        except:
            st.error("🛑 There was a problem with OpenAI Servers")
            time.sleep(5)
            st.rerun()
            
        

    def get_response(domanda):
        #create a message
        if "thread_id" in st.session_state:
            try:
                message = openai.beta.threads.messages.create(
                    thread_id=st.session_state.thread_id,
                    role="user",
                    content=domanda
                )
            
                #run
                run = openai.beta.threads.runs.create(
                    thread_id=st.session_state.thread_id,
                    assistant_id=id_assistente,
                )
            
                return run.id
            except:
                st.error("🛑 There was a problem with OpenAI Servers")

        time.sleep(5)
        st.rerun()

    def check_status(run_id):
        try: 
            run = openai.beta.threads.runs.retrieve(
                thread_id=st.session_state.thread_id,
                run_id=run_id,
            )
            return run.status
        except:
            st.error("🛑 There was a problem with OpenAI Servers")
            time.sleep(5)
            st.rerun()


    input = st.chat_input(placeholder="🖊 What skill would you like to build a pathway for?")

    if input:
        st.session_state.msg.append(input)
        with st.spinner("Processing..."):
            run_id = get_response(input)
            status = check_status(run_id)
            
            while status != "completed":
                status = check_status(run_id)
                time.sleep(3)
            
            response = openai.beta.threads.messages.list(
                thread_id=st.session_state.thread_id
            )

            if response.data:
                print(response.data[0].content[0].text.value)
                st.session_state.msg_bot.append(response.data[0].content[0].text.value) 
            else:
                st.session_state.msg_bot.append("😫 Sorry, I didn't understand. Can you rephrase?")

    pp_avatar_img = "content/pathway_planner.png"
    pa_avatar_img = "content/pathway_author.png"

    if "msg_bot" in st.session_state:
        bot_messages_count = len(st.session_state.msg_bot)
        for i in range(len(st.session_state.msg_bot)):
            with st.chat_message("ai",avatar = pp_avatar_img):
                st.write(st.session_state.msg_bot[i])
                

            if "msg" in st.session_state:
                if i < len(st.session_state.msg):
                    if st.session_state.msg[i]:
                        with st.chat_message("user", avatar = pa_avatar_img):
                            st.write(st.session_state.msg[i])

    if "msg_bot" in st.session_state:
        if len(st.session_state.msg) > 0 :
            export_chat()

If you would like help building your Custom ChatGPT or integrating it into your streamlit app you can reach me here.



Comments


Commenting has been turned off.
bottom of page