invincible-jha commited on
Commit
09bef47
·
verified ·
1 Parent(s): 912dd7d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +64 -101
app.py CHANGED
@@ -12,90 +12,10 @@ from crewai import Agent as CrewAgent, Task, Crew
12
  import autogen
13
  from langchain_openai import ChatOpenAI
14
 
15
- # Set up logging
16
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
17
- logger = logging.getLogger(__name__)
18
-
19
- # Check for OpenAI API key
20
- if 'OPENAI_API_KEY' not in os.environ:
21
- logger.error("OPENAI_API_KEY environment variable is not set.")
22
- logger.info("Please set the OPENAI_API_KEY environment variable before running this script.")
23
- sys.exit(1)
24
-
25
- # Initialize the client with the Mistral-7B-Instruct-v0.2 model
26
- try:
27
- client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
28
- except Exception as e:
29
- logger.error(f"Failed to initialize InferenceClient: {e}")
30
- sys.exit(1)
31
-
32
- # Shared context for both agents
33
- 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.
34
-
35
- Key points about Zerodha:
36
- 1. India's largest discount broker, known for innovative technology and low-cost trading.
37
- 2. Flat fee structure: ₹20 per executed order for intraday and F&O trades, zero brokerage for delivery equity investments.
38
- 3. Main trading platform: Kite (web and mobile).
39
- 4. Coin platform for commission-free direct mutual fund investments.
40
- 5. Extensive educational resources through Varsity.
41
- 6. Additional tools: Sentinel (price alerts) and ChartIQ (advanced charting).
42
- 7. Console for account management and administrative tasks.
43
-
44
- Always prioritize user safety, ethical investing practices, and transparent communication. Never provide information that could mislead users or bring disrepute to Zerodha."""
45
-
46
- # Guardrail functions
47
- def sanitize_input(input_text):
48
- return re.sub(r'[<>&\']', '', input_text)
49
-
50
- approved_topics = ['account opening', 'trading', 'fees', 'platforms', 'funds', 'regulations', 'support']
51
- vectorizer = CountVectorizer()
52
- classifier = MultinomialNB()
53
-
54
- X = vectorizer.fit_transform(approved_topics)
55
- y = np.arange(len(approved_topics))
56
- classifier.fit(X, y)
57
-
58
- def is_relevant_topic(query):
59
- query_vector = vectorizer.transform([query])
60
- prediction = classifier.predict(query_vector)
61
- return prediction[0] in range(len(approved_topics))
62
-
63
- def redact_sensitive_info(text):
64
- text = re.sub(r'\b\d{10,12}\b', '[REDACTED]', text)
65
- text = re.sub(r'[A-Z]{5}[0-9]{4}[A-Z]', '[REDACTED]', text)
66
- return text
67
-
68
- def check_response_content(response):
69
- unauthorized_patterns = [
70
- r'\b(guarantee|assured|certain)\b.*\b(returns|profit)\b',
71
- r'\b(buy|sell)\b.*\b(specific stocks?|shares?)\b'
72
- ]
73
- return not any(re.search(pattern, response, re.IGNORECASE) for pattern in unauthorized_patterns)
74
-
75
- def check_confidence(response):
76
- uncertain_phrases = ["I'm not sure", "It's possible", "I don't have enough information"]
77
- return not any(phrase.lower() in response.lower() for phrase in uncertain_phrases)
78
-
79
- async def generate_response(prompt):
80
- try:
81
- return await client.text_generation(prompt, max_new_tokens=500, temperature=0.7)
82
- except Exception as e:
83
- logger.error(f"Error generating response: {e}")
84
- return "I apologize, but I'm having trouble generating a response at the moment. Please try again later."
85
-
86
- def post_process_response(response):
87
- response = re.sub(r'\b(stupid|dumb|idiotic|foolish)\b', 'mistaken', response, flags=re.IGNORECASE)
88
-
89
- 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):
90
- response += "\n\nIs there anything else I can help you with regarding Zerodha's services?"
91
-
92
- if re.search(r'\b(invest|trade|buy|sell|market)\b', response, re.IGNORECASE):
93
- 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."
94
-
95
- return response
96
-
97
- # CrewAI and AutoGen setup
98
- chat_model = ChatOpenAI(model="gpt-3.5-turbo")
99
 
100
  communication_expert_crew = CrewAgent(
101
  role='Communication Expert',
@@ -164,25 +84,68 @@ async def zerodha_support(message, history):
164
  sanitized_message = redact_sensitive_info(sanitized_message)
165
 
166
  # Use crewAI for initial query rephrasing
167
- rephrase_task = Task(
168
- description=f"Rephrase the following user query with empathy and respect: '{sanitized_message}'",
169
- agent=communication_expert_crew
170
- )
 
171
 
172
- crew = Crew(
173
- agents=[communication_expert_crew],
174
- tasks=[rephrase_task],
175
- verbose=2
176
- )
177
 
178
- rephrased_query = crew.kickoff()
 
 
 
179
 
180
  # Use AutoGen for generating the response
181
- async def get_autogen_response():
182
- await user_proxy.a_initiate_chat(
183
- response_expert_autogen,
184
- message=f"Please provide a respectful and empathetic response to the following query: '{rephrased_query}'"
185
- )
186
- return response_expert_autogen.last_message()["content"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
187
 
188
- res
 
 
12
  import autogen
13
  from langchain_openai import ChatOpenAI
14
 
15
+ # ... (previous code remains the same)
16
+
17
+ # Modify the CrewAI and AutoGen setup
18
+ chat_model = ChatOpenAI(model_name="gpt-3.5-turbo")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  communication_expert_crew = CrewAgent(
21
  role='Communication Expert',
 
84
  sanitized_message = redact_sensitive_info(sanitized_message)
85
 
86
  # Use crewAI for initial query rephrasing
87
+ try:
88
+ rephrase_task = Task(
89
+ description=f"Rephrase the following user query with empathy and respect: '{sanitized_message}'",
90
+ agent=communication_expert_crew
91
+ )
92
 
93
+ crew = Crew(
94
+ agents=[communication_expert_crew],
95
+ tasks=[rephrase_task],
96
+ verbose=2
97
+ )
98
 
99
+ rephrased_query = crew.kickoff()
100
+ except Exception as e:
101
+ logger.error(f"Error in CrewAI rephrasing: {e}")
102
+ rephrased_query = sanitized_message # Fallback to original message if rephrasing fails
103
 
104
  # Use AutoGen for generating the response
105
+ try:
106
+ response = await get_autogen_response(rephrased_query)
107
+ except Exception as e:
108
+ logger.error(f"Error in AutoGen response generation: {e}")
109
+ response = "I apologize, but I'm having trouble generating a response at the moment. Please try again later."
110
+
111
+ if not check_response_content(response):
112
+ response += "\n\nPlease note that I cannot provide specific investment advice or guarantee returns. For personalized guidance, please consult with a qualified financial advisor."
113
+
114
+ if not check_confidence(response):
115
+ return "I apologize, but I'm not confident in providing an accurate answer to this query. For the most up-to-date and accurate information, please contact Zerodha's customer support directly."
116
+
117
+ final_response = post_process_response(response)
118
+
119
+ return final_response
120
+ except Exception as e:
121
+ logger.error(f"Error in zerodha_support: {e}")
122
+ return "I apologize, but an error occurred while processing your request. Please try again later."
123
+
124
+ async def get_autogen_response(query):
125
+ await user_proxy.a_initiate_chat(
126
+ response_expert_autogen,
127
+ message=f"Please provide a respectful and empathetic response to the following query: '{query}'"
128
+ )
129
+ return response_expert_autogen.last_message()["content"]
130
+
131
+ # Gradio interface setup
132
+ demo = gr.ChatInterface(
133
+ zerodha_support,
134
+ chatbot=gr.Chatbot(height=600),
135
+ textbox=gr.Textbox(placeholder="Ask your question about Zerodha here...", container=False, scale=7),
136
+ title="Zerodha Support Assistant",
137
+ description="Ask questions about Zerodha's services, trading, account management, and more. Our multi-agent system ensures respectful and empathetic responses.",
138
+ theme="soft",
139
+ examples=[
140
+ "How do I open a Zerodha account?",
141
+ "I'm frustrated with the recent changes to the Kite platform. Can you help?",
142
+ "What are the risks involved in F&O trading?",
143
+ "I think there's an error in my account statement. What should I do?",
144
+ "Can you explain Zerodha's policy on intraday trading margins?",
145
+ "I'm new to investing. What resources does Zerodha offer for beginners?",
146
+ "How does Zerodha ensure the security of my investments and personal data?"
147
+ ],
148
+ )
149
 
150
+ if __name__ == "__main__":
151
+ demo.launch()