IAMTFRMZA commited on
Commit
86adc68
·
verified ·
1 Parent(s): 7ac34ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -51
app.py CHANGED
@@ -44,9 +44,15 @@ else:
44
  unsafe_allow_html=True
45
  )
46
 
47
- # Initialize authentication state
48
  if "authenticated" not in st.session_state:
49
  st.session_state.authenticated = False
 
 
 
 
 
 
50
 
51
  # Login screen
52
  if not st.session_state.authenticated:
@@ -63,14 +69,11 @@ if not st.session_state.authenticated:
63
  else:
64
  st.error("Incorrect username or password. Please try again.")
65
 
66
- # Main chat UI using streamlit-chat
67
  else:
68
- if "messages" not in st.session_state:
69
- st.session_state["messages"] = []
70
-
71
  st.divider()
72
 
73
- # Display chat history with avatars
74
  for i, msg in enumerate(st.session_state["messages"]):
75
  if msg["role"] == "assistant":
76
  st.markdown(f'<img src="https://www.carfind.co.za/images/Carfind-Icon.svg" width="30" style="vertical-align: middle;"> <strong>Carfind Assistant:</strong> {msg["content"]}', unsafe_allow_html=True)
@@ -91,59 +94,63 @@ else:
91
  with col_clear:
92
  if st.button("🗑️", help="Clear chat"):
93
  st.session_state.messages = []
 
 
94
  st.rerun()
95
 
96
- # Handle OpenAI assistant (with loop protection)
97
- if user_input and openai_key:
98
- if len(st.session_state.messages) == 0 or user_input != st.session_state.messages[-1]["content"]:
99
- st.session_state.messages.append({"role": "user", "content": user_input})
100
-
101
- with st.spinner("Thinking and typing... 💬"):
102
- client = OpenAI(api_key=openai_key)
103
- ASSISTANT_ID = "asst_5gQR21fOsmHil11FGBzEArA7"
104
-
105
- def save_transcript(messages):
106
- with open("chat_logs.txt", "a") as log:
107
- log.write(f"\n--- New Chat ({datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n")
108
- for msg in messages:
109
- log.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
110
- log.write("--- End Chat ---\n")
111
-
112
- try:
113
- thread = client.beta.threads.create()
114
- thread_id = thread.id
115
-
116
- client.beta.threads.messages.create(
 
 
 
 
 
 
 
 
 
 
 
 
117
  thread_id=thread_id,
118
- role="user",
119
- content=user_input
120
  )
 
 
 
121
 
122
- run = client.beta.threads.runs.create(
123
- thread_id=thread_id,
124
- assistant_id=ASSISTANT_ID
125
- )
126
-
127
- while True:
128
- run_status = client.beta.threads.runs.retrieve(
129
- thread_id=thread_id,
130
- run_id=run.id
131
- )
132
- if run_status.status == "completed":
133
- break
134
- time.sleep(1)
135
-
136
- messages_response = client.beta.threads.messages.list(thread_id=thread_id)
137
- assistant_reply = messages_response.data[0].content[0].text.value
138
 
139
- if assistant_reply.strip().lower() != user_input.strip().lower():
140
- st.session_state.messages.append({"role": "assistant", "content": assistant_reply})
141
- save_transcript(st.session_state.messages)
 
 
142
 
143
- st.rerun()
144
 
145
- except Exception as e:
146
- st.error(f"An error occurred: {str(e)}")
147
 
148
  elif not openai_key:
149
  st.error("OpenAI key not found. Please ensure it is set as a Hugging Face secret.")
 
44
  unsafe_allow_html=True
45
  )
46
 
47
+ # Initialize authentication and state
48
  if "authenticated" not in st.session_state:
49
  st.session_state.authenticated = False
50
+ if "messages" not in st.session_state:
51
+ st.session_state["messages"] = []
52
+ if "last_user_input" not in st.session_state:
53
+ st.session_state.last_user_input = ""
54
+ if "last_assistant_response" not in st.session_state:
55
+ st.session_state.last_assistant_response = ""
56
 
57
  # Login screen
58
  if not st.session_state.authenticated:
 
69
  else:
70
  st.error("Incorrect username or password. Please try again.")
71
 
72
+ # Main chat UI
73
  else:
 
 
 
74
  st.divider()
75
 
76
+ # Display chat history
77
  for i, msg in enumerate(st.session_state["messages"]):
78
  if msg["role"] == "assistant":
79
  st.markdown(f'<img src="https://www.carfind.co.za/images/Carfind-Icon.svg" width="30" style="vertical-align: middle;"> <strong>Carfind Assistant:</strong> {msg["content"]}', unsafe_allow_html=True)
 
94
  with col_clear:
95
  if st.button("🗑️", help="Clear chat"):
96
  st.session_state.messages = []
97
+ st.session_state.last_user_input = ""
98
+ st.session_state.last_assistant_response = ""
99
  st.rerun()
100
 
101
+ # Only trigger on new distinct input
102
+ if user_input and user_input != st.session_state.last_user_input and openai_key:
103
+ st.session_state.last_user_input = user_input
104
+ st.session_state.messages.append({"role": "user", "content": user_input})
105
+
106
+ with st.spinner("Thinking and typing... 💬"):
107
+ client = OpenAI(api_key=openai_key)
108
+ ASSISTANT_ID = "asst_5gQR21fOsmHil11FGBzEArA7"
109
+
110
+ def save_transcript(messages):
111
+ with open("chat_logs.txt", "a") as log:
112
+ log.write(f"\n--- New Chat ({datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n")
113
+ for msg in messages:
114
+ log.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
115
+ log.write("--- End Chat ---\n")
116
+
117
+ try:
118
+ thread = client.beta.threads.create()
119
+ thread_id = thread.id
120
+
121
+ client.beta.threads.messages.create(
122
+ thread_id=thread_id,
123
+ role="user",
124
+ content=user_input
125
+ )
126
+
127
+ run = client.beta.threads.runs.create(
128
+ thread_id=thread_id,
129
+ assistant_id=ASSISTANT_ID
130
+ )
131
+
132
+ while True:
133
+ run_status = client.beta.threads.runs.retrieve(
134
  thread_id=thread_id,
135
+ run_id=run.id
 
136
  )
137
+ if run_status.status == "completed":
138
+ break
139
+ time.sleep(1)
140
 
141
+ messages_response = client.beta.threads.messages.list(thread_id=thread_id)
142
+ assistant_reply = messages_response.data[0].content[0].text.value.strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
 
144
+ if (assistant_reply.lower() != user_input.lower() and
145
+ assistant_reply != st.session_state.last_assistant_response):
146
+ st.session_state.messages.append({"role": "assistant", "content": assistant_reply})
147
+ st.session_state.last_assistant_response = assistant_reply
148
+ save_transcript(st.session_state.messages)
149
 
150
+ st.rerun()
151
 
152
+ except Exception as e:
153
+ st.error(f"An error occurred: {str(e)}")
154
 
155
  elif not openai_key:
156
  st.error("OpenAI key not found. Please ensure it is set as a Hugging Face secret.")