deepali1021 commited on
Commit
60ce1fd
·
verified ·
1 Parent(s): b092604

Update utils/_graph_util.py

Browse files
Files changed (1) hide show
  1. utils/_graph_util.py +155 -156
utils/_graph_util.py CHANGED
@@ -1,157 +1,156 @@
1
- from turtle import st
2
- from typing import TypedDict, Dict
3
- from langgraph.graph import StateGraph, END
4
- from langchain_core.prompts import ChatPromptTemplate
5
- from langchain_core.runnables.graph import MermaidDrawMethod
6
- from IPython.display import display , Image
7
- from langchain_openai import ChatOpenAI
8
- import os
9
- from dotenv import load_dotenv
10
-
11
- from utils._admin_util import create_rag
12
-
13
- class State(TypedDict):
14
- query: str
15
- category: str
16
- sentiment: str
17
- response: str
18
-
19
- def check_api_key():
20
- load_dotenv()
21
- """Verify that the API key is set and valid"""
22
- api_key = os.getenv("OPENAI_API_KEY")
23
- print("api_key", api_key)
24
- if not api_key:
25
- raise ValueError("OpenAI API key not found in environment variables")
26
- return api_key
27
-
28
- api_key = check_api_key()
29
-
30
- llm = ChatOpenAI(
31
- model="gpt-3.5-turbo",
32
- openai_api_key=api_key,
33
- temperature=0.7
34
- )
35
-
36
- def rag(state: State)->State:
37
- rag_chain = create_rag()
38
- # Extract just the query string from the state
39
- query = state["query"]
40
- print("query", query)
41
- response = rag_chain.invoke(query) # Pass the string directly, not a dict
42
- print("response", response)
43
- return {"response": response}
44
-
45
- def categorize(state: State) -> State:
46
- "HR, IT, Transportation"
47
- prompt = ChatPromptTemplate.from_template(
48
- "Categorize the following query into one of these categories: "
49
- "HR, IT, Transportation, Other. Query: {query}"
50
- )
51
- chain = prompt | llm
52
- category = chain.invoke({"query": state["query"]}).content
53
- return {"category": category}
54
-
55
- def analyze_sentiment(state: State) -> State:
56
- prompt = ChatPromptTemplate.from_template(
57
- "Analyze the sentiment of the following customer query"
58
- "Response with either 'Position', 'Neutral' , or 'Negative'. Query: {query}"
59
- )
60
- chain = prompt | llm
61
- sentiment = chain.invoke({"query": state["query"]}).content
62
- return {"sentiment": sentiment}
63
-
64
-
65
- def handle_hr(state: State)->State:
66
- prompt = ChatPromptTemplate.from_template(
67
- "Provide a HR support response to the following query : {query}"
68
- )
69
- chain = prompt | llm
70
- response = chain.invoke({"query": state["query"]}).content
71
- return {"response": response}
72
-
73
- def handle_it(state: State)->State:
74
- prompt = ChatPromptTemplate.from_template(
75
- "Provide a IT support response to the following query : {query}"
76
- )
77
- chain = prompt | llm
78
- response = chain.invoke({"query": state["query"]}).content
79
- return {"response": response}
80
-
81
- def handle_transportation(state: State)->State:
82
- prompt = ChatPromptTemplate.from_template(
83
- "Provide a transportation support response to the following query : {query}"
84
- )
85
- chain = prompt | llm
86
- response = chain.invoke({"query": state["query"]}).content
87
- return {"response": response}
88
-
89
- def handle_general(state: State)->State:
90
- prompt = ChatPromptTemplate.from_template(
91
- "Provide a general support response to the following query : {query}"
92
- )
93
- chain = prompt | llm
94
- response = chain.invoke({"query": state["query"]}).content
95
- return {"response": response}
96
-
97
- def escalate(state: State)->State:
98
- return {"response": "This query has been escalate to a human agent due to its negative sentiment"}
99
-
100
- def route_query(state: State)->State:
101
- if state["sentiment"] == "Negative":
102
- return "escalate"
103
- elif state["category"] == "HR":
104
- return "handle_hr"
105
- elif state["category"] == "IT":
106
- return "handle_it"
107
- elif state["category"] == "Transportation":
108
- return "handle_transportation"
109
- else:
110
- return "handle_general"
111
-
112
- def rout_to_agent(state: State)->State:
113
- if "i don't know" in state["response"].lower():
114
- print(state["response"])
115
- print("return analyze_sentiment")
116
- return "analyze_sentiment"
117
- else:
118
- return "END"
119
-
120
-
121
- def run_customer_support(query: str)->Dict[str, str]:
122
- workflow = StateGraph(State)
123
- workflow.add_node("categorize", categorize)
124
- workflow.add_node("rag", rag)
125
- workflow.add_node("analyze_sentiment", analyze_sentiment)
126
- workflow.add_node("handle_hr", handle_hr)
127
- workflow.add_node("handle_it", handle_it)
128
- workflow.add_node("handle_transportation", handle_transportation)
129
- workflow.add_node("escalate", escalate)
130
-
131
- workflow.add_edge("categorize", "rag")
132
- workflow.add_conditional_edges("rag", rout_to_agent, {"analyze_sentiment": "analyze_sentiment", "END": END})
133
- workflow.add_conditional_edges(
134
- "analyze_sentiment",
135
- route_query,
136
- {
137
- "handle_hr" : "handle_hr",
138
- "handle_it" : "handle_it",
139
- "handle_transportation" : "handle_transportation",
140
- "escalate": "escalate"
141
- }
142
- )
143
-
144
- workflow.add_edge("handle_hr", END)
145
- workflow.add_edge("handle_it", END)
146
- workflow.add_edge("handle_transportation", END)
147
- workflow.add_edge("escalate", END)
148
-
149
- workflow.set_entry_point("categorize")
150
-
151
- app = workflow.compile()
152
- results = app.invoke({"query": query})
153
- return {
154
- "category": results.get('category', ''), # Returns empty string if key missing
155
- "sentiment": results.get('sentiment', ''),
156
- "response": results['response']
157
  }
 
1
+ from typing import TypedDict, Dict
2
+ from langgraph.graph import StateGraph, END
3
+ from langchain_core.prompts import ChatPromptTemplate
4
+ from langchain_core.runnables.graph import MermaidDrawMethod
5
+ from IPython.display import display , Image
6
+ from langchain_openai import ChatOpenAI
7
+ import os
8
+ from dotenv import load_dotenv
9
+
10
+ from utils._admin_util import create_rag
11
+
12
+ class State(TypedDict):
13
+ query: str
14
+ category: str
15
+ sentiment: str
16
+ response: str
17
+
18
+ def check_api_key():
19
+ load_dotenv()
20
+ """Verify that the API key is set and valid"""
21
+ api_key = os.getenv("OPENAI_API_KEY")
22
+ print("api_key", api_key)
23
+ if not api_key:
24
+ raise ValueError("OpenAI API key not found in environment variables")
25
+ return api_key
26
+
27
+ api_key = check_api_key()
28
+
29
+ llm = ChatOpenAI(
30
+ model="gpt-3.5-turbo",
31
+ openai_api_key=api_key,
32
+ temperature=0.7
33
+ )
34
+
35
+ def rag(state: State)->State:
36
+ rag_chain = create_rag()
37
+ # Extract just the query string from the state
38
+ query = state["query"]
39
+ print("query", query)
40
+ response = rag_chain.invoke(query) # Pass the string directly, not a dict
41
+ print("response", response)
42
+ return {"response": response}
43
+
44
+ def categorize(state: State) -> State:
45
+ "HR, IT, Transportation"
46
+ prompt = ChatPromptTemplate.from_template(
47
+ "Categorize the following query into one of these categories: "
48
+ "HR, IT, Transportation, Other. Query: {query}"
49
+ )
50
+ chain = prompt | llm
51
+ category = chain.invoke({"query": state["query"]}).content
52
+ return {"category": category}
53
+
54
+ def analyze_sentiment(state: State) -> State:
55
+ prompt = ChatPromptTemplate.from_template(
56
+ "Analyze the sentiment of the following customer query"
57
+ "Response with either 'Position', 'Neutral' , or 'Negative'. Query: {query}"
58
+ )
59
+ chain = prompt | llm
60
+ sentiment = chain.invoke({"query": state["query"]}).content
61
+ return {"sentiment": sentiment}
62
+
63
+
64
+ def handle_hr(state: State)->State:
65
+ prompt = ChatPromptTemplate.from_template(
66
+ "Provide a HR support response to the following query : {query}"
67
+ )
68
+ chain = prompt | llm
69
+ response = chain.invoke({"query": state["query"]}).content
70
+ return {"response": response}
71
+
72
+ def handle_it(state: State)->State:
73
+ prompt = ChatPromptTemplate.from_template(
74
+ "Provide a IT support response to the following query : {query}"
75
+ )
76
+ chain = prompt | llm
77
+ response = chain.invoke({"query": state["query"]}).content
78
+ return {"response": response}
79
+
80
+ def handle_transportation(state: State)->State:
81
+ prompt = ChatPromptTemplate.from_template(
82
+ "Provide a transportation support response to the following query : {query}"
83
+ )
84
+ chain = prompt | llm
85
+ response = chain.invoke({"query": state["query"]}).content
86
+ return {"response": response}
87
+
88
+ def handle_general(state: State)->State:
89
+ prompt = ChatPromptTemplate.from_template(
90
+ "Provide a general support response to the following query : {query}"
91
+ )
92
+ chain = prompt | llm
93
+ response = chain.invoke({"query": state["query"]}).content
94
+ return {"response": response}
95
+
96
+ def escalate(state: State)->State:
97
+ return {"response": "This query has been escalate to a human agent due to its negative sentiment"}
98
+
99
+ def route_query(state: State)->State:
100
+ if state["sentiment"] == "Negative":
101
+ return "escalate"
102
+ elif state["category"] == "HR":
103
+ return "handle_hr"
104
+ elif state["category"] == "IT":
105
+ return "handle_it"
106
+ elif state["category"] == "Transportation":
107
+ return "handle_transportation"
108
+ else:
109
+ return "handle_general"
110
+
111
+ def rout_to_agent(state: State)->State:
112
+ if "i don't know" in state["response"].lower():
113
+ print(state["response"])
114
+ print("return analyze_sentiment")
115
+ return "analyze_sentiment"
116
+ else:
117
+ return "END"
118
+
119
+
120
+ def run_customer_support(query: str)->Dict[str, str]:
121
+ workflow = StateGraph(State)
122
+ workflow.add_node("categorize", categorize)
123
+ workflow.add_node("rag", rag)
124
+ workflow.add_node("analyze_sentiment", analyze_sentiment)
125
+ workflow.add_node("handle_hr", handle_hr)
126
+ workflow.add_node("handle_it", handle_it)
127
+ workflow.add_node("handle_transportation", handle_transportation)
128
+ workflow.add_node("escalate", escalate)
129
+
130
+ workflow.add_edge("categorize", "rag")
131
+ workflow.add_conditional_edges("rag", rout_to_agent, {"analyze_sentiment": "analyze_sentiment", "END": END})
132
+ workflow.add_conditional_edges(
133
+ "analyze_sentiment",
134
+ route_query,
135
+ {
136
+ "handle_hr" : "handle_hr",
137
+ "handle_it" : "handle_it",
138
+ "handle_transportation" : "handle_transportation",
139
+ "escalate": "escalate"
140
+ }
141
+ )
142
+
143
+ workflow.add_edge("handle_hr", END)
144
+ workflow.add_edge("handle_it", END)
145
+ workflow.add_edge("handle_transportation", END)
146
+ workflow.add_edge("escalate", END)
147
+
148
+ workflow.set_entry_point("categorize")
149
+
150
+ app = workflow.compile()
151
+ results = app.invoke({"query": query})
152
+ return {
153
+ "category": results.get('category', ''), # Returns empty string if key missing
154
+ "sentiment": results.get('sentiment', ''),
155
+ "response": results['response']
 
156
  }