haonan-li commited on
Commit
f661a7e
·
1 Parent(s): e077ff8

Add docker

Browse files
Files changed (5) hide show
  1. Dockerfile +32 -0
  2. app.py +294 -0
  3. assets/banner.jpg +0 -0
  4. requirements.txt +15 -0
  5. utils.py +18 -0
Dockerfile ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10-slim
2
+
3
+ RUN apt-get update && \
4
+ apt-get install -y \
5
+ bash \
6
+ git git-lfs \
7
+ wget curl procps \
8
+ htop vim nano unzip tmux
9
+
10
+
11
+ WORKDIR /app
12
+ RUN useradd -m -u 1000 user
13
+ USER user
14
+ ENV PATH="/home/user/.local/bin:$PATH"
15
+
16
+
17
+ # All users can use /home/user as their home directory
18
+ ENV HOME=/home/user
19
+ RUN mkdir $HOME/.cache $HOME/.config \
20
+ && chmod -R 777 $HOME
21
+
22
+
23
+ # Copy the current directory contents into the container at $HOME/app setting the owner to the user
24
+ COPY --chown=user . $HOME/app
25
+ WORKDIR $HOME/app
26
+
27
+
28
+ # COPY --chown=user ./requirements.txt requirements.txt
29
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
30
+
31
+ # COPY --chown=1000 ./ /app
32
+ CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import gradio as gr
3
+ from huggingface_hub import InferenceClient
4
+ import spaces
5
+ import transformers
6
+ from fastchat.conversation import get_conv_template
7
+ import subprocess
8
+ import os
9
+ from utils import toolgen_request
10
+ import ast
11
+ import modelscope_studio.components.antd as antd
12
+ import modelscope_studio.components.base as ms
13
+
14
+ """
15
+ For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
16
+ """
17
+ # client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
18
+
19
+
20
+ # def respond(
21
+ # message,
22
+ # history: list[tuple[str, str]],
23
+ # system_message,
24
+ # max_tokens,
25
+ # temperature,
26
+ # top_p,
27
+ # ):
28
+ # messages = [{"role": "system", "content": system_message}]
29
+
30
+ # for val in history:
31
+ # if val[0]:
32
+ # messages.append({"role": "user", "content": val[0]})
33
+ # if val[1]:
34
+ # messages.append({"role": "assistant", "content": val[1]})
35
+
36
+ # messages.append({"role": "user", "content": message})
37
+
38
+ # response = ""
39
+
40
+ # for message in client.chat_completion(
41
+ # messages,
42
+ # max_tokens=max_tokens,
43
+ # stream=True,
44
+ # temperature=temperature,
45
+ # top_p=top_p,
46
+ # ):
47
+ # token = message.choices[0].delta.content
48
+
49
+ # response += token
50
+ # yield response
51
+
52
+
53
+ # rapidapi_wrapper = RapidAPIWrapper(
54
+ # toolbench_key="2FrSLuUC37WJypPTsv0Rqw8kE5nD1YzMaxtbich4KIde9NOHjG",
55
+ # rapidapi_key="",
56
+ # )
57
+ # toolgen = ToolGen(
58
+ # "reasonwang/ToolGen-WoSystem-Llama-3-8B-Instruct",
59
+ # indexing="Atomic",
60
+ # tools=rapidapi_wrapper,
61
+ # )
62
+ # subprocess.run("rm -rf /data-nvme/zerogpu-offload/*", env={}, shell=True)
63
+
64
+ # @spaces.GPU(duration=15)
65
+ # def respond(
66
+ # message,
67
+ # history: list[tuple[str, str]],
68
+ # system_message,
69
+ # max_tokens,
70
+ # temperature,
71
+ # top_p,
72
+ # ):
73
+ # messages = [{"role": "system", "content": system_message}]
74
+ # for val in history:
75
+ # if val[0]:
76
+ # messages.append({"role": "user", "content": val[0]})
77
+ # if val[1]:
78
+ # messages.append({"role": "assistant", "content": val[1]})
79
+ # messages.append({"role": "user", "content": message})
80
+ # conv = get_conv_template("llama-3")
81
+ # for message in messages:
82
+ # conv.append_message(conv.roles[0] if message['role'] == 'user' else conv.roles[1], message['content'])
83
+ # conv.append_message(conv.roles[1], None)
84
+ # prompt = conv.get_prompt()
85
+ # # print(prompt)
86
+
87
+ # inputs = tokenizer(prompt, return_tensors='pt')
88
+ # input_length = inputs["input_ids"].shape[1]
89
+
90
+ # for k, v in inputs.items():
91
+ # inputs[k] = v.to("cuda")
92
+ # outputs = model.generate(
93
+ # **inputs,
94
+ # max_new_tokens=max_tokens,
95
+ # temperature=temperature,
96
+ # top_p=top_p,
97
+ # )
98
+ # output_ids = outputs[0][input_length:-1]
99
+ # output_length = output_ids.shape[0]
100
+ # generated_text = tokenizer.decode(output_ids)
101
+ # yield generated_text
102
+
103
+ # @spaces.GPU(duration=30)
104
+ # def toolgen_respond(
105
+ # message,
106
+ # history: list[tuple[str, str]],
107
+ # system_message,
108
+ # max_tokens,
109
+ # temperature,
110
+ # top_p,
111
+ # ):
112
+ # messages = [
113
+ # {"role": "system", "content": system_message},
114
+ # {"role": "user", "content": message},
115
+ # ]
116
+ # toolgen.restart()
117
+ # contents = ""
118
+ # for content in toolgen.start(
119
+ # single_chain_max_step=10,
120
+ # start_messages=messages,
121
+ # streaming=True,
122
+ # ):
123
+ # contents += content
124
+ # yield contents
125
+
126
+ # toolgen_respond.zerogpu = True
127
+
128
+ """
129
+ For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
130
+ """
131
+ def test_click(query):
132
+ print(query)
133
+
134
+ return f'''<p style="color:red;">I am red: {query} is a query </p>''', f'''<p style="color:blue;">I am blue: {query} is a query </p>'''
135
+
136
+ def resolve_image(filename):
137
+ return os.path.join(os.path.dirname(__file__), filename)
138
+
139
+ # @gr.render(inputs=[query])
140
+ # def show_split(text):
141
+ # if len(text) == 0:
142
+ # gr.Markdown("## No Input Provided")
143
+ # else:
144
+ # for letter in text:
145
+ # with gr.Row():
146
+ # text = gr.Textbox(letter)
147
+ # btn = gr.Button("Clear")
148
+ # btn.click(lambda: gr.Textbox(value=""), None, text)
149
+
150
+ example_queries = [
151
+ ["I'm a football fan and I'm curious about the different team names used in different leagues and countries. Can you provide me with an extensive list of football team names and their short names? It would be great if I could access more than 7000 team names. Additionally, I would like to see the first 25 team names and their short names using the basic plan."],
152
+ ["I want to eat some cakes. Please recommend some websites about cakes for me."],
153
+ ["My company is hosting a rugby event and we need to provide pre-match form information to the participants. Can you fetch the pre-match form for a specific rugby match? We would also like to see the incidents that occurred during the match."],
154
+ ["I'm a photographer and want to capture the beauty of the beach during sunrise and sunset. Can you provide me with the astronomy data for a specific location? It would be great to know the sunrise and sunset times. Additionally, I would like to retrieve the high and low tide information for that location."],
155
+ ["Give me some information about the president of the United States. I want you to directly answer this question, do not call any tool."],
156
+ ["I want you to give up this task."],
157
+ ]
158
+
159
+ action_color_palette = [
160
+ "#b9d9eb",
161
+ "#fde8f7",
162
+ "#d9d577",
163
+ "#b784e7",
164
+ "#f9a596",
165
+ "#ece2d0",
166
+ "#d3c2ce",
167
+ ]
168
+
169
+
170
+ def run(query):
171
+ endpoint = "http://localhost:5000/generate"
172
+ random.shuffle(action_color_palette)
173
+
174
+ agent_content = []
175
+ observation_content = []
176
+
177
+ unfinished_content = {
178
+ "title": "Unfinished"
179
+ }
180
+ yield [unfinished_content], [unfinished_content]
181
+ action_count = 0
182
+
183
+ for status in toolgen_request(endpoint, query, system_prompt=None):
184
+
185
+ if "message" in status:
186
+ with gr.Column():
187
+ agent_content.append({
188
+ "title": "Thought",
189
+ "content": status['message']['content']
190
+ })
191
+ # gr.Markdown(f"Thought: {status['message']['content']}")
192
+ agent_content.append({
193
+ "title": "Action",
194
+ "content": status['message']['action'],
195
+ "color": action_color_palette[action_count % len(action_color_palette)]
196
+ })
197
+ action_count += 1
198
+ # gr.Markdown(f"Action: {status['message']['action']}")
199
+ agent_content.append({
200
+ "title": "Arguments",
201
+ "content": status['message']['arguments']
202
+ })
203
+ # gr.Markdown(f"Action Input: {status['message']['arguments']}")
204
+ yield agent_content + [unfinished_content], observation_content + [unfinished_content]
205
+ elif "observation" in status:
206
+ observation_content.append({
207
+ "title": "Observation",
208
+ "content": status["observation"]
209
+ })
210
+ yield agent_content+ [unfinished_content], observation_content+ [unfinished_content]
211
+ # with gr.Column():
212
+ # gr.Markdown(status["observation"])
213
+ yield agent_content, observation_content
214
+
215
+
216
+ with gr.Blocks(delete_cache=(600, 600)) as demo:
217
+ with ms.Application():
218
+ with antd.ConfigProvider():
219
+
220
+ with gr.Column():
221
+
222
+ gr.Markdown("""
223
+ ## Complete Tasks with [ToolGen](https://arxiv.org/abs/2410.03439): New Paradigm for LLM Agent
224
+ * 🚀 Input a query and click "Inference" to complete the task. The whole process may take some time.
225
+ * 🛠️ Currently we only support tools in ToolBench, we are committed to develop ToolGen for more tools.
226
+ * 🎮 Have fun!
227
+
228
+
229
+ """)
230
+ with antd.Card(elem_style=dict(marginBottom=4),
231
+ styles=dict(body=dict(padding=4))):
232
+ with antd.Flex(elem_style=dict(width="100%",height="100%"),
233
+ justify="center",
234
+ align="center",
235
+ gap=0):
236
+ with ms.Div(elem_style=dict(flexShrink=0)):
237
+ antd.Image(resolve_image("./assets/banner.jpg"), preview=False, height=80, width=900)
238
+
239
+ # with antd.Flex(vertical=True, justify="flex-start", align="center"):
240
+ # with antd.Flex(vertical=True, justify="center", align="flex-start"):
241
+ # with antd.Flex(vertical=True, justify="center", align="center"):
242
+ with gr.Row():
243
+ with gr.Column():
244
+ query = gr.TextArea(placeholder="Type your query here...", label="Query")
245
+ generate_btn = gr.Button("Inference")
246
+ examples = gr.Examples(example_queries, label="Examples", inputs=query)
247
+ # gr.Markdown("""*NOTE: Gaussian file can be very large (~50MB), it will take a while to display and download.*""")
248
+
249
+ # with antd.Flex(vertical=True, justify="flex-start", align="center"):
250
+ # with antd.Flex(vertical=True, justify="center", align="flex-start"):
251
+ # with antd.Flex(vertical=True, justify="center", align="center"):
252
+ with gr.Column():
253
+ agent_box = gr.TextArea(placeholder="Agent", visible=False)
254
+ with antd.Card(size="small", bordered=False):
255
+ ms.Div("Agent", elem_style={"font-weight": "bold"})
256
+ @gr.render(inputs=[agent_box], triggers=[agent_box.change])
257
+ def render_agent(agent_content):
258
+ agent_content = ast.literal_eval(agent_content)
259
+ for content in agent_content:
260
+ if content['title'] == "Unfinished":
261
+ with antd.Card(title="Generating...", size='small', bordered=False, loading=True):
262
+ pass
263
+ else:
264
+ if content['title'] == "Action":
265
+ with antd.Card(title=content['title'], size="small", bordered=False):
266
+ ms.Div(content['content'], elem_style={"background-color": content["color"], "font-weight": "bold", "border-radius": "6px", "display": "inline-block"})
267
+ else:
268
+ with antd.Card(title=content['title'], size="small", bordered=False):
269
+ ms.Div(content['content'])
270
+
271
+ # with antd.Flex(vertical=True, justify="flex-start", align="center"):
272
+ # with antd.Flex(vertical=True, justify="center", align="flex-start"):
273
+ # with antd.Flex(vertical=True, justify="center", align="center"):
274
+ with gr.Column():
275
+ system_box = gr.TextArea(placeholder="System", visible=False)
276
+ with antd.Card(size="small", bordered=False):
277
+ ms.Div("System", elem_style={"font-weight": "bold"})
278
+ @gr.render(inputs=[system_box], triggers=[system_box.change])
279
+ def render_agent(observation_content):
280
+ observation_content = ast.literal_eval(observation_content)
281
+ for content in observation_content:
282
+ if content['title'] == "Unfinished":
283
+ with antd.Card(title="Processing...", size='small', bordered=False, loading=True):
284
+ pass
285
+ else:
286
+ with antd.Card(title=content['title'], size="small", bordered=False):
287
+ ms.Div(content['content'])
288
+
289
+ generate_btn.click(run, inputs=[query], outputs=[agent_box, system_box], time_limit=120)
290
+
291
+
292
+
293
+ if __name__ == "__main__":
294
+ demo.launch(server_port=7860)
assets/banner.jpg ADDED
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio
2
+ huggingface_hub
3
+ slowapi
4
+ tenacity
5
+ openai
6
+ transformers
7
+ termcolor
8
+ unidecode
9
+ modelscope_studio
10
+ flask
11
+ accelerate
12
+ bitsandbytes
13
+ fschat
14
+ spaces
15
+ torch==2.4.0
utils.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import requests
3
+
4
+ def toolgen_request(endpoint_url, query, system_prompt=None):
5
+ payload = {
6
+ "query": query,
7
+ "system_prompt": system_prompt
8
+ }
9
+
10
+ try:
11
+ response = requests.post(endpoint_url, json=payload, stream=True) # Enable streaming
12
+ response.raise_for_status() # Raise an error for HTTP errors
13
+ for line in response.iter_lines(decode_unicode=True):
14
+ if line: # Filter out keep-alive new lines
15
+ yield json.loads(line) # Parse each line as JSON
16
+ except requests.exceptions.RequestException as e:
17
+ print(f"Error calling ToolGen model: {e}")
18
+ yield {"error": str(e)}