swayam-the-coder commited on
Commit
47589e6
1 Parent(s): 8dceab8

Upload task.py

Browse files
Files changed (1) hide show
  1. task.py +183 -0
task.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import streamlit as st
3
+ from langchain_openai import ChatOpenAI
4
+ from langchain.vectorstores import FAISS
5
+ import pandas as pd
6
+
7
+ # Environment setup
8
+ os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_KEY")
9
+
10
+ # Streamlit page setup
11
+ st.set_page_config(
12
+ page_title="Airtel AI Agent System",
13
+ page_icon="🤖",
14
+ layout="wide",
15
+ initial_sidebar_state="expanded"
16
+ )
17
+
18
+ # Sidebar setup
19
+ with st.sidebar:
20
+ airtel_logo = "https://1000logos.net/wp-content/uploads/2023/06/Airtel-logo.jpg" # Airtel logo URL
21
+ st.image(airtel_logo, use_column_width=True)
22
+ st.markdown("### Welcome to Airtel AI Help Bot")
23
+ st.markdown("**Instructions:**")
24
+ st.markdown("- Use the chat interface to ask questions about Airtel services.")
25
+ st.markdown("- You can also initiate specific tasks like SIM swap or plan details.")
26
+ st.markdown("Feel free to ask any queries you have!")
27
+
28
+ # Apply custom CSS for the red-and-white theme
29
+ st.markdown(
30
+ """
31
+ <style>
32
+ .stApp {
33
+ background-color: white;
34
+ }
35
+ header {
36
+ background-color: #e60000;
37
+ }
38
+ .stButton>button {
39
+ background-color: #e60000;
40
+ color: white;
41
+ }
42
+ .stTextInput>div>input {
43
+ background-color: #ffffff;
44
+ border: 2px solid #e60000;
45
+ color: black;
46
+ }
47
+ .css-1mgb8k9.e1fqkh3o3 {
48
+ background-color: white;
49
+ }
50
+ .css-18ni7ap.e8zbici0 {
51
+ background-color: white;
52
+ }
53
+ footer {
54
+ background-color: white;
55
+ }
56
+ </style>
57
+ """,
58
+ unsafe_allow_html=True,
59
+ )
60
+
61
+ # Page title
62
+ st.title("Airtel AI Agent System Demo")
63
+
64
+ # Initialize session state to store chat history
65
+ if "messages" not in st.session_state:
66
+ st.session_state.messages = []
67
+
68
+ # User input for chat interface
69
+ user_input = st.text_input("Enter your message:")
70
+
71
+ # Initialize agents' tasks
72
+ def conversation_agent(state):
73
+ """Handles general conversations with the user."""
74
+ llm = ChatOpenAI(model_name="gpt-3.5-turbo")
75
+
76
+ try:
77
+ response = llm.invoke(state["question"])
78
+ # Ensure that response is not None
79
+ if response and response.content:
80
+ parsed_response = response.content # Directly access content from AIMessage object
81
+ else:
82
+ parsed_response = "I'm sorry, I couldn't generate a response."
83
+ except Exception as e:
84
+ parsed_response = f"An error occurred: {e}"
85
+
86
+ return {"question": state["question"], "response": parsed_response, "intent": "conversation"}
87
+
88
+ def website_query_agent(state):
89
+ """Handles queries by retrieving relevant data from Airtel website stored in vector DB."""
90
+ vectorstore = FAISS.load_local("path_to_faiss_index") # Assuming Airtel data is preloaded in FAISS
91
+ docs = vectorstore.similarity_search(state["question"])
92
+ response = "\n".join([doc.page_content for doc in docs[:3]]) # Return top 3 relevant docs
93
+ return {"question": state["question"], "response": response, "intent": "website_query"}
94
+
95
+ def fallback_agent(state):
96
+ """Returns a fallback message for unrelated queries."""
97
+ return {"question": state["question"], "response": "Sorry, I don't have an answer for that.", "intent": "fallback"}
98
+
99
+ def sim_swap_agent(state):
100
+ """Handles SIM swap workflow by triggering a form to collect user details."""
101
+ st.write("---Sim Swap Request---")
102
+
103
+ # File path to store the data
104
+ file_path = "sim_swap_requests.xlsx"
105
+
106
+ # Form for collecting user details
107
+ with st.form("sim_swap_form"):
108
+ name = st.text_input("Enter your name:")
109
+ phone_number = st.text_input("Enter your phone number:")
110
+ submit = st.form_submit_button("Submit")
111
+
112
+ if submit:
113
+ new_data = {"Name": [name], "Phone Number": [phone_number]}
114
+ df_new = pd.DataFrame(new_data)
115
+
116
+ # Check if the Excel file already exists
117
+ if os.path.exists(file_path):
118
+ df_existing = pd.read_excel(file_path)
119
+ df_updated = pd.concat([df_existing, df_new], ignore_index=True)
120
+ else:
121
+ df_updated = df_new
122
+
123
+ # Save the updated DataFrame to Excel
124
+ df_updated.to_excel(file_path, index=False)
125
+ return {"question": state["question"], "response": f"SIM Swap request submitted for {name} with phone number {phone_number}.", "intent": "sim_swap"}
126
+
127
+ return {"question": state["question"], "response": "Please fill in your details for SIM swap.", "intent": "sim_swap"}
128
+
129
+ def plan_details_agent(state):
130
+ """Handles plan details workflow by collecting phone number and returning a standard plan."""
131
+ with st.form("plan_details_form"):
132
+ phone_number = st.text_input("Enter your phone number:")
133
+ submit = st.form_submit_button("Submit")
134
+
135
+ if submit:
136
+ return {"question": state["question"], "response": f"Plan details for {phone_number}: You are on a standard plan of 999 INR/month.", "intent": "plan_details"}
137
+
138
+ return {"question": state["question"], "response": "Please enter your phone number to check plan details.", "intent": "plan_details"}
139
+
140
+ # Decision logic
141
+ def decide_agent(state):
142
+ question = state["question"].lower()
143
+ if "sim swap" in question or "swap sim" in question:
144
+ return "sim_swap"
145
+ elif "plan details" in question or "active plan" in question:
146
+ return "plan_details"
147
+ elif "airtel" in question:
148
+ return "conversation"
149
+ elif "website" in question or "airtel website" in question:
150
+ return "website_query"
151
+ else:
152
+ return "fallback"
153
+
154
+ # Workflow logic
155
+ workflow = {
156
+ "conversation": conversation_agent,
157
+ "website_query": website_query_agent,
158
+ "sim_swap": sim_swap_agent,
159
+ "plan_details": plan_details_agent,
160
+ "fallback": fallback_agent,
161
+ }
162
+
163
+ # Function to handle user input and generate responses
164
+ def handle_query(query):
165
+ state = {"question": query, "response": "", "intent": ""}
166
+ next_agent = decide_agent(state)
167
+ if next_agent in workflow:
168
+ agent = workflow[next_agent]
169
+ output = agent(state)
170
+ return output["response"]
171
+
172
+ # Chat Interface
173
+ if user_input:
174
+ st.session_state.messages.append({"role": "user", "content": user_input})
175
+ bot_response = handle_query(user_input)
176
+ st.session_state.messages.append({"role": "bot", "content": bot_response})
177
+
178
+ # Display chat messages in reverse order (latest message on top)
179
+ for message in reversed(st.session_state.messages):
180
+ if message["role"] == "user":
181
+ st.chat_message("user").markdown(message["content"])
182
+ else:
183
+ st.chat_message("bot").markdown(message["content"])