lorashen commited on
Commit
e5ec5ab
·
verified ·
1 Parent(s): 400312c

upload langgraph examples

Browse files
examples/langgraph/eval.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import re
3
+ import requests
4
+ from datetime import date,timedelta
5
+ from openai import OpenAI
6
+ import csv
7
+
8
+ def resolve(slot):
9
+ pos=slot.find("place_name")
10
+ if pos!=-1:
11
+ bgpos=slot[pos:].find(":")
12
+ citypos=slot[pos+bgpos:].find("'")
13
+ oldcity=slot[pos+bgpos+1:pos+bgpos+citypos]
14
+ oldcity=oldcity.strip()
15
+ if oldcity=="my city":
16
+ newcity="new york"
17
+ slot=slot[:pos+bgpos+1]+str(newcity)+slot[pos+bgpos+citypos:]
18
+ pos=slot.find("date")
19
+ if pos!=-1:
20
+ bgpos=slot[pos:].find(":")
21
+ datepos=slot[pos+bgpos:].find("'")
22
+ olddate=slot[pos+bgpos+1:pos+bgpos+datepos]
23
+ olddate=olddate.strip()
24
+ today=date.today()
25
+ weekday=date.isoweekday(today)% 7
26
+ #print(today)
27
+ #print(weekday)
28
+ newdate2=None
29
+ if olddate=="today":
30
+ newdate=str(today)
31
+ elif olddate=="tomorrow":
32
+ newdate=today+timedelta(days=1)
33
+ elif olddate=="this week":
34
+ weekday=date.isoweekday(today)% 7
35
+ newdate2=today+ timedelta(days=7-weekday)
36
+ newdate=today-timedelta(days=weekday-1)
37
+ elif olddate=="last week":
38
+ weekday=date.isoweekday(today)% 7
39
+ newdate2=today-timedelta(days=weekday)
40
+ newdate=today-timedelta(days=weekday+6)
41
+
42
+ elif olddate=="this weekend":
43
+ weekday=date.isoweekday(today)% 7
44
+ newdate=today+timedelta(days=6-weekday)
45
+ newdate2=today+timedelta(days=7-weekday)
46
+ elif olddate=="sunday":
47
+ weekday=date.isoweekday(today)% 7
48
+ newdate=today+timedelta(7-weekday)
49
+ elif olddate=="august fifteenth":
50
+ if str(today).find("-")!=-1:
51
+ ypos=str(today).find("-")
52
+ newdate=str(today)[:ypos+1]+"08-15"
53
+ else:
54
+ newdate="08-15"
55
+ else:
56
+ newdate=olddate
57
+ #print(slot)
58
+ slot=slot[:pos+bgpos+1]+str(newdate)+slot[pos+bgpos+datepos:]
59
+ if newdate2:
60
+ slot=slot+",'date2:"+str(newdate2)+"'"
61
+ #print(slot)
62
+ pos=slot.find("timeofday")
63
+ oldtimeofday=""
64
+ if pos!=-1:
65
+ bgpos=slot[pos:].find(":")
66
+ datepos=slot[pos+bgpos:].find("'")
67
+ oldtimeofday=slot[pos+bgpos+1:pos+bgpos+datepos]
68
+ oldtimeofday=oldtimeofday.strip()
69
+ cpos=slot[pos:].rfind(",")
70
+ if cpos!=-1:
71
+ slot=slot[:cpos]+slot[pos+bgpos+datepos+1:]
72
+ else:
73
+ cpos=slot[pos:].find(",")
74
+ if cpos==-1:
75
+ cbpos=slot[:pos].rfind(",")
76
+ if cbpos==-1:
77
+ slot=slot[:pos]+slot[pos+bgpos+datepos+1:]
78
+ else:
79
+ slot=slot[:cbpos]+slot[pos+bgpos+datepos+1:]
80
+ else:
81
+ slot=slot[:pos]+slot[cpos+1:]
82
+ pos=slot.find("time:")
83
+ if pos==-1:
84
+ pos=slot.find("time :")
85
+ if pos!=-1:
86
+ bgpos=slot[pos:].find(":")
87
+ timepos=slot[pos+bgpos:].find("'")
88
+ oldtime=slot[pos+bgpos+1:pos+bgpos+timepos]
89
+ oldtime=oldtime.strip()
90
+ newtime=oldtime.replace("five","05:00").replace("six","06:00").replace("nine","09:00").replace("ten","10:00").replace("three","3:00").replace("one","1:00")
91
+ if not(newtime.endswith("am") or newtime.endswith("pm")):
92
+ if oldtimeofday=="morning":
93
+ newtime=newtime+" am"
94
+ elif oldtimeofday=="evening":
95
+ newtime=newtime+" pm"
96
+ elif oldtimeofday.find("afternoon")!=-1:
97
+ newtime=newtime+" pm"
98
+ #print(slot)
99
+ slot=slot[:pos]+"time:"+str(newtime)+slot[pos+bgpos+timepos:]
100
+ #print(slot)
101
+ else:
102
+ if oldtimeofday.find("afternoon")!=-1:
103
+ newtime="12:00"
104
+ newtime2="17:00"
105
+ #print(slot)
106
+ slot=slot+",'from_time:"+newtime+"','to_time:"+newtime2+"'"
107
+ #print(slot)
108
+ pos=slot.find("time2:")
109
+ if pos==-1:
110
+ pos=slot.find("time2 :")
111
+ if pos!=-1:
112
+ bgpos=slot[pos:].find(":")
113
+ timepos=slot[pos+bgpos:].find("'")
114
+ oldtime=slot[pos+bgpos+1:pos+bgpos+timepos]
115
+ oldtime=oldtime.strip()
116
+ newtime=oldtime.replace("five","05:00").replace("six","06:00").replace("nine","09:00").replace("ten","10:00").replace("three","3:00").replace("one","1:00")
117
+ if not(newtime.endswith("am") or newtime.endswith("pm")):
118
+ if oldtimeofday=="morning":
119
+ newtime=newtime+" am"
120
+ elif oldtimeofday=="evening":
121
+ newtime=newtime+" pm"
122
+ elif oldtimeofday.find("afternoon")!=-1:
123
+ newtime=newtime+" pm"
124
+ #print(slot)
125
+ slot=slot[:pos]+"to_time:"+str(newtime)+slot[pos+bgpos+timepos:]
126
+ slot=slot.replace("'time:","'from_time:")
127
+
128
+
129
+ return slot
130
+ def read_data(file_path):
131
+ queries=[]
132
+ with open(file_path, newline='') as csvfile:
133
+ spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
134
+ count=0
135
+ for row in spamreader:
136
+ if count==0:
137
+ count+=1
138
+ continue
139
+ #print(row[2])
140
+ #print(len(row))
141
+ iid=row[0]
142
+ slot=row[3]
143
+ slot=slot.strip('[]')
144
+ slot=resolve(slot)
145
+ query={"iid":iid,"query":row[1],"intent":row[2],"slot":slot}#,"slots":slot,"domain":row[4]}
146
+ queries.append(query)
147
+ return queries
148
+ if __name__=="__main__":
149
+ client = OpenAI()
150
+ tasks=read_data("~/data/test.csv")
151
+ intp=re.compile(r"intent:[a-z_]+[,\\n]")
152
+ resp=re.compile(r'{"code":"SUCCESS","data"(.)+')#[":, \}\{a-zA-Z0-9\_]+,"msg":".."}')
153
+ for i in range(70,100):
154
+ print("-----*****------")
155
+ print(i)
156
+ data=[]
157
+ with open(str(i)+".log") as f:
158
+ lines=f.readlines()
159
+ for line in lines:
160
+ if line.find("whole_manager")!=-1 and line.find("receives the following")!=-1:
161
+ continue
162
+ else:
163
+ data.append(line)
164
+ content="\n".join(data)
165
+ intentf=intp.findall(content)
166
+ goldintent=tasks[i]["intent"]
167
+ if intentf:
168
+ intent=intentf[-1]
169
+ if intent.find("weather")!=-1 or intent.find("news_query")!=-1 or intent.find("qa")!=-1 or intent.find("stock")!=-1 or intent.find("general")!=-1 or intent.find("currency")!=-1:
170
+ if goldintent.find("weather")!=-1 or goldintent.find("news_query")!=-1 or goldintent.find("qa")!=-1 or goldintent.find("stock")!=-1 or goldintent.find("general")!=-1 or goldintent.find("currency")!=-1:
171
+ if content.find("\"results\"")==-1 and content.find("\"data\"")==-1 and content.find("\"success\"")==-1:
172
+ print("ChatCompletionMessage(content='the result is wrong. no server response.')")
173
+ continue
174
+ else:
175
+ print("ChatCompletionMessage(content='')")
176
+ else:
177
+ print("ChatCompletionMessage(content='the result is wrong. intent error.')")
178
+ continue
179
+ #pass
180
+ else:
181
+ resf= resp.search(content)
182
+ if resf:
183
+ sizer=len(resf.groups())
184
+ res=resf.group(sizer-1)
185
+ msg=[{"role": "system", "content":"please judge the following result is right or wrong. if slot is {} and result also {}, it is right. if slot are same, it is right. If intent is datetime_query, then the slot date:"+str(date.today())+" can be neglected. The slot change_to and change_amount are not the same. if time is same, no matter if has am/pm, it is right. if slot music_genre or event_name has difference, then can neglect it. if slot is descriptor:all, then can neglect it, other descriptor can not neglect. the slot person is same with slot from_person and to_person. if slot is query:song name, can be neglected. the place_name will be resolved, so if it is added by state name and country name, it is right."},{"role":"user", "content":"The golden slot is :{"+tasks[i]["slot"]+"}. The result is "+res}],
186
+ print(msg)
187
+ completion = client.chat.completions.create(
188
+ model="gpt-4",
189
+ temperature=0.0,
190
+ messages=[{"role": "system", "content":"please judge the following result is right or wrong. if slot is {} and result also {}, it is right. if slot are same, it is right. If intent is datetime_query, then the slot date:"+str(date.today())+" can be neglected. The slot change_to and change_amount are not the same. if time is same, no matter if has am/pm, it is right. if slot music_genre or event_name has difference, then can neglect it. if slot is descriptor:all, then can neglect it, other descriptor can not neglect. the slot person is same with slot from_person and to_person. if slot is query:song name, can be neglected. the place_name will be resolved, so if it is added by state name and country name, it is right."},{"role":"user", "content":"The golden slot is :{"+tasks[i]["slot"]+"}. The result is "+res}],
191
+ )
192
+ print(completion.choices[0].message)
193
+ else:
194
+ print("ChatCompletionMessage(content='the result is wrong')")
195
+ continue
196
+ else:
197
+ if content.find("\"results\"")==-1 and content.find("\"data\"")==-1 and content.find("\"success\"")==-1:
198
+ print("ChatCompletionMessage(content='the result is wrong. no server response.')")
199
+ continue
200
+ if goldintent.find("weather")!=-1 or goldintent.find("news_query")!=-1 or goldintent.find("qa")!=-1 or goldintent.find("stock")!=-1 or goldintent.find("general")!=-1 or goldintent.find("currency")!=-1:
201
+ msg=[{"role": "system", "content":"please judge the following content finish the task is right or wrong. Must has the server response ,if not, it's wrong. if intent is general_quirky, if it's a chit-chat like 'are you happy', and there is no chit-chat reply to user, it is wrong. If intent is weather_query, need to provide the weather condition, and if no weather condition, it is wrong. if intent is qa, the response need to provide the answer to the question, and if only provide url, it is wrong. if ask for currency, the result need provide the conversion rate, the currency name may be Proper Noun, it is right. also need to check if the annotaion are the same with server response"},{"role": "user", "content": "the task is "+tasks[i]["query"]+". The annotation is "+tasks[i]["slot"]+"\n"+"\n".join(data)+"\nyour answer is :"}],
202
+ print(msg)
203
+ try:
204
+ completion = client.chat.completions.create(
205
+ model="gpt-4",
206
+ temperature=0.0,
207
+ messages=[{"role": "system", "content":"please judge the following content finish the task is right or wrong. Must has the server response ,if not, it's wrong. if intent is general_quirky, if it's a chit-chat like 'are you happy', and there is no chit-chat reply to user, it is wrong. If intent is weather_query, need to provide the weather condition, and if no weather condition, it is wrong. if intent is qa, the response need to provide the infomation to the question, and if only provide url, it is wrong. if ask for currency, the result need provide the conversion rate, the currency name may be Proper Noun, it is right. also need to check if the annotaion are the same with server response"},{"role": "user", "content": "the task is "+tasks[i]["query"]+". The annotation is "+tasks[i]["slot"]+"\n"+"\n".join(data)+"\nyour answer is :"}],
208
+ )
209
+
210
+ print(completion.choices[0].message)
211
+ except:
212
+ completion = client.chat.completions.create(
213
+ model="gpt-4",
214
+ temperature=0.0,
215
+ messages=[{"role": "system", "content":"please judge the following content finish the task is right or wrong. Must has the server response ,if not, it's wrong. if intent is general_quirky, if it's a chit-chat like 'are you happy', and there is no chit-chat reply to user, it is wrong. If intent is weather_query, need to provide the weather condition, and if no weather condition, it is wrong. if intent is qa, the response need to provide the answer to the question, and if only provide url, it is wrong. if ask for currency, the result need provide the conversion rate, the currency name may be Proper Noun, it is right. also need to check if the annotaion are the same with server response"},{"role": "user", "content": "the task is "+tasks[i]["query"]+". The annotation is "+tasks[i]["slot"]+"\n"+"\n".join(data)[-16000:]+"\nyour answer is :"}],
216
+ )
217
+ print(completion.choices[0].message)
218
+
219
+
220
+ else:
221
+ msg=[{"role": "system", "content":"please judge the following content finish the task is right or wrong. Must has the server response {\"code\":\"SUCCESS\"},if not, it's wrong. if response is not supported intent, it is wrong."},{"role": "user", "content": "the task is "+tasks[i]["query"]+". The annotation is "+tasks[i]["slot"]+"\n"+"\n".join(data)+"\nyour answer is :"}],
222
+ print(msg)
223
+ try:
224
+ completion = client.chat.completions.create(
225
+ model="gpt-4",
226
+ temperature=0.0,
227
+ messages=[{"role": "system", "content":"please judge the following content finish the task is right or wrong. Must has the server response {\"code\":\"SUCCESS\"},if not, it's wrong. if response is not supported intent, it is wrong. If the server response need further more information, it is right."},{"role": "user", "content": "the task is "+tasks[i]["query"]+". The annotation is "+tasks[i]["slot"]+"\n"+"\n".join(data)+"\nyour answer is :"}],
228
+ )
229
+
230
+ print(completion.choices[0].message)
231
+ except:
232
+ completion = client.chat.completions.create(
233
+ model="gpt-4",
234
+ temperature=0.0,
235
+ messages=[{"role": "system", "content":"please judge the following content finish the task is right or wrong. Must has the server response {\"code\":\"SUCCESS\"},if not, it's wrong. if response is not supported intent, it is wrong. If the server response need further more information, it is right."},{"role": "user", "content": "the task is "+tasks[i]["query"]+". The annotation is "+tasks[i]["slot"]+"\n"+"\n".join(data)[-16000:]+"\nyour answer is :"}],
236
+ )
237
+
238
+ print(completion.choices[0].message)
239
+
examples/langgraph/eval.sh ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ python3 eval.py > eval.log
2
+ python3 stat.py
examples/langgraph/run.sh CHANGED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ for f in $(seq 0 99);
3
+ do
4
+ echo $f
5
+ timeout 240s python3 test.py $f > $f.log
6
+ done
examples/langgraph/stat.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ wrong=0
3
+ right=0
4
+ wrongcount=0
5
+ rightcount=0
6
+ judgesent=re.compile(r"ChatCompletionMessage")
7
+ with open("eval.log") as f:
8
+ lines=f.readlines()
9
+ for line in lines:
10
+ lowline=line.lower()
11
+ if line.startswith("-----**"):
12
+ if wrong>0:
13
+ wrongcount+=1
14
+ elif right>0:
15
+ rightcount+=1
16
+ else:
17
+ print("error")
18
+ wrong=0
19
+ right=0
20
+ elif judgesent.match(line):
21
+ if lowline.find("wrong")!=-1 or lowline.find("incorrect")!=-1 or lowline.find("not completed")!=-1:
22
+ wrong+=1
23
+ elif lowline.find("right")!=-1 or lowline.find("correct")!=-1:
24
+ right+=1
25
+ elif lowline.find("content=''")!=-1:
26
+ pass
27
+ else:
28
+ print("error")
29
+ if wrong>0:
30
+ wrongcount+=1
31
+ else:
32
+ rightcount+=1
33
+ acc=float(rightcount)/100
34
+ print(acc,"right",rightcount,"wrong",wrongcount)
examples/langgraph/test.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Annotated, List
2
+
3
+ from langchain_core.tools import tool
4
+ from datetime import date, datetime
5
+ import requests
6
+ from typing_extensions import TypedDict
7
+ import csv
8
+ import sys
9
+ import json
10
+ @tool
11
+ def time_tool() -> str:
12
+ """get today's date"""
13
+ results = date.today()
14
+ return str(results)
15
+
16
+
17
+ @tool
18
+ def request_tool(url: Annotated[str, "the url to be requested"]) -> str:
19
+ """send request using get method to the url"""
20
+ response=requests.get(url)
21
+ print(response.text)
22
+ return response.text
23
+
24
+
25
+ from typing import List, Optional
26
+ from typing_extensions import Literal
27
+ from langchain_core.language_models.chat_models import BaseChatModel
28
+
29
+ from langgraph.graph import StateGraph, MessagesState, START, END
30
+ from langgraph.types import Command
31
+ from langchain_core.messages import HumanMessage, trim_messages
32
+
33
+
34
+ def make_supervisor_node(llm: BaseChatModel, members: list[str]) -> str:
35
+ options = ["FINISH"] + members
36
+ system_prompt = (
37
+ "You are a supervisor tasked with managing a conversation between the"
38
+ f" following workers to finish the first user's cmd: {members}. Given the following user request,"
39
+ " respond with the worker to act next. you are controlling smart home system, you have intent, time, location, and url agent and request to complete the user's task. You should first use intent to complete the intent prediction. Then if the result has time or location params, please try to ask time or location to solve the time and location. At last you should choose the url using url agent, and then use request to send and receive request to the url such as weather server and then use genresponse to generate response, then finalize the task. Even if the request's response is need further information or is a question, do not further answer the question, just finish the task."
40
+ " The response need to be the worker to act next, for example: {\"next\": \"FINISH\"}. When finished,"
41
+ " respond with FINISH. the data in json."
42
+ )
43
+
44
+ class Router(TypedDict):
45
+ """Worker to route to next. If no workers needed, route to FINISH."""
46
+
47
+ next: Literal[*options]
48
+
49
+ def supervisor_node(state: MessagesState) -> Command[Literal[*members, "__end__"]]:
50
+ """An LLM-based router."""
51
+ messages = [
52
+ {"role": "system", "content": system_prompt},
53
+ ] + state["messages"]
54
+ response = llm.with_structured_output(Router).invoke(messages)
55
+ print(response)
56
+ goto = json.loads(response)["next"]
57
+ if goto == "FINISH":
58
+ goto = END
59
+
60
+ return Command(goto=goto)
61
+
62
+ return supervisor_node
63
+
64
+
65
+ from langchain_core.messages import HumanMessage
66
+ from langchain_openai import ChatOpenAI
67
+ from langgraph.prebuilt import create_react_agent
68
+
69
+ llm = ChatOpenAI(model="gpt-4",temperature=0)
70
+ #llm = ChatOpenAI(model="gpt-4o",temperature=0)
71
+ #json_llm = llm.bind(response_format={"type": "json_object"})
72
+ #structured_llm = llm.with_structured_output(method="json_mode", include_raw=True)
73
+ intent_agent = create_react_agent(llm, tools=[],state_modifier=(
74
+ "read the examples and results, predict intent for the sentence. for 'set the alarm to two pm', first predict the domain, as domain:alarm, then the intent and slots, as the format: intent:alarm_set,time:two pm.\n\
75
+ The intents are calendar:calendar_set,calendar_remove,calendar_query\n\
76
+ lists:lists_query,lists_remove,lists_createoradd\n\
77
+ music:play_music,music_likeness,playlists_createoradd,music_settings,music_dislikeness,music_query\n\
78
+ news:news_query,news_subscription\n\
79
+ alarm:alarm_set,alarm_query,alarm_remove,alarm_change\n\
80
+ email:email_sendemail,email_query,email_querycontact,email_subscription,email_addcontact,email_remove\n\
81
+ iot:iot_hue_lightcolor,iot_hue_lightother,iot_coffee,iot_hue_lightdim,iot_hue_lightup,audio_volume_mute,iot_hue_lightoff,audio_volume_up,iot_wemo_off,audio_volume_other,iot_cleaning,iot_wemo_on,audio_volume_down\n\
82
+ weather:weather_query\n\
83
+ datetime:datetime_query,datetime_convert\n\
84
+ stock:qa_stock\n\
85
+ qa:qa_factoid,general_quirky,qa_definition,general_joke,qa_maths\n\
86
+ greet:general_greet\n\
87
+ currency:qa_currency\n\
88
+ transport:transport_taxi,transport_ticket,transport_query,transport_traffic\n\
89
+ recommendation:recommendation_events,recommendation_movies,recommendation_locations\n\
90
+ podcast:play_podcasts\n\
91
+ audiobook:play_audiobook\n\
92
+ radio:play_radio,radio_query\n\
93
+ takeaway:takeaway_query,takeaway_order\n\
94
+ social:social_query,social_post\n\
95
+ cooking:cooking_recipe\n\
96
+ phone:phone_text,phone_notification\n\
97
+ game:play_game\n\
98
+ "
99
+ "Don't ask follow-up questions. data in json."
100
+ )
101
+ )
102
+ time_agent = create_react_agent(llm, tools=[time_tool],state_modifier=(
103
+ "You are a time agent. Read the time params in slots, and convert to formated time. if has date, call the time_tool to get today's date. Then calculate the date according to today's date. The time is 10:00. If has time, the time format should be 10:00."
104
+ "Don't try to answer the first question directly. Don't ask follow-up questions. data in json."
105
+ )
106
+ )
107
+ request_agent = create_react_agent(llm, tools=[request_tool],state_modifier=(
108
+ "Always call the request_tool to request the url and get the response from the server"
109
+ "data in json."
110
+ )
111
+ )
112
+
113
+
114
+ def intent_node(state: MessagesState) -> Command[Literal["supervisor"]]:
115
+ result = intent_agent.invoke(state)
116
+ return Command(
117
+ update={
118
+ "messages": [
119
+ HumanMessage(content=result["messages"][-1].content, name="intent")
120
+ ]
121
+ },
122
+ # We want our workers to ALWAYS "report back" to the supervisor when done
123
+ goto="supervisor",
124
+ )
125
+ def time_node(state: MessagesState) -> Command[Literal["supervisor"]]:
126
+ result = time_agent.invoke(state)
127
+ return Command(
128
+ update={
129
+ "messages": [
130
+ HumanMessage(content=result["messages"][-1].content, name="time")
131
+ ]
132
+ },
133
+ # We want our workers to ALWAYS "report back" to the supervisor when done
134
+ goto="supervisor",
135
+ )
136
+ def request_node(state: MessagesState) -> Command[Literal["supervisor"]]:
137
+ result = request_agent.invoke(state)
138
+ return Command(
139
+ update={
140
+ "messages": [
141
+ HumanMessage(content=result["messages"][-1].content, name="request")
142
+ ]
143
+ },
144
+ # We want our workers to ALWAYS "report back" to the supervisor when done
145
+ goto="supervisor",
146
+ )
147
+
148
+
149
+ location_agent = create_react_agent(llm, tools=[], state_modifier=(
150
+ "You are a location agent. Read the location params in slots, and convert to formated location. if location is in house, do not need to resolve. current location is new york."
151
+ "Don't ask follow-up questions. data format in json."
152
+ )
153
+ )
154
+ # currency server is https://www.amdoren.com/api/currency.php?api_key={key}&from={currency}&to={currency2}&amount={amount}\n\
155
+ url_agent = create_react_agent(llm, tools=[], state_modifier=(
156
+ "You are a url agent. Read the params in intent and slots, then choose the url from the servers' url list. also need to modify the slot name to the url description:\
157
+ qa server is http://api.serpstack.com/search?access_key={key}&query={query}\n\
158
+ news query server is http://api.mediastack.com/v1/news?access_key={key}&keywords={keyword}&date={date}&sort=published_desc\n\
159
+ news subscription server http://127.0.0.1:3020/news,intent(news_subscription),iid,news_topic,\
160
+ weather server first request https://geocoding-api.open-meteo.com/v1/search?name={place_name}&count=10&language=en&format=json to get latitude and latitude, then request https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}&daily=temperature_2m_max,temperature_2m_min,sunrise,sunset,uv_index_max,rain_sum,showers_sum,snowfall_sum,wind_speed_10m_max\n\
161
+ stock server is first to get the stock symbol http://api.serpstack.com/search? access_key = {key}& query = {name} stock symbol , then request to this server http://api.marketstack.com/v1/eod? access_key = {key}& symbols = {symbol}&limit=5\n\
162
+ currency server is https://api.freecurrencyapi.com/v1/latest?apikey={key}&base_currency={currency}&currencies={currency2}\n\
163
+ http://127.0.0.1:3000/alarm, intent(alarm_query,alarm_set),iid,event_name,descriptor,time,from_time,to_time,\
164
+ http://127.0.0.1:3001/audiobook,intent(play_audiobook), iid,player_setting,house_place,media_type,descriptor,audiobook_name,author_name,\
165
+ http://127.0.0.1:3002/calendar,intent(calendar_query,calendar_remove,calendar_set),iid,event_name,descriptor,person,relation,date,time,from_time,to_time,\
166
+ http://127.0.0.1:3003/cooking,intent(cooking_recipe),iid,food_type,descriptor,\
167
+ http://127.0.0.1:3004/datetime,intent(datetime_convert,datetime_query),iid,place_name,descriptor,time_zone,time_zone2,date,time,time2,\
168
+ http://127.0.0.1:3005/email,intent(email_query,email_sendemail),iid,setting,person,to_person,from_person,relation,to_relation,from_relation,email_folder,time,date,email_address,app_name,query,content,personal_info,\
169
+ http://127.0.0.1:3006/game,intent(play_game),iid,game_name,\
170
+ http://127.0.0.1:3007/iot,intent(iot_coffee,iot_hue_lightcolor,iot_hue_lightother,iot_hue_lightdim,iot_hue_lightup,audio_volume_mute,iot_hue_lightoff,audio_volume_up,iot_wemo_off,audio_volume_other,iot_cleaning,iot_wemo_on,audio_volume_down),iid,device_type,house_place,time,color_type,change_amount,change_to,item_name,setting,\
171
+ http://127.0.0.1:3008/lists,intent(lists_query,lists_remove,lists_createoradd),iid,list_name,item_name,descriptor,time,date,\
172
+ http://127.0.0.1:3009/music,intent(play_music,music_likeness,playlists_createoradd,music_settings,music_dislikeness,music_query),iid,player_setting,descriptor,artist_name,song_name,playlist_name,music_genre,query,\
173
+ http://127.0.0.1:3010/phone,intent(phone_text,phone_notification),iid,device_type,event_name,text,\
174
+ http://127.0.0.1:3011/podcasts,intent(play_podcasts),iid,podcast_name,player_setting,podcast_descriptor,\
175
+ http://127.0.0.1:3013/radio,intent(play_radio,radio_query),iid,radio_name,app_name,person_name,music_genre,device_type,house_place,player_setting,descriptor,query,time,\
176
+ http://127.0.0.1:3014/recommendation,intent(recommendation_events,recommendation_movies,recommendation_locations),iid,business_type,food_type,movie_type,movie_name,date,place_name,event_name,descriptor,\
177
+ http://127.0.0.1:3015/social,intent(social_query,social_post),iid,media_type,person,business_name,content,date,descriptor,\
178
+ http://127.0.0.1:3017/takeaway,intent(takeaway_query,takeaway_order),iid,food_type,order_type,business_type,business_name,place_name,date,time,descriptor,\
179
+ http://127.0.0.1:3018/transport,intent(transport_taxi,transport_ticket,transport_query,transport_traffic),iid,transport_agency,transport_type,business_type,business_name,place_name,to_place_name,from_place_name,query,date,time,descriptor,\
180
+ then all the url format should be http://127.0.0.1:3002/calendar?intent=calendar_remove&event_name=meeting\n\
181
+ data in json."
182
+ )
183
+ )
184
+ response_agent = create_react_agent(llm, tools=[], state_modifier=(
185
+ "You are a genresponse agent. Read the content, and generate response to the first user's cmd. The format should be 'response':'...'"
186
+ "Don't ask follow-up questions. data format in json."
187
+ )
188
+ )
189
+
190
+
191
+ def location_node(state: MessagesState) -> Command[Literal["supervisor"]]:
192
+ result = location_agent.invoke(state)
193
+ return Command(
194
+ update={
195
+ "messages": [
196
+ HumanMessage(content=result["messages"][-1].content, name="location")
197
+ ]
198
+ },
199
+ # We want our workers to ALWAYS "report back" to the supervisor when done
200
+ goto="supervisor",
201
+ )
202
+
203
+ def url_node(state: MessagesState) -> Command[Literal["supervisor"]]:
204
+ result = url_agent.invoke(state)
205
+ return Command(
206
+ update={
207
+ "messages": [
208
+ HumanMessage(content=result["messages"][-1].content, name="url")
209
+ ]
210
+ },
211
+ # We want our workers to ALWAYS "report back" to the supervisor when done
212
+ goto="supervisor",
213
+ )
214
+
215
+ def response_node(state: MessagesState) -> Command[Literal["supervisor"]]:
216
+ result = response_agent.invoke(state)
217
+ return Command(
218
+ update={
219
+ "messages": [
220
+ HumanMessage(content=result["messages"][-1].content, name="genresponse")
221
+ ]
222
+ },
223
+ # We want our workers to ALWAYS "report back" to the supervisor when done
224
+ goto="supervisor",
225
+ )
226
+
227
+ research_supervisor_node = make_supervisor_node(llm, ["intent", "time", "location", "url", "request", "genresponse"])
228
+
229
+ research_builder = StateGraph(MessagesState)
230
+ research_builder.add_node("supervisor", research_supervisor_node)
231
+ research_builder.add_node("intent", intent_node)
232
+ research_builder.add_node("time", time_node)
233
+ research_builder.add_node("location", location_node)
234
+ research_builder.add_node("url", url_node)
235
+ research_builder.add_node("request", request_node)
236
+ research_builder.add_node("genresponse", response_node)
237
+
238
+ research_builder.add_edge(START, "supervisor")
239
+ research_graph = research_builder.compile()
240
+ def read_data(file_path):
241
+ queries=[]
242
+ with open(file_path, newline='') as csvfile:
243
+ spamreader = csv.reader(csvfile, delimiter=',', quotechar='"')
244
+ count=0
245
+ for row in spamreader:
246
+ if count==0:
247
+ count+=1
248
+ continue
249
+ #print(row[2])
250
+ #print(len(row))
251
+ iid=row[0]
252
+ query={"iid":iid,"query":row[1]}#,"slots":slot,"domain":row[4]}
253
+ queries.append(query)
254
+ return queries
255
+
256
+ if __name__=="__main__":
257
+ tasks=read_data("~/data/test.csv")
258
+ #print(tasks)
259
+ index = int(sys.argv[1])
260
+ tasks=tasks[index:index+1]
261
+ for task in tasks:
262
+
263
+ for s in research_graph.stream(
264
+ {"messages": [("user", task["query"])]},
265
+ {"recursion_limit": 100},
266
+ ):
267
+ print(s)
268
+ print("---")