IAMTFRMZA commited on
Commit
6dad2a2
·
verified ·
1 Parent(s): bfb0f65

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -65
app.py CHANGED
@@ -1,72 +1,105 @@
1
  import streamlit as st
2
  from openai import OpenAI
3
  import time
 
4
 
5
- st.set_page_config(page_title="Carfind.co.za Ai Assistant")
 
6
 
7
- st.title("Carfind.co.za Ai Assistant")
 
 
8
  st.caption("Chat with Carfind.co.za and Find your Next Car Fast")
9
 
10
- # Sidebar for API Key input
11
- with st.sidebar:
12
- OPENAI_API_KEY = st.text_input("Enter your C2 Group of Technologies Access Key", type="password")
13
-
14
- if OPENAI_API_KEY:
15
- client = OpenAI(api_key=OPENAI_API_KEY)
16
- else:
17
- st.error("Please enter your C2 Group of Technologies Access Key to continue.")
18
- st.stop()
19
-
20
- ASSISTANT_ID = "asst_5gQR21fOsmHil11FGBzEArA7"
21
-
22
- # Initialize session state for chat history
23
- if "messages" not in st.session_state:
24
- st.session_state["messages"] = []
25
-
26
- # Display chat history
27
- for message in st.session_state.messages:
28
- role, content = message["role"], message["content"]
29
- st.chat_message(role).write(content)
30
-
31
- # Process user input
32
- if prompt := st.chat_input():
33
- st.session_state.messages.append({"role": "user", "content": prompt})
34
- st.chat_message("user").write(prompt)
35
-
36
- try:
37
- # Create a new thread for conversation
38
- thread = client.beta.threads.create()
39
- thread_id = thread.id
40
-
41
- # Send user message to OpenAI API
42
- client.beta.threads.messages.create(
43
- thread_id=thread_id,
44
- role="user",
45
- content=prompt
46
- )
47
-
48
- # Run the assistant to generate a response
49
- run = client.beta.threads.runs.create(
50
- thread_id=thread_id,
51
- assistant_id=ASSISTANT_ID
52
- )
53
-
54
- # Wait for response
55
- while True:
56
- run_status = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
57
- if run_status.status == "completed":
58
- break
59
- time.sleep(1)
60
-
61
- # Retrieve assistant response
62
- messages = client.beta.threads.messages.list(thread_id=thread_id)
63
- assistant_message = messages.data[0].content[0].text.value
64
-
65
- # Display assistant's response
66
- st.chat_message("assistant").write(assistant_message)
67
-
68
- # Store in session state
69
- st.session_state.messages.append({"role": "assistant", "content": assistant_message})
70
-
71
- except Exception as e:
72
- st.error(f"Error: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from openai import OpenAI
3
  import time
4
+ import datetime
5
 
6
+ # Set your API key as a variable (securely from env in HF or paste here)
7
+ openai_key = "YOUR_OPENAI_API_KEY_HERE"
8
 
9
+ st.set_page_config(page_title="Carfind.co.za AI Assistant")
10
+
11
+ st.title("Carfind.co.za AI Assistant")
12
  st.caption("Chat with Carfind.co.za and Find your Next Car Fast")
13
 
14
+ # Simple login system
15
+ if "authenticated" not in st.session_state:
16
+ st.session_state.authenticated = False
17
+
18
+ if not st.session_state.authenticated:
19
+ st.subheader("Login")
20
+ username = st.text_input("Username")
21
+ password = st.text_input("Password", type="password")
22
+
23
+ if st.button("Login"):
24
+ if username == "[email protected]" and password == "Pass.123":
25
+ st.session_state.authenticated = True
26
+ st.success("Login successful!")
27
+ st.experimental_rerun()
28
+ else:
29
+ st.error("Invalid username or password.")
30
+
31
+ # Show chat interface only if logged in
32
+ if st.session_state.authenticated:
33
+ # Sidebar with clear chat button and chat log link
34
+ with st.sidebar:
35
+ if st.button("🧹 Clear Chat"):
36
+ st.session_state.messages = []
37
+ st.success("Chat history cleared.")
38
+ st.markdown("---")
39
+ st.markdown("**Chat logs are saved locally in `chat_logs.txt`.**")
40
+
41
+ # Initialize OpenAI client
42
+ client = OpenAI(api_key=openai_key)
43
+
44
+ ASSISTANT_ID = "asst_5gQR21fOsmHil11FGBzEArA7"
45
+
46
+ # Initialize session state for chat history
47
+ if "messages" not in st.session_state:
48
+ st.session_state["messages"] = []
49
+
50
+ # Display chat history
51
+ for message in st.session_state.messages:
52
+ role, content = message["role"], message["content"]
53
+ st.chat_message(role).write(content)
54
+
55
+ # Helper function to save chat transcripts
56
+ def save_transcript(messages):
57
+ with open("chat_logs.txt", "a") as f:
58
+ f.write(f"\n--- New Chat ({datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n")
59
+ for msg in messages:
60
+ f.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
61
+ f.write("--- End Chat ---\n")
62
+
63
+ # Process user input
64
+ if prompt := st.chat_input("Type your message here..."):
65
+ st.session_state.messages.append({"role": "user", "content": prompt})
66
+ st.chat_message("user").write(prompt)
67
+
68
+ try:
69
+ # Create a new thread
70
+ thread = client.beta.threads.create()
71
+ thread_id = thread.id
72
+
73
+ # Send user message
74
+ client.beta.threads.messages.create(
75
+ thread_id=thread_id,
76
+ role="user",
77
+ content=prompt
78
+ )
79
+
80
+ # Run assistant
81
+ run = client.beta.threads.runs.create(
82
+ thread_id=thread_id,
83
+ assistant_id=ASSISTANT_ID
84
+ )
85
+
86
+ # Wait for completion
87
+ while True:
88
+ run_status = client.beta.threads.runs.retrieve(thread_id=thread_id, run_id=run.id)
89
+ if run_status.status == "completed":
90
+ break
91
+ time.sleep(1)
92
+
93
+ # Get assistant response
94
+ messages = client.beta.threads.messages.list(thread_id=thread_id)
95
+ assistant_message = messages.data[0].content[0].text.value
96
+
97
+ # Display and store response
98
+ st.chat_message("assistant").write(assistant_message)
99
+ st.session_state.messages.append({"role": "assistant", "content": assistant_message})
100
+
101
+ # Save conversation transcript every interaction
102
+ save_transcript(st.session_state.messages)
103
+
104
+ except Exception as e:
105
+ st.error(f"Error: {str(e)}")