IAMTFRMZA commited on
Commit
e69869b
Β·
verified Β·
1 Parent(s): d6ba0ba

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -63
app.py CHANGED
@@ -1,26 +1,34 @@
1
  import streamlit as st
 
2
  from openai import OpenAI
3
  import time
4
  import datetime
5
  import os
6
 
7
- # Securely get credentials
8
  generated_user = os.getenv("User")
9
  generated_password = os.getenv("Password")
10
  openai_key = os.getenv("openai_key")
 
11
 
12
- # Streamlit app configuration
13
  st.set_page_config(page_title="Carfind.co.za AI Assistant", layout="wide")
14
- st.title("πŸš— Carfind.co.za AI Assistant")
15
  st.caption("Chat with Carfind.co.za and find your next car fast")
16
 
17
- # Initialize authentication state
 
 
 
 
 
 
 
 
 
18
  if "authenticated" not in st.session_state:
19
  st.session_state.authenticated = False
20
 
21
- # Login screen
22
  if not st.session_state.authenticated:
23
- st.subheader("πŸ” Login")
24
  username = st.text_input("Username")
25
  password = st.text_input("Password", type="password")
26
 
@@ -33,82 +41,65 @@ if not st.session_state.authenticated:
33
  else:
34
  st.error("Incorrect username or password. Please try again.")
35
 
36
- # Main chat interface
37
  else:
38
  st.divider()
39
 
40
- if "messages" not in st.session_state:
41
- st.session_state["messages"] = []
42
-
43
- # Display chat history
44
- for message in st.session_state.messages:
45
- role = message["role"]
46
- content = message["content"]
47
- if role == "assistant":
48
- st.markdown(f'<img src="https://www.carfind.co.za/images/Carfind-Icon.svg" width="30" style="vertical-align: middle;"> <strong>Carfind Assistant:</strong> {content}', unsafe_allow_html=True)
49
- else:
50
- st.chat_message(role).write(content)
51
-
52
- # Input with clear chat button
53
- col_clear, col_input = st.columns([1, 8])
54
 
55
- with col_clear:
56
- if st.button("🧹 Clear Chat"):
57
- st.session_state.messages = []
58
- st.success("Chat history cleared.")
59
 
60
- with col_input:
61
- user_input = st.chat_input("Type your message here...")
 
 
 
62
 
63
- if openai_key:
64
  client = OpenAI(api_key=openai_key)
65
- ASSISTANT_ID = "asst_5gQR21fOsmHil11FGBzEArA7"
66
-
67
- def save_transcript(messages):
68
- with open("chat_logs.txt", "a") as log:
69
- log.write(f"\n--- New Chat ({datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n")
70
- for msg in messages:
71
- log.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
72
- log.write("--- End Chat ---\n")
73
 
74
  if user_input:
75
- if len(st.session_state.messages) == 0 or user_input != st.session_state.messages[-1]["content"]:
76
- st.session_state.messages.append({"role": "user", "content": user_input})
77
- st.chat_message("user").write(user_input)
78
-
79
- try:
80
- thread = client.beta.threads.create()
81
- thread_id = thread.id
82
-
83
- client.beta.threads.messages.create(
84
- thread_id=thread_id,
85
- role="user",
86
- content=user_input
87
- )
88
-
89
  run = client.beta.threads.runs.create(
90
- thread_id=thread_id,
91
- assistant_id=ASSISTANT_ID
92
  )
93
 
94
  while True:
95
  run_status = client.beta.threads.runs.retrieve(
96
- thread_id=thread_id,
97
- run_id=run.id
98
  )
99
  if run_status.status == "completed":
100
  break
101
  time.sleep(1)
102
 
103
- messages = client.beta.threads.messages.list(thread_id=thread_id)
104
- assistant_message = messages.data[0].content[0].text.value.strip()
 
 
 
 
 
 
 
 
 
105
 
106
- if assistant_message.lower() != user_input.lower():
107
- st.markdown(f'<img src="https://www.carfind.co.za/images/Carfind-Icon.svg" width="30" style="vertical-align: middle;"> <strong>Carfind Assistant:</strong> {assistant_message}', unsafe_allow_html=True)
108
- st.session_state.messages.append({"role": "assistant", "content": assistant_message})
109
- save_transcript(st.session_state.messages)
110
 
111
- except Exception as e:
112
- st.error(f"An error occurred: {str(e)}")
113
  else:
114
- st.error("OpenAI key not found. Please ensure it is set as a Hugging Face secret.")
 
1
  import streamlit as st
2
+ from streamlit_chat import message
3
  from openai import OpenAI
4
  import time
5
  import datetime
6
  import os
7
 
 
8
  generated_user = os.getenv("User")
9
  generated_password = os.getenv("Password")
10
  openai_key = os.getenv("openai_key")
11
+ assistant_id = os.getenv("ASSISTANT_ID")
12
 
 
13
  st.set_page_config(page_title="Carfind.co.za AI Assistant", layout="wide")
14
+ st.markdown("<h1 style='text-align: center;'>Carfind.co.za AI Assistant</h1>", unsafe_allow_html=True)
15
  st.caption("Chat with Carfind.co.za and find your next car fast")
16
 
17
+ dark_mode = st.toggle("πŸŒ™ Switch to Light Mode", value=True)
18
+
19
+ st.markdown("""
20
+ <style>
21
+ .stChatMessage { max-width: 85%; border-radius: 12px; padding: 8px; }
22
+ .stChatMessage[data-testid="stChatMessage-user"] { background: #333; color: white; }
23
+ .stChatMessage[data-testid="stChatMessage-assistant"] { background: #00529B; color: white; }
24
+ </style>
25
+ """, unsafe_allow_html=True)
26
+
27
  if "authenticated" not in st.session_state:
28
  st.session_state.authenticated = False
29
 
 
30
  if not st.session_state.authenticated:
31
+ st.subheader("πŸ”‘ Login")
32
  username = st.text_input("Username")
33
  password = st.text_input("Password", type="password")
34
 
 
41
  else:
42
  st.error("Incorrect username or password. Please try again.")
43
 
 
44
  else:
45
  st.divider()
46
 
47
+ if "thread_id" not in st.session_state:
48
+ st.session_state["thread_id"] = None
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ input_col, clear_col = st.columns([8, 1])
51
+ with input_col:
52
+ user_input = st.text_input("Type your message here...", key="chat_input")
 
53
 
54
+ with clear_col:
55
+ if st.button("πŸ—‘οΈ", help="Clear Chat"):
56
+ st.session_state["thread_id"] = None
57
+ st.success("Chat cleared.")
58
+ st.rerun()
59
 
60
+ if openai_key and assistant_id:
61
  client = OpenAI(api_key=openai_key)
 
 
 
 
 
 
 
 
62
 
63
  if user_input:
64
+ # Create thread once and reuse it
65
+ if not st.session_state["thread_id"]:
66
+ thread = client.beta.threads.create()
67
+ st.session_state["thread_id"] = thread.id
68
+
69
+ # Add user message to thread
70
+ client.beta.threads.messages.create(
71
+ thread_id=st.session_state["thread_id"], role="user", content=user_input
72
+ )
73
+
74
+ try:
75
+ with st.spinner("Thinking and typing... πŸ’­"):
76
+ # Run assistant
 
77
  run = client.beta.threads.runs.create(
78
+ thread_id=st.session_state["thread_id"], assistant_id=assistant_id
 
79
  )
80
 
81
  while True:
82
  run_status = client.beta.threads.runs.retrieve(
83
+ thread_id=st.session_state["thread_id"], run_id=run.id
 
84
  )
85
  if run_status.status == "completed":
86
  break
87
  time.sleep(1)
88
 
89
+ # βœ… Fetch the entire conversation history:
90
+ messages_response = client.beta.threads.messages.list(
91
+ thread_id=st.session_state["thread_id"]
92
+ )
93
+
94
+ # Display the entire conversation (in chronological order)
95
+ for msg in reversed(messages_response.data):
96
+ if msg.role == "user":
97
+ message(msg.content[0].text.value, is_user=True, avatar_style="adventurer")
98
+ else:
99
+ message(f"**Carfind Assistant:** {msg.content[0].text.value}", is_user=False, avatar_style="bottts")
100
 
101
+ except Exception as e:
102
+ st.error(f"An error occurred: {str(e)}")
 
 
103
 
 
 
104
  else:
105
+ st.error("⚠️ OpenAI key or Assistant ID not found. Please ensure both are set as Hugging Face secrets.")