-
Notifications
You must be signed in to change notification settings - Fork 195
/
model.py
555 lines (464 loc) · 18.3 KB
/
model.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
import os
import textwrap
from time import sleep
import autopep8
import openai
import streamlit as st
from tqdm import trange
from demogpt.chains.chains import Chains
from demogpt.chains.task_chains import TaskChains
from demogpt.chains.task_chains_seperate import TaskChainsSeperate
from demogpt.utils import (getCodeSnippet, getCodeSnippetSeperate,
getFunctionNames, init, initSeperate,
reorderTasksForChatApp)
class DemoGPT:
def __init__(
self,
openai_api_key=os.getenv("OPENAI_API_KEY", ""),
model_name="gpt-3.5-turbo-0613",
max_steps=10,
plan_max_steps = 3,
openai_api_base="",
):
assert len(
openai_api_key.strip()
), "Either give openai_api_key as an argument or put it in the environment variable"
self.model_name = model_name
self.openai_api_key = openai_api_key
self.max_steps = max_steps # max iteration for refining the model purpose
self.plan_max_steps = plan_max_steps # max iteration for refining the plan
self.openai_api_base = openai_api_base
self.FAIL_MESSAGE = """🚀✨ Impressive! While DemoGPT can handle a galaxy of app ideas,
you've shot for the stars with a unique one. We're ramping up our engines to meet such visionary requests.
Give us a little time, and we'll be right there with you.\n\n📧
Care to leave your email? We'll notify you when we're ready for this stellar journey!"""
self.gpt4_message = """
🚫 Access Denied to GPT-4!
Hey there! It looks like you're trying to create an app with GPT-4, but unfortunately, you don't have the required access. Fear not! You can:
Upgrade your access through OpenAI's platform.
Opt for another model that you have access to and give it another whirl.
We appreciate your understanding and look forward to seeing what you create! 😊
"""
try:
self.available_models = [model["id"] for model in openai.Model.list(api_key=openai_api_key)["data"] if "gpt" in model["id"]]
except:
self.available_models = []
raise AssertionError("Invalid OpenAI API Key")
else:
assert (not self.model_name) or self.model_name in self.available_models , self.gpt4_message
Chains.setLlm(
self.model_name, self.openai_api_key, openai_api_base=self.openai_api_base, has_gpt4=self.hasGPT4
)
TaskChains.setLlm(
self.model_name, self.openai_api_key, openai_api_base=self.openai_api_base
)
TaskChainsSeperate.setLlm(
self.model_name, self.openai_api_key, openai_api_base=self.openai_api_base
)
@property
def hasGPT4(self):
return "gpt-4-0613" in self.available_models
def setModel(self, model_name):
if model_name not in self.available_models:
raise AssertionError(self.gpt4_message)
self.model_name = model_name
Chains.setLlm(
self.model_name, self.openai_api_key, openai_api_base=self.openai_api_base, has_gpt4=self.hasGPT4
)
TaskChains.setLlm(
self.model_name, self.openai_api_key, openai_api_base=self.openai_api_base
)
TaskChainsSeperate.setLlm(
self.model_name, self.openai_api_key, openai_api_base=self.openai_api_base
)
def __repr__(self) -> str:
return f"DemoGPT(model_name='{self.model_name}',max_steps={self.max_steps})"
def callForChat(
self,
instruction="Create a translation system that converts English to French",
title="",
app_type={}
):
yield {
"stage": "system_inputs",
"completed": False,
"percentage": 0,
"done": False,
"message": "System inputs are being detected...",
"failed": False,
}
system_inputs = Chains.systemInputs(instruction=instruction)
yield {
"stage": "plan",
"completed": False,
"percentage": 10,
"done": False,
"message": "Plan creation has started...",
"failed": False,
}
plan = Chains.planWithInputs(
instruction=instruction, system_inputs=system_inputs, app_type=app_type
)
yield {
"stage": "plan",
"completed": True,
"percentage": 20,
"done": False,
"message": "Plan has been generated.",
"failed": False,
}
sleep(1)
yield {
"stage": "plan_controlling",
"completed": True,
"percentage": 25,
"done": False,
"message": "Plan is being controlled.",
"failed": False,
}
plan_controller_result = Chains.planController(plan=plan, app_type=app_type)
for _ in trange(self.plan_max_steps):
if not plan_controller_result["valid"]:
plan = Chains.planRefiner(
instruction=instruction,
plan=plan,
feedback=plan_controller_result["feedback"],
app_type=app_type,
)
plan_controller_result = Chains.planController(
plan=plan, app_type=app_type
)
else:
break
yield {
"stage": "task",
"completed": False,
"percentage": 30,
"done": False,
"message": "Task generation has started...",
"failed": False,
}
task_list = Chains.tasks(
instruction=instruction, plan=plan, app_type=app_type
)
yield {
"stage": "task",
"completed": True,
"percentage": 50,
"done": False,
"message": "Tasks have been generated.",
"tasks": task_list,
"failed": False,
}
sleep(1)
yield {
"stage": "task_controlling",
"completed": True,
"percentage": 55,
"done": False,
"message": "Tasks are being controlled.",
"failed": False,
}
task_controller_result = Chains.taskController(
tasks=task_list, app_type=app_type
)
for _ in trange(self.max_steps):
if not task_controller_result["valid"]:
try:
task_list = Chains.refineTasks(
instruction=instruction,
tasks=task_list,
feedback=task_controller_result["feedback"],
app_type=app_type,
)
task_controller_result = Chains.taskController(
tasks=task_list, app_type=app_type
)
except Exception as e:
print(e)
if "16k" in Chains.model:
break
st.toast(
"To increase the window size, changing model type to gpt-3.5-turbo-16k-0613"
)
Chains.setModel("gpt-3.5-turbo-16k-0613")
else:
break
if not task_controller_result["valid"]:
yield {
"stage": "task",
"completed": False,
"percentage": 100,
"done": False,
"message": self.FAIL_MESSAGE,
"failed": True,
}
else:
title = Chains.title(instruction=instruction)
task_list = reorderTasksForChatApp(task_list) # for chat apps, remove the code between chat input and chat output
code_snippets = init(title)
sleep(1)
yield {
"stage": "draft",
"completed": False,
"percentage": 60,
"done": False,
"message": "Converting tasks to code snippets...",
"title":title
}
num_of_tasks = len(task_list)
for i, task in enumerate(task_list):
code = getCodeSnippet(instruction, task, code_snippets, self.max_steps)
code = "#" + task["description"] + "\n" + code
code_snippets += code
yield {
"stage": "draft",
"completed": i + 1 == num_of_tasks,
"percentage": 60 + int(20 * (i + 1) / num_of_tasks),
"done": False,
"message": f"{i+1}/{num_of_tasks} tasks have been converted to code",
"code": code,
"title":title
}
sleep(1)
yield {
"stage": "draft",
"completed": False,
"percentage": 85,
"done": False,
"message": "Code snippets are being combined...",
"title":title
}
final_code = code_snippets
# finalize the format
final_code = autopep8.fix_code(final_code)
final_code = Chains.addAboutAndHTU(instruction, title, final_code, plan)
yield {
"stage": "final",
"completed": True,
"percentage": 100,
"done": True,
"message": "Final code has been generated. Directing to the demo page...",
"code": final_code,
"title":title
}
def __call__(self, instruction, title=""):
try:
for data in self.run(instruction):
yield data
except Exception as e:
print(e)
yield {
"stage": "task",
"completed": False,
"percentage": 100,
"done": False,
"message": self.FAIL_MESSAGE,
"failed": True
}
def run(
self,
instruction="Create a translation system that converts English to French",
title="",
):
def getCode(imports, functions, prefix, inputs, outputs, how_to, about, title):
return f"""
{imports}
{functions}
{prefix}
{how_to}
{about}
with st.form(key="form"):
st.title('{title}')
{inputs}
submit_button = st.form_submit_button(label='Submit')
if not openai_api_key.startswith('sk-'):
st.warning('Please enter your OpenAI API key!', icon='⚠')
if submit_button:
{outputs}
"""
yield {
"stage": "system_inputs",
"completed": False,
"percentage": 0,
"done": False,
"message": "System inputs are being detected...",
"failed": False,
}
app_type = Chains.appType(instruction=instruction)
if app_type["is_chat"] == "true":
for data in self.callForChat(instruction, app_type=app_type):
yield data
else:
system_inputs = Chains.systemInputs(instruction=instruction)
yield {
"stage": "plan",
"completed": False,
"percentage": 10,
"done": False,
"message": "Plan creation has started...",
"failed": False,
}
sleep(10)
plan = Chains.planWithInputs(
instruction=instruction, system_inputs=system_inputs, app_type=app_type
)
yield {
"stage": "plan",
"completed": True,
"percentage": 20,
"done": False,
"message": "Plan has been generated.",
"failed": False,
}
sleep(1)
yield {
"stage": "plan_controlling",
"completed": True,
"percentage": 25,
"done": False,
"message": "Plan is being controlled.",
"failed": False,
}
plan_controller_result = Chains.planController(plan=plan, app_type=app_type)
for _ in trange(self.plan_max_steps):
sleep(10)
if not plan_controller_result["valid"]:
plan = Chains.planRefiner(
instruction=instruction,
plan=plan,
feedback=plan_controller_result["feedback"],
app_type=app_type,
)
plan_controller_result = Chains.planController(
plan=plan, app_type=app_type
)
else:
break
yield {
"stage": "task",
"completed": False,
"percentage": 30,
"done": False,
"message": "Task generation has started...",
"failed": False,
}
task_list = Chains.tasks(
instruction=instruction, plan=plan, app_type=app_type
)
yield {
"stage": "task",
"completed": True,
"percentage": 50,
"done": False,
"message": "Tasks have been generated.",
"tasks": task_list,
"failed": False,
}
sleep(1)
yield {
"stage": "task_controlling",
"completed": True,
"percentage": 55,
"done": False,
"message": "Tasks are being controlled.",
"failed": False,
}
task_controller_result = Chains.taskController(
tasks=task_list, app_type=app_type
)
for _ in trange(self.max_steps):
sleep(10)
if not task_controller_result["valid"]:
try:
task_list = Chains.refineTasks(
instruction=instruction,
tasks=task_list,
feedback=task_controller_result["feedback"],
app_type=app_type,
)
task_controller_result = Chains.taskController(
tasks=task_list, app_type=app_type
)
except Exception as e:
print(e)
if "16k" in Chains.model:
break
st.toast(
"To increase the window size, changing model type to gpt-3.5-turbo-16k-0613"
)
Chains.setModel("gpt-3.5-turbo-16k-0613")
else:
break
if not task_controller_result["valid"]:
yield {
"stage": "task",
"completed": False,
"percentage": 100,
"done": False,
"message": self.FAIL_MESSAGE,
"failed": True,
}
else:
imports = ""
functions = ""
inputs = ""
outputs = ""
title = Chains.title(instruction=instruction)
task_list = reorderTasksForChatApp(task_list) # for chat apps, remove the code between chat input and chat output
res = initSeperate(title)
prefix = res["prefix"]
imports = res["imports"]
code_snippets = res["code"]
sleep(1)
yield {
"stage": "draft",
"completed": False,
"percentage": 60,
"done": False,
"message": "Converting tasks to code snippets...",
"title":title
}
num_of_tasks = len(task_list)
for i, task in enumerate(task_list):
res = getCodeSnippetSeperate(instruction, task, code_snippets, self.max_steps)
code = "#" + task["description"] + "\n" + res["code"]
if res["imports"] not in imports:
imports += res["imports"] + "\n"
functions += res["functions"] + "\n"
inputs += res["inputs"] + "\n"
outputs += res["outputs"] + "\n"
code_snippets += code
yield {
"stage": "draft",
"completed": i + 1 == num_of_tasks,
"percentage": 60 + int(20 * (i + 1) / num_of_tasks),
"done": False,
"message": f"{i+1}/{num_of_tasks} tasks have been converted to code",
"code": code,
"title":title
}
sleep(1)
yield {
"stage": "draft",
"completed": False,
"percentage": 85,
"done": False,
"message": "Code snippets are being combined...",
"title":title
}
inputs = textwrap.indent(inputs, 4*' ')
outputs = textwrap.indent(outputs, 8*' ')
how_to, about = Chains.getAboutAndHTU(instruction, title, plan)
final_code = getCode(imports, functions, prefix, inputs, outputs, how_to, about, title)
# finalize the format
final_code = autopep8.fix_code(final_code)
yield {
"stage": "final",
"completed": True,
"percentage": 100,
"done": True,
"message": "Final code has been generated. Directing to the demo page...",
"code": final_code,
"title":title
}