DataMine commited on
Commit
d9315ce
·
verified ·
1 Parent(s): e1d0acb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -156
app.py CHANGED
@@ -1,156 +1,163 @@
1
- import streamlit as st
2
- import requests
3
- import json
4
- import time
5
-
6
- # Define API Key and Base URL
7
- API_KEY = "tauHGktuvULkGzYof5jKdVCNfZZryj32"
8
- API_BASE_URL = "https://oapi.tasking.ai/v1"
9
- MODEL_ID = "X5lMcszUYZvPpFnigD8mCfPI"
10
-
11
- # Streamlit interface setup
12
- st.set_page_config(page_title="Custom Assistant", page_icon="🤖", layout="centered")
13
- st.title("🤖 AI-Buddy Assistant")
14
-
15
- # Custom CSS to increase font size and make the sidebar interactive
16
- st.markdown("""
17
- <style>
18
- .sidebar .sidebar-content {
19
- font-size: 1.3rem;
20
- color: #333333;
21
- background-color: #f9f9f9;
22
- padding: 20px;
23
- border-radius: 10px;
24
- }
25
- .sidebar .sidebar-content h1 {
26
- font-size: 1.8rem;
27
- font-weight: bold;
28
- color: #ff4b4b;
29
- margin-bottom: 15px;
30
- }
31
- .sidebar .sidebar-content select, .sidebar .sidebar-content textarea, .sidebar .sidebar-content input {
32
- border: 2px solid #ff4b4b;
33
- padding: 12px;
34
- font-size: 1.2rem;
35
- margin-bottom: 15px;
36
- border-radius: 5px;
37
- }
38
- .sidebar .sidebar-content button {
39
- background-color: #ff4b4b;
40
- color: white;
41
- font-size: 1.2rem;
42
- padding: 10px 20px;
43
- border-radius: 5px;
44
- border: none;
45
- cursor: pointer;
46
- transition: background-color 0.3s ease;
47
- }
48
- .sidebar .sidebar-content button:hover {
49
- background-color: #ff6565;
50
- }
51
- .st-chat-message p {
52
- font-size: 1.3rem;
53
- }
54
- </style>
55
- """, unsafe_allow_html=True)
56
-
57
- # Sidebar for AI in Profession
58
- st.sidebar.title("Want to know how AI helps in your profession and the role of AI-Buddy?")
59
- st.sidebar.write("Select your details below and discover the potential of AI in your career!")
60
-
61
- # Dropdown options for profession with 'Other' option
62
- professions = ["Software Engineer", "Data Scientist", "Marketing Specialist", "Financial Analyst", "Teacher", "Doctor", "Project Manager", "Consultant", "Business Analyst", "Other"]
63
-
64
- # Dropdown options for field with 'Other' option
65
- fields = ["IT", "Healthcare", "Education", "Finance", "Marketing", "Engineering", "Sales", "Human Resources", "Consulting", "Other"]
66
-
67
- # Dropdowns for profession and field
68
- profession = st.sidebar.selectbox("Choose Your Profession", professions)
69
- field = st.sidebar.selectbox("Choose Your Field/Domain", fields)
70
-
71
- # If 'Other' is selected, show a text input for custom entry
72
- if profession == "Other":
73
- profession = st.sidebar.text_input("Please specify your profession")
74
-
75
- if field == "Other":
76
- field = st.sidebar.text_input("Please specify your field")
77
-
78
- # Text area for additional description
79
- description = st.sidebar.text_area("About you (a short description)", placeholder="Briefly describe your role")
80
-
81
- # Submit button
82
- if st.sidebar.button("Submit"):
83
- # Add input details as a message to chat history
84
- st.session_state.messages.append(
85
- {"role": "user", "content": f"My profession is {profession} in the {field} field. Here’s a bit about me: {description}. Tell me how AI and AI-Buddy can help me."}
86
- )
87
-
88
- # Initialize chat history
89
- if "messages" not in st.session_state:
90
- st.session_state.messages = [
91
- {"role": "assistant", "content": "Hello! How can I assist you today?"}
92
- ]
93
-
94
- # Function to make a request to the custom API
95
- def get_chat_response():
96
- headers = {
97
- "Content-Type": "application/json",
98
- "Authorization": f"Bearer {API_KEY}",
99
- }
100
- data = {
101
- "model": MODEL_ID,
102
- "messages": st.session_state.messages # Send entire conversation history
103
- }
104
-
105
- try:
106
- response = requests.post(f"{API_BASE_URL}/chat/completions", headers=headers, json=data)
107
-
108
- if response.status_code == 200:
109
- response_json = response.json()
110
- content = response_json["choices"][0]["message"]["content"]
111
-
112
- try:
113
- content_parsed = json.loads(content)
114
- return content_parsed["choices"][0]["message"]["content"]
115
- except json.JSONDecodeError:
116
- return content
117
- else:
118
- raise Exception(f"API Error: {response.status_code} - {response.text}")
119
-
120
- except Exception as e:
121
- st.error("Re-enter the prompt")
122
- print(f"Error: {e}")
123
- return None
124
-
125
- # Function to simulate streaming effect for displaying assistant's response
126
- def display_response_streaming(response_content):
127
- response_placeholder = st.empty() # Create a placeholder for assistant's response
128
- streaming_text = ""
129
- for char in response_content:
130
- streaming_text += char
131
- response_placeholder.write(streaming_text)
132
- time.sleep(0.05) # Small delay to simulate typing effect
133
-
134
- # Chat interface - User Input
135
- if prompt := st.chat_input("Type your message"):
136
- # Append user's message to the chat history
137
- st.session_state.messages.append({"role": "user", "content": prompt})
138
-
139
- # Display chat history and generate assistant response
140
- for message in st.session_state.messages:
141
- with st.chat_message(message["role"]):
142
- st.write(message["content"])
143
-
144
- # Generate assistant response if the last message is from the user
145
- if st.session_state.messages[-1]["role"] == "user":
146
- with st.chat_message("assistant"):
147
- with st.spinner("Thinking..."):
148
- # Get assistant's response based on the entire conversation history
149
- response_content = get_chat_response()
150
- if response_content:
151
- # Stream the assistant's response chunk by chunk
152
- display_response_streaming(response_content)
153
- # Append the assistant's response to the chat history
154
- st.session_state.messages.append({"role": "assistant", "content": response_content})
155
- else:
156
- st.write("Sorry, Re-enter the prompt")
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ import json
4
+ import time
5
+
6
+ # Define API Key and Base URL
7
+ API_KEY = "tauHGktuvULkGzYof5jKdVCNfZZryj32"
8
+ API_BASE_URL = "https://oapi.tasking.ai/v1"
9
+ MODEL_ID = "X5lMcszUYZvPpFnigD8mCfPI"
10
+
11
+ # Streamlit interface setup
12
+ st.set_page_config(page_title="Custom Assistant", page_icon="🤖", layout="centered")
13
+ st.markdown('<a href="#sidebar" style="font-size: 1.2rem; color: #ff4b4b; text-decoration: none;">⬅️ Go to Sidebar to know how AI helps in your profession</a>', unsafe_allow_html=True)
14
+ st.title("🤖 AI-Buddy Assistant")
15
+
16
+ # Custom CSS to increase font size and make sidebar mobile-friendly
17
+ st.markdown("""
18
+ <style>
19
+ .sidebar .sidebar-content {
20
+ font-size: 1.1rem;
21
+ color: #333333;
22
+ background-color: #f9f9f9;
23
+ padding: 15px;
24
+ border-radius: 8px;
25
+ }
26
+ .sidebar .sidebar-content h1 {
27
+ font-size: 1.5rem;
28
+ font-weight: bold;
29
+ color: #ff4b4b;
30
+ margin-bottom: 10px;
31
+ }
32
+ .sidebar .sidebar-content select, .sidebar .sidebar-content textarea, .sidebar .sidebar-content input {
33
+ border: 2px solid #ff4b4b;
34
+ padding: 10px;
35
+ font-size: 1.1rem;
36
+ margin-bottom: 10px;
37
+ border-radius: 5px;
38
+ }
39
+ .sidebar .sidebar-content button {
40
+ background-color: #ff4b4b;
41
+ color: white;
42
+ font-size: 1.1rem;
43
+ padding: 8px 15px;
44
+ border-radius: 5px;
45
+ border: none;
46
+ cursor: pointer;
47
+ transition: background-color 0.3s ease;
48
+ }
49
+ .sidebar .sidebar-content button:hover {
50
+ background-color: #ff6565;
51
+ }
52
+ .st-chat-message p {
53
+ font-size: 1.1rem;
54
+ }
55
+ </style>
56
+ """, unsafe_allow_html=True)
57
+
58
+ # Sidebar for AI in Profession
59
+ st.sidebar.title("Want to know how AI helps in your profession and the role of AI-Buddy?")
60
+ st.sidebar.write("Select your details below and discover the potential of AI in your career!")
61
+
62
+ # Dropdown options for profession with 'Other' option
63
+ professions = ["Software Engineer", "Data Scientist", "Marketing Specialist", "Financial Analyst", "Teacher", "Doctor", "Project Manager", "Consultant", "Business Analyst", "Other"]
64
+
65
+ # Dropdown options for field with 'Other' option
66
+ fields = ["IT", "Healthcare", "Education", "Finance", "Marketing", "Engineering", "Sales", "Human Resources", "Consulting", "Other"]
67
+
68
+ # Mandatory Dropdowns for profession and field
69
+ profession = st.sidebar.selectbox("Choose Your Profession", professions, key="profession")
70
+ field = st.sidebar.selectbox("Choose Your Field/Domain", fields, key="field")
71
+
72
+ # If 'Other' is selected, require text input for custom profession/field
73
+ if profession == "Other":
74
+ profession = st.sidebar.text_input("Please specify your profession", key="custom_profession")
75
+ if field == "Other":
76
+ field = st.sidebar.text_input("Please specify your field", key="custom_field")
77
+
78
+ # Text area for additional description
79
+ description = st.sidebar.text_area("About you (a short description)", placeholder="Briefly describe your role", key="description")
80
+
81
+ # Submit button with mandatory field checks
82
+ if st.sidebar.button("Submit"):
83
+ # Check if all required fields are filled
84
+ if not profession or not field or (profession == "Other" and not st.session_state.custom_profession) or (field == "Other" and not st.session_state.custom_field):
85
+ st.sidebar.error("Please fill in all required fields.")
86
+ else:
87
+ # Add input details as a message to chat history
88
+ st.session_state.messages.append(
89
+ {"role": "user", "content": f"My profession is {profession} in the {field} field. Here’s a bit about me: {description}. Tell me how AI and AI-Buddy can help me."}
90
+ )
91
+ # Clear the sidebar content to simulate sidebar closure
92
+ st.sidebar.empty()
93
+ st.sidebar.write("Details submitted! You can continue chatting below.")
94
+
95
+ # Initialize chat history
96
+ if "messages" not in st.session_state:
97
+ st.session_state.messages = [
98
+ {"role": "assistant", "content": "Hello! How can I assist you today?"}
99
+ ]
100
+
101
+ # Function to make a request to the custom API
102
+ def get_chat_response():
103
+ headers = {
104
+ "Content-Type": "application/json",
105
+ "Authorization": f"Bearer {API_KEY}",
106
+ }
107
+ data = {
108
+ "model": MODEL_ID,
109
+ "messages": st.session_state.messages # Send entire conversation history
110
+ }
111
+
112
+ try:
113
+ response = requests.post(f"{API_BASE_URL}/chat/completions", headers=headers, json=data)
114
+
115
+ if response.status_code == 200:
116
+ response_json = response.json()
117
+ content = response_json["choices"][0]["message"]["content"]
118
+
119
+ try:
120
+ content_parsed = json.loads(content)
121
+ return content_parsed["choices"][0]["message"]["content"]
122
+ except json.JSONDecodeError:
123
+ return content
124
+ else:
125
+ raise Exception(f"API Error: {response.status_code} - {response.text}")
126
+
127
+ except Exception as e:
128
+ st.error("Re-enter the prompt")
129
+ print(f"Error: {e}")
130
+ return None
131
+
132
+ # Function to simulate streaming effect for displaying assistant's response
133
+ def display_response_streaming(response_content):
134
+ response_placeholder = st.empty() # Create a placeholder for assistant's response
135
+ streaming_text = ""
136
+ for char in response_content:
137
+ streaming_text += char
138
+ response_placeholder.write(streaming_text)
139
+ time.sleep(0.05) # Small delay to simulate typing effect
140
+
141
+ # Chat interface - User Input
142
+ if prompt := st.chat_input("Type your message"):
143
+ # Append user's message to the chat history
144
+ st.session_state.messages.append({"role": "user", "content": prompt})
145
+
146
+ # Display chat history and generate assistant response
147
+ for message in st.session_state.messages:
148
+ with st.chat_message(message["role"]):
149
+ st.write(message["content"])
150
+
151
+ # Generate assistant response if the last message is from the user
152
+ if st.session_state.messages[-1]["role"] == "user":
153
+ with st.chat_message("assistant"):
154
+ with st.spinner("Thinking..."):
155
+ # Get assistant's response based on the entire conversation history
156
+ response_content = get_chat_response()
157
+ if response_content:
158
+ # Stream the assistant's response chunk by chunk
159
+ display_response_streaming(response_content)
160
+ # Append the assistant's response to the chat history
161
+ st.session_state.messages.append({"role": "assistant", "content": response_content})
162
+ else:
163
+ st.write("Sorry, Re-enter the prompt")