invincible-jha commited on
Commit
d09ad37
·
verified ·
1 Parent(s): 1d49ac8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +8 -110
app.py CHANGED
@@ -7,30 +7,11 @@ import re
7
  import numpy as np
8
  from sklearn.feature_extraction.text import CountVectorizer
9
  from sklearn.naive_bayes import MultinomialNB
10
- import asyncio
11
 
12
  # Set up logging
13
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
14
  logger = logging.getLogger(__name__)
15
 
16
- # Check Python version
17
- if sys.version_info < (3, 7):
18
- logger.error("This script requires Python 3.7 or higher")
19
- sys.exit(1)
20
-
21
- # Check for required packages
22
- required_packages = ['gradio', 'autogen', 'huggingface_hub', 'numpy', 'scikit-learn', 'crewai']
23
- for package in required_packages:
24
- try:
25
- __import__(package)
26
- except ImportError:
27
- logger.error(f"Required package '{package}' is not installed. Please install it using 'pip install {package}'")
28
- sys.exit(1)
29
-
30
- # Now that we've checked for packages, we can safely import them
31
- import autogen
32
- from crewai import Agent as CrewAgent, Task, Crew
33
-
34
  # Check for Hugging Face API key
35
  if 'HUGGINGFACE_API_KEY' not in os.environ:
36
  logger.error("HUGGINGFACE_API_KEY environment variable is not set.")
@@ -45,8 +26,8 @@ except Exception as e:
45
  logger.error(f"Failed to initialize InferenceClient: {e}")
46
  sys.exit(1)
47
 
48
- # Shared context for both agents
49
- SHARED_CONTEXT = """You are part of a multi-agent system designed to provide respectful, empathetic, and accurate support for Zerodha, a leading Indian financial services company. Your role is crucial in ensuring all interactions uphold the highest standards of customer service while maintaining Zerodha's excellent reputation.
50
 
51
  Key points about Zerodha:
52
  1. India's largest discount broker, known for innovative technology and low-cost trading.
@@ -110,61 +91,8 @@ def post_process_response(response):
110
 
111
  return response
112
 
113
- # CrewAI and AutoGen setup
114
- communication_expert_crew = CrewAgent(
115
- role='Communication Expert',
116
- goal='Interpret and rephrase user queries with empathy and respect',
117
- backstory="""You are an expert in communication, specializing in understanding and rephrasing queries to ensure they are interpreted in the most positive and constructive light. Your role is crucial in setting the tone for respectful and empathetic interactions.""",
118
- verbose=True,
119
- allow_delegation=False,
120
- tools=[generate_response]
121
- )
122
-
123
- response_expert_crew = CrewAgent(
124
- role='Response Expert',
125
- goal='Provide accurate, helpful, and emotionally intelligent responses to user queries',
126
- backstory="""You are an expert in Zerodha's services and policies, with a keen ability to provide comprehensive and empathetic responses. Your role is to ensure that all user queries are addressed accurately while maintaining a respectful and supportive tone.""",
127
- verbose=True,
128
- allow_delegation=False,
129
- tools=[generate_response]
130
- )
131
-
132
- communication_expert_autogen = autogen.AssistantAgent(
133
- name="Communication_Expert",
134
- system_message=SHARED_CONTEXT + """
135
- As the Communication Expert, your primary role is to interpret user queries with the utmost respect and empathy. You should:
136
- 1. Rephrase the user's query to ensure it's understood in the most positive and constructive light.
137
- 2. Identify and highlight any emotional subtext or concerns in the query.
138
- 3. Frame the query in a way that invites a supportive and informative response.
139
- 4. Ensure that any potential complaints or frustrations are acknowledged respectfully.
140
-
141
- Your output should be a rephrased version of the user's query that maintains its original intent while setting the stage for an empathetic and respectful response.""",
142
- llm_config={"config_list": [{"model": "gpt-3.5-turbo"}]}
143
- )
144
-
145
- response_expert_autogen = autogen.AssistantAgent(
146
- name="Response_Expert",
147
- system_message=SHARED_CONTEXT + """
148
- As the Response Expert, your role is to provide accurate, helpful, and emotionally intelligent responses to user queries. You should:
149
- 1. Address the user's question or concern directly and comprehensively.
150
- 2. Maintain a tone of respect and empathy throughout your response.
151
- 3. Provide clear, factual information about Zerodha's services and policies.
152
- 4. When discussing financial matters, include appropriate disclaimers and encourage users to seek professional advice for complex decisions.
153
- 5. For complaints or concerns, acknowledge them respectfully and provide constructive guidance or escalation paths.
154
- 6. Always uphold Zerodha's reputation for transparency and user-centric service.
155
-
156
- Your output should be a complete, informative response that addresses the user's query while demonstrating empathy and respect.""",
157
- llm_config={"config_list": [{"model": "gpt-3.5-turbo"}]}
158
- )
159
-
160
- user_proxy = autogen.UserProxyAgent(
161
- name="User_Proxy",
162
- human_input_mode="NEVER",
163
- max_consecutive_auto_reply=1
164
- )
165
-
166
  # Main function
167
- async def zerodha_support(message, history):
168
  try:
169
  sanitized_message = sanitize_input(message)
170
 
@@ -173,29 +101,8 @@ async def zerodha_support(message, history):
173
 
174
  sanitized_message = redact_sensitive_info(sanitized_message)
175
 
176
- # Use crewAI for initial query rephrasing
177
- rephrase_task = Task(
178
- description=f"Rephrase the following user query with empathy and respect: '{sanitized_message}'",
179
- agent=communication_expert_crew
180
- )
181
-
182
- crew = Crew(
183
- agents=[communication_expert_crew],
184
- tasks=[rephrase_task],
185
- verbose=2
186
- )
187
-
188
- rephrased_query = crew.kickoff()
189
-
190
- # Use AutoGen for generating the response
191
- async def get_autogen_response():
192
- await user_proxy.a_initiate_chat(
193
- response_expert_autogen,
194
- message=f"Please provide a respectful and empathetic response to the following query: '{rephrased_query}'"
195
- )
196
- return response_expert_autogen.last_message()["content"]
197
-
198
- response = await get_autogen_response()
199
 
200
  if not check_response_content(response):
201
  response += "\n\nPlease note that I cannot provide specific investment advice or guarantee returns. For personalized guidance, please consult with a qualified financial advisor."
@@ -210,17 +117,13 @@ async def zerodha_support(message, history):
210
  logger.error(f"Error in zerodha_support: {e}")
211
  return "I apologize, but an error occurred while processing your request. Please try again later."
212
 
213
- # Wrap the asynchronous function for Gradio
214
- def zerodha_support_wrapper(message, history):
215
- return asyncio.run(zerodha_support(message, history))
216
-
217
  # Gradio interface setup
218
  demo = gr.ChatInterface(
219
- zerodha_support_wrapper,
220
  chatbot=gr.Chatbot(height=600),
221
  textbox=gr.Textbox(placeholder="Ask your question about Zerodha here...", container=False, scale=7),
222
  title="Zerodha Support Assistant",
223
- description="Ask questions about Zerodha's services, trading, account management, and more. Our multi-agent system ensures respectful and empathetic responses.",
224
  theme="soft",
225
  examples=[
226
  "How do I open a Zerodha account?",
@@ -234,9 +137,4 @@ demo = gr.ChatInterface(
234
  )
235
 
236
  if __name__ == "__main__":
237
- try:
238
- public_url = demo.launch(share=True, server_name="0.0.0.0", server_port=7860)
239
- logger.info(f"\n\nSHAREABLE LINK: {public_url}\n\n")
240
- except Exception as e:
241
- logger.error(f"Failed to launch Gradio interface: {e}")
242
- sys.exit(1)
 
7
  import numpy as np
8
  from sklearn.feature_extraction.text import CountVectorizer
9
  from sklearn.naive_bayes import MultinomialNB
 
10
 
11
  # Set up logging
12
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
13
  logger = logging.getLogger(__name__)
14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  # Check for Hugging Face API key
16
  if 'HUGGINGFACE_API_KEY' not in os.environ:
17
  logger.error("HUGGINGFACE_API_KEY environment variable is not set.")
 
26
  logger.error(f"Failed to initialize InferenceClient: {e}")
27
  sys.exit(1)
28
 
29
+ # Shared context for the AI assistant
30
+ SHARED_CONTEXT = """You are an AI assistant designed to provide respectful, empathetic, and accurate support for Zerodha, a leading Indian financial services company. Your role is to ensure all interactions uphold the highest standards of customer service while maintaining Zerodha's excellent reputation.
31
 
32
  Key points about Zerodha:
33
  1. India's largest discount broker, known for innovative technology and low-cost trading.
 
91
 
92
  return response
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  # Main function
95
+ def zerodha_support(message, history):
96
  try:
97
  sanitized_message = sanitize_input(message)
98
 
 
101
 
102
  sanitized_message = redact_sensitive_info(sanitized_message)
103
 
104
+ # Generate response
105
+ response = generate_response(f"{SHARED_CONTEXT}\n\nUser: {sanitized_message}\nAssistant:")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
  if not check_response_content(response):
108
  response += "\n\nPlease note that I cannot provide specific investment advice or guarantee returns. For personalized guidance, please consult with a qualified financial advisor."
 
117
  logger.error(f"Error in zerodha_support: {e}")
118
  return "I apologize, but an error occurred while processing your request. Please try again later."
119
 
 
 
 
 
120
  # Gradio interface setup
121
  demo = gr.ChatInterface(
122
+ zerodha_support,
123
  chatbot=gr.Chatbot(height=600),
124
  textbox=gr.Textbox(placeholder="Ask your question about Zerodha here...", container=False, scale=7),
125
  title="Zerodha Support Assistant",
126
+ description="Ask questions about Zerodha's services, trading, account management, and more. Our system ensures respectful and empathetic responses.",
127
  theme="soft",
128
  examples=[
129
  "How do I open a Zerodha account?",
 
137
  )
138
 
139
  if __name__ == "__main__":
140
+ demo.launch()