Spaces:
Running
Running
File size: 2,779 Bytes
4060393 613e1de 4060393 613e1de 4060393 613e1de 4060393 f9aa563 4060393 f9aa563 4060393 f9aa563 2b8b374 f9aa563 2b8b374 4060393 f9aa563 4060393 f9aa563 4060393 f9aa563 4060393 f9aa563 4060393 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
import streamlit as st
from openai import OpenAI
import time
st.set_page_config(page_title="Pathologai")
st.title("Wits Pathology Ai Assistant")
st.caption("Chat with an Ai Assistant on your Pathology Queries")
# Sidebar for API Key input
with st.sidebar:
OPENAI_API_KEY = st.text_input("Enter your C2 Group of Technologies Access Key", type="password")
if OPENAI_API_KEY:
client = OpenAI(api_key=OPENAI_API_KEY)
else:
st.error("Please enter your C2 Group of Technologies Access Key to continue.")
st.stop()
ASSISTANT_ID = "asst_Iu6cCU4CyugmAD2yPgktyivH"
# Initialize session state
if "messages" not in st.session_state:
st.session_state.messages = []
if "thread_id" not in st.session_state:
st.session_state.thread_id = None
# Clear chat button
if st.button("Clear Chat", use_container_width=True):
st.session_state.messages = []
st.session_state.thread_id = None
st.rerun()
# Display chat history
for message in st.session_state.messages:
role, content = message["role"], message["content"]
st.chat_message(role).write(content)
# Process user input
if prompt := st.chat_input():
st.session_state.messages.append({"role": "user", "content": prompt})
st.chat_message("user").write(prompt)
try:
# Create a new thread only if one doesn't exist yet
if st.session_state.thread_id is None:
thread = client.beta.threads.create()
st.session_state.thread_id = thread.id
thread_id = st.session_state.thread_id
# Send user message to OpenAI API in the existing thread
client.beta.threads.messages.create(
thread_id=thread_id,
role="user",
content=prompt
)
# Run the assistant to generate a response
run = client.beta.threads.runs.create(
thread_id=thread_id,
assistant_id=ASSISTANT_ID
)
# Wait for response
while True:
run_status = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
if run_status.status == "completed":
break
time.sleep(1)
# Retrieve assistant response
messages = client.beta.threads.messages.list(thread_id=thread_id)
# Get the most recent assistant message
for message in reversed(messages.data):
if message.role == "assistant":
assistant_message = message.content[0].text.value
break
# Display assistant's response
st.chat_message("assistant").write(assistant_message)
# Store in session state
st.session_state.messages.append({"role": "assistant", "content": assistant_message})
except Exception as e:
st.error(f"Error: {str(e)}")
|