清华开源ChatGPT自动编程ChatDev项目utils.py代码解读
这段代码是一个名为utils.py
的模块,包含了一些工具函数和装饰器。下面是对每个函数的作用和添加的注释:
import html
import logging
import re
import time
import markdown
import inspect
from camel.messages.system_messages import SystemMessage
from online_log.app import send_msg
# 获取当前时间
def now():
return time.strftime("%Y%m%d%H%M%S", time.localtime())
# 在线记录日志并打印信息
def log_and_print_online(role, content=None):
if not content:
logging.info(role + "\n")
send_msg("System", role)
print(role + "\n")
else:
print(str(role) + ": " + str(content) + "\n")
logging.info(str(role) + ": " + str(content) + "\n")
if isinstance(content, SystemMessage): # 判断消息类型是否为系统消息
records_kv = []
content.meta_dict["content"] = content.content
for key in content.meta_dict:
value = content.meta_dict[key]
value = str(value)
value = html.unescape(value) # 反转义HTML字符实体
value = markdown.markdown(value) # 将文本转换为Markdown格式
value = re.sub(r'<[^>]*>', '', value) # 移除HTML标签
value = value.replace("\n", " ") # 替换换行为空格
records_kv.append([key, value])
content = "**[SystemMessage**]\n\n" + convert_to_markdown_table(records_kv)
else:
role = str(role)
content = str(content)
send_msg(role, content) # 发送消息到在线日志记录平台
# 将记录键值对列表转换为Markdown格式的表格
def convert_to_markdown_table(records_kv):
# 创建Markdown表头
header = "| Parameter | Value |\n| --- | --- |"
# 创建Markdown表格行
rows = [f"| **{key}** | {value} |" for (key, value) in records_kv]
# 组合表头和表行形成最终的Markdown表格
markdown_table = header + "\n" + '\n'.join(rows)
return markdown_table
# 记录函数参数的装饰器
def log_arguments(func):
def wrapper(*args, **kwargs):
sig = inspect.signature(func)
params = sig.parameters
all_args = {}
all_args.update({name: value for name, value in zip(params.keys(), args)})
all_args.update(kwargs)
records_kv = []
for name, value in all_args.items():
if name in ["self", "chat_env", "task_type"]:
continue
value = str(value)
value = html.unescape(value)
value = markdown.markdown(value)
value = re.sub(r'<[^>]*>', '', value)
value = value.replace("\n", " ")
records_kv.append([name, value])
records = f"**[{func.__name__}]**\n\n" + convert_to_markdown_table(records_kv)
log_and_print_online("System", records)
return func(*args, **kwargs)
return wrapper
这些函数提供了一些常用的工具功能,如记录日志、发送在线消息、获取当前时间等。而装饰器log_arguments
用于记录函数参数信息,将参数转换为Markdown格式的表格,并通过log_and_print_online
函数将记录的信息进行在线打印和日志记录。