File size: 6,752 Bytes
d9315ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69f873d
d9315ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import streamlit as st
import requests
import json
import time

# Define API Key and Base URL
API_KEY = "tauHGktuvULkGzYof5jKdVCNfZZryj32"
API_BASE_URL = "https://oapi.tasking.ai/v1"
MODEL_ID = "X5lMcszUYZvPpFnigD8mCfPI"

# Streamlit interface setup
st.set_page_config(page_title="Custom Assistant", page_icon="🤖", layout="centered")
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)
st.title("🤖 AI-Buddy Assistant")

# Custom CSS to increase font size and make sidebar mobile-friendly
st.markdown("""
    <style>
        .sidebar .sidebar-content {
            font-size: 1.1rem;
            color: #333333;
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 8px;
        }
        .sidebar .sidebar-content h1 {
            font-size: 1.5rem;
            font-weight: bold;
            color: #ff4b4b;
            margin-bottom: 10px;
        }
        .sidebar .sidebar-content select, .sidebar .sidebar-content textarea, .sidebar .sidebar-content input {
            border: 2px solid #ff4b4b;
            padding: 10px;
            font-size: 1.1rem;
            margin-bottom: 10px;
            border-radius: 5px;
        }
        .sidebar .sidebar-content button {
            background-color: #ff4b4b;
            color: white;
            font-size: 1.1rem;
            padding: 8px 15px;
            border-radius: 5px;
            border: none;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .sidebar .sidebar-content button:hover {
            background-color: #ff6565;
        }
        .st-chat-message p {
            font-size: 1.1rem;
        }
    </style>
""", unsafe_allow_html=True)

# Sidebar for AI in Profession
st.sidebar.title("Want to know how AI helps in your profession and the role of AI-Buddy?")
st.sidebar.write("Select your details below and discover the potential of AI in your career!")

# Dropdown options for profession with 'Other' option
professions = ["Software Engineer", "Business","Student", "Data Scientist", "Marketing Specialist", "Financial Analyst", "Teacher", "Doctor", "Project Manager", "Consultant", "Business Analyst", "Other"]

# Dropdown options for field with 'Other' option
fields = ["IT", "Healthcare", "Education", "Finance", "Marketing", "Engineering", "Sales", "Human Resources", "Consulting", "Other"]

# Mandatory Dropdowns for profession and field
profession = st.sidebar.selectbox("Choose Your Profession", professions, key="profession")
field = st.sidebar.selectbox("Choose Your Field/Domain", fields, key="field")

# If 'Other' is selected, require text input for custom profession/field
if profession == "Other":
    profession = st.sidebar.text_input("Please specify your profession", key="custom_profession")
if field == "Other":
    field = st.sidebar.text_input("Please specify your field", key="custom_field")

# Text area for additional description
description = st.sidebar.text_area("About you (a short description)", placeholder="Briefly describe your role", key="description")

# Submit button with mandatory field checks
if st.sidebar.button("Submit"):
    # Check if all required fields are filled
    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):
        st.sidebar.error("Please fill in all required fields.")
    else:
        # Add input details as a message to chat history
        st.session_state.messages.append(
            {"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."}
        )
        # Clear the sidebar content to simulate sidebar closure
        st.sidebar.empty()
        st.sidebar.write("Details submitted! You can continue chatting below.")

# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = [
        {"role": "assistant", "content": "Hello! How can I assist you today?"}
    ]

# Function to make a request to the custom API
def get_chat_response():
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {API_KEY}",
    }
    data = {
        "model": MODEL_ID,
        "messages": st.session_state.messages  # Send entire conversation history
    }

    try:
        response = requests.post(f"{API_BASE_URL}/chat/completions", headers=headers, json=data)
        
        if response.status_code == 200:
            response_json = response.json()
            content = response_json["choices"][0]["message"]["content"]

            try:
                content_parsed = json.loads(content)
                return content_parsed["choices"][0]["message"]["content"]
            except json.JSONDecodeError:
                return content
        else:
            raise Exception(f"API Error: {response.status_code} - {response.text}")

    except Exception as e:
        st.error("Re-enter the prompt")
        print(f"Error: {e}")
        return None

# Function to simulate streaming effect for displaying assistant's response
def display_response_streaming(response_content):
    response_placeholder = st.empty()  # Create a placeholder for assistant's response
    streaming_text = ""
    for char in response_content:
        streaming_text += char
        response_placeholder.write(streaming_text)
        time.sleep(0.05)  # Small delay to simulate typing effect

# Chat interface - User Input
if prompt := st.chat_input("Type your message"):
    # Append user's message to the chat history
    st.session_state.messages.append({"role": "user", "content": prompt})

# Display chat history and generate assistant response
for message in st.session_state.messages:
    with st.chat_message(message["role"]):
        st.write(message["content"])

# Generate assistant response if the last message is from the user
if st.session_state.messages[-1]["role"] == "user":
    with st.chat_message("assistant"):
        with st.spinner("Thinking..."):
            # Get assistant's response based on the entire conversation history
            response_content = get_chat_response()
            if response_content:
                # Stream the assistant's response chunk by chunk
                display_response_streaming(response_content)
                # Append the assistant's response to the chat history
                st.session_state.messages.append({"role": "assistant", "content": response_content})
            else:
                st.write("Sorry, Re-enter the prompt")