callanwu commited on
Commit
2ee1dc0
1 Parent(s): 4ecdaad

add sop_generation

Browse files
Files changed (2) hide show
  1. app copy.py +0 -395
  2. app.py +392 -4
app copy.py DELETED
@@ -1,395 +0,0 @@
1
- import sys
2
- import os
3
- import argparse
4
- from gradio_base import WebUI, UIHelper, PORT, HOST, Client
5
- from gradio_config import GradioConfig as gc
6
- from typing import List, Tuple, Any
7
- import gradio as gr
8
- import time
9
- from Agent import Agent
10
- from design_states import get_desgin_states,get_cot_result
11
- from gen_utils import *
12
- from utils import get_embedding,cos_sim
13
- import torch
14
- import json
15
- import openai
16
-
17
- def get_embedding(sentence,api_key):
18
- openai.api_key = api_key
19
- embedding_model = openai.Embedding
20
- embed = embedding_model.create(
21
- model="text-embedding-ada-002",
22
- input=sentence
23
- )
24
- embed = embed["data"][0]["embedding"]
25
- embed = torch.tensor(embed,dtype=torch.float32)
26
- if len(embed.shape)==1:
27
- embed = embed.unsqueeze(0)
28
- return embed
29
-
30
- class GeneralUI(WebUI):
31
- def render_and_register_ui(self):
32
- # bind the agent with avatar
33
- self.agent_name:list = [self.cache["agents_name"]] if isinstance(self.cache["agents_name"], str) else self.cache['agents_name']
34
- gc.add_agent(self.agent_name)
35
-
36
- def handle_message(self, history, state, agent_name, token, node_name):
37
- if state % 10 == 0:
38
- self.data_history.append({agent_name: token})
39
- elif state % 10 == 1:
40
- # Same state. Need to add new bubble in same bubble.
41
- self.data_history[-1][agent_name] += token
42
- elif state % 10 == 2:
43
- # New state. Need to add new bubble.
44
- history.append([None, ""])
45
- self.data_history.clear()
46
- self.data_history.append({agent_name: token})
47
- else:
48
- assert False, "Invalid state."
49
- render_data = self.render_bubble(history, self.data_history, node_name, render_node_name= True)
50
- return render_data
51
-
52
- def __init__(
53
- self,
54
- client_cmd: list,
55
- socket_host: str = HOST,
56
- socket_port: int = PORT,
57
- bufsize: int = 1024,
58
- ui_name: str = "GeneralUI"
59
- ):
60
- super(GeneralUI, self).__init__(client_cmd, socket_host, socket_port, bufsize, ui_name)
61
- self.first_recieve_from_client()
62
- self.current_node_name = ""
63
- self.data_history = None
64
- for _ in ['agents_name', 'api_key']:
65
- assert _ in self.cache
66
-
67
- def generate_sop(self,api_key,proxy,target):
68
- os.environ["API_KEY"] = api_key
69
- # os.environ["PROXY"] = proxy
70
- self.design_assistant = "An assistant that can help users create content such as articles, blogs, advertising copy, etc"
71
- self.tutor = "A tutor who provides personalized learning resources for students to help them understand complex concepts and problems"
72
- self.online_medical_consultant = "An online medical consultant who offers preliminary medical advice to patients and answers common questions about diseases, symptoms, and treatments."
73
- self.online_legal_consultant = "An online legal advisor who can respond to inquiries related to legal matters, providing basic legal information and advice."
74
- self.online_financial_advisor = "An online financial advisor who can analyze financial markets and data, offering investment advice and market forecasts to users."
75
- self.virtual_tour_guide = "A virtual tour guide providing destination information, travel recommendations, and virtual travel experiences for travelers."
76
- self.design_assistant = get_embedding(self.design_assistant,api_key)
77
- self.tutor = get_embedding(self.tutor,api_key)
78
- self.online_medical_consultant = get_embedding(self.online_medical_consultant,api_key)
79
- self.online_legal_consultant = get_embedding(self.online_legal_consultant,api_key)
80
- self.online_financial_advisor = get_embedding(self.online_financial_advisor,api_key)
81
- self.virtual_tour_guide = get_embedding(self.virtual_tour_guide,api_key)
82
- self.embeddings = torch.cat([self.design_assistant,self.tutor,self.online_medical_consultant,self.online_legal_consultant,self.online_financial_advisor,self.virtual_tour_guide],dim = 0)
83
- self.SOP["config"]["API_KEY"] = api_key
84
- # self.SOP["config"]["PROXY"] = proxy
85
- target_tensor = get_embedding(target,api_key)
86
- sim_scores = cos_sim(target_tensor, self.embeddings)[0]
87
- top_k_score, top_k_idx = torch.topk(sim_scores,k = 1)
88
- if top_k_score > 0.7:
89
- index = top_k_idx
90
- else:
91
- index = 0
92
- target = get_cot_result(target)
93
- design_states = get_desgin_states(target,index)
94
- root = design_states[0]["state_name"]
95
- agents = get_agents(design_states)
96
- relations = get_relations(design_states)
97
- states = gen_states(design_states)
98
- for state_name,state_dict in states.items():
99
- state_dict["begin_role"] = list(agents.keys())[0]
100
- state_dict["begin_query"] = "Now that we are in the **{}**, I'm glad to offer you assistance.".format(state_name)
101
- self.SOP["root"] = root
102
- self.SOP["relations"] = relations
103
- self.SOP["agents"] = agents
104
- self.SOP["states"] = states
105
- # 将字典写入JSON文件
106
- print(self.SOP)
107
- file_name = 'generated_sop.json'
108
- with open(file_name, "w",encoding="utf-8") as json_file:
109
- json.dump(self.SOP, json_file ,indent=4,ensure_ascii=False)
110
- return file_name
111
-
112
- def load_sop_fn(self,sop):
113
- return sop.name
114
-
115
- def construct_ui(self):
116
- with gr.Blocks(css=gc.CSS) as demo:
117
- with gr.Tab(label="SOP generation") as tab1:
118
- self.SOP = {
119
- "config": {
120
- "API_KEY": "sk-********",
121
- "MAX_CHAT_HISTORY": "5",
122
- "User_Names": '["User"]',
123
- },
124
- "root": "state1",
125
- "relations": {
126
- "state1": {"0": "state1", "1": "state2"},
127
- "state2": {"0": "state2", "1": "end_state"},
128
- },
129
- "agents": None,
130
- "states": None,
131
- }
132
- gr.Markdown("""# Generate Agent""")
133
- with gr.Row():
134
- self.api_key_sop_generation = gr.Textbox(label="api_key")
135
- self.proxy_sop_generation = gr.Textbox(label="proxy",visible=False)
136
- with gr.Row():
137
- self.requirement_sop_generation = gr.Textbox(value ="a shopping assistant help customer to buy the commodity",label="requirement")
138
- with gr.Row():
139
- self.generated_sop = gr.File(label="generated_file")
140
- self.generate_button = gr.Button(label="Generate")
141
- self.generate_button.click(fn = self.generate_sop,inputs=[self.api_key_sop_generation,self.proxy_sop_generation,self.requirement_sop_generation],outputs=[self.generated_sop])
142
- with gr.Tab(label="Chat") as tab2:
143
- uploaded_sop = gr.State()
144
- with gr.Row():
145
- sop = gr.File(label="upload your custmized SOP")
146
- load_sop_btn = gr.Button(value="Load SOP")
147
- load_sop_btn.click(self.load_sop_fn, sop,uploaded_sop)
148
- with gr.Column():
149
- self.radio_mode = gr.Radio(
150
- [Client.SINGLE_MODE],
151
- label = Client.MODE_LABEL,
152
- info = Client.MODE_INFO,
153
- value= Client.SINGLE_MODE,
154
- interactive=True
155
- # label="Select the execution mode",
156
- # info="Single mode refers to when the current agent output ends, it will stop running until you click to continue. Auto mode refers to when you complete the input, all agents will continue to output until the task ends."
157
- )
158
- self.text_api = gr.Textbox(
159
- value = self.cache["api_key"],
160
- placeholder="openai key",
161
- label="Please input valid openai key for gpt-3.5-turbo-16k."
162
- )
163
- self.btn_start = gr.Button(
164
- value="Start😁(Click here to start!)",
165
- )
166
- self.chatbot = gr.Chatbot(
167
- elem_id="chatbot1",
168
- label="Dialog",
169
- visible=False,
170
- height=700
171
- )
172
- self.btn_next = gr.Button(
173
- value="Next Agent Start",
174
- visible=False
175
- )
176
- with gr.Row():
177
- self.text_input = gr.Textbox(
178
- placeholder="Please enter your content.",
179
- label="Input",
180
- scale=9,
181
- visible=False
182
- )
183
- self.btn_send = gr.Button(
184
- value="Send",
185
- visible=False
186
- )
187
- self.btn_reset = gr.Button(
188
- value="Restart",
189
- visible=False
190
- )
191
-
192
- all_components = [self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
193
-
194
- self.btn_start.click(
195
- fn = self.btn_start_when_click,
196
- inputs=[self.radio_mode, self.text_api,uploaded_sop],
197
- outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next, self.radio_mode, self.text_api]
198
- ).then(
199
- fn = self.btn_start_after_click,
200
- inputs=[self.chatbot],
201
- outputs=all_components
202
- )
203
-
204
- self.btn_send.click(
205
- fn=self.btn_send_when_click,
206
- inputs=[self.text_input, self.chatbot],
207
- outputs=all_components
208
- ).then(
209
- fn=self.btn_send_after_click,
210
- inputs=[self.text_input, self.chatbot],
211
- outputs=all_components
212
- )
213
-
214
- self.text_input.submit(
215
- fn=self.btn_send_when_click,
216
- inputs=[self.text_input, self.chatbot],
217
- outputs=all_components
218
- ).then(
219
- fn=self.btn_send_after_click,
220
- inputs=[self.text_input, self.chatbot],
221
- outputs=all_components
222
- )
223
-
224
- self.btn_reset.click(
225
- fn=self.btn_reset_when_click,
226
- inputs=[],
227
- outputs=all_components
228
- ).then(
229
- fn=self.btn_reset_after_click,
230
- inputs=[],
231
- outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next, self.radio_mode, self.text_api]
232
- )
233
-
234
- self.btn_next.click(
235
- fn=self.btn_next_when_click,
236
- inputs=[self.chatbot],
237
- outputs=all_components
238
- ).then(
239
- fn=self.btn_next_after_click,
240
- inputs=[self.chatbot],
241
- outputs=all_components
242
- )
243
-
244
- self.demo = demo
245
-
246
- def btn_start_when_click(self, mode, api,sop):
247
- """
248
- inputs=[mode, api]
249
- outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next, self.radio_mode]
250
- """
251
- print("server: send ", mode, api)
252
- self.send_start_cmd({"mode": mode, "api_key":api,"uploaded_sop": sop})
253
- agents,roles_to_names,names_to_roles = Agent.from_config(str(sop))
254
- agents_name = []
255
- for i in names_to_roles :
256
- for j in names_to_roles[i]:
257
- agents_name.append(j+"("+names_to_roles[i][j]+")")
258
- self.new_render_and_register_ui(agents_name)
259
- return gr.Button.update(visible=False), \
260
- gr.Button.update(visible=False),\
261
- gr.Button.update(visible=False),\
262
- gr.Chatbot.update(visible=True),\
263
- gr.Textbox.update(visible=False),\
264
- gr.Button.update(visible=False),\
265
- gr.Radio.update(visible=False),\
266
- gr.Textbox.update(visible=False)
267
-
268
- def new_render_and_register_ui(self,agent_names):
269
- gc.add_agent(agent_names, 0)
270
-
271
- def btn_start_after_click(self, history):
272
- """
273
- inputs=[self.chatbot]
274
- outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
275
- """
276
- if self.data_history is None:
277
- self.data_history = list()
278
- receive_server = self.receive_server
279
- while True:
280
- data_list: List = receive_server.send(None)
281
- for item in data_list:
282
- data = eval(item)
283
- assert isinstance(data, list)
284
- state, agent_name, token, node_name = data
285
- self.current_node_name = node_name
286
- assert isinstance(state, int)
287
- assert state in [10, 11, 12, 30, 99, 98]
288
- if state == 99:
289
- # finish
290
- yield gr.Button.update(visible=False),\
291
- gr.Button.update(visible=True, interactive=False),\
292
- gr.Button.update(visible=True, interactive=True),\
293
- history,\
294
- gr.Textbox.update(visible=True, interactive=False),\
295
- gr.Button.update(visible=False)
296
- return
297
- elif state == 98:
298
- # single mode
299
- yield gr.Button.update(visible=False), \
300
- gr.Button.update(visible=False),\
301
- gr.Button.update(visible=True),\
302
- history,\
303
- gr.Textbox.update(visible=False),\
304
- gr.Button.update(visible=True, value=f"Next Agent: 🤖{agent_name} | Next Node: ⭕{node_name}")
305
- return
306
- elif state == 30:
307
- # user input
308
- yield gr.Button.update(visible=False), \
309
- gr.Button.update(visible=True),\
310
- gr.Button.update(visible=True),\
311
- history,\
312
- gr.Textbox.update(visible=True, value=""),\
313
- gr.Button.update(visible=False)
314
- return
315
- history = self.handle_message(history, state, agent_name, token, node_name)
316
- yield gr.Button.update(visible=False), \
317
- gr.Button.update(visible=False),\
318
- gr.Button.update(visible=False),\
319
- history,\
320
- gr.Textbox.update(visible=False),\
321
- gr.Button.update(visible=False)
322
-
323
- def btn_send_when_click(self, text_input, history):
324
- '''
325
- inputs=[self.text_input, self.chatbot]
326
- outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
327
- '''
328
- history = self.handle_message(history, 10, 'User', text_input, self.current_node_name)
329
- self.send_message("<USER>"+text_input+self.SIGN["SPLIT"])
330
- yield gr.Button.update(visible=False), \
331
- gr.Button.update(visible=False),\
332
- gr.Button.update(visible=False),\
333
- history,\
334
- gr.Textbox.update(visible=False),\
335
- gr.Button.update(visible=False)
336
- return
337
-
338
- def btn_send_after_click(self, text_input, history):
339
- '''
340
- inputs=[self.text_input, self.chatbot]
341
- outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
342
- '''
343
- yield from self.btn_start_after_click(history=history)
344
- return
345
-
346
- def btn_reset_when_click(self):
347
- """
348
- outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
349
- """
350
- return gr.Button.update(interactive=False), gr.Button.update(interactive=False), gr.Button.update(interactive=False, value="Restarting....."), gr.Chatbot.update(label="Dialog"), \
351
- gr.Textbox.update(interactive=False), gr.Button.update(visible=False)
352
-
353
- def btn_reset_after_click(self):
354
- """
355
- outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next, self.radio_mode]
356
- """
357
- self.reset()
358
- self.first_recieve_from_client(reset_mode=True)
359
- self.current_node_name = ""
360
- self.data_history = None
361
- return gr.Button.update(interactive=True, visible=True), \
362
- gr.Button.update(interactive=True, visible=False), \
363
- gr.Button.update(interactive=True, value="Restart", visible=False), \
364
- gr.Chatbot.update(label="Dialog", visible=False, value=None), \
365
- gr.Textbox.update(interactive=True, visible=False),\
366
- gr.Button.update(visible=False),\
367
- gr.Radio.update(visible=True), \
368
- gr.Textbox.update(visible=True)
369
-
370
- def btn_next_when_click(self, history):
371
- """
372
- outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
373
- """
374
- yield gr.Button.update(visible=False), \
375
- gr.Button.update(visible=False),\
376
- gr.Button.update(visible=False),\
377
- history,\
378
- gr.Textbox.update(visible=False),\
379
- gr.Button.update(visible=False)
380
- self.send_message("nothing")
381
- return
382
-
383
- def btn_next_after_click(self, history):
384
- time.sleep(1)
385
- yield from self.btn_start_after_click(history=history)
386
- return
387
-
388
- if __name__ == '__main__':
389
- parser = argparse.ArgumentParser(description='A demo of chatbot')
390
- parser.add_argument('--agent', type=str, help='path to SOP json')
391
- args = parser.parse_args()
392
-
393
- ui = GeneralUI(client_cmd=["python3","gradio_backend.py"])
394
- ui.construct_ui()
395
- ui.run(share=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app.py CHANGED
@@ -1,7 +1,395 @@
 
 
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
2
 
3
- def greet(name):
4
- return "Hello " + name + "!!"
 
 
 
 
 
 
 
 
 
 
5
 
6
- iface = gr.Interface(fn=greet, inputs="text", outputs="text")
7
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import os
3
+ import argparse
4
+ from gradio_base import WebUI, UIHelper, PORT, HOST, Client
5
+ from gradio_config import GradioConfig as gc
6
+ from typing import List, Tuple, Any
7
  import gradio as gr
8
+ import time
9
+ from Agent import Agent
10
+ from design_states import get_desgin_states,get_cot_result
11
+ from gen_utils import *
12
+ from utils import get_embedding,cos_sim
13
+ import torch
14
+ import json
15
+ import openai
16
 
17
+ def get_embedding(sentence,api_key):
18
+ openai.api_key = api_key
19
+ embedding_model = openai.Embedding
20
+ embed = embedding_model.create(
21
+ model="text-embedding-ada-002",
22
+ input=sentence
23
+ )
24
+ embed = embed["data"][0]["embedding"]
25
+ embed = torch.tensor(embed,dtype=torch.float32)
26
+ if len(embed.shape)==1:
27
+ embed = embed.unsqueeze(0)
28
+ return embed
29
 
30
+ class GeneralUI(WebUI):
31
+ def render_and_register_ui(self):
32
+ # bind the agent with avatar
33
+ self.agent_name:list = [self.cache["agents_name"]] if isinstance(self.cache["agents_name"], str) else self.cache['agents_name']
34
+ gc.add_agent(self.agent_name)
35
+
36
+ def handle_message(self, history, state, agent_name, token, node_name):
37
+ if state % 10 == 0:
38
+ self.data_history.append({agent_name: token})
39
+ elif state % 10 == 1:
40
+ # Same state. Need to add new bubble in same bubble.
41
+ self.data_history[-1][agent_name] += token
42
+ elif state % 10 == 2:
43
+ # New state. Need to add new bubble.
44
+ history.append([None, ""])
45
+ self.data_history.clear()
46
+ self.data_history.append({agent_name: token})
47
+ else:
48
+ assert False, "Invalid state."
49
+ render_data = self.render_bubble(history, self.data_history, node_name, render_node_name= True)
50
+ return render_data
51
+
52
+ def __init__(
53
+ self,
54
+ client_cmd: list,
55
+ socket_host: str = HOST,
56
+ socket_port: int = PORT,
57
+ bufsize: int = 1024,
58
+ ui_name: str = "GeneralUI"
59
+ ):
60
+ super(GeneralUI, self).__init__(client_cmd, socket_host, socket_port, bufsize, ui_name)
61
+ self.first_recieve_from_client()
62
+ self.current_node_name = ""
63
+ self.data_history = None
64
+ for _ in ['agents_name', 'api_key']:
65
+ assert _ in self.cache
66
+
67
+ def generate_sop(self,api_key,proxy,target):
68
+ os.environ["API_KEY"] = api_key
69
+ # os.environ["PROXY"] = proxy
70
+ self.design_assistant = "An assistant that can help users create content such as articles, blogs, advertising copy, etc"
71
+ self.tutor = "A tutor who provides personalized learning resources for students to help them understand complex concepts and problems"
72
+ self.online_medical_consultant = "An online medical consultant who offers preliminary medical advice to patients and answers common questions about diseases, symptoms, and treatments."
73
+ self.online_legal_consultant = "An online legal advisor who can respond to inquiries related to legal matters, providing basic legal information and advice."
74
+ self.online_financial_advisor = "An online financial advisor who can analyze financial markets and data, offering investment advice and market forecasts to users."
75
+ self.virtual_tour_guide = "A virtual tour guide providing destination information, travel recommendations, and virtual travel experiences for travelers."
76
+ self.design_assistant = get_embedding(self.design_assistant,api_key)
77
+ self.tutor = get_embedding(self.tutor,api_key)
78
+ self.online_medical_consultant = get_embedding(self.online_medical_consultant,api_key)
79
+ self.online_legal_consultant = get_embedding(self.online_legal_consultant,api_key)
80
+ self.online_financial_advisor = get_embedding(self.online_financial_advisor,api_key)
81
+ self.virtual_tour_guide = get_embedding(self.virtual_tour_guide,api_key)
82
+ self.embeddings = torch.cat([self.design_assistant,self.tutor,self.online_medical_consultant,self.online_legal_consultant,self.online_financial_advisor,self.virtual_tour_guide],dim = 0)
83
+ self.SOP["config"]["API_KEY"] = api_key
84
+ # self.SOP["config"]["PROXY"] = proxy
85
+ target_tensor = get_embedding(target,api_key)
86
+ sim_scores = cos_sim(target_tensor, self.embeddings)[0]
87
+ top_k_score, top_k_idx = torch.topk(sim_scores,k = 1)
88
+ if top_k_score > 0.7:
89
+ index = top_k_idx
90
+ else:
91
+ index = 0
92
+ target = get_cot_result(target)
93
+ design_states = get_desgin_states(target,index)
94
+ root = design_states[0]["state_name"]
95
+ agents = get_agents(design_states)
96
+ relations = get_relations(design_states)
97
+ states = gen_states(design_states)
98
+ for state_name,state_dict in states.items():
99
+ state_dict["begin_role"] = list(agents.keys())[0]
100
+ state_dict["begin_query"] = "Now that we are in the **{}**, I'm glad to offer you assistance.".format(state_name)
101
+ self.SOP["root"] = root
102
+ self.SOP["relations"] = relations
103
+ self.SOP["agents"] = agents
104
+ self.SOP["states"] = states
105
+ # 将字典写入JSON文件
106
+ print(self.SOP)
107
+ file_name = 'generated_sop.json'
108
+ with open(file_name, "w",encoding="utf-8") as json_file:
109
+ json.dump(self.SOP, json_file ,indent=4,ensure_ascii=False)
110
+ return file_name
111
+
112
+ def load_sop_fn(self,sop):
113
+ return sop.name
114
+
115
+ def construct_ui(self):
116
+ with gr.Blocks(css=gc.CSS) as demo:
117
+ with gr.Tab(label="SOP generation") as tab1:
118
+ self.SOP = {
119
+ "config": {
120
+ "API_KEY": "sk-********",
121
+ "MAX_CHAT_HISTORY": "5",
122
+ "User_Names": '["User"]',
123
+ },
124
+ "root": "state1",
125
+ "relations": {
126
+ "state1": {"0": "state1", "1": "state2"},
127
+ "state2": {"0": "state2", "1": "end_state"},
128
+ },
129
+ "agents": None,
130
+ "states": None,
131
+ }
132
+ gr.Markdown("""# Generate Agent""")
133
+ with gr.Row():
134
+ self.api_key_sop_generation = gr.Textbox(label="api_key")
135
+ self.proxy_sop_generation = gr.Textbox(label="proxy",visible=False)
136
+ with gr.Row():
137
+ self.requirement_sop_generation = gr.Textbox(value ="a shopping assistant help customer to buy the commodity",label="requirement")
138
+ with gr.Row():
139
+ self.generated_sop = gr.File(label="generated_file")
140
+ self.generate_button = gr.Button(label="Generate")
141
+ self.generate_button.click(fn = self.generate_sop,inputs=[self.api_key_sop_generation,self.proxy_sop_generation,self.requirement_sop_generation],outputs=[self.generated_sop])
142
+ with gr.Tab(label="Chat") as tab2:
143
+ uploaded_sop = gr.State()
144
+ with gr.Row():
145
+ sop = gr.File(label="upload your custmized SOP")
146
+ load_sop_btn = gr.Button(value="Load SOP")
147
+ load_sop_btn.click(self.load_sop_fn, sop,uploaded_sop)
148
+ with gr.Column():
149
+ self.radio_mode = gr.Radio(
150
+ [Client.SINGLE_MODE],
151
+ label = Client.MODE_LABEL,
152
+ info = Client.MODE_INFO,
153
+ value= Client.SINGLE_MODE,
154
+ interactive=True
155
+ # label="Select the execution mode",
156
+ # info="Single mode refers to when the current agent output ends, it will stop running until you click to continue. Auto mode refers to when you complete the input, all agents will continue to output until the task ends."
157
+ )
158
+ self.text_api = gr.Textbox(
159
+ value = self.cache["api_key"],
160
+ placeholder="openai key",
161
+ label="Please input valid openai key for gpt-3.5-turbo-16k."
162
+ )
163
+ self.btn_start = gr.Button(
164
+ value="Start😁(Click here to start!)",
165
+ )
166
+ self.chatbot = gr.Chatbot(
167
+ elem_id="chatbot1",
168
+ label="Dialog",
169
+ visible=False,
170
+ height=700
171
+ )
172
+ self.btn_next = gr.Button(
173
+ value="Next Agent Start",
174
+ visible=False
175
+ )
176
+ with gr.Row():
177
+ self.text_input = gr.Textbox(
178
+ placeholder="Please enter your content.",
179
+ label="Input",
180
+ scale=9,
181
+ visible=False
182
+ )
183
+ self.btn_send = gr.Button(
184
+ value="Send",
185
+ visible=False
186
+ )
187
+ self.btn_reset = gr.Button(
188
+ value="Restart",
189
+ visible=False
190
+ )
191
+
192
+ all_components = [self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
193
+
194
+ self.btn_start.click(
195
+ fn = self.btn_start_when_click,
196
+ inputs=[self.radio_mode, self.text_api,uploaded_sop],
197
+ outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next, self.radio_mode, self.text_api]
198
+ ).then(
199
+ fn = self.btn_start_after_click,
200
+ inputs=[self.chatbot],
201
+ outputs=all_components
202
+ )
203
+
204
+ self.btn_send.click(
205
+ fn=self.btn_send_when_click,
206
+ inputs=[self.text_input, self.chatbot],
207
+ outputs=all_components
208
+ ).then(
209
+ fn=self.btn_send_after_click,
210
+ inputs=[self.text_input, self.chatbot],
211
+ outputs=all_components
212
+ )
213
+
214
+ self.text_input.submit(
215
+ fn=self.btn_send_when_click,
216
+ inputs=[self.text_input, self.chatbot],
217
+ outputs=all_components
218
+ ).then(
219
+ fn=self.btn_send_after_click,
220
+ inputs=[self.text_input, self.chatbot],
221
+ outputs=all_components
222
+ )
223
+
224
+ self.btn_reset.click(
225
+ fn=self.btn_reset_when_click,
226
+ inputs=[],
227
+ outputs=all_components
228
+ ).then(
229
+ fn=self.btn_reset_after_click,
230
+ inputs=[],
231
+ outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next, self.radio_mode, self.text_api]
232
+ )
233
+
234
+ self.btn_next.click(
235
+ fn=self.btn_next_when_click,
236
+ inputs=[self.chatbot],
237
+ outputs=all_components
238
+ ).then(
239
+ fn=self.btn_next_after_click,
240
+ inputs=[self.chatbot],
241
+ outputs=all_components
242
+ )
243
+
244
+ self.demo = demo
245
+
246
+ def btn_start_when_click(self, mode, api,sop):
247
+ """
248
+ inputs=[mode, api]
249
+ outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next, self.radio_mode]
250
+ """
251
+ print("server: send ", mode, api)
252
+ self.send_start_cmd({"mode": mode, "api_key":api,"uploaded_sop": sop})
253
+ agents,roles_to_names,names_to_roles = Agent.from_config(str(sop))
254
+ agents_name = []
255
+ for i in names_to_roles :
256
+ for j in names_to_roles[i]:
257
+ agents_name.append(j+"("+names_to_roles[i][j]+")")
258
+ self.new_render_and_register_ui(agents_name)
259
+ return gr.Button.update(visible=False), \
260
+ gr.Button.update(visible=False),\
261
+ gr.Button.update(visible=False),\
262
+ gr.Chatbot.update(visible=True),\
263
+ gr.Textbox.update(visible=False),\
264
+ gr.Button.update(visible=False),\
265
+ gr.Radio.update(visible=False),\
266
+ gr.Textbox.update(visible=False)
267
+
268
+ def new_render_and_register_ui(self,agent_names):
269
+ gc.add_agent(agent_names, 0)
270
+
271
+ def btn_start_after_click(self, history):
272
+ """
273
+ inputs=[self.chatbot]
274
+ outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
275
+ """
276
+ if self.data_history is None:
277
+ self.data_history = list()
278
+ receive_server = self.receive_server
279
+ while True:
280
+ data_list: List = receive_server.send(None)
281
+ for item in data_list:
282
+ data = eval(item)
283
+ assert isinstance(data, list)
284
+ state, agent_name, token, node_name = data
285
+ self.current_node_name = node_name
286
+ assert isinstance(state, int)
287
+ assert state in [10, 11, 12, 30, 99, 98]
288
+ if state == 99:
289
+ # finish
290
+ yield gr.Button.update(visible=False),\
291
+ gr.Button.update(visible=True, interactive=False),\
292
+ gr.Button.update(visible=True, interactive=True),\
293
+ history,\
294
+ gr.Textbox.update(visible=True, interactive=False),\
295
+ gr.Button.update(visible=False)
296
+ return
297
+ elif state == 98:
298
+ # single mode
299
+ yield gr.Button.update(visible=False), \
300
+ gr.Button.update(visible=False),\
301
+ gr.Button.update(visible=True),\
302
+ history,\
303
+ gr.Textbox.update(visible=False),\
304
+ gr.Button.update(visible=True, value=f"Next Agent: 🤖{agent_name} | Next Node: ⭕{node_name}")
305
+ return
306
+ elif state == 30:
307
+ # user input
308
+ yield gr.Button.update(visible=False), \
309
+ gr.Button.update(visible=True),\
310
+ gr.Button.update(visible=True),\
311
+ history,\
312
+ gr.Textbox.update(visible=True, value=""),\
313
+ gr.Button.update(visible=False)
314
+ return
315
+ history = self.handle_message(history, state, agent_name, token, node_name)
316
+ yield gr.Button.update(visible=False), \
317
+ gr.Button.update(visible=False),\
318
+ gr.Button.update(visible=False),\
319
+ history,\
320
+ gr.Textbox.update(visible=False),\
321
+ gr.Button.update(visible=False)
322
+
323
+ def btn_send_when_click(self, text_input, history):
324
+ '''
325
+ inputs=[self.text_input, self.chatbot]
326
+ outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
327
+ '''
328
+ history = self.handle_message(history, 10, 'User', text_input, self.current_node_name)
329
+ self.send_message("<USER>"+text_input+self.SIGN["SPLIT"])
330
+ yield gr.Button.update(visible=False), \
331
+ gr.Button.update(visible=False),\
332
+ gr.Button.update(visible=False),\
333
+ history,\
334
+ gr.Textbox.update(visible=False),\
335
+ gr.Button.update(visible=False)
336
+ return
337
+
338
+ def btn_send_after_click(self, text_input, history):
339
+ '''
340
+ inputs=[self.text_input, self.chatbot]
341
+ outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
342
+ '''
343
+ yield from self.btn_start_after_click(history=history)
344
+ return
345
+
346
+ def btn_reset_when_click(self):
347
+ """
348
+ outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
349
+ """
350
+ return gr.Button.update(interactive=False), gr.Button.update(interactive=False), gr.Button.update(interactive=False, value="Restarting....."), gr.Chatbot.update(label="Dialog"), \
351
+ gr.Textbox.update(interactive=False), gr.Button.update(visible=False)
352
+
353
+ def btn_reset_after_click(self):
354
+ """
355
+ outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next, self.radio_mode]
356
+ """
357
+ self.reset()
358
+ self.first_recieve_from_client(reset_mode=True)
359
+ self.current_node_name = ""
360
+ self.data_history = None
361
+ return gr.Button.update(interactive=True, visible=True), \
362
+ gr.Button.update(interactive=True, visible=False), \
363
+ gr.Button.update(interactive=True, value="Restart", visible=False), \
364
+ gr.Chatbot.update(label="Dialog", visible=False, value=None), \
365
+ gr.Textbox.update(interactive=True, visible=False),\
366
+ gr.Button.update(visible=False),\
367
+ gr.Radio.update(visible=True), \
368
+ gr.Textbox.update(visible=True)
369
+
370
+ def btn_next_when_click(self, history):
371
+ """
372
+ outputs=[self.btn_start, self.btn_send, self.btn_reset, self.chatbot, self.text_input, self.btn_next]
373
+ """
374
+ yield gr.Button.update(visible=False), \
375
+ gr.Button.update(visible=False),\
376
+ gr.Button.update(visible=False),\
377
+ history,\
378
+ gr.Textbox.update(visible=False),\
379
+ gr.Button.update(visible=False)
380
+ self.send_message("nothing")
381
+ return
382
+
383
+ def btn_next_after_click(self, history):
384
+ time.sleep(1)
385
+ yield from self.btn_start_after_click(history=history)
386
+ return
387
+
388
+ if __name__ == '__main__':
389
+ parser = argparse.ArgumentParser(description='A demo of chatbot')
390
+ parser.add_argument('--agent', type=str, help='path to SOP json')
391
+ args = parser.parse_args()
392
+
393
+ ui = GeneralUI(client_cmd=["python","gradio_backend.py"])
394
+ ui.construct_ui()
395
+ ui.run()