File size: 11,531 Bytes
11e0376
cffb5aa
5e9e416
f81e511
a35fa4d
 
 
 
 
 
5e9e416
af799b3
5e9e416
 
 
c121218
5e9e416
 
 
c121218
5e9e416
c121218
5e9e416
 
 
c121218
cc70e87
c121218
 
cc70e87
c121218
5e9e416
 
 
0905f7c
a35fa4d
cc70e87
a35fa4d
cc70e87
a35fa4d
 
c121218
a35fa4d
 
 
 
cc70e87
0905f7c
78dfff8
cc70e87
 
 
 
c4df480
 
c121218
86c3750
11e0376
d2a7c88
86c3750
 
 
 
 
 
 
71586bc
 
 
 
86c3750
c121218
86c3750
c121218
78dfff8
b3d1811
71586bc
b3d1811
 
78dfff8
9f68e0d
0905f7c
9f68e0d
cc70e87
 
a35fa4d
c4df480
4c925d3
a35fa4d
 
4c925d3
cc70e87
a35fa4d
 
cc70e87
a35fa4d
af799b3
a35fa4d
 
 
71586bc
 
 
 
f81e511
86c3750
f81e511
 
78dfff8
a35fa4d
af799b3
 
9f68e0d
d5931c3
 
 
f81e511
 
 
cc70e87
 
44c82d2
af799b3
 
f81e511
af799b3
45d6a3f
af799b3
 
0d8cdc8
44c82d2
86c3750
af799b3
 
86c3750
af799b3
45d6a3f
af799b3
 
 
11e0376
45d6a3f
af799b3
 
 
44c82d2
 
 
af799b3
 
d5931c3
af799b3
 
 
cc70e87
af799b3
 
 
 
 
 
44c82d2
45d6a3f
86c3750
45d6a3f
11e0376
44c82d2
 
45d6a3f
af799b3
 
c121218
9f68e0d
af799b3
 
8d878e6
d2a7c88
8d878e6
86c3750
11e0376
 
45d6a3f
0d8cdc8
45d6a3f
 
 
11e0376
 
 
45d6a3f
0d8cdc8
45d6a3f
 
11e0376
 
 
71586bc
af799b3
11e0376
d2a7c88
2f0960b
d2a7c88
2f0960b
 
 
 
8d878e6
11e0376
 
 
 
 
2f0960b
 
11e0376
2f0960b
 
11e0376
d2a7c88
2f0960b
 
 
 
 
 
 
 
 
11e0376
 
 
d2a7c88
 
 
 
 
 
 
 
af799b3
541b9a9
45d6a3f
 
af799b3
3ce6c94
af799b3
86c3750
11e0376
 
45d6a3f
0d8cdc8
af799b3
 
71586bc
 
11e0376
71586bc
 
11e0376
71586bc
f81e511
 
 
86c3750
 
f81e511
 
 
86c3750
f81e511
2b7f22e
f81e511
71586bc
f81e511
d5931c3
71586bc
11e0376
 
 
 
 
71586bc
86c3750
 
 
 
 
 
f81e511
 
 
 
 
86c3750
9f68e0d
 
c121218
af799b3
0905f7c
9f68e0d
71586bc
af799b3
cc70e87
c121218
 
cc70e87
c121218
fb97b78
af799b3
c121218
 
 
 
cc70e87
c121218
fb97b78
c121218
fb97b78
c121218
 
 
9f68e0d
c121218
af799b3
c121218
 
 
9f68e0d
71586bc
9f68e0d
71586bc
9f68e0d
71586bc
c4df480
 
9f68e0d
71586bc
 
 
 
 
c4df480
fb97b78
71586bc
9f68e0d
 
c4df480
a35fa4d
c4df480
a35fa4d
 
c4df480
0905f7c
c4df480
c121218
0905f7c
c4df480
fb97b78
c4df480
0905f7c
c4df480
 
c121218
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
from concurrent.futures import ThreadPoolExecutor
import re
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, Union

import gradio as gr

import ai


class Component(ABC):
    def __init__(self, id_: int):
        # Internal state
        self._id = id_
        self._source = self.__class__.__name__
        self.vname: str

        # Gradio state
        self.component_id: gr.Number
        self.gr_component: Union[gr.Box, gr.Textbox]
        self.output: gr.Textbox
        self.visible: gr.Number

    def render(self) -> None:
        self.component_id = gr.Number(value=self._id, visible=False)
        self.visible = gr.Number(0, visible=False)
        self.gr_component = self._render()

    @abstractmethod
    def _render(self) -> Union[gr.Box, gr.Textbox]:
        ...


class Input(Component):
    vname = "v"

    def _render(self) -> gr.Textbox:
        self.output = gr.Textbox(
            label=f"Input: {{{self.vname}{self._id}}}",
            interactive=True,
            placeholder="Variable value",
            visible=False,
        )
        return self.output


class TaskComponent(Component, ABC):
    vname = "t"

    def __init__(self, id_: int, value: str = "", visible: bool = False):
        super().__init__(id_)
        self._initial_value = value
        self._initial_visbility = visible
        self.name: str
        self.input: gr.Textbox

    def format_input(self, input: str, vars_in_scope: Dict[str, Any]) -> str:
        input = input.strip()
        prompt_vars = [v for v in re.findall("{(.*)}", input)]
        undefined_vars = prompt_vars - vars_in_scope.keys()
        if len(undefined_vars) > 0:
            raise KeyError(
                f"The variables :: {undefined_vars} are being used before being defined."
            )
        return input.format(**vars_in_scope)

    @property
    def n_inputs(self) -> int:
        return len(self.inputs)

    @property
    @abstractmethod
    def inputs(self) -> List[gr.Textbox]:
        ...

    @abstractmethod
    def execute(self, *args, vars_in_scope: Dict[str, Any]):
        ...


class AITask(TaskComponent):
    name = "AI Task"

    def _render(self) -> gr.Box:
        with gr.Box(visible=self._initial_visbility) as gr_component:
            with gr.Row():
                self.input = gr.Textbox(
                    label="Instructions",
                    lines=10,
                    interactive=True,
                    placeholder="What would you like ChatGPT to do?",
                    value=self._initial_value,
                )
                self.output = gr.Textbox(
                    label=f"Output: {{{self.vname}{self._id}}}",
                    lines=10,
                    interactive=True,
                )
            return gr_component

    @property
    def inputs(self) -> List[gr.Textbox]:
        return [self.input]

    def execute(self, prompt: str, vars_in_scope: Dict[str, Any]) -> Optional[str]:
        formatted_prompt = self.format_input(prompt, vars_in_scope)
        if formatted_prompt:
            return ai.llm.next([{"role": "user", "content": formatted_prompt}])


class CodeTask(TaskComponent):
    name = "Code Task"

    def __init__(
        self, id_: int, value: str = "", visible: bool = False, code_value: str = ""
    ):
        super().__init__(id_, value, visible)
        self._initial_code_value = code_value

    def _render(self) -> gr.Column:
        with gr.Column(visible=self._initial_visbility) as gr_component:
            self.code_prompt = gr.Textbox(
                label="What would you like to do?",
                interactive=True,
                value=self._initial_code_value,
            )
            generate_code = gr.Button("Generate code")
            with gr.Row():
                with gr.Column():
                    with gr.Accordion(label="Generated code", open=False) as accordion:
                        self.accordion = accordion
                        self.raw_output = gr.Textbox(
                            label="Raw output",
                            lines=5,
                            interactive=False,
                        )
                        self.packages = gr.Textbox(
                            label="The following packages will be installed",
                            interactive=True,
                        )
                        self.script = gr.Textbox(
                            label="Code to be executed",
                            lines=10,
                            interactive=True,
                        )
                        self.error_message = gr.HighlightedText(
                            value=None, visible=False
                        )

                    self.input = gr.Textbox(
                        label="Input", interactive=True, value=self._initial_value
                    )
                with gr.Column():
                    self.output = gr.Textbox(
                        label=f"Output: {{{self.vname}{self._id}}}",
                        lines=10,
                        interactive=True,
                    )

            generate_code.click(
                self.generate_code,
                inputs=[self.code_prompt],
                outputs=[
                    self.raw_output,
                    self.packages,
                    self.script,
                    self.error_message,
                    self.accordion,
                ],
            )

        return gr_component

    @staticmethod
    def generate_code(code_prompt: str):
        import json
        import traceback

        raw_output = ""
        packages = ""
        script = ""
        error_message = gr.HighlightedText.update(None, visible=False)
        accordion = gr.Accordion.update()

        if not code_prompt:
            return (
                raw_output,
                packages,
                script,
                error_message,
                accordion,
            )

        def llm_call(prompt):
            return ai.llm.next([{"role": "user", "content": prompt}], temperature=0)

        print(f"Generating code.")
        try:
            raw_output = llm_call(
                f"""{code_prompt}

Write one python function for the request above.
Use pip packages where available.
For example, if you wanted to make a google search, use the googlesearch-python package instead of scraping google.
Include only the necessary imports.
Instead of printing or saving to disk, the function should return the data."""
            )
            with ThreadPoolExecutor() as executor:
                packages, script = tuple(
                    executor.map(
                        llm_call,
                        [
                            f"""The following text has some python code:
{raw_output}

Find the pip packages that need to be installed and get their corresponsing names in pip.
Package names in the imports and in pip might be different. Use the correct pip names.
                            
Put them in a valid JSON:
```
{{
    "packages": Python list to be used with eval(). If no packages, empty list.
}}
```""",
                            f"""The following text has some python code:
{raw_output}

Extract it. Remove anything after the function definition.""",
                        ],
                    )
                )
            for packages in re.findall("{.*}", packages, re.DOTALL):
                try:
                    packages = json.loads(packages)
                    packages = packages["packages"]
                except:
                    print(packages)
                    traceback.print_exc()
                    packages = "ERROR"
        except Exception as e:
            traceback.print_exc()
            error_message = gr.HighlightedText.update(
                value=[(str(e), "ERROR")], visible=True
            )
            accordion = gr.Accordion.update(open=True)
        return (
            raw_output,
            packages,
            script.replace("```python", "").replace("```", "").strip(),
            error_message,
            accordion,
        )

    @property
    def inputs(self) -> List[gr.Textbox]:
        return [self.packages, self.script, self.input]

    def execute(
        self, packages: str, function: str, input: str, vars_in_scope: Dict[str, Any]
    ):
        if not function:
            return None

        import inspect

        def install():
            import subprocess
            import sys

            for p in eval(packages):
                print(f"Installing {p}")
                subprocess.check_call([sys.executable, "-m", "pip", "install", p])

        function = function.strip()
        function = f"import os\nos.environ = {{}}\n\n{function}"
        exec(function, locals())
        # Looking for the last defined function
        for var in reversed(locals().values()):
            if callable(var):
                self._toolkit_func = var
                break

        if len(inspect.getfullargspec(self._toolkit_func)[0]) > 0:
            formatted_input = self.format_input(input, vars_in_scope)
            try:
                formatted_input = eval(formatted_input)
            except:
                pass
            if formatted_input:
                install()
                return self._toolkit_func(formatted_input)
            return None
        install()
        return self._toolkit_func()


class Task(Component):
    available_tasks = [AITask, CodeTask]
    vname = "t"

    def __init__(self, id_: int):
        super().__init__(id_)
        self._inner_tasks = [t(id_) for t in self.available_tasks]
        self.gr_component: gr.Box

    def _render(self) -> gr.Box:
        with gr.Box(visible=False) as gr_component:
            self.active_index = gr.Dropdown(
                [AITask.name, CodeTask.name],
                label="Pick a new Task",
                type="index",
            )
            for t in self._inner_tasks:
                t.render()

            self.active_index.select(
                self.pick_task,
                inputs=[self.active_index],
                outputs=[t.gr_component for t in self._inner_tasks],
            )
        return gr_component

    @staticmethod
    def pick_task(idx: int) -> List[Dict]:
        update = [gr.Box.update(visible=False)] * len(Task.available_tasks)
        update[idx] = gr.Box.update(visible=True)
        return update

    @property
    def inputs(self) -> List[gr.Textbox]:
        return [i for t in self._inner_tasks for i in t.inputs]

    @property
    def outputs(self) -> List[gr.Textbox]:
        return [t.output for t in self._inner_tasks]

    @property
    def inner_n_inputs(self) -> List[int]:
        return [t.n_inputs for t in self._inner_tasks]

    def execute(self, active_index, *args, vars_in_scope: Dict[str, Any]):
        inner_task = self._inner_tasks[active_index]
        print(f"Executing {self._source}: {self._id}")
        return inner_task.execute(*args, vars_in_scope)


MAX_TASKS = 10

all_tasks = {i: Task(i) for i in range(MAX_TASKS)}


class Tasks:
    @classmethod
    def visibilities(cls) -> List[gr.Number]:
        return [t.visible for t in all_tasks.values()]

    @classmethod
    def active_indexes(cls) -> List[gr.Dropdown]:
        return [t.active_index for t in all_tasks.values()]

    @classmethod
    def gr_components(cls) -> List[gr.Box]:
        return [t.gr_component for t in all_tasks.values()]