Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -10,12 +10,101 @@ from sklearn.naive_bayes import MultinomialNB
|
|
10 |
import asyncio
|
11 |
from crewai import Agent as CrewAgent, Task, Crew
|
12 |
import autogen
|
13 |
-
|
14 |
-
|
15 |
-
#
|
16 |
-
|
17 |
-
|
18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
communication_expert_crew = CrewAgent(
|
21 |
role='Communication Expert',
|
@@ -23,7 +112,7 @@ communication_expert_crew = CrewAgent(
|
|
23 |
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.""",
|
24 |
verbose=True,
|
25 |
allow_delegation=False,
|
26 |
-
|
27 |
)
|
28 |
|
29 |
response_expert_crew = CrewAgent(
|
@@ -32,7 +121,7 @@ response_expert_crew = CrewAgent(
|
|
32 |
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.""",
|
33 |
verbose=True,
|
34 |
allow_delegation=False,
|
35 |
-
|
36 |
)
|
37 |
|
38 |
llm_config = {
|
@@ -73,6 +162,13 @@ user_proxy = autogen.UserProxyAgent(
|
|
73 |
max_consecutive_auto_reply=1
|
74 |
)
|
75 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
# Main function
|
77 |
async def zerodha_support(message, history):
|
78 |
try:
|
@@ -121,13 +217,6 @@ async def zerodha_support(message, history):
|
|
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,
|
|
|
10 |
import asyncio
|
11 |
from crewai import Agent as CrewAgent, Task, Crew
|
12 |
import autogen
|
13 |
+
import openai
|
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 |
+
# Set OpenAI API key
|
26 |
+
openai.api_key = os.environ['OPENAI_API_KEY']
|
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 |
+
logger.error(f"Failed to initialize InferenceClient: {e}")
|
33 |
+
sys.exit(1)
|
34 |
+
|
35 |
+
# Shared context for both agents
|
36 |
+
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.
|
37 |
+
|
38 |
+
Key points about Zerodha:
|
39 |
+
1. India's largest discount broker, known for innovative technology and low-cost trading.
|
40 |
+
2. Flat fee structure: ₹20 per executed order for intraday and F&O trades, zero brokerage for delivery equity investments.
|
41 |
+
3. Main trading platform: Kite (web and mobile).
|
42 |
+
4. Coin platform for commission-free direct mutual fund investments.
|
43 |
+
5. Extensive educational resources through Varsity.
|
44 |
+
6. Additional tools: Sentinel (price alerts) and ChartIQ (advanced charting).
|
45 |
+
7. Console for account management and administrative tasks.
|
46 |
+
|
47 |
+
Always prioritize user safety, ethical investing practices, and transparent communication. Never provide information that could mislead users or bring disrepute to Zerodha."""
|
48 |
+
|
49 |
+
# Guardrail functions
|
50 |
+
def sanitize_input(input_text):
|
51 |
+
return re.sub(r'[<>&\']', '', input_text)
|
52 |
+
|
53 |
+
approved_topics = ['account opening', 'trading', 'fees', 'platforms', 'funds', 'regulations', 'support']
|
54 |
+
vectorizer = CountVectorizer()
|
55 |
+
classifier = MultinomialNB()
|
56 |
+
|
57 |
+
X = vectorizer.fit_transform(approved_topics)
|
58 |
+
y = np.arange(len(approved_topics))
|
59 |
+
classifier.fit(X, y)
|
60 |
+
|
61 |
+
def is_relevant_topic(query):
|
62 |
+
query_vector = vectorizer.transform([query])
|
63 |
+
prediction = classifier.predict(query_vector)
|
64 |
+
return prediction[0] in range(len(approved_topics))
|
65 |
+
|
66 |
+
def redact_sensitive_info(text):
|
67 |
+
text = re.sub(r'\b\d{10,12}\b', '[REDACTED]', text)
|
68 |
+
text = re.sub(r'[A-Z]{5}[0-9]{4}[A-Z]', '[REDACTED]', text)
|
69 |
+
return text
|
70 |
+
|
71 |
+
def check_response_content(response):
|
72 |
+
unauthorized_patterns = [
|
73 |
+
r'\b(guarantee|assured|certain)\b.*\b(returns|profit)\b',
|
74 |
+
r'\b(buy|sell)\b.*\b(specific stocks?|shares?)\b'
|
75 |
+
]
|
76 |
+
return not any(re.search(pattern, response, re.IGNORECASE) for pattern in unauthorized_patterns)
|
77 |
+
|
78 |
+
def check_confidence(response):
|
79 |
+
uncertain_phrases = ["I'm not sure", "It's possible", "I don't have enough information"]
|
80 |
+
return not any(phrase.lower() in response.lower() for phrase in uncertain_phrases)
|
81 |
+
|
82 |
+
async def generate_response(prompt):
|
83 |
+
try:
|
84 |
+
return await client.text_generation(prompt, max_new_tokens=500, temperature=0.7)
|
85 |
+
except Exception as e:
|
86 |
+
logger.error(f"Error generating response: {e}")
|
87 |
+
return "I apologize, but I'm having trouble generating a response at the moment. Please try again later."
|
88 |
+
|
89 |
+
def post_process_response(response):
|
90 |
+
response = re.sub(r'\b(stupid|dumb|idiotic|foolish)\b', 'mistaken', response, flags=re.IGNORECASE)
|
91 |
+
|
92 |
+
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):
|
93 |
+
response += "\n\nIs there anything else I can help you with regarding Zerodha's services?"
|
94 |
+
|
95 |
+
if re.search(r'\b(invest|trade|buy|sell|market)\b', response, re.IGNORECASE):
|
96 |
+
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."
|
97 |
+
|
98 |
+
return response
|
99 |
+
|
100 |
+
# CrewAI and AutoGen setup
|
101 |
+
def get_openai_response(prompt):
|
102 |
+
response = openai.Completion.create(
|
103 |
+
engine="text-davinci-002",
|
104 |
+
prompt=prompt,
|
105 |
+
max_tokens=150
|
106 |
+
)
|
107 |
+
return response.choices[0].text.strip()
|
108 |
|
109 |
communication_expert_crew = CrewAgent(
|
110 |
role='Communication Expert',
|
|
|
112 |
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.""",
|
113 |
verbose=True,
|
114 |
allow_delegation=False,
|
115 |
+
tools=[get_openai_response]
|
116 |
)
|
117 |
|
118 |
response_expert_crew = CrewAgent(
|
|
|
121 |
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.""",
|
122 |
verbose=True,
|
123 |
allow_delegation=False,
|
124 |
+
tools=[get_openai_response]
|
125 |
)
|
126 |
|
127 |
llm_config = {
|
|
|
162 |
max_consecutive_auto_reply=1
|
163 |
)
|
164 |
|
165 |
+
async def get_autogen_response(query):
|
166 |
+
await user_proxy.a_initiate_chat(
|
167 |
+
response_expert_autogen,
|
168 |
+
message=f"Please provide a respectful and empathetic response to the following query: '{query}'"
|
169 |
+
)
|
170 |
+
return response_expert_autogen.last_message()["content"]
|
171 |
+
|
172 |
# Main function
|
173 |
async def zerodha_support(message, history):
|
174 |
try:
|
|
|
217 |
logger.error(f"Error in zerodha_support: {e}")
|
218 |
return "I apologize, but an error occurred while processing your request. Please try again later."
|
219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
220 |
# Gradio interface setup
|
221 |
demo = gr.ChatInterface(
|
222 |
zerodha_support,
|