Files changed (1) hide show
  1. app.py +301 -291
app.py CHANGED
@@ -1,292 +1,302 @@
1
- import sys
2
- sys.path.append("BMTools/")
3
-
4
- import gradio as gr
5
- from bmtools.agent.tools_controller import MTQuestionAnswerer, load_valid_tools
6
- from bmtools.agent.singletool import STQuestionAnswerer
7
- from langchain.schema import AgentFinish
8
- import os
9
- import requests
10
-
11
- from tool_server import run_tool_server
12
- from threading import Thread
13
- from multiprocessing import Process
14
- import time
15
-
16
- tool_server_flag = False
17
- def start_tool_server():
18
- # server = Thread(target=run_tool_server)
19
- server = Process(target=run_tool_server)
20
- server.start()
21
- global tool_server_flag
22
- tool_server_flag = True
23
-
24
-
25
- available_models = ["ChatGPT", "GPT-3.5"]
26
- DEFAULTMODEL = "ChatGPT" # "GPT-3.5"
27
-
28
- tools_mappings = {
29
- "klarna": "https://www.klarna.com/",
30
- "weather": "http://127.0.0.1:8079/tools/weather/",
31
- # "database": "http://127.0.0.1:8079/tools/database/",
32
- # "db_diag": "http://127.0.0.1:8079/tools/db_diag/",
33
- "chemical-prop": "http://127.0.0.1:8079/tools/chemical-prop/",
34
- "douban-film": "http://127.0.0.1:8079/tools/douban-film/",
35
- "wikipedia": "http://127.0.0.1:8079/tools/wikipedia/",
36
- # "wikidata": "http://127.0.0.1:8079/tools/wikidata/",
37
- "wolframalpha": "http://127.0.0.1:8079/tools/wolframalpha/",
38
- "bing_search": "http://127.0.0.1:8079/tools/bing_search/",
39
- "office-ppt": "http://127.0.0.1:8079/tools/office-ppt/",
40
- "stock": "http://127.0.0.1:8079/tools/stock/",
41
- "bing_map": "http://127.0.0.1:8079/tools/bing_map/",
42
- # "baidu_map": "http://127.0.0.1:8079/tools/baidu_map/",
43
- "zillow": "http://127.0.0.1:8079/tools/zillow/",
44
- "airbnb": "http://127.0.0.1:8079/tools/airbnb/",
45
- "job_search": "http://127.0.0.1:8079/tools/job_search/",
46
- # "baidu-translation": "http://127.0.0.1:8079/tools/baidu-translation/",
47
- # "nllb-translation": "http://127.0.0.1:8079/tools/nllb-translation/",
48
- "tutorial": "http://127.0.0.1:8079/tools/tutorial/",
49
- "file_operation": "http://127.0.0.1:8079/tools/file_operation/",
50
- "meta_analysis": "http://127.0.0.1:8079/tools/meta_analysis/",
51
- "code_interpreter": "http://127.0.0.1:8079/tools/code_interpreter/",
52
- "arxiv": "http://127.0.0.1:8079/tools/arxiv/",
53
- "google_places": "http://127.0.0.1:8079/tools/google_places/",
54
- "google_serper": "http://127.0.0.1:8079/tools/google_serper/",
55
- "google_scholar": "http://127.0.0.1:8079/tools/google_scholar/",
56
- "python": "http://127.0.0.1:8079/tools/python/",
57
- "sceneXplain": "http://127.0.0.1:8079/tools/sceneXplain/",
58
- "shell": "http://127.0.0.1:8079/tools/shell/",
59
- "image_generation": "http://127.0.0.1:8079/tools/image_generation/",
60
- "hugging_tools": "http://127.0.0.1:8079/tools/hugging_tools/",
61
- "gradio_tools": "http://127.0.0.1:8079/tools/gradio_tools/",
62
- }
63
-
64
- valid_tools_info = []
65
- all_tools_list = []
66
-
67
- gr.close_all()
68
-
69
- MAX_TURNS = 30
70
- MAX_BOXES = MAX_TURNS * 2
71
-
72
- return_msg = []
73
- chat_history = ""
74
-
75
- MAX_SLEEP_TIME = 40
76
- def load_tools():
77
- global valid_tools_info
78
- global all_tools_list
79
- try:
80
- valid_tools_info = load_valid_tools(tools_mappings)
81
- except BaseException as e:
82
- print(repr(e))
83
- all_tools_list = sorted(list(valid_tools_info.keys()))
84
- return gr.update(choices=all_tools_list)
85
-
86
- def set_environ(OPENAI_API_KEY: str,
87
- WOLFRAMALPH_APP_ID: str = "",
88
- WEATHER_API_KEYS: str = "",
89
- BING_SUBSCRIPT_KEY: str = "",
90
- ALPHA_VANTAGE_KEY: str = "",
91
- BING_MAP_KEY: str = "",
92
- BAIDU_TRANSLATE_KEY: str = "",
93
- RAPIDAPI_KEY: str = "",
94
- SERPER_API_KEY: str = "",
95
- GPLACES_API_KEY: str = "",
96
- SCENEX_API_KEY: str = "",
97
- STEAMSHIP_API_KEY: str = "",
98
- HUGGINGFACE_API_KEY: str = "",):
99
- os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
100
- os.environ["WOLFRAMALPH_APP_ID"] = WOLFRAMALPH_APP_ID
101
- os.environ["WEATHER_API_KEYS"] = WEATHER_API_KEYS
102
- os.environ["BING_SUBSCRIPT_KEY"] = BING_SUBSCRIPT_KEY
103
- os.environ["ALPHA_VANTAGE_KEY"] = ALPHA_VANTAGE_KEY
104
- os.environ["BING_MAP_KEY"] = BING_MAP_KEY
105
- os.environ["BAIDU_TRANSLATE_KEY"] = BAIDU_TRANSLATE_KEY
106
- os.environ["RAPIDAPI_KEY"] = RAPIDAPI_KEY
107
- os.environ["SERPER_API_KEY"] = SERPER_API_KEY
108
- os.environ["GPLACES_API_KEY"] = GPLACES_API_KEY
109
- os.environ["SCENEX_API_KEY"] = SCENEX_API_KEY
110
- os.environ["STEAMSHIP_API_KEY"] = STEAMSHIP_API_KEY
111
- os.environ["HUGGINGFACE_API_KEY"] = HUGGINGFACE_API_KEY
112
- if not tool_server_flag:
113
- start_tool_server()
114
- time.sleep(MAX_SLEEP_TIME)
115
- return gr.update(value="OK!")
116
-
117
- def show_avatar_imgs(tools_chosen):
118
- if len(tools_chosen) == 0:
119
- tools_chosen = list(valid_tools_info.keys())
120
- img_template = '<a href="{}" style="float: left"> <img style="margin:5px" src="{}.png" width="24" height="24" alt="avatar" /> {} </a>'
121
- imgs = [valid_tools_info[tool]['avatar'] for tool in tools_chosen if valid_tools_info[tool]['avatar'] != None]
122
- imgs = ' '.join([img_template.format(img, img, tool) for img, tool in zip(imgs, tools_chosen)])
123
- return [gr.update(value='<span class="">' + imgs + '</span>', visible=True), gr.update(visible=True)]
124
-
125
- def answer_by_tools(question, tools_chosen, model_chosen):
126
- global return_msg
127
- return_msg += [(question, None), (None, '...')]
128
- yield [gr.update(visible=True, value=return_msg), gr.update(), gr.update()]
129
- OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY', '')
130
-
131
- if len(tools_chosen) == 0: # if there is no tools chosen, we use all todo (TODO: What if the pool is too large.)
132
- tools_chosen = list(valid_tools_info.keys())
133
-
134
- if len(tools_chosen) == 1:
135
- answerer = STQuestionAnswerer(OPENAI_API_KEY.strip(), stream_output=True, llm=model_chosen)
136
- agent_executor = answerer.load_tools(tools_chosen[0], valid_tools_info[tools_chosen[0]],
137
- prompt_type="react-with-tool-description", return_intermediate_steps=True)
138
- else:
139
- answerer = MTQuestionAnswerer(OPENAI_API_KEY.strip(),
140
- load_valid_tools({k: tools_mappings[k] for k in tools_chosen}),
141
- stream_output=True, llm=model_chosen)
142
-
143
- agent_executor = answerer.build_runner()
144
-
145
- global chat_history
146
- chat_history += "Question: " + question + "\n"
147
- question = chat_history
148
- for inter in agent_executor(question):
149
- if isinstance(inter, AgentFinish): continue
150
- result_str = []
151
- return_msg.pop()
152
- if isinstance(inter, dict):
153
- result_str.append("<font color=red>Answer:</font> {}".format(inter['output']))
154
- chat_history += "Answer:" + inter['output'] + "\n"
155
- result_str.append("...")
156
- else:
157
- try:
158
- not_observation = inter[0].log
159
- except:
160
- print(inter[0])
161
- not_observation = inter[0]
162
- if not not_observation.startswith('Thought:'):
163
- not_observation = "Thought: " + not_observation
164
- chat_history += not_observation
165
- not_observation = not_observation.replace('Thought:', '<font color=green>Thought: </font>')
166
- not_observation = not_observation.replace('Action:', '<font color=purple>Action: </font>')
167
- not_observation = not_observation.replace('Action Input:', '<font color=purple>Action Input: </font>')
168
- result_str.append("{}".format(not_observation))
169
- result_str.append("<font color=blue>Action output:</font>\n{}".format(inter[1]))
170
- chat_history += "\nAction output:" + inter[1] + "\n"
171
- result_str.append("...")
172
- return_msg += [(None, result) for result in result_str]
173
- yield [gr.update(visible=True, value=return_msg), gr.update(), gr.update()]
174
- return_msg.pop()
175
- if return_msg[-1][1].startswith("<font color=red>Answer:</font> "):
176
- return_msg[-1] = (return_msg[-1][0], return_msg[-1][1].replace("<font color=red>Answer:</font> ",
177
- "<font color=green>Final Answer:</font> "))
178
- yield [gr.update(visible=True, value=return_msg), gr.update(visible=True), gr.update(visible=False)]
179
-
180
-
181
- def retrieve(tools_search):
182
- if tools_search == "":
183
- return gr.update(choices=all_tools_list)
184
- else:
185
- url = "http://127.0.0.1:8079/retrieve"
186
- param = {
187
- "query": tools_search
188
- }
189
- response = requests.post(url, json=param)
190
- result = response.json()
191
- retrieved_tools = result["tools"]
192
- return gr.update(choices=retrieved_tools)
193
-
194
-
195
- def clear_retrieve():
196
- return [gr.update(value=""), gr.update(choices=all_tools_list)]
197
-
198
-
199
- def clear_history():
200
- global return_msg
201
- global chat_history
202
- return_msg = []
203
- chat_history = ""
204
- yield gr.update(visible=True, value=return_msg)
205
-
206
- with gr.Blocks() as demo:
207
- with gr.Row():
208
- with gr.Column(scale=14):
209
- gr.Markdown("<h1 align='left'> BMTools </h1>")
210
- with gr.Column(scale=1):
211
- gr.Markdown('<img src="https://openbmb.cn/openbmb/img/head_logo.e9d9f3f.png" width="140">')
212
-
213
- with gr.Tab("Key setting"):
214
- OPENAI_API_KEY = gr.Textbox(label="OpenAI API KEY:", placeholder="sk-...", type="text")
215
- WOLFRAMALPH_APP_ID = gr.Textbox(label="Wolframalpha app id:", placeholder="Key to use wlframalpha", type="text")
216
- WEATHER_API_KEYS = gr.Textbox(label="Weather api key:", placeholder="Key to use weather api", type="text")
217
- BING_SUBSCRIPT_KEY = gr.Textbox(label="Bing subscript key:", placeholder="Key to use bing search", type="text")
218
- ALPHA_VANTAGE_KEY = gr.Textbox(label="Stock api key:", placeholder="Key to use stock api", type="text")
219
- BING_MAP_KEY = gr.Textbox(label="Bing map key:", placeholder="Key to use bing map", type="text")
220
- BAIDU_TRANSLATE_KEY = gr.Textbox(label="Baidu translation key:", placeholder="Key to use baidu translation", type="text")
221
- RAPIDAPI_KEY = gr.Textbox(label="Rapidapi key:", placeholder="Key to use zillow, airbnb and job search", type="text")
222
- SERPER_API_KEY = gr.Textbox(label="Serper key:", placeholder="Key to use google serper and google scholar", type="text")
223
- GPLACES_API_KEY = gr.Textbox(label="Google places key:", placeholder="Key to use google places", type="text")
224
- SCENEX_API_KEY = gr.Textbox(label="Scenex api key:", placeholder="Key to use sceneXplain", type="text")
225
- STEAMSHIP_API_KEY = gr.Textbox(label="Steamship api key:", placeholder="Key to use image generation", type="text")
226
- HUGGINGFACE_API_KEY = gr.Textbox(label="Huggingface api key:", placeholder="Key to use models in huggingface hub", type="text")
227
- key_set_btn = gr.Button(value="Set keys!")
228
-
229
-
230
- with gr.Tab("Chat with Tool"):
231
- with gr.Row():
232
- with gr.Column(scale=4):
233
- with gr.Row():
234
- with gr.Column(scale=0.85):
235
- txt = gr.Textbox(show_label=False, placeholder="Question here. Use Shift+Enter to add new line.",
236
- lines=1).style(container=False)
237
- with gr.Column(scale=0.15, min_width=0):
238
- buttonChat = gr.Button("Chat")
239
-
240
- chatbot = gr.Chatbot(show_label=False, visible=True).style(height=600)
241
- buttonClear = gr.Button("Clear History")
242
- buttonStop = gr.Button("Stop", visible=False)
243
-
244
- with gr.Column(scale=1):
245
- model_chosen = gr.Dropdown(
246
- list(available_models), value=DEFAULTMODEL, multiselect=False, label="Model provided",
247
- info="Choose the model to solve your question, Default means ChatGPT."
248
- )
249
- with gr.Row():
250
- tools_search = gr.Textbox(
251
- lines=1,
252
- label="Tools Search",
253
- placeholder="Please input some text to search tools.",
254
- )
255
- buttonSearch = gr.Button("Reset search condition")
256
- tools_chosen = gr.CheckboxGroup(
257
- choices=all_tools_list,
258
- value=["chemical-prop"],
259
- label="Tools provided",
260
- info="Choose the tools to solve your question.",
261
- )
262
-
263
- key_set_btn.click(fn=set_environ, inputs=[
264
- OPENAI_API_KEY,
265
- WOLFRAMALPH_APP_ID,
266
- WEATHER_API_KEYS,
267
- BING_SUBSCRIPT_KEY,
268
- ALPHA_VANTAGE_KEY,
269
- BING_MAP_KEY,
270
- BAIDU_TRANSLATE_KEY,
271
- RAPIDAPI_KEY,
272
- SERPER_API_KEY,
273
- GPLACES_API_KEY,
274
- SCENEX_API_KEY,
275
- STEAMSHIP_API_KEY,
276
- HUGGINGFACE_API_KEY,
277
- ], outputs=key_set_btn)
278
- key_set_btn.click(fn=load_tools, outputs=tools_chosen)
279
-
280
- tools_search.change(retrieve, tools_search, tools_chosen)
281
- buttonSearch.click(clear_retrieve, [], [tools_search, tools_chosen])
282
-
283
- txt.submit(lambda: [gr.update(value=''), gr.update(visible=False), gr.update(visible=True)], [],
284
- [txt, buttonClear, buttonStop])
285
- inference_event = txt.submit(answer_by_tools, [txt, tools_chosen, model_chosen], [chatbot, buttonClear, buttonStop])
286
- buttonChat.click(answer_by_tools, [txt, tools_chosen, model_chosen], [chatbot, buttonClear, buttonStop])
287
- buttonStop.click(lambda: [gr.update(visible=True), gr.update(visible=False)], [], [buttonClear, buttonStop],
288
- cancels=[inference_event])
289
- buttonClear.click(clear_history, [], chatbot)
290
-
291
- # demo.queue().launch(share=False, inbrowser=True, server_name="127.0.0.1", server_port=7001)
 
 
 
 
 
 
 
 
 
 
292
  demo.queue().launch()
 
1
+ import sys
2
+ sys.path.append("BMTools/")
3
+
4
+ import gradio as gr
5
+ from bmtools.agent.tools_controller import MTQuestionAnswerer, load_valid_tools
6
+ from bmtools.agent.singletool import STQuestionAnswerer
7
+ from langchain.schema import AgentFinish
8
+ import os
9
+ import requests
10
+
11
+ from tool_server import run_tool_server
12
+ from threading import Thread
13
+ from multiprocessing import Process
14
+ import time
15
+
16
+ tool_server_flag = False
17
+ def start_tool_server():
18
+ # server = Thread(target=run_tool_server)
19
+ server = Process(target=run_tool_server)
20
+ server.start()
21
+ global tool_server_flag
22
+ tool_server_flag = True
23
+
24
+
25
+ available_models = ["ChatGPT", "GPT-3.5"]
26
+ DEFAULTMODEL = "ChatGPT" # "GPT-3.5"
27
+
28
+ tools_mappings = {
29
+ "klarna": "https://www.klarna.com/",
30
+ "weather": "http://127.0.0.1:8079/tools/weather/",
31
+ # "database": "http://127.0.0.1:8079/tools/database/",
32
+ # "db_diag": "http://127.0.0.1:8079/tools/db_diag/",
33
+ "chemical-prop": "http://127.0.0.1:8079/tools/chemical-prop/",
34
+ "douban-film": "http://127.0.0.1:8079/tools/douban-film/",
35
+ "wikipedia": "http://127.0.0.1:8079/tools/wikipedia/",
36
+ # "wikidata": "http://127.0.0.1:8079/tools/kg/wikidata/",
37
+ "wolframalpha": "http://127.0.0.1:8079/tools/wolframalpha/",
38
+ "bing_search": "http://127.0.0.1:8079/tools/bing_search/",
39
+ "office-ppt": "http://127.0.0.1:8079/tools/office-ppt/",
40
+ "stock": "http://127.0.0.1:8079/tools/stock/",
41
+ "bing_map": "http://127.0.0.1:8079/tools/map.bing_map/",
42
+ # "baidu_map": "http://127.0.0.1:8079/tools/map/baidu_map/",
43
+ "zillow": "http://127.0.0.1:8079/tools/zillow/",
44
+ "airbnb": "http://127.0.0.1:8079/tools/airbnb/",
45
+ "job_search": "http://127.0.0.1:8079/tools/job_search/",
46
+ # "baidu-translation": "http://127.0.0.1:8079/tools/translation/baidu-translation/",
47
+ # "nllb-translation": "http://127.0.0.1:8079/tools/translation/nllb-translation/",
48
+ "tutorial": "http://127.0.0.1:8079/tools/tutorial/",
49
+ "file_operation": "http://127.0.0.1:8079/tools/file_operation/",
50
+ "meta_analysis": "http://127.0.0.1:8079/tools/meta_analysis/",
51
+ "code_interpreter": "http://127.0.0.1:8079/tools/code_interpreter/",
52
+ "arxiv": "http://127.0.0.1:8079/tools/arxiv/",
53
+ "google_places": "http://127.0.0.1:8079/tools/google_places/",
54
+ "google_serper": "http://127.0.0.1:8079/tools/google_serper/",
55
+ "google_scholar": "http://127.0.0.1:8079/tools/google_scholar/",
56
+ "python": "http://127.0.0.1:8079/tools/python/",
57
+ "sceneXplain": "http://127.0.0.1:8079/tools/sceneXplain/",
58
+ "shell": "http://127.0.0.1:8079/tools/shell/",
59
+ "image_generation": "http://127.0.0.1:8079/tools/image_generation/",
60
+ "hugging_tools": "http://127.0.0.1:8079/tools/hugging_tools/",
61
+ "gradio_tools": "http://127.0.0.1:8079/tools/gradio_tools/",
62
+ "travel": "http://127.0.0.1:8079/tools/travel",
63
+ "walmart": "http://127.0.0.1:8079/tools/walmart",
64
+ }
65
+
66
+ valid_tools_info = []
67
+ all_tools_list = []
68
+
69
+ gr.close_all()
70
+
71
+ MAX_TURNS = 30
72
+ MAX_BOXES = MAX_TURNS * 2
73
+
74
+ return_msg = []
75
+ chat_history = ""
76
+
77
+ MAX_SLEEP_TIME = 40
78
+ def load_tools():
79
+ global valid_tools_info
80
+ global all_tools_list
81
+ try:
82
+ valid_tools_info = load_valid_tools(tools_mappings)
83
+ except BaseException as e:
84
+ print(repr(e))
85
+ all_tools_list = sorted(list(valid_tools_info.keys()))
86
+ return gr.update(choices=all_tools_list)
87
+
88
+ def set_environ(OPENAI_API_KEY: str,
89
+ WOLFRAMALPH_APP_ID: str = "",
90
+ WEATHER_API_KEYS: str = "",
91
+ BING_SUBSCRIPT_KEY: str = "",
92
+ ALPHA_VANTAGE_KEY: str = "",
93
+ BING_MAP_KEY: str = "",
94
+ BAIDU_TRANSLATE_KEY: str = "",
95
+ RAPIDAPI_KEY: str = "",
96
+ SERPER_API_KEY: str = "",
97
+ GPLACES_API_KEY: str = "",
98
+ SCENEX_API_KEY: str = "",
99
+ STEAMSHIP_API_KEY: str = "",
100
+ HUGGINGFACE_API_KEY: str = "",
101
+ AMADEUS_ID: str = "",
102
+ AMADEUS_KEY: str = "",):
103
+ os.environ["OPENAI_API_KEY"] = OPENAI_API_KEY
104
+ os.environ["WOLFRAMALPH_APP_ID"] = WOLFRAMALPH_APP_ID
105
+ os.environ["WEATHER_API_KEYS"] = WEATHER_API_KEYS
106
+ os.environ["BING_SUBSCRIPT_KEY"] = BING_SUBSCRIPT_KEY
107
+ os.environ["ALPHA_VANTAGE_KEY"] = ALPHA_VANTAGE_KEY
108
+ os.environ["BING_MAP_KEY"] = BING_MAP_KEY
109
+ os.environ["BAIDU_TRANSLATE_KEY"] = BAIDU_TRANSLATE_KEY
110
+ os.environ["RAPIDAPI_KEY"] = RAPIDAPI_KEY
111
+ os.environ["SERPER_API_KEY"] = SERPER_API_KEY
112
+ os.environ["GPLACES_API_KEY"] = GPLACES_API_KEY
113
+ os.environ["SCENEX_API_KEY"] = SCENEX_API_KEY
114
+ os.environ["STEAMSHIP_API_KEY"] = STEAMSHIP_API_KEY
115
+ os.environ["HUGGINGFACE_API_KEY"] = HUGGINGFACE_API_KEY
116
+ os.environ["AMADEUS_ID"] = AMADEUS_ID
117
+ os.environ["AMADEUS_KEY"] = AMADEUS_KEY
118
+ if not tool_server_flag:
119
+ start_tool_server()
120
+ time.sleep(MAX_SLEEP_TIME)
121
+ return gr.update(value="OK!")
122
+
123
+ def show_avatar_imgs(tools_chosen):
124
+ if len(tools_chosen) == 0:
125
+ tools_chosen = list(valid_tools_info.keys())
126
+ img_template = '<a href="{}" style="float: left"> <img style="margin:5px" src="{}.png" width="24" height="24" alt="avatar" /> {} </a>'
127
+ imgs = [valid_tools_info[tool]['avatar'] for tool in tools_chosen if valid_tools_info[tool]['avatar'] != None]
128
+ imgs = ' '.join([img_template.format(img, img, tool) for img, tool in zip(imgs, tools_chosen)])
129
+ return [gr.update(value='<span class="">' + imgs + '</span>', visible=True), gr.update(visible=True)]
130
+
131
+ def answer_by_tools(question, tools_chosen, model_chosen):
132
+ global return_msg
133
+ return_msg += [(question, None), (None, '...')]
134
+ yield [gr.update(visible=True, value=return_msg), gr.update(), gr.update()]
135
+ OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY', '')
136
+
137
+ if len(tools_chosen) == 0: # if there is no tools chosen, we use all todo (TODO: What if the pool is too large.)
138
+ tools_chosen = list(valid_tools_info.keys())
139
+
140
+ if len(tools_chosen) == 1:
141
+ answerer = STQuestionAnswerer(OPENAI_API_KEY.strip(), stream_output=True, llm=model_chosen)
142
+ agent_executor = answerer.load_tools(tools_chosen[0], valid_tools_info[tools_chosen[0]],
143
+ prompt_type="react-with-tool-description", return_intermediate_steps=True)
144
+ else:
145
+ answerer = MTQuestionAnswerer(OPENAI_API_KEY.strip(),
146
+ load_valid_tools({k: tools_mappings[k] for k in tools_chosen}),
147
+ stream_output=True, llm=model_chosen)
148
+
149
+ agent_executor = answerer.build_runner()
150
+
151
+ global chat_history
152
+ chat_history += "Question: " + question + "\n"
153
+ question = chat_history
154
+ for inter in agent_executor(question):
155
+ if isinstance(inter, AgentFinish): continue
156
+ result_str = []
157
+ return_msg.pop()
158
+ if isinstance(inter, dict):
159
+ result_str.append("<font color=red>Answer:</font> {}".format(inter['output']))
160
+ chat_history += "Answer:" + inter['output'] + "\n"
161
+ result_str.append("...")
162
+ else:
163
+ try:
164
+ not_observation = inter[0].log
165
+ except:
166
+ print(inter[0])
167
+ not_observation = inter[0]
168
+ if not not_observation.startswith('Thought:'):
169
+ not_observation = "Thought: " + not_observation
170
+ chat_history += not_observation
171
+ not_observation = not_observation.replace('Thought:', '<font color=green>Thought: </font>')
172
+ not_observation = not_observation.replace('Action:', '<font color=purple>Action: </font>')
173
+ not_observation = not_observation.replace('Action Input:', '<font color=purple>Action Input: </font>')
174
+ result_str.append("{}".format(not_observation))
175
+ result_str.append("<font color=blue>Action output:</font>\n{}".format(inter[1]))
176
+ chat_history += "\nAction output:" + inter[1] + "\n"
177
+ result_str.append("...")
178
+ return_msg += [(None, result) for result in result_str]
179
+ yield [gr.update(visible=True, value=return_msg), gr.update(), gr.update()]
180
+ return_msg.pop()
181
+ if return_msg[-1][1].startswith("<font color=red>Answer:</font> "):
182
+ return_msg[-1] = (return_msg[-1][0], return_msg[-1][1].replace("<font color=red>Answer:</font> ",
183
+ "<font color=green>Final Answer:</font> "))
184
+ yield [gr.update(visible=True, value=return_msg), gr.update(visible=True), gr.update(visible=False)]
185
+
186
+
187
+ def retrieve(tools_search):
188
+ if tools_search == "":
189
+ return gr.update(choices=all_tools_list)
190
+ else:
191
+ url = "http://127.0.0.1:8079/retrieve"
192
+ param = {
193
+ "query": tools_search
194
+ }
195
+ response = requests.post(url, json=param)
196
+ result = response.json()
197
+ retrieved_tools = result["tools"]
198
+ return gr.update(choices=retrieved_tools)
199
+
200
+
201
+ def clear_retrieve():
202
+ return [gr.update(value=""), gr.update(choices=all_tools_list)]
203
+
204
+
205
+ def clear_history():
206
+ global return_msg
207
+ global chat_history
208
+ return_msg = []
209
+ chat_history = ""
210
+ yield gr.update(visible=True, value=return_msg)
211
+
212
+ with gr.Blocks() as demo:
213
+ with gr.Row():
214
+ with gr.Column(scale=14):
215
+ gr.Markdown("<h1 align='left'> BMTools </h1>")
216
+ with gr.Column(scale=1):
217
+ gr.Markdown('<img src="https://openbmb.cn/openbmb/img/head_logo.e9d9f3f.png" width="140">')
218
+
219
+ with gr.Tab("Key setting"):
220
+ OPENAI_API_KEY = gr.Textbox(label="OpenAI API KEY:", placeholder="sk-...", type="text")
221
+ WOLFRAMALPH_APP_ID = gr.Textbox(label="Wolframalpha app id:", placeholder="Key to use wlframalpha", type="text")
222
+ WEATHER_API_KEYS = gr.Textbox(label="Weather api key:", placeholder="Key to use weather api", type="text")
223
+ BING_SUBSCRIPT_KEY = gr.Textbox(label="Bing subscript key:", placeholder="Key to use bing search", type="text")
224
+ ALPHA_VANTAGE_KEY = gr.Textbox(label="Stock api key:", placeholder="Key to use stock api", type="text")
225
+ BING_MAP_KEY = gr.Textbox(label="Bing map key:", placeholder="Key to use bing map", type="text")
226
+ BAIDU_TRANSLATE_KEY = gr.Textbox(label="Baidu translation key:", placeholder="Key to use baidu translation", type="text")
227
+ RAPIDAPI_KEY = gr.Textbox(label="Rapidapi key:", placeholder="Key to use zillow, airbnb and job search", type="text")
228
+ SERPER_API_KEY = gr.Textbox(label="Serper key:", placeholder="Key to use google serper and google scholar", type="text")
229
+ GPLACES_API_KEY = gr.Textbox(label="Google places key:", placeholder="Key to use google places", type="text")
230
+ SCENEX_API_KEY = gr.Textbox(label="Scenex api key:", placeholder="Key to use sceneXplain", type="text")
231
+ STEAMSHIP_API_KEY = gr.Textbox(label="Steamship api key:", placeholder="Key to use image generation", type="text")
232
+ HUGGINGFACE_API_KEY = gr.Textbox(label="Huggingface api key:", placeholder="Key to use models in huggingface hub", type="text")
233
+ AMADEUS_ID = gr.Textbox(label="Amadeus id:", placeholder="Id to use Amadeus", type="text")
234
+ AMADEUS_KEY = gr.Textbox(label="Amadeus key:", placeholder="Key to use Amadeus", type="text")
235
+ key_set_btn = gr.Button(value="Set keys!")
236
+
237
+
238
+ with gr.Tab("Chat with Tool"):
239
+ with gr.Row():
240
+ with gr.Column(scale=4):
241
+ with gr.Row():
242
+ with gr.Column(scale=0.85):
243
+ txt = gr.Textbox(show_label=False, placeholder="Question here. Use Shift+Enter to add new line.",
244
+ lines=1).style(container=False)
245
+ with gr.Column(scale=0.15, min_width=0):
246
+ buttonChat = gr.Button("Chat")
247
+
248
+ chatbot = gr.Chatbot(show_label=False, visible=True).style(height=600)
249
+ buttonClear = gr.Button("Clear History")
250
+ buttonStop = gr.Button("Stop", visible=False)
251
+
252
+ with gr.Column(scale=1):
253
+ model_chosen = gr.Dropdown(
254
+ list(available_models), value=DEFAULTMODEL, multiselect=False, label="Model provided",
255
+ info="Choose the model to solve your question, Default means ChatGPT."
256
+ )
257
+ with gr.Row():
258
+ tools_search = gr.Textbox(
259
+ lines=1,
260
+ label="Tools Search",
261
+ placeholder="Please input some text to search tools.",
262
+ )
263
+ buttonSearch = gr.Button("Reset search condition")
264
+ tools_chosen = gr.CheckboxGroup(
265
+ choices=all_tools_list,
266
+ value=["chemical-prop"],
267
+ label="Tools provided",
268
+ info="Choose the tools to solve your question.",
269
+ )
270
+
271
+ key_set_btn.click(fn=set_environ, inputs=[
272
+ OPENAI_API_KEY,
273
+ WOLFRAMALPH_APP_ID,
274
+ WEATHER_API_KEYS,
275
+ BING_SUBSCRIPT_KEY,
276
+ ALPHA_VANTAGE_KEY,
277
+ BING_MAP_KEY,
278
+ BAIDU_TRANSLATE_KEY,
279
+ RAPIDAPI_KEY,
280
+ SERPER_API_KEY,
281
+ GPLACES_API_KEY,
282
+ SCENEX_API_KEY,
283
+ STEAMSHIP_API_KEY,
284
+ HUGGINGFACE_API_KEY,
285
+ AMADEUS_ID,
286
+ AMADEUS_KEY,
287
+ ], outputs=key_set_btn)
288
+ key_set_btn.click(fn=load_tools, outputs=tools_chosen)
289
+
290
+ tools_search.change(retrieve, tools_search, tools_chosen)
291
+ buttonSearch.click(clear_retrieve, [], [tools_search, tools_chosen])
292
+
293
+ txt.submit(lambda: [gr.update(value=''), gr.update(visible=False), gr.update(visible=True)], [],
294
+ [txt, buttonClear, buttonStop])
295
+ inference_event = txt.submit(answer_by_tools, [txt, tools_chosen, model_chosen], [chatbot, buttonClear, buttonStop])
296
+ buttonChat.click(answer_by_tools, [txt, tools_chosen, model_chosen], [chatbot, buttonClear, buttonStop])
297
+ buttonStop.click(lambda: [gr.update(visible=True), gr.update(visible=False)], [], [buttonClear, buttonStop],
298
+ cancels=[inference_event])
299
+ buttonClear.click(clear_history, [], chatbot)
300
+
301
+ # demo.queue().launch(share=False, inbrowser=True, server_name="127.0.0.1", server_port=7001)
302
  demo.queue().launch()