g-ur's picture
Update app.py
7463c95
import streamlit as st
import openai
import uuid
import time
import os
from openai import OpenAI
openai.api_key = os.environ['OPENAI_API_KEY']
client = OpenAI()
MODEL = "gpt-4-1106-preview"
if "session_id" not in st.session_state: # Used to identify each session
st.session_state.session_id = str(uuid.uuid4())
if "run" not in st.session_state: # Stores the run state of the assistant
st.session_state.run = {"status": None}
if "messages" not in st.session_state: # Stores the messages of the assistant
st.session_state.messages = []
if "retry_error" not in st.session_state: # Used for error handling
st.session_state.retry_error = 0
st.set_page_config(page_title="Manuales de Procedimientos de SCHT")
st.sidebar.title("NORMA G.050 - SEGURIDAD DURANTE LA CONSTRUCCI脫N")
st.sidebar.divider()
st.sidebar.markdown("Versi贸n actual: none")
st.sidebar.markdown(st.session_state.session_id)
st.sidebar.divider()
if "assistant" not in st.session_state:
st.session_state.assistant = openai.beta.assistants.retrieve(assistant_id='asst_7zlPmM2Q7PNiYoJCsQtfgRJX')
# Create a new thread for this session
st.session_state.thread = client.beta.threads.create(
metadata={
'session_id': st.session_state.session_id,
}
)
# Refresh Session Button
if st.button("Reiniciar (Se borrar谩n los mensajes anteriores)"):
st.session_state.session_id = str(uuid.uuid4()) # Reset session ID
st.session_state.messages = [] # Reset messages
st.session_state.run = {"status": None} # Reset run state
st.session_state.retry_error = 0 # Reset error count
# You might also need to reset or recreate the assistant and thread here
st.rerun()
# If the run is completed, display the messages
elif hasattr(st.session_state.run, 'status') and st.session_state.run.status == "completed":
# Retrieve the list of messages
st.session_state.messages = client.beta.threads.messages.list(
thread_id=st.session_state.thread.id
)
# Display messages
for message in reversed(st.session_state.messages.data):
if message.role in ["user", "assistant"]:
with st.chat_message(message.role):
for content_part in message.content:
message_text = content_part.text.value
st.markdown(message_text)
if prompt := st.chat_input("Escribe tu consulta sobre la Norma G.050 - Seguridad durante la contrucci贸n"):
with st.chat_message('user'):
st.write(prompt)
# Add message to the thread
st.session_state.messages = client.beta.threads.messages.create(
thread_id=st.session_state.thread.id,
role="user",
content=prompt
)
# Do a run to process the messages in the thread
st.session_state.run = client.beta.threads.runs.create(
thread_id=st.session_state.thread.id,
assistant_id=st.session_state.assistant.id,
)
if st.session_state.retry_error < 3:
time.sleep(3) # Wait 1 second before checking run status
st.rerun()
# Check if 'run' object has 'status' attribute
if hasattr(st.session_state.run, 'status'):
# Handle the 'running' status
if st.session_state.run.status == "running":
with st.chat_message('assistant'):
st.write("Pensando ......")
if st.session_state.retry_error < 3:
time.sleep(1) # Short delay to prevent immediate rerun, adjust as needed
st.rerun()
# Handle the 'failed' status
elif st.session_state.run.status == "failed":
st.session_state.retry_error += 1
with st.chat_message('assistant'):
if st.session_state.retry_error < 3:
st.write("Hubo un error, probando de nuevo ......")
time.sleep(3) # Longer delay before retrying
st.rerun()
else:
st.error("ERROR: La p谩gina de Open AI puede estar recibiendo demasiados pedidos, prueba en unos momentos ......")
# Handle any status that is not 'completed'
elif st.session_state.run.status != "completed":
# Attempt to retrieve the run again, possibly redundant if there's no other status but 'running' or 'failed'
st.session_state.run = client.beta.threads.runs.retrieve(
thread_id=st.session_state.thread.id,
run_id=st.session_state.run.id,
)
if st.session_state.retry_error < 3:
time.sleep(3)
st.rerun()