Spaces:
Running
Running
import streamlit as st | |
from openai import OpenAI | |
import time | |
st.set_page_config(page_title="Carfind.co.za Ai Assistant") | |
st.title("Carfind.co.za Ai Assistant") | |
st.caption("Chat with Carfind.co.za and Find your Next Car Fast") | |
# 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_5gQR21fOsmHil11FGBzEArA7" | |
# Initialize session state for chat history | |
if "messages" not in st.session_state: | |
st.session_state["messages"] = [] | |
# 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 for conversation | |
thread = client.beta.threads.create() | |
thread_id = thread.id | |
# Send user message to OpenAI API | |
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) | |
assistant_message = messages.data[0].content[0].text.value | |
# 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)}") | |