invincible-jha commited on
Commit
bdb68b7
·
verified ·
1 Parent(s): 5b2aed4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +140 -20
app.py CHANGED
@@ -2,7 +2,6 @@ import os
2
  import sys
3
  import logging
4
  import gradio as gr
5
- import autogen
6
  from huggingface_hub import InferenceClient
7
  import re
8
  import numpy as np
@@ -12,36 +11,157 @@ import asyncio
12
 
13
  # Set up logging
14
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
 
15
 
16
  # Check Python version
17
  if sys.version_info < (3, 7):
18
- logging.error("This script requires Python 3.7 or higher")
19
  sys.exit(1)
20
 
21
- # Check and set environment variables
22
- required_env_vars = ['HUGGINGFACE_API_KEY']
23
- for var in required_env_vars:
24
- if var not in os.environ:
25
- logging.error(f"Environment variable {var} is not set")
 
 
26
  sys.exit(1)
27
 
 
 
 
 
 
 
 
 
 
 
28
  # Initialize the client with the Mistral-7B-Instruct-v0.2 model
29
  try:
30
- client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
 
31
  except Exception as e:
32
- logging.error(f"Failed to initialize InferenceClient: {e}")
33
  sys.exit(1)
34
 
35
- # Rest of your code (SHARED_CONTEXT, guardrail functions, etc.) remains the same
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
- # CrewAI setup
38
- try:
39
- from crewai import Agent as CrewAgent, Task, Crew
40
- except ImportError:
41
- logging.error("Failed to import crewai. Make sure it's installed: pip install crewai")
42
- sys.exit(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- # CrewAI and AutoGen setup remains the same
 
 
 
 
45
 
46
  # Main function
47
  async def zerodha_support(message, history):
@@ -87,7 +207,7 @@ async def zerodha_support(message, history):
87
 
88
  return final_response
89
  except Exception as e:
90
- logging.error(f"Error in zerodha_support: {e}")
91
  return "I apologize, but an error occurred while processing your request. Please try again later."
92
 
93
  # Wrap the asynchronous function for Gradio
@@ -116,7 +236,7 @@ demo = gr.ChatInterface(
116
  if __name__ == "__main__":
117
  try:
118
  public_url = demo.launch(share=True, server_name="0.0.0.0", server_port=7860)
119
- print(f"\n\nSHAREABLE LINK: {public_url}\n\n")
120
  except Exception as e:
121
- logging.error(f"Failed to launch Gradio interface: {e}")
122
  sys.exit(1)
 
2
  import sys
3
  import logging
4
  import gradio as gr
 
5
  from huggingface_hub import InferenceClient
6
  import re
7
  import numpy as np
 
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.")
37
+ logger.info("Please set the HUGGINGFACE_API_KEY environment variable before running this script.")
38
+ sys.exit(1)
39
+
40
  # Initialize the client with the Mistral-7B-Instruct-v0.2 model
41
  try:
42
+ client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2",
43
+ token=os.environ['HUGGINGFACE_API_KEY'])
44
  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.
53
+ 2. Flat fee structure: ₹20 per executed order for intraday and F&O trades, zero brokerage for delivery equity investments.
54
+ 3. Main trading platform: Kite (web and mobile).
55
+ 4. Coin platform for commission-free direct mutual fund investments.
56
+ 5. Extensive educational resources through Varsity.
57
+ 6. Additional tools: Sentinel (price alerts) and ChartIQ (advanced charting).
58
+ 7. Console for account management and administrative tasks.
59
+
60
+ Always prioritize user safety, ethical investing practices, and transparent communication. Never provide information that could mislead users or bring disrepute to Zerodha."""
61
+
62
+ # Guardrail functions
63
+ def sanitize_input(input_text):
64
+ return re.sub(r'[<>&\']', '', input_text)
65
+
66
+ approved_topics = ['account opening', 'trading', 'fees', 'platforms', 'funds', 'regulations', 'support']
67
+ vectorizer = CountVectorizer()
68
+ classifier = MultinomialNB()
69
+
70
+ X = vectorizer.fit_transform(approved_topics)
71
+ y = np.arange(len(approved_topics))
72
+ classifier.fit(X, y)
73
+
74
+ def is_relevant_topic(query):
75
+ query_vector = vectorizer.transform([query])
76
+ prediction = classifier.predict(query_vector)
77
+ return prediction[0] in range(len(approved_topics))
78
+
79
+ def redact_sensitive_info(text):
80
+ text = re.sub(r'\b\d{10,12}\b', '[REDACTED]', text)
81
+ text = re.sub(r'[A-Z]{5}[0-9]{4}[A-Z]', '[REDACTED]', text)
82
+ return text
83
+
84
+ def check_response_content(response):
85
+ unauthorized_patterns = [
86
+ r'\b(guarantee|assured|certain)\b.*\b(returns|profit)\b',
87
+ r'\b(buy|sell)\b.*\b(specific stocks?|shares?)\b'
88
+ ]
89
+ return not any(re.search(pattern, response, re.IGNORECASE) for pattern in unauthorized_patterns)
90
+
91
+ def check_confidence(response):
92
+ uncertain_phrases = ["I'm not sure", "It's possible", "I don't have enough information"]
93
+ return not any(phrase.lower() in response.lower() for phrase in uncertain_phrases)
94
+
95
+ def generate_response(prompt):
96
+ try:
97
+ return client.text_generation(prompt, max_new_tokens=500, temperature=0.7)
98
+ except Exception as e:
99
+ logger.error(f"Error generating response: {e}")
100
+ return "I apologize, but I'm having trouble generating a response at the moment. Please try again later."
101
+
102
+ def post_process_response(response):
103
+ response = re.sub(r'\b(stupid|dumb|idiotic|foolish)\b', 'mistaken', response, flags=re.IGNORECASE)
104
+
105
+ if not re.search(r'(Thank you|Is there anything else|Hope this helps|Let me know if you need more information)\s*$', response, re.IGNORECASE):
106
+ response += "\n\nIs there anything else I can help you with regarding Zerodha's services?"
107
+
108
+ if re.search(r'\b(invest|trade|buy|sell|market)\b', response, re.IGNORECASE):
109
+ response += "\n\nPlease note that this information is for educational purposes only and should not be considered as financial advice. Always do your own research and consider consulting with a qualified financial advisor before making investment decisions."
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):
 
207
 
208
  return final_response
209
  except Exception as e:
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
 
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)