IAMTFRMZA commited on
Commit
41458b2
Β·
verified Β·
1 Parent(s): 5c03320

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -29
app.py CHANGED
@@ -1,19 +1,21 @@
1
  import streamlit as st
2
- from streamlit_chat import message
3
  from openai import OpenAI
4
  import time
5
  import os
 
6
 
 
7
  generated_user = os.getenv("User")
8
  generated_password = os.getenv("Password")
9
  openai_key = os.getenv("openai_key")
10
  assistant_id = os.getenv("ASSISTANT_ID")
11
 
 
12
  st.set_page_config(page_title="Carfind.co.za AI Assistant", layout="wide")
13
  st.markdown("<h1 style='text-align: center;'>πŸš— Carfind.co.za AI Assistant</h1>", unsafe_allow_html=True)
14
  st.caption("Chat with Carfind.co.za and find your next car fast")
15
 
16
- # Updated styling for readability
17
  st.markdown("""
18
  <style>
19
  .stChatMessage { max-width: 85%; border-radius: 12px; padding: 8px; }
@@ -22,6 +24,11 @@ st.markdown("""
22
  </style>
23
  """, unsafe_allow_html=True)
24
 
 
 
 
 
 
25
  if "authenticated" not in st.session_state:
26
  st.session_state.authenticated = False
27
 
@@ -37,13 +44,14 @@ if not st.session_state.authenticated:
37
  time.sleep(1)
38
  st.rerun()
39
  else:
40
- st.error("Incorrect username or password. Please try again.")
41
 
42
  else:
43
  st.divider()
44
 
45
  if "thread_id" not in st.session_state:
46
  st.session_state["thread_id"] = None
 
47
 
48
  input_col, clear_col = st.columns([8, 1])
49
  with input_col:
@@ -52,6 +60,7 @@ else:
52
  with clear_col:
53
  if st.button("πŸ—‘οΈ", help="Clear Chat"):
54
  st.session_state["thread_id"] = None
 
55
  st.success("Chat cleared.")
56
  st.rerun()
57
 
@@ -59,19 +68,19 @@ else:
59
  client = OpenAI(api_key=openai_key)
60
 
61
  if user_input:
62
- # Create thread if it doesn't exist
63
  if not st.session_state["thread_id"]:
64
  thread = client.beta.threads.create()
65
  st.session_state["thread_id"] = thread.id
66
 
67
- # Add user message to the thread
68
  client.beta.threads.messages.create(
69
  thread_id=st.session_state["thread_id"], role="user", content=user_input
70
  )
 
71
 
72
  try:
73
- with st.spinner("Thinking and typing... πŸ’­"):
74
- # Trigger assistant run
75
  run = client.beta.threads.runs.create(
76
  thread_id=st.session_state["thread_id"], assistant_id=assistant_id
77
  )
@@ -84,34 +93,40 @@ else:
84
  break
85
  time.sleep(1)
86
 
87
- # Retrieve entire conversation history
88
  messages_response = client.beta.threads.messages.list(
89
  thread_id=st.session_state["thread_id"]
90
  )
91
 
92
- # Assistant icon
93
- assistant_icon_html = "<img src='https://www.carfind.co.za/images/Carfind-Icon.svg' width='22' style='vertical-align:middle;'/>"
94
-
95
- # Display conversation
96
- for msg in reversed(messages_response.data):
97
- if msg.role == "user":
98
- # Add simple user avatar (πŸ‘€) for each message
99
- st.markdown(
100
- f"<div style='background-color:#f0f0f0; color:#000000; padding:10px; border-radius:8px; margin:5px 0;'>"
101
- f"πŸ‘€ <strong>You:</strong> {msg.content[0].text.value}"
102
- f"</div>",
103
- unsafe_allow_html=True
104
- )
105
- else:
106
- st.markdown(
107
- f"<div style='background-color:#D6E9FE; color:#000000; padding:10px; border-radius:8px; margin:5px 0;'>"
108
- f"{assistant_icon_html} <strong>Carfind Assistant:</strong> {msg.content[0].text.value}"
109
- f"</div>",
110
- unsafe_allow_html=True
111
- )
112
 
113
  except Exception as e:
114
  st.error(f"An error occurred: {str(e)}")
115
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  else:
117
- st.error("⚠️ OpenAI key or Assistant ID not found. Please ensure both are set as Hugging Face secrets.")
 
1
  import streamlit as st
 
2
  from openai import OpenAI
3
  import time
4
  import os
5
+ import datetime
6
 
7
+ # Load secrets
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
+ # Setup Streamlit
14
  st.set_page_config(page_title="Carfind.co.za AI Assistant", layout="wide")
15
  st.markdown("<h1 style='text-align: center;'>πŸš— Carfind.co.za AI Assistant</h1>", unsafe_allow_html=True)
16
  st.caption("Chat with Carfind.co.za and find your next car fast")
17
 
18
+ # Styling
19
  st.markdown("""
20
  <style>
21
  .stChatMessage { max-width: 85%; border-radius: 12px; padding: 8px; }
 
24
  </style>
25
  """, unsafe_allow_html=True)
26
 
27
+ # Create transcripts folder
28
+ if not os.path.exists("chat_logs"):
29
+ os.makedirs("chat_logs")
30
+
31
+ # Authentication
32
  if "authenticated" not in st.session_state:
33
  st.session_state.authenticated = False
34
 
 
44
  time.sleep(1)
45
  st.rerun()
46
  else:
47
+ st.error("Incorrect username or password.")
48
 
49
  else:
50
  st.divider()
51
 
52
  if "thread_id" not in st.session_state:
53
  st.session_state["thread_id"] = None
54
+ st.session_state["chat_history"] = []
55
 
56
  input_col, clear_col = st.columns([8, 1])
57
  with input_col:
 
60
  with clear_col:
61
  if st.button("πŸ—‘οΈ", help="Clear Chat"):
62
  st.session_state["thread_id"] = None
63
+ st.session_state["chat_history"] = []
64
  st.success("Chat cleared.")
65
  st.rerun()
66
 
 
68
  client = OpenAI(api_key=openai_key)
69
 
70
  if user_input:
71
+ # Start new thread if needed
72
  if not st.session_state["thread_id"]:
73
  thread = client.beta.threads.create()
74
  st.session_state["thread_id"] = thread.id
75
 
76
+ # Add user message to OpenAI thread
77
  client.beta.threads.messages.create(
78
  thread_id=st.session_state["thread_id"], role="user", content=user_input
79
  )
80
+ st.session_state["chat_history"].append(("user", user_input))
81
 
82
  try:
83
+ with st.spinner("Thinking... πŸ’­"):
 
84
  run = client.beta.threads.runs.create(
85
  thread_id=st.session_state["thread_id"], assistant_id=assistant_id
86
  )
 
93
  break
94
  time.sleep(1)
95
 
96
+ # Get assistant response
97
  messages_response = client.beta.threads.messages.list(
98
  thread_id=st.session_state["thread_id"]
99
  )
100
 
101
+ # The latest assistant reply
102
+ assistant_reply = messages_response.data[0].content[0].text.value
103
+ st.session_state["chat_history"].append(("assistant", assistant_reply))
104
+
105
+ # Save chat log after each response
106
+ timestamp = datetime.datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
107
+ with open(f"chat_logs/chat_{timestamp}.txt", "w") as log_file:
108
+ for role, content in st.session_state["chat_history"]:
109
+ log_file.write(f"{role.capitalize()}: {content}\n")
 
 
 
 
 
 
 
 
 
 
 
110
 
111
  except Exception as e:
112
  st.error(f"An error occurred: {str(e)}")
113
 
114
+ # Assistant icon inline
115
+ assistant_icon_html = "<img src='https://www.carfind.co.za/images/Carfind-Icon.svg' width='22' style='vertical-align:middle;'/>"
116
+
117
+ # Display chat history top-down
118
+ for role, content in st.session_state["chat_history"]:
119
+ if role == "user":
120
+ st.markdown(
121
+ f"<div style='background-color:#f0f0f0; color:#000000; padding:10px; border-radius:8px; margin:5px 0;'>"
122
+ f"πŸ‘€ <strong>You:</strong> {content}"
123
+ f"</div>", unsafe_allow_html=True
124
+ )
125
+ else:
126
+ st.markdown(
127
+ f"<div style='background-color:#D6E9FE; color:#000000; padding:10px; border-radius:8px; margin:5px 0;'>"
128
+ f"{assistant_icon_html} <strong>Carfind Assistant:</strong> {content}"
129
+ f"</div>", unsafe_allow_html=True
130
+ )
131
  else:
132
+ st.error("⚠️ OpenAI key or Assistant ID not found. Make sure both are set as Hugging Face secrets.")