File size: 6,957 Bytes
5b2aed4
 
 
f46801a
29cdc30
f46801a
 
 
 
414a697
9a244e8
 
912dd7d
f46801a
09bef47
 
 
 
912dd7d
9a244e8
 
 
 
 
 
912dd7d
9a244e8
 
 
 
 
 
 
 
912dd7d
9a244e8
 
81887fd
912dd7d
81887fd
 
9a244e8
 
 
 
 
 
 
 
 
 
81887fd
9a244e8
 
 
 
 
 
 
 
 
 
 
 
 
 
81887fd
9a244e8
 
 
 
 
 
 
 
5305f8e
414a697
5b2aed4
 
 
 
 
 
 
 
9a244e8
09bef47
 
 
 
 
9a244e8
09bef47
 
 
 
 
9a244e8
09bef47
 
 
 
9a244e8
 
09bef47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a244e8
09bef47
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
import os
import sys
import logging
import gradio as gr
from huggingface_hub import InferenceClient
import re
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
import asyncio
from crewai import Agent as CrewAgent, Task, Crew
import autogen
from langchain_openai import ChatOpenAI

# ... (previous code remains the same)

# Modify the CrewAI and AutoGen setup
chat_model = ChatOpenAI(model_name="gpt-3.5-turbo")

communication_expert_crew = CrewAgent(
    role='Communication Expert',
    goal='Interpret and rephrase user queries with empathy and respect',
    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.""",
    verbose=True,
    allow_delegation=False,
    llm=chat_model
)

response_expert_crew = CrewAgent(
    role='Response Expert',
    goal='Provide accurate, helpful, and emotionally intelligent responses to user queries',
    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.""",
    verbose=True,
    allow_delegation=False,
    llm=chat_model
)

llm_config = {
    "config_list": [{"model": "gpt-3.5-turbo"}]
}

communication_expert_autogen = autogen.AssistantAgent(
    name="Communication_Expert",
    system_message=SHARED_CONTEXT + """
As the Communication Expert, your primary role is to interpret user queries with the utmost respect and empathy. You should:
1. Rephrase the user's query to ensure it's understood in the most positive and constructive light.
2. Identify and highlight any emotional subtext or concerns in the query.
3. Frame the query in a way that invites a supportive and informative response.
4. Ensure that any potential complaints or frustrations are acknowledged respectfully.

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.""",
    llm_config=llm_config
)

response_expert_autogen = autogen.AssistantAgent(
    name="Response_Expert",
    system_message=SHARED_CONTEXT + """
As the Response Expert, your role is to provide accurate, helpful, and emotionally intelligent responses to user queries. You should:
1. Address the user's question or concern directly and comprehensively.
2. Maintain a tone of respect and empathy throughout your response.
3. Provide clear, factual information about Zerodha's services and policies.
4. When discussing financial matters, include appropriate disclaimers and encourage users to seek professional advice for complex decisions.
5. For complaints or concerns, acknowledge them respectfully and provide constructive guidance or escalation paths.
6. Always uphold Zerodha's reputation for transparency and user-centric service.

Your output should be a complete, informative response that addresses the user's query while demonstrating empathy and respect.""",
    llm_config=llm_config
)

user_proxy = autogen.UserProxyAgent(
    name="User_Proxy",
    human_input_mode="NEVER",
    max_consecutive_auto_reply=1
)

# Main function
async def zerodha_support(message, history):
    try:
        sanitized_message = sanitize_input(message)
        
        if not is_relevant_topic(sanitized_message):
            return "I'm sorry, but I can only assist with queries related to Zerodha's services and trading. Could you please ask a question about your Zerodha account, trading, or our platforms?"
        
        sanitized_message = redact_sensitive_info(sanitized_message)

        # Use crewAI for initial query rephrasing
        try:
            rephrase_task = Task(
                description=f"Rephrase the following user query with empathy and respect: '{sanitized_message}'",
                agent=communication_expert_crew
            )

            crew = Crew(
                agents=[communication_expert_crew],
                tasks=[rephrase_task],
                verbose=2
            )

            rephrased_query = crew.kickoff()
        except Exception as e:
            logger.error(f"Error in CrewAI rephrasing: {e}")
            rephrased_query = sanitized_message  # Fallback to original message if rephrasing fails

        # Use AutoGen for generating the response
        try:
            response = await get_autogen_response(rephrased_query)
        except Exception as e:
            logger.error(f"Error in AutoGen response generation: {e}")
            response = "I apologize, but I'm having trouble generating a response at the moment. Please try again later."

        if not check_response_content(response):
            response += "\n\nPlease note that I cannot provide specific investment advice or guarantee returns. For personalized guidance, please consult with a qualified financial advisor."

        if not check_confidence(response):
            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."

        final_response = post_process_response(response)

        return final_response
    except Exception as e:
        logger.error(f"Error in zerodha_support: {e}")
        return "I apologize, but an error occurred while processing your request. Please try again later."

async def get_autogen_response(query):
    await user_proxy.a_initiate_chat(
        response_expert_autogen,
        message=f"Please provide a respectful and empathetic response to the following query: '{query}'"
    )
    return response_expert_autogen.last_message()["content"]

# Gradio interface setup
demo = gr.ChatInterface(
    zerodha_support,
    chatbot=gr.Chatbot(height=600),
    textbox=gr.Textbox(placeholder="Ask your question about Zerodha here...", container=False, scale=7),
    title="Zerodha Support Assistant",
    description="Ask questions about Zerodha's services, trading, account management, and more. Our multi-agent system ensures respectful and empathetic responses.",
    theme="soft",
    examples=[
        "How do I open a Zerodha account?",
        "I'm frustrated with the recent changes to the Kite platform. Can you help?",
        "What are the risks involved in F&O trading?",
        "I think there's an error in my account statement. What should I do?",
        "Can you explain Zerodha's policy on intraday trading margins?",
        "I'm new to investing. What resources does Zerodha offer for beginners?",
        "How does Zerodha ensure the security of my investments and personal data?"
    ],
)

if __name__ == "__main__":
    demo.launch()