invincible-jha commited on
Commit
3407fb1
1 Parent(s): 81d245d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -45
app.py CHANGED
@@ -1,63 +1,112 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
 
27
 
28
- response = ""
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
 
38
 
39
- response += token
40
- yield response
41
 
 
 
 
 
 
 
42
  """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
 
 
58
  ],
59
  )
60
 
61
-
62
  if __name__ == "__main__":
63
- demo.launch()
 
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
+ import os
4
+ import re
5
 
6
+ # Initialize the client with the Zephyr 7B model
 
 
7
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
9
+ # Shared context for both agents
10
+ 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.
11
 
12
+ Key points about Zerodha:
13
+ 1. India's largest discount broker, known for innovative technology and low-cost trading.
14
+ 2. Flat fee structure: ₹20 per executed order for intraday and F&O trades, zero brokerage for delivery equity investments.
15
+ 3. Main trading platform: Kite (web and mobile).
16
+ 4. Coin platform for commission-free direct mutual fund investments.
17
+ 5. Extensive educational resources through Varsity.
18
+ 6. Additional tools: Sentinel (price alerts) and ChartIQ (advanced charting).
19
+ 7. Console for account management and administrative tasks.
 
20
 
21
+ Always prioritize user safety, ethical investing practices, and transparent communication. Never provide information that could mislead users or bring disrepute to Zerodha."""
 
 
 
 
22
 
23
+ # Communication Expert context
24
+ COMMUNICATION_EXPERT_CONTEXT = SHARED_CONTEXT + """
25
+ As the Communication Expert, your primary role is to interpret user queries with the utmost respect and empathy. You should:
26
+ 1. Rephrase the user's query to ensure it's understood in the most positive and constructive light.
27
+ 2. Identify and highlight any emotional subtext or concerns in the query.
28
+ 3. Frame the query in a way that invites a supportive and informative response.
29
+ 4. Ensure that any potential complaints or frustrations are acknowledged respectfully.
30
 
31
+ 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."""
32
 
33
+ # Response Expert context
34
+ RESPONSE_EXPERT_CONTEXT = SHARED_CONTEXT + """
35
+ As the Response Expert, your role is to provide accurate, helpful, and emotionally intelligent responses to user queries. You should:
36
+ 1. Address the user's question or concern directly and comprehensively.
37
+ 2. Maintain a tone of respect and empathy throughout your response.
38
+ 3. Provide clear, factual information about Zerodha's services and policies.
39
+ 4. When discussing financial matters, include appropriate disclaimers and encourage users to seek professional advice for complex decisions.
40
+ 5. For complaints or concerns, acknowledge them respectfully and provide constructive guidance or escalation paths.
41
+ 6. Always uphold Zerodha's reputation for transparency and user-centric service.
42
 
43
+ Your output should be a complete, informative response that addresses the user's query while demonstrating empathy and respect."""
 
44
 
45
+ def format_prompt(context, message):
46
+ return f"""<s>[INST] <<SYS>>
47
+ {context}
48
+ <</SYS>>
49
+
50
+ {message} [/INST]
51
  """
52
+
53
+ def communication_expert(query):
54
+ prompt = format_prompt(COMMUNICATION_EXPERT_CONTEXT, f"Please rephrase the following user query with empathy and respect: '{query}'")
55
+ response = client.text_generation(prompt, max_new_tokens=200, temperature=0.7)
56
+ return response
57
+
58
+ def response_expert(rephrased_query):
59
+ prompt = format_prompt(RESPONSE_EXPERT_CONTEXT, f"Please provide a respectful and empathetic response to the following query: '{rephrased_query}'")
60
+ response = client.text_generation(prompt, max_new_tokens=500, temperature=0.7)
61
+ return response
62
+
63
+ def post_process_response(response):
64
+ # Remove any potentially disrespectful language
65
+ response = re.sub(r'\b(stupid|dumb|idiotic|foolish)\b', 'mistaken', response, flags=re.IGNORECASE)
66
+
67
+ # Ensure the response ends respectfully
68
+ 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):
69
+ response += "\n\nIs there anything else I can help you with regarding Zerodha's services?"
70
+
71
+ # Add a disclaimer for financial advice
72
+ if re.search(r'\b(invest|trade|buy|sell|market)\b', response, re.IGNORECASE):
73
+ 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."
74
+
75
+ return response
76
+
77
+ def zerodha_support(message, history):
78
+ # Step 1: Communication Expert rephrases the query
79
+ rephrased_query = communication_expert(message)
80
+ print(f"Rephrased query: {rephrased_query}") # Debug print
81
+
82
+ # Step 2: Response Expert generates a response
83
+ initial_response = response_expert(rephrased_query)
84
+ print(f"Initial response: {initial_response}") # Debug print
85
+
86
+ # Step 3: Post-process the response
87
+ final_response = post_process_response(initial_response)
88
+ print(f"Final response: {final_response}") # Debug print
89
+
90
+ return final_response
91
+
92
  demo = gr.ChatInterface(
93
+ zerodha_support,
94
+ chatbot=gr.Chatbot(height=600),
95
+ textbox=gr.Textbox(placeholder="Ask your question about Zerodha here...", container=False, scale=7),
96
+ title="Zerodha Support Assistant",
97
+ description="Ask questions about Zerodha's services, trading, account management, and more. Our multi-agent system ensures respectful and empathetic responses.",
98
+ theme="soft",
99
+ examples=[
100
+ "How do I open a Zerodha account?",
101
+ "I'm frustrated with the recent changes to the Kite platform. Can you help?",
102
+ "What are the risks involved in F&O trading?",
103
+ "I think there's an error in my account statement. What should I do?",
104
+ "Can you explain Zerodha's policy on intraday trading margins?",
105
+ "I'm new to investing. What resources does Zerodha offer for beginners?",
106
+ "How does Zerodha ensure the security of my investments and personal data?"
107
  ],
108
  )
109
 
 
110
  if __name__ == "__main__":
111
+ public_url = demo.launch(share=True, server_name="0.0.0.0", server_port=7860)
112
+ print(f"\n\nSHAREABLE LINK: {public_url}\n\n")