-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent.py
More file actions
243 lines (203 loc) · 8.1 KB
/
Copy pathagent.py
File metadata and controls
243 lines (203 loc) · 8.1 KB
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
from dotenv import load_dotenv
# Imports for Graph and state
from typing import TypedDict, Literal
from langgraph.graph import StateGraph, END
# Imports for LLM and prompts
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain_core.prompts import ChatPromptTemplate
# Load environmant variables
load_dotenv()
# Define the graph state
class TicketState(TypedDict):
"""
Represents the state of the customer support ticket as it moves through the graph.
"""
query: str
category: Literal[
"Technical Support",
"Billing Inquiry",
"Product Feedback",
"General Question",
"Unclear"
]
response: str
# Define the LLM
llm = ChatGoogleGenerativeAI(model="gemini-1.5-flash-latest", temperature=0)
# Define the prompt for the classification tasks
classification_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"""You are an AI assistant specialized in classifying customer support tickets.
Your goal is to accurately categorize the user's query into one of the following categories:
'Technical Support', 'Billing Inquiry', 'Product Feedback', 'General Question'.
If the query does not fit clearly into any of these, classify it as 'Unclear'.
Respond ONLY with the exact category name and nothing else.""",
),
("human", "Customer query: {query}"),
]
)
# Define prompts for each response type
technical_response_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful and concise customer support agent for technical issues.",
),
("human", "Customer query: {query}"),
]
)
billing_response_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful and concise customer support agent for billing inquiries.",
),
("human", "Customer query: {query}"),
]
)
feedback_response_prompt = ChatPromptTemplate.from_messages(
[
("system", "You are a friendly and concise customer support agent."),
("human", "Customer query: {query}"),
]
)
general_response_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful and concise customer support agent for general questions.",
),
("human", "Customer query: {query}"),
]
)
unclear_response_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a customer support agent. The user's query was unclear. Politely ask them to rephrase.",
),
("human", "Customer query: {query}"),
]
)
# Define the nodes
# Classification node
def classify_ticket(state: TicketState) -> TicketState:
"""Classifies the incoming customer query using the Gemini LLM."""
print("\n---CLASSIFYING TICKET---")
query = state["query"]
classification_chain = classification_prompt | llm
predicted_category = classification_chain.invoke({"query": query}).content.strip()
valid_categories = {
"Technical Support",
"Billing Inquiry",
"Product Feedback",
"General Question",
"Unclear"
}
if predicted_category not in valid_categories:
print(
f"WARNING: LLM returned an unexpected category: '{predicted_category}'. Defaulting to 'Unclear'."
)
predicted_category = "Unclear"
print(f"Ticket classified as: {predicted_category}")
return {"category": predicted_category}
# Handler nodes
def handle_technical(state: TicketState) -> TicketState:
"""Generates a response for a 'Technical Support' ticket."""
print("\n---HANDLING TECHNICAL ISSUE---")
response_chain = technical_response_prompt | llm
generated_response = response_chain.invoke({"query": state["query"]}).content
print(f"Technical Response: {generated_response}")
return {"response": generated_response}
def handle_billing(state: TicketState) -> TicketState:
"""Generates a response for a 'Billing Inquiry' ticket."""
print("\n---HANDLING BILLING INQUIRY---")
response_chain = billing_response_prompt | llm
generated_response = response_chain.invoke({"query": state["query"]}).content
print(f"Billing Response: {generated_response}")
return {"response": generated_response}
def handle_feedback(state: TicketState) -> TicketState:
"""Generates a response for a 'Product Feedback' ticket."""
print("\n---HANDLING PRODUCT FEEDBACK---")
response_chain = feedback_response_prompt | llm
generated_response = response_chain.invoke({"query": state["query"]}).content
print(f"Feedback Response: {generated_response}")
return {"response": generated_response}
def handle_general(state: TicketState) -> TicketState:
"""Generates a response for a 'General Question' ticket."""
print("\n---HANDLING GENERAL QUESTION---")
response_chain = general_response_prompt | llm
generated_response = response_chain.invoke({"query": state["query"]}).content
print(f"General Response: {generated_response}")
return {"response": generated_response}
def handle_unclear(state: TicketState) -> TicketState:
"""Generates a response for an 'Unclear' ticket."""
print("\n---HANDLING UNCLEAR TICKET---")
response_chain = unclear_response_prompt | llm
generated_response = response_chain.invoke({"query": state["query"]}).content
print(f"Unclear Response: {generated_response}")
return {"response": generated_response}
# --Define routing logic --
# The router function for our conditional edges.
def route_ticket(state: TicketState) -> str:
"""Routes the ticket to the appropriate handler node based on its classified category."""
print("---ROUTING TICKET---")
category = state["category"]
print(f"Routing based on category: {category}")
if category == "Technical Support":
return "handle_technical"
elif category == "Billing Inquiry":
return "handle_billing"
elif category == "Product Feedback":
return "handle_feedback"
elif category == "General Question":
return "handle_general"
else:
return "handle_unclear"
#create langgraph - put it all together
def build_agent_graph():
# Initialize the graph with our TicketState.
workflow = StateGraph(TicketState)
# Add all our functions as nodes in the graph.
workflow.add_node("classify_ticket", classify_ticket)
workflow.add_node("handle_technical", handle_technical)
workflow.add_node("handle_billing", handle_billing)
workflow.add_node("handle_feedback", handle_feedback)
workflow.add_node("handle_general", handle_general)
workflow.add_node("handle_unclear", handle_unclear)
# Set the entry point. All tickets start here.
workflow.set_entry_point("classify_ticket")
# Add conditional edges from the classification node.
# This is where the routing logic runs.
workflow.add_conditional_edges(
"classify_ticket",
route_ticket,
)
# After each handler, the process is complete.
workflow.add_edge("handle_technical", END)
workflow.add_edge("handle_billing", END)
workflow.add_edge("handle_feedback", END)
workflow.add_edge("handle_general", END)
workflow.add_edge("handle_unclear", END)
# Compile the graph into a runnable application.
app = workflow.compile()
return app
#run the agent with test queries
if __name__ == "__main__":
app = build_agent_graph()
print("\n--- Running Customer Support Agent ---")
test_queries = [
"My Wi-Fi keeps disconnecting, how can I fix this?",
"I see an unfamiliar charge of $100 on my last statement.",
"I love the new dark mode feature in your app!",
"What payment methods do you accept?",
"I need help with... something. It's not working.",
]
for query in test_queries:
print(f"\nProcessing: '{query}'")
initial_state = {"query": query, "category": "Unclear", "response": ""}
final_state = app.invoke(initial_state)
print(f"\nFinal State: {final_state}")
print("=" * 60)
print("\nAgent execution finished.")