johann22 commited on
Commit
84df34e
1 Parent(s): 05e56df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +350 -2
app.py CHANGED
@@ -1,11 +1,359 @@
 
 
 
1
  from huggingface_hub import InferenceClient
2
  import gradio as gr
3
- import random
4
- import prompts
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  client = InferenceClient(
6
  "mistralai/Mixtral-8x7B-Instruct-v0.1"
7
  )
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  def format_prompt(message, history):
10
  prompt = "<s>"
11
  for user_prompt, bot_response in history:
 
1
+ import os
2
+ import subprocess
3
+ import random
4
  from huggingface_hub import InferenceClient
5
  import gradio as gr
6
+ from i_search import google
7
+ from i_search import i_search as i_s
8
+ from prompts import (
9
+ ACTION_PROMPT,
10
+ ADD_PROMPT,
11
+ COMPRESS_HISTORY_PROMPT,
12
+ LOG_PROMPT,
13
+ LOG_RESPONSE,
14
+ MODIFY_PROMPT,
15
+ PREFIX,
16
+ SEARCH_QUERY,
17
+ READ_PROMPT,
18
+ TASK_PROMPT,
19
+ UNDERSTAND_TEST_RESULTS_PROMPT,
20
+ )
21
+ from utils import parse_action, parse_file_content, read_python_module_structure
22
  client = InferenceClient(
23
  "mistralai/Mixtral-8x7B-Instruct-v0.1"
24
  )
25
 
26
+ ############################################
27
+
28
+
29
+ VERBOSE = True
30
+ MAX_HISTORY = 100
31
+ #MODEL = "gpt-3.5-turbo" # "gpt-4"
32
+
33
+
34
+ def format_prompt(message, history):
35
+ prompt = "<s>"
36
+ for user_prompt, bot_response in history:
37
+ prompt += f"[INST] {user_prompt} [/INST]"
38
+ prompt += f" {bot_response}</s> "
39
+ prompt += f"[INST] {message} [/INST]"
40
+ return prompt
41
+
42
+
43
+
44
+ def run_gpt(
45
+ prompt_template,
46
+ stop_tokens,
47
+ max_tokens,
48
+ module_summary,
49
+ purpose,
50
+ **prompt_kwargs,
51
+ ):
52
+ seed = random.randint(1,1111111111111111)
53
+
54
+ generate_kwargs = dict(
55
+ temperature=0.9,
56
+ max_new_tokens=10480,
57
+ top_p=0.95,
58
+ repetition_penalty=1.0,
59
+ do_sample=True,
60
+ seed=seed,
61
+ )
62
+
63
+
64
+ content = PREFIX.format(
65
+ purpose=purpose,
66
+ ) + prompt_template.format(**prompt_kwargs)
67
+ if VERBOSE:
68
+ print(LOG_PROMPT.format(content))
69
+
70
+
71
+ #formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history)
72
+ #formatted_prompt = format_prompt(f'{content}', history)
73
+
74
+ stream = client.text_generation(content, **generate_kwargs, stream=True, details=True, return_full_text=False)
75
+ resp = ""
76
+ for response in stream:
77
+ resp += response.token.text
78
+ #yield resp
79
+ '''
80
+ resp = openai.ChatCompletion.create(
81
+ model=MODEL,
82
+ messages=[
83
+ {"role": "system", "content": content},
84
+ ],
85
+ temperature=0.0,
86
+ max_tokens=max_tokens,
87
+ stop=stop_tokens if stop_tokens else None,
88
+ )["choices"][0]["message"]["content"]
89
+ '''
90
+ if VERBOSE:
91
+ print(LOG_RESPONSE.format(resp))
92
+ return resp
93
+
94
+
95
+ def compress_history(purpose, task, history, directory):
96
+ module_summary, _, _ = read_python_module_structure(directory)
97
+ resp = run_gpt(
98
+ COMPRESS_HISTORY_PROMPT,
99
+ stop_tokens=["observation:", "task:", "action:", "thought:"],
100
+ max_tokens=512,
101
+ module_summary=module_summary,
102
+ purpose=purpose,
103
+ task=task,
104
+ history=history,
105
+ )
106
+ history = "observation: {}\n".format(resp)
107
+ return history
108
+
109
+ def call_search(purpose, task, history, directory, action_input):
110
+ print("CALLING SEARCH")
111
+ if "http" in action_input:
112
+ if "<" in action_input:
113
+ action_input = action_input.strip("<")
114
+ if ">" in action_input:
115
+ action_input = action_input.strip(">")
116
+ response = i_s(action_input)
117
+ #response = google(search_return)
118
+ print(response)
119
+ history += "observation: search result is: {}\n".format(response)
120
+ else:
121
+ history += "observation: I need to provide a valid URL to 'action: SEARCH action_input=URL'"
122
+ return "MAIN", None, history, task
123
+
124
+ def call_main(purpose, task, history, directory, action_input):
125
+ module_summary, _, _ = read_python_module_structure(directory)
126
+ resp = run_gpt(
127
+ ACTION_PROMPT,
128
+ stop_tokens=["observation:", "task:"],
129
+ max_tokens=256,
130
+ module_summary=module_summary,
131
+ purpose=purpose,
132
+ task=task,
133
+ history=history,
134
+ )
135
+ lines = resp.strip().strip("\n").split("\n")
136
+ for line in lines:
137
+ if line == "":
138
+ continue
139
+ if line.startswith("thought: "):
140
+ history += "{}\n".format(line)
141
+ elif line.startswith("action: "):
142
+
143
+ action_name, action_input = parse_action(line)
144
+ print (f'ACTION_NAME :: {action_name}')
145
+ print (f'ACTION_INPUT :: {action_input}')
146
+
147
+ history += "{}\n".format(line)
148
+ if action_name=="COMPLETE" or action_input=="COMPLETE":
149
+ task = "END"
150
+ return action_name, action_input, history, task
151
+ else:
152
+ return action_name, action_input, history, task
153
+ else:
154
+ assert False, "unknown action: {}".format(line)
155
+ return "MAIN", None, history, task
156
+
157
+
158
+ def call_test(purpose, task, history, directory, action_input):
159
+ result = subprocess.run(
160
+ ["python", "-m", "pytest", "--collect-only", directory],
161
+ capture_output=True,
162
+ text=True,
163
+ )
164
+ if result.returncode != 0:
165
+ history += "observation: there are no tests! Test should be written in a test folder under {}\n".format(
166
+ directory
167
+ )
168
+ return "MAIN", None, history, task
169
+ result = subprocess.run(
170
+ ["python", "-m", "pytest", directory], capture_output=True, text=True
171
+ )
172
+ if result.returncode == 0:
173
+ history += "observation: tests pass\n"
174
+ return "MAIN", None, history, task
175
+ module_summary, content, _ = read_python_module_structure(directory)
176
+ resp = run_gpt(
177
+ UNDERSTAND_TEST_RESULTS_PROMPT,
178
+ stop_tokens=[],
179
+ max_tokens=256,
180
+ module_summary=module_summary,
181
+ purpose=purpose,
182
+ task=task,
183
+ history=history,
184
+ stdout=result.stdout[:5000], # limit amount of text
185
+ stderr=result.stderr[:5000], # limit amount of text
186
+ )
187
+ history += "observation: tests failed: {}\n".format(resp)
188
+ return "MAIN", None, history, task
189
+
190
+
191
+ def call_set_task(purpose, task, history, directory, action_input):
192
+ module_summary, content, _ = read_python_module_structure(directory)
193
+ task = run_gpt(
194
+ TASK_PROMPT,
195
+ stop_tokens=[],
196
+ max_tokens=64,
197
+ module_summary=module_summary,
198
+ purpose=purpose,
199
+ task=task,
200
+ history=history,
201
+ ).strip("\n")
202
+ history += "observation: task has been updated to: {}\n".format(task)
203
+ return "MAIN", None, history, task
204
+
205
+
206
+ def call_read(purpose, task, history, directory, action_input):
207
+ if not os.path.exists(action_input):
208
+ history += "observation: file does not exist\n"
209
+ return "MAIN", None, history, task
210
+ module_summary, content, _ = read_python_module_structure(directory)
211
+ f_content = (
212
+ content[action_input] if content[action_input] else "< document is empty >"
213
+ )
214
+ resp = run_gpt(
215
+ READ_PROMPT,
216
+ stop_tokens=[],
217
+ max_tokens=256,
218
+ module_summary=module_summary,
219
+ purpose=purpose,
220
+ task=task,
221
+ history=history,
222
+ file_path=action_input,
223
+ file_contents=f_content,
224
+ ).strip("\n")
225
+ history += "observation: {}\n".format(resp)
226
+ return "MAIN", None, history, task
227
+
228
+
229
+ def call_modify(purpose, task, history, directory, action_input):
230
+ if not os.path.exists(action_input):
231
+ history += "observation: file does not exist\n"
232
+ return "MAIN", None, history, task
233
+ (
234
+ module_summary,
235
+ content,
236
+ _,
237
+ ) = read_python_module_structure(directory)
238
+ f_content = (
239
+ content[action_input] if content[action_input] else "< document is empty >"
240
+ )
241
+ resp = run_gpt(
242
+ MODIFY_PROMPT,
243
+ stop_tokens=["action:", "thought:", "observation:"],
244
+ max_tokens=2048,
245
+ module_summary=module_summary,
246
+ purpose=purpose,
247
+ task=task,
248
+ history=history,
249
+ file_path=action_input,
250
+ file_contents=f_content,
251
+ )
252
+ new_contents, description = parse_file_content(resp)
253
+ if new_contents is None:
254
+ history += "observation: failed to modify file\n"
255
+ return "MAIN", None, history, task
256
+
257
+ with open(action_input, "w") as f:
258
+ f.write(new_contents)
259
+
260
+ history += "observation: file successfully modified\n"
261
+ history += "observation: {}\n".format(description)
262
+ return "MAIN", None, history, task
263
+
264
+
265
+ def call_add(purpose, task, history, directory, action_input):
266
+ d = os.path.dirname(action_input)
267
+ if not d.startswith(directory):
268
+ history += "observation: files must be under directory {}\n".format(directory)
269
+ elif not action_input.endswith(".py"):
270
+ history += "observation: can only write .py files\n"
271
+ else:
272
+ if d and not os.path.exists(d):
273
+ os.makedirs(d)
274
+ if not os.path.exists(action_input):
275
+ module_summary, _, _ = read_python_module_structure(directory)
276
+ resp = run_gpt(
277
+ ADD_PROMPT,
278
+ stop_tokens=["action:", "thought:", "observation:"],
279
+ max_tokens=2048,
280
+ module_summary=module_summary,
281
+ purpose=purpose,
282
+ task=task,
283
+ history=history,
284
+ file_path=action_input,
285
+ )
286
+ new_contents, description = parse_file_content(resp)
287
+ if new_contents is None:
288
+ history += "observation: failed to write file\n"
289
+ return "MAIN", None, history, task
290
+
291
+ with open(action_input, "w") as f:
292
+ f.write(new_contents)
293
+
294
+ history += "observation: file successfully written\n"
295
+ history += "obsertation: {}\n".format(description)
296
+ else:
297
+ history += "observation: file already exists\n"
298
+ return "MAIN", None, history, task
299
+ def end_fn(purpose, task, history, directory, action_input):
300
+ task = "END"
301
+ return "COMPLETE", None, history, task
302
+ NAME_TO_FUNC = {
303
+ "MAIN": call_main,
304
+ "UPDATE-TASK": call_set_task,
305
+ "SEARCH": call_search,
306
+ "COMPLETE": end_fn,
307
+
308
+ }
309
+
310
+
311
+ def run_action(purpose, task, history, directory, action_name, action_input):
312
+ if action_name == "COMPLETE":
313
+ task="END"
314
+ return action_name, action_input, history, task
315
+
316
+ # compress the history when it is long
317
+ if len(history.split("\n")) > MAX_HISTORY:
318
+ if VERBOSE:
319
+ print("COMPRESSING HISTORY")
320
+ history = compress_history(purpose, task, history, directory)
321
+
322
+ assert action_name in NAME_TO_FUNC
323
+
324
+ print("RUN: ", action_name, action_input)
325
+ return NAME_TO_FUNC[action_name](purpose, task, history, directory, action_input)
326
+
327
+
328
+ def run(purpose, directory, task=None):
329
+ history = ""
330
+ action_name = "UPDATE-TASK" if task is None else "MAIN"
331
+ action_input = None
332
+ while True:
333
+ print("")
334
+ print("")
335
+ print("---")
336
+ print("purpose:", purpose)
337
+ print("task:", task)
338
+ print("---")
339
+ print(history)
340
+ print("---")
341
+
342
+ action_name, action_input, history, task = run_action(
343
+ purpose,
344
+ task,
345
+ history,
346
+ directory,
347
+ action_name,
348
+ action_input,
349
+ )
350
+ if task == "END":
351
+ return history
352
+
353
+
354
+
355
+ ################################################
356
+
357
  def format_prompt(message, history):
358
  prompt = "<s>"
359
  for user_prompt, bot_response in history: