Last active
August 9, 2023 13:56
-
-
Save liaokongVFX/88fc73a7778f06d9edd501924e041f98 to your computer and use it in GitHub Desktop.
一个使用GPT帮助分析报错的装饰器
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
import traceback | |
from functools import wraps | |
import openai | |
openai.api_base = '' | |
openai.api_key = '' | |
allow_class_methods = ['__init__'] | |
def _explain_error(func): | |
response = openai.ChatCompletion.create( | |
model='gpt-3.5-turbo', | |
temperature=0.5, | |
messages=[ | |
{'role': 'system', | |
'content': '你是一名优秀的Python错误解释助手,我会给你报错所在的函数内容以及报错信息,' | |
'请准确详细的解释错误的原因和注明错误行数,并给出具体修改建议及代码示例,尽量减少不必要的废话。' | |
'请按以下格式返回:\n1.错误原因:{}\n2.修改建议:{}'}, | |
{'role': 'user', | |
'content': '报错函数上下文:\n"""{}""",报错信息:\n"""{}"""'.format( | |
inspect.getsource(func), traceback.format_exc())} | |
], | |
) | |
raise Exception(response["choices"][0]['message']['content']) | |
def exception_gpt(func_or_class): | |
if type(func_or_class) == type: | |
# 处理特殊函数 | |
for func_name in allow_class_methods: | |
if func_name not in dir(func_or_class): | |
continue | |
special_func = getattr(func_or_class, func_name) | |
@wraps(special_func) | |
def init_wrapper(*args, **kwargs): | |
try: | |
special_func(*args, **kwargs) | |
except: | |
_explain_error(func) | |
setattr(func_or_class, func_name, init_wrapper) | |
functions = [func_name for func_name in dir(func_or_class) if | |
callable(getattr(func_or_class, func_name)) and | |
not func_name.endswith('__')] | |
# 处理普通函数 | |
for func_name in functions: | |
func = getattr(func_or_class, func_name) | |
@wraps(func) | |
def inner(*args, **kwargs): | |
try: | |
return func(*args, **kwargs) | |
except: | |
_explain_error(func) | |
setattr(func_or_class, func_name, inner) | |
return func_or_class | |
else: | |
@wraps(func_or_class) | |
def inner(*args, **kwargs): | |
try: | |
return func_or_class(*args, **kwargs) | |
except: | |
_explain_error(func_or_class) | |
return inner | |
if __name__ == '__main__': | |
@exception_gpt | |
def aa(): | |
a = 6 | |
print(aaa) | |
# for x in a: | |
# print(x) | |
aa() | |
@exception_gpt | |
class A(object): | |
def __init__(self): | |
self.a = dfgdfgdf() | |
def run(self): | |
print(self.a[4]) | |
pass | |
a = A() | |
a.run() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment