add english comments.

This commit is contained in:
刘棒棒 2023-09-13 23:16:38 +08:00
parent 6a21488486
commit 1d42a98fc8

View file

@ -10,22 +10,21 @@ from interpreter.interpreter import Interpreter
from metagpt.logs import logger
from metagpt.config import CONFIG
from metagpt.utils.highlight import highlight
from metagpt.actions.clone_function import CloneFunction, run_fucntion_code, run_fucntion_script
from metagpt.actions.run_code import RunCode
from metagpt.actions.clone_function import CloneFunction, run_function_code, run_function_script
def extract_python_code(code: str):
"""提取代码块: 如果代码注释相同,则只保留最后一个代码块."""
# 使用正则表达式匹配注释块和相关的代码
"""Extract code blocks: If the code comments are the same, only the last code block is kept."""
# Use regular expressions to match comment blocks and related code.
pattern = r'(#\s[^\n]*)\n(.*?)(?=\n\s*#|$)'
matches = re.findall(pattern, code, re.DOTALL)
# 提取每个相同注释的最后一个代码块
# Extract the last code block when encountering the same comment.
unique_comments = {}
for comment, code_block in matches:
unique_comments[comment] = code_block
# 组装结果字符串
# concatenate into functional form
result_code = '\n'.join([f"{comment}\n{code_block}" for comment, code_block in unique_comments.items()])
header_code = code[:code.find("#")]
code = header_code + result_code
@ -56,28 +55,28 @@ class OpenCodeInterpreter(object):
if language not in ('python'):
raise NotImplementedError(f"Not support to parse language {language}!")
# 定义函数形式
# set function form
if function_format is None:
assert language == 'python', f"Expect python language for default function_format, but got {language}."
function_format = """def {function_name}():\n{code}"""
# 解析open-interpreter respond message中的代码模块
# Extract the code module in the open-interpreter respond message.
code = [item['function_call']['parsed_arguments']['code'] for item in query_respond
if "function_call" in item
and "parsed_arguments" in item["function_call"]
and 'language' in item["function_call"]['parsed_arguments']
and item["function_call"]['parsed_arguments']['language'] == language]
# 添加缩进
# add indent.
indented_code_str = textwrap.indent("\n".join(code), ' ' * 4)
# 按照代码注释, 返回去重后的代码
# Return the code after deduplication.
if language == "python":
return extract_python_code(function_format.format(function_name=function_name, code=indented_code_str))
def gen_query(func: Callable, args, kwargs) -> str:
# 函数的注释, 也就是query的主体
# Get the annotation of the function as part of the query.
desc = func.__doc__
signature = inspect.signature(func)
# 获取函数wrapped的签名和入参的赋值
# Get the signature of the wrapped function and the assignment of the input parameters as part of the query.
bound_args = signature.bind(*args, **kwargs)
bound_args.apply_defaults()
query = f"{desc}, {bound_args.arguments}, If you must use a third-party package, use the most popular ones, for example: pandas, numpy, ta, ..."
@ -97,29 +96,30 @@ class OpenInterpreterDecorator(object):
def __call__(self, wrapped):
@wrapt.decorator
async def wrapper(wrapped: Callable, instance, args, kwargs):
# 获取被装饰的函数名
# Get the decorated function name.
func_name = wrapped.__name__
# 如果脚本在本地存在而且不需要clearcode则从脚本执行该函数
# If the script exists locally and clearcode is not required, execute the function from the script.
if Path(self.code_file_path).is_file() and not self.clear_code:
return run_fucntion_script(self.code_file_path, func_name, *args, **kwargs)
return run_function_script(self.code_file_path, func_name, *args, **kwargs)
# 使用open-interpreter逐步生成代码
# Auto run generate code by using open-interpreter.
interpreter = OpenCodeInterpreter()
query = gen_query(wrapped, args, kwargs)
logger.info(f"query for OpenCodeInterpreter: \n {query}")
respond = interpreter.chat(query)
# 将open-interpreter逐步生成的代码组装成无入参的函数
# Assemble the code blocks generated by open-interpreter into a function without parameters.
func_code = interpreter.extract_function(respond, func_name)
# 把code克隆为wrapped即保持code和wrapped函数有相同的入参和返回值类型
# Clone the `func_code` into wrapped, that is,
# keep the `func_code` and wrapped functions with the same input parameter and return value types.
template_func = gen_template_fun(wrapped)
cf = CloneFunction()
code = await cf.run(template_func=template_func, source_code=func_code)
# 在终端显示生成的函数
# Display the generated function in the terminal.
logger_code = highlight(code, "python")
logger.info(f"Creating following Python function:\n{logger_code}")
# 执行该函数
# execute this function.
try:
res = run_fucntion_code(code, func_name, *args, **kwargs)
res = run_function_code(code, func_name, *args, **kwargs)
if self.save_code:
cf._save(self.code_file_path, code)
except Exception as e: