Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -2,24 +2,24 @@ import os
|
|
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
|
8 |
from sklearn.feature_extraction.text import CountVectorizer
|
9 |
from sklearn.naive_bayes import MultinomialNB
|
10 |
import asyncio
|
11 |
from crewai import Agent, Task, Crew
|
|
|
12 |
import random
|
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 |
-
#
|
19 |
try:
|
20 |
-
|
21 |
except Exception as e:
|
22 |
-
logger.error(f"Failed to initialize
|
23 |
sys.exit(1)
|
24 |
|
25 |
# Shared context for both agents
|
@@ -69,14 +69,6 @@ def check_confidence(response):
|
|
69 |
uncertain_phrases = ["I'm not sure", "It's possible", "I don't have enough information"]
|
70 |
return not any(phrase.lower() in response.lower() for phrase in uncertain_phrases)
|
71 |
|
72 |
-
async def generate_response(prompt):
|
73 |
-
try:
|
74 |
-
response = await client.text_generation(prompt, max_new_tokens=500, temperature=0.7)
|
75 |
-
return response
|
76 |
-
except Exception as e:
|
77 |
-
logger.error(f"Error generating response: {e}")
|
78 |
-
return "I apologize, but I'm having trouble generating a response at the moment. Please try again later."
|
79 |
-
|
80 |
def post_process_response(response):
|
81 |
response = re.sub(r'\b(stupid|dumb|idiotic|foolish)\b', 'mistaken', response, flags=re.IGNORECASE)
|
82 |
|
@@ -94,7 +86,8 @@ communication_expert_crew = Agent(
|
|
94 |
goal='Interpret and rephrase user queries with empathy and respect',
|
95 |
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.""",
|
96 |
verbose=True,
|
97 |
-
allow_delegation=False
|
|
|
98 |
)
|
99 |
|
100 |
response_expert_crew = Agent(
|
@@ -102,32 +95,8 @@ response_expert_crew = Agent(
|
|
102 |
goal='Provide accurate, helpful, and emotionally intelligent responses to user queries',
|
103 |
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.""",
|
104 |
verbose=True,
|
105 |
-
allow_delegation=False
|
106 |
-
|
107 |
-
|
108 |
-
# Task definitions
|
109 |
-
rephrase_task = Task(
|
110 |
-
description="Rephrase the user query with empathy and respect",
|
111 |
-
agent=communication_expert_crew,
|
112 |
-
async_execution=True,
|
113 |
-
context=[
|
114 |
-
{
|
115 |
-
"role": "system",
|
116 |
-
"content": SHARED_CONTEXT
|
117 |
-
}
|
118 |
-
]
|
119 |
-
)
|
120 |
-
|
121 |
-
response_task = Task(
|
122 |
-
description="Provide an accurate and helpful response to the user query",
|
123 |
-
agent=response_expert_crew,
|
124 |
-
async_execution=True,
|
125 |
-
context=[
|
126 |
-
{
|
127 |
-
"role": "system",
|
128 |
-
"content": SHARED_CONTEXT
|
129 |
-
}
|
130 |
-
]
|
131 |
)
|
132 |
|
133 |
# Main function
|
@@ -142,12 +111,17 @@ async def zerodha_support(message, history, username):
|
|
142 |
|
143 |
# Use crewAI for initial query rephrasing
|
144 |
try:
|
145 |
-
rephrase_task
|
|
|
|
|
|
|
|
|
146 |
crew = Crew(
|
147 |
agents=[communication_expert_crew],
|
148 |
tasks=[rephrase_task],
|
149 |
verbose=2
|
150 |
)
|
|
|
151 |
rephrased_query = await crew.kickoff()
|
152 |
except Exception as e:
|
153 |
logger.error(f"Error in CrewAI rephrasing: {e}")
|
@@ -155,12 +129,17 @@ async def zerodha_support(message, history, username):
|
|
155 |
|
156 |
# Generate response using Response Expert
|
157 |
try:
|
158 |
-
response_task
|
|
|
|
|
|
|
|
|
159 |
crew = Crew(
|
160 |
agents=[response_expert_crew],
|
161 |
tasks=[response_task],
|
162 |
verbose=2
|
163 |
)
|
|
|
164 |
response = await crew.kickoff()
|
165 |
except Exception as e:
|
166 |
logger.error(f"Error in CrewAI response generation: {e}")
|
@@ -238,11 +217,10 @@ with gr.Blocks(css=custom_css) as demo:
|
|
238 |
submit_button = gr.Button("Send")
|
239 |
|
240 |
with gr.Column(scale=1):
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
gr.HTML("</div>")
|
246 |
|
247 |
gr.HTML("<h4>Quick Links</h4>")
|
248 |
gr.HTML("<ul><li><a href='https://zerodha.com/varsity/' target='_blank'>Zerodha Varsity</a></li><li><a href='https://console.zerodha.com/' target='_blank'>Zerodha Console</a></li></ul>")
|
|
|
2 |
import sys
|
3 |
import logging
|
4 |
import gradio as gr
|
|
|
5 |
import re
|
6 |
import numpy as np
|
7 |
from sklearn.feature_extraction.text import CountVectorizer
|
8 |
from sklearn.naive_bayes import MultinomialNB
|
9 |
import asyncio
|
10 |
from crewai import Agent, Task, Crew
|
11 |
+
from langchain.llms import HuggingFaceHub
|
12 |
import random
|
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 |
+
# Set up the Mistral model using HuggingFaceHub
|
19 |
try:
|
20 |
+
mistral_llm = HuggingFaceHub(repo_id="mistralai/Mistral-7B-Instruct-v0.2", model_kwargs={"temperature": 0.7, "max_new_tokens": 500})
|
21 |
except Exception as e:
|
22 |
+
logger.error(f"Failed to initialize Mistral model: {e}")
|
23 |
sys.exit(1)
|
24 |
|
25 |
# Shared context for both agents
|
|
|
69 |
uncertain_phrases = ["I'm not sure", "It's possible", "I don't have enough information"]
|
70 |
return not any(phrase.lower() in response.lower() for phrase in uncertain_phrases)
|
71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
72 |
def post_process_response(response):
|
73 |
response = re.sub(r'\b(stupid|dumb|idiotic|foolish)\b', 'mistaken', response, flags=re.IGNORECASE)
|
74 |
|
|
|
86 |
goal='Interpret and rephrase user queries with empathy and respect',
|
87 |
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.""",
|
88 |
verbose=True,
|
89 |
+
allow_delegation=False,
|
90 |
+
llm=mistral_llm
|
91 |
)
|
92 |
|
93 |
response_expert_crew = Agent(
|
|
|
95 |
goal='Provide accurate, helpful, and emotionally intelligent responses to user queries',
|
96 |
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.""",
|
97 |
verbose=True,
|
98 |
+
allow_delegation=False,
|
99 |
+
llm=mistral_llm
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
100 |
)
|
101 |
|
102 |
# Main function
|
|
|
111 |
|
112 |
# Use crewAI for initial query rephrasing
|
113 |
try:
|
114 |
+
rephrase_task = Task(
|
115 |
+
description=f"Rephrase the following user query with empathy and respect: '{sanitized_message}'",
|
116 |
+
agent=communication_expert_crew
|
117 |
+
)
|
118 |
+
|
119 |
crew = Crew(
|
120 |
agents=[communication_expert_crew],
|
121 |
tasks=[rephrase_task],
|
122 |
verbose=2
|
123 |
)
|
124 |
+
|
125 |
rephrased_query = await crew.kickoff()
|
126 |
except Exception as e:
|
127 |
logger.error(f"Error in CrewAI rephrasing: {e}")
|
|
|
129 |
|
130 |
# Generate response using Response Expert
|
131 |
try:
|
132 |
+
response_task = Task(
|
133 |
+
description=f"Provide an accurate and helpful response to the user query: '{rephrased_query}'",
|
134 |
+
agent=response_expert_crew
|
135 |
+
)
|
136 |
+
|
137 |
crew = Crew(
|
138 |
agents=[response_expert_crew],
|
139 |
tasks=[response_task],
|
140 |
verbose=2
|
141 |
)
|
142 |
+
|
143 |
response = await crew.kickoff()
|
144 |
except Exception as e:
|
145 |
logger.error(f"Error in CrewAI response generation: {e}")
|
|
|
217 |
submit_button = gr.Button("Send")
|
218 |
|
219 |
with gr.Column(scale=1):
|
220 |
+
gr.HTML("<div class='user-info'>")
|
221 |
+
user_display = gr.Textbox(label="Logged in as", interactive=False)
|
222 |
+
ticket_number = gr.Textbox(label="Support Ticket", value=generate_ticket_number(), interactive=False)
|
223 |
+
gr.HTML("</div>")
|
|
|
224 |
|
225 |
gr.HTML("<h4>Quick Links</h4>")
|
226 |
gr.HTML("<ul><li><a href='https://zerodha.com/varsity/' target='_blank'>Zerodha Varsity</a></li><li><a href='https://console.zerodha.com/' target='_blank'>Zerodha Console</a></li></ul>")
|