Skip to content

Commit

Permalink
fix: incorrect type parser (langgenius#3682)
Browse files Browse the repository at this point in the history
  • Loading branch information
Yeuoly authored Apr 22, 2024
1 parent b2535e7 commit 2a213c6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
11 changes: 9 additions & 2 deletions api/core/helper/code_executor/jina2_transformer.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
import json
import re
from base64 import b64encode

from core.helper.code_executor.template_transformer import TemplateTransformer

PYTHON_RUNNER = """
import jinja2
from json import loads
from base64 import b64decode
template = jinja2.Template('''{{code}}''')
def main(**inputs):
return template.render(**inputs)
# execute main function, and return the result
output = main(**{{inputs}})
inputs = b64decode('{{inputs}}').decode('utf-8')
output = main(**loads(inputs))
result = f'''<<RESULT>>{output}<<RESULT>>'''
Expand All @@ -39,6 +43,7 @@ def main(**inputs):

JINJA2_PRELOAD = f"""
import jinja2
from base64 import b64decode
def _jinja2_preload_():
# prepare jinja2 environment, load template and render before to avoid sandbox issue
Expand All @@ -60,9 +65,11 @@ def transform_caller(cls, code: str, inputs: dict) -> tuple[str, str]:
:return:
"""

inputs_str = b64encode(json.dumps(inputs, ensure_ascii=False).encode()).decode('utf-8')

# transform jinja2 template to python code
runner = PYTHON_RUNNER.replace('{{code}}', code)
runner = runner.replace('{{inputs}}', json.dumps(inputs, indent=4, ensure_ascii=False))
runner = runner.replace('{{inputs}}', inputs_str)

return runner, JINJA2_PRELOAD

Expand Down
11 changes: 8 additions & 3 deletions api/core/helper/code_executor/python_transformer.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
import json
import re
from base64 import b64encode

from core.helper.code_executor.template_transformer import TemplateTransformer

PYTHON_RUNNER = """# declare main function here
{{code}}
from json import loads, dumps
from base64 import b64decode
# execute main function, and return the result
# inputs is a dict, and it
output = main(**{{inputs}})
inputs = b64decode('{{inputs}}').decode('utf-8')
output = main(**json.loads(inputs))
# convert output to json and print
output = json.dumps(output, indent=4)
output = dumps(output, indent=4)
result = f'''<<RESULT>>
{output}
Expand Down Expand Up @@ -54,7 +59,7 @@ def transform_caller(cls, code: str, inputs: dict) -> tuple[str, str]:
"""

# transform inputs to json string
inputs_str = json.dumps(inputs, indent=4, ensure_ascii=False)
inputs_str = b64encode(json.dumps(inputs, ensure_ascii=False).encode()).decode('utf-8')

# replace code and inputs
runner = PYTHON_RUNNER.replace('{{code}}', code)
Expand Down

0 comments on commit 2a213c6

Please sign in to comment.