invincible-jha commited on
Commit
06b60e9
·
verified ·
1 Parent(s): a1b124b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -45
app.py CHANGED
@@ -9,21 +9,11 @@ from sklearn.feature_extraction.text import CountVectorizer
9
  from sklearn.naive_bayes import MultinomialNB
10
  import asyncio
11
  from crewai import Agent as CrewAgent, Task, Crew
12
- import openai
13
 
14
  # Set up logging
15
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
16
  logger = logging.getLogger(__name__)
17
 
18
- # Check for OpenAI API key
19
- if 'OPENAI_API_KEY' not in os.environ:
20
- logger.error("OPENAI_API_KEY environment variable is not set.")
21
- logger.info("Please set the OPENAI_API_KEY environment variable before running this script.")
22
- sys.exit(1)
23
-
24
- # Set OpenAI API key
25
- openai.api_key = os.environ['OPENAI_API_KEY']
26
-
27
  # Initialize the client with the Mistral-7B-Instruct-v0.2 model
28
  try:
29
  client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
@@ -31,7 +21,7 @@ except Exception as e:
31
  logger.error(f"Failed to initialize InferenceClient: {e}")
32
  sys.exit(1)
33
 
34
- # Shared context for agents
35
  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.
36
 
37
  Key points about Zerodha:
@@ -78,24 +68,44 @@ def check_confidence(response):
78
  uncertain_phrases = ["I'm not sure", "It's possible", "I don't have enough information"]
79
  return not any(phrase.lower() in response.lower() for phrase in uncertain_phrases)
80
 
81
- # Agent setup using CrewAI only
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
  communication_expert_crew = CrewAgent(
83
  role='Communication Expert',
84
  goal='Interpret and rephrase user queries with empathy and respect',
85
- backstory=SHARED_CONTEXT,
86
  verbose=True,
87
- allow_delegation=False
 
88
  )
89
 
90
  response_expert_crew = CrewAgent(
91
  role='Response Expert',
92
  goal='Provide accurate, helpful, and emotionally intelligent responses to user queries',
93
- backstory=SHARED_CONTEXT,
94
  verbose=True,
95
- allow_delegation=False
 
96
  )
97
 
98
- # Main function for handling user queries
99
  async def zerodha_support(message, history):
100
  try:
101
  sanitized_message = sanitize_input(message)
@@ -105,33 +115,30 @@ async def zerodha_support(message, history):
105
 
106
  sanitized_message = redact_sensitive_info(sanitized_message)
107
 
108
- # CrewAI for rephrasing query
109
- rephrase_task = Task(
110
- description=f"Rephrase the following user query with empathy and respect: '{sanitized_message}'",
111
- agent=communication_expert_crew
112
- )
113
-
114
- crew = Crew(
115
- agents=[communication_expert_crew],
116
- tasks=[rephrase_task],
117
- verbose=2
118
- )
119
-
120
- rephrased_query = await crew.kickoff()
121
-
122
- # CrewAI for generating the response
123
- response_task = Task(
124
- description=f"Generate a comprehensive and empathetic response to: '{rephrased_query}'",
125
- agent=response_expert_crew
126
- )
127
-
128
- response_crew = Crew(
129
- agents=[response_expert_crew],
130
- tasks=[response_task],
131
- verbose=2
132
- )
133
-
134
- response = await response_crew.kickoff()
135
 
136
  if not check_response_content(response):
137
  response += "\n\nPlease note that I cannot provide specific investment advice or guarantee returns. For personalized guidance, please consult with a qualified financial advisor."
@@ -166,4 +173,4 @@ demo = gr.ChatInterface(
166
  )
167
 
168
  if __name__ == "__main__":
169
- demo.launch()
 
9
  from sklearn.naive_bayes import MultinomialNB
10
  import asyncio
11
  from crewai import Agent as CrewAgent, Task, Crew
 
12
 
13
  # Set up logging
14
  logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
15
  logger = logging.getLogger(__name__)
16
 
 
 
 
 
 
 
 
 
 
17
  # Initialize the client with the Mistral-7B-Instruct-v0.2 model
18
  try:
19
  client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
 
21
  logger.error(f"Failed to initialize InferenceClient: {e}")
22
  sys.exit(1)
23
 
24
+ # Shared context for both agents
25
  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.
26
 
27
  Key points about Zerodha:
 
68
  uncertain_phrases = ["I'm not sure", "It's possible", "I don't have enough information"]
69
  return not any(phrase.lower() in response.lower() for phrase in uncertain_phrases)
70
 
71
+ async def generate_response(prompt):
72
+ try:
73
+ return await client.text_generation(prompt, max_new_tokens=500, temperature=0.7)
74
+ except Exception as e:
75
+ logger.error(f"Error generating response: {e}")
76
+ return "I apologize, but I'm having trouble generating a response at the moment. Please try again later."
77
+
78
+ def post_process_response(response):
79
+ response = re.sub(r'\b(stupid|dumb|idiotic|foolish)\b', 'mistaken', response, flags=re.IGNORECASE)
80
+
81
+ 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):
82
+ response += "\n\nIs there anything else I can help you with regarding Zerodha's services?"
83
+
84
+ if re.search(r'\b(invest|trade|buy|sell|market)\b', response, re.IGNORECASE):
85
+ 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."
86
+
87
+ return response
88
+
89
+ # CrewAI setup
90
  communication_expert_crew = CrewAgent(
91
  role='Communication Expert',
92
  goal='Interpret and rephrase user queries with empathy and respect',
93
+ 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.""",
94
  verbose=True,
95
+ allow_delegation=False,
96
+ tools=[generate_response]
97
  )
98
 
99
  response_expert_crew = CrewAgent(
100
  role='Response Expert',
101
  goal='Provide accurate, helpful, and emotionally intelligent responses to user queries',
102
+ 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.""",
103
  verbose=True,
104
+ allow_delegation=False,
105
+ tools=[generate_response]
106
  )
107
 
108
+ # Main function
109
  async def zerodha_support(message, history):
110
  try:
111
  sanitized_message = sanitize_input(message)
 
115
 
116
  sanitized_message = redact_sensitive_info(sanitized_message)
117
 
118
+ # Use crewAI for initial query rephrasing
119
+ try:
120
+ rephrase_task = Task(
121
+ description=f"Rephrase the following user query with empathy and respect: '{sanitized_message}'",
122
+ agent=communication_expert_crew
123
+ )
124
+
125
+ crew = Crew(
126
+ agents=[communication_expert_crew],
127
+ tasks=[rephrase_task],
128
+ verbose=2
129
+ )
130
+
131
+ rephrased_query = crew.kickoff()
132
+ except Exception as e:
133
+ logger.error(f"Error in CrewAI rephrasing: {e}")
134
+ rephrased_query = sanitized_message # Fallback to original message if rephrasing fails
135
+
136
+ # Generate response using Mistral model
137
+ try:
138
+ response = await generate_response(f"{SHARED_CONTEXT}\n\nUser: {rephrased_query}\nAssistant:")
139
+ except Exception as e:
140
+ logger.error(f"Error in response generation: {e}")
141
+ response = "I apologize, but I'm having trouble generating a response at the moment. Please try again later."
 
 
 
142
 
143
  if not check_response_content(response):
144
  response += "\n\nPlease note that I cannot provide specific investment advice or guarantee returns. For personalized guidance, please consult with a qualified financial advisor."
 
173
  )
174
 
175
  if __name__ == "__main__":
176
+ demo.launch()