lgaleana commited on
Commit
11e0376
1 Parent(s): 86c3750

More fixes

Browse files
Files changed (1) hide show
  1. components.py +66 -56
components.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import re
2
  from abc import ABC, abstractmethod
3
  from typing import Any, Dict, List, Union
@@ -54,6 +55,7 @@ class TaskComponent(ABC):
54
  self._source = self.__class__.__name__
55
 
56
  def format_input(self, input: str, vars_in_scope: Dict[str, Any]) -> str:
 
57
  prompt_vars = [v for v in re.findall("{(.*?)}", input)]
58
  undefined_vars = prompt_vars - vars_in_scope.keys()
59
  if len(undefined_vars) > 0:
@@ -133,7 +135,7 @@ class CodeTask(TaskComponent):
133
  label="The following packages will be installed",
134
  interactive=True,
135
  )
136
- self.function = gr.Textbox(
137
  label="Code to be executed",
138
  lines=10,
139
  interactive=True,
@@ -157,7 +159,7 @@ class CodeTask(TaskComponent):
157
  outputs=[
158
  self.raw_output,
159
  self.packages,
160
- self.function,
161
  error_message,
162
  accordion,
163
  ],
@@ -170,62 +172,66 @@ class CodeTask(TaskComponent):
170
  import json
171
 
172
  raw_output = ""
173
- parsed_output = {"pip": "", "script": ""}
 
174
  error_message = gr.HighlightedText.update(None, visible=False)
175
  accordion = gr.Accordion.update()
176
 
177
  if not code_prompt:
178
  return (
179
- "",
180
- "",
181
- "",
182
  error_message,
183
  accordion,
184
  )
185
 
 
 
 
186
  print(f"Generating code.")
187
  try:
188
- raw_output = ai.llm.next(
189
- [
190
- {
191
- "role": "user",
192
- "content": f"""
193
- Write a python function for the following request:
194
- {code_prompt}
195
-
196
- Do't save anything to disk. Instead, the function should return the necessary data.
197
- Include necessary imports.
198
- """,
199
- }
200
- ],
201
- temperature=0,
202
- )
203
- extractions = ai.llm.next(
204
- [
205
- {
206
- "role": "user",
207
- "content": f"""
208
- The following text has a python function with some packages that might need to be installed:
209
- {raw_output}
210
-
211
- What is the pip install command to install the needed packages?
212
- Package names in the imports and in pip might be different. Use the correct pip names.
213
- Extract the imports and the function definition.
214
-
215
- Write a JSON:
216
- {{
217
- "pip": Pip command. If no packages, empty string.
218
- "script": A python script to be executed with exec(). Include only the imports and the function definition.
219
- }}
220
- ```
221
- """,
222
- }
223
- ],
224
- temperature=0,
225
- )
226
- parsed_output = json.loads(
227
- re.search("({.*})", extractions, re.DOTALL).group(0)
228
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  except Exception as e:
230
  import traceback
231
 
@@ -236,30 +242,34 @@ class CodeTask(TaskComponent):
236
  accordion = gr.Accordion.update(open=True)
237
  return (
238
  raw_output,
239
- parsed_output["pip"],
240
- parsed_output["script"],
241
  error_message,
242
  accordion,
243
  )
244
 
245
  @property
246
  def inputs(self) -> List[gr.Textbox]:
247
- return [self.packages, self.function, self.input]
248
 
249
  def execute(
250
- self, pip_command: str, function: str, input: str, vars_in_scope: Dict[str, Any]
251
  ):
252
  import inspect
 
 
253
 
254
- if pip_command:
255
- import subprocess
256
- import sys
257
 
258
- subprocess.check_call([sys.executable, "-m"] + pip_command.split(" "))
 
259
 
260
  exec(function, locals())
261
- # Should be last function in scope
262
- self._toolkit_func = list(locals().items())[-1][1]
 
 
 
263
 
264
  if len(inspect.getfullargspec(self._toolkit_func)[0]) > 0:
265
  formatted_input = self.format_input(input, vars_in_scope)
 
1
+ from concurrent.futures import ThreadPoolExecutor
2
  import re
3
  from abc import ABC, abstractmethod
4
  from typing import Any, Dict, List, Union
 
55
  self._source = self.__class__.__name__
56
 
57
  def format_input(self, input: str, vars_in_scope: Dict[str, Any]) -> str:
58
+ input = input.strip()
59
  prompt_vars = [v for v in re.findall("{(.*?)}", input)]
60
  undefined_vars = prompt_vars - vars_in_scope.keys()
61
  if len(undefined_vars) > 0:
 
135
  label="The following packages will be installed",
136
  interactive=True,
137
  )
138
+ self.script = gr.Textbox(
139
  label="Code to be executed",
140
  lines=10,
141
  interactive=True,
 
159
  outputs=[
160
  self.raw_output,
161
  self.packages,
162
+ self.script,
163
  error_message,
164
  accordion,
165
  ],
 
172
  import json
173
 
174
  raw_output = ""
175
+ packages = ""
176
+ script = ""
177
  error_message = gr.HighlightedText.update(None, visible=False)
178
  accordion = gr.Accordion.update()
179
 
180
  if not code_prompt:
181
  return (
182
+ raw_output,
183
+ packages,
184
+ script,
185
  error_message,
186
  accordion,
187
  )
188
 
189
+ def llm_call(prompt):
190
+ return ai.llm.next([{"role": "user", "content": prompt}], temperature=0)
191
+
192
  print(f"Generating code.")
193
  try:
194
+ raw_output = llm_call(
195
+ f"""
196
+ Write a python function for the following request:
197
+ {code_prompt}
198
+
199
+ Do't save anything to disk. Instead, the function should return the necessary data.
200
+ Use pip packages where available.
201
+ For example, make a google search, use the googlesearch-python package instead of scraping google.
202
+ Include necessary imports.
203
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  )
205
+ with ThreadPoolExecutor() as executor:
206
+ packages, script = tuple(
207
+ executor.map(
208
+ llm_call,
209
+ [
210
+ f"""
211
+ The following text has a python function with some packages that might need to be installed:
212
+ {raw_output}
213
+
214
+ Find the packages that need to be installed with pip and get their corresponsing names in pip.
215
+ Package names in the imports and in pip might be different. Use the correct pip names.
216
+
217
+ Put them in a JSON:
218
+ ```
219
+ {{
220
+ "packages": Python list to be used with eval(). If no packages, empty list.
221
+ }}
222
+ ```
223
+ """,
224
+ f"""
225
+ The following text has a python function with some imports:
226
+ {raw_output}
227
+
228
+ Extract the imports and the function definition. Nothing else.
229
+ """,
230
+ ],
231
+ )
232
+ )
233
+ packages = json.loads(re.search("({.*})", packages, re.DOTALL).group(0))
234
+ packages = packages["packages"]
235
  except Exception as e:
236
  import traceback
237
 
 
242
  accordion = gr.Accordion.update(open=True)
243
  return (
244
  raw_output,
245
+ packages,
246
+ script.replace("```python", "").replace("```", "").strip(),
247
  error_message,
248
  accordion,
249
  )
250
 
251
  @property
252
  def inputs(self) -> List[gr.Textbox]:
253
+ return [self.packages, self.script, self.input]
254
 
255
  def execute(
256
+ self, packages: str, function: str, input: str, vars_in_scope: Dict[str, Any]
257
  ):
258
  import inspect
259
+ import subprocess
260
+ import sys
261
 
262
+ function = function.strip()
 
 
263
 
264
+ for p in eval(packages):
265
+ subprocess.check_call([sys.executable, "-m", "pip", "install", p])
266
 
267
  exec(function, locals())
268
+ # Looking for the last defined function
269
+ for var in reversed(locals().values()):
270
+ if callable(var):
271
+ self._toolkit_func = var
272
+ break
273
 
274
  if len(inspect.getfullargspec(self._toolkit_func)[0]) > 0:
275
  formatted_input = self.format_input(input, vars_in_scope)