Skip to content

Commit 9c60cd4

Browse files
committed
feat(args_check): Add the check for argues in config.py, and print the check result.
1 parent a967c76 commit 9c60cd4

File tree

3 files changed

+168
-6
lines changed

3 files changed

+168
-6
lines changed

llm_api/llm_api_default.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,10 @@ def set_config(self, api_config: dict) -> bool:
2727
return True
2828

2929
def generate_text(self, messages: list) -> bool:
30-
31-
self.response = unionchat(provider=self.provider, model=self.model_name,
32-
messages=messages)
33-
30+
try:
31+
self.response = unionchat(provider=self.provider, model=self.model_name, messages=messages)
32+
except Exception as e:
33+
raise e
3434
return True
3535

3636
def get_respond_content(self) -> str:

llm_api/load_api.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import importlib
2+
import warnings
23

34
from config.config import llm_api_impl
45

@@ -12,5 +13,7 @@ def get_llm_api_class():
1213

1314
# 使用工厂函数获取类实例
1415
def create_llm_api_instance():
15-
cls = get_llm_api_class()
16-
return cls()
16+
with warnings.catch_warnings():
17+
warnings.simplefilter("ignore", category=UserWarning)
18+
cls = get_llm_api_class()
19+
return cls()

utils/args_check.py

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
import requests
2+
from tabulate import tabulate
3+
4+
def check_config():
5+
"""
6+
Check the configuration
7+
:return: bool
8+
"""
9+
results = []
10+
try:
11+
import config.config as config
12+
if check_exist(config, ["llm_api_impl", "api_config", "gpt_message",
13+
"gitlab_server_url", "gitlab_private_token"]):
14+
results.append(["Configuration parameter existence", "Passed", "", "✅ Required parameters are available."])
15+
else:
16+
results.append(["Configuration parameter existence", "Failed", "Required parameters are missing", "❌ Required parameters are missing"])
17+
return print_results(results)
18+
19+
api_check = check_api_config(config)
20+
if api_check['passed']:
21+
results.append(["API interface", "Passed", "", "✅ Model invocation can be used."])
22+
else:
23+
results.append(["API interface", "Failed", "\n".join(api_check['errors']), "❌ Model invocation cannot be used."])
24+
25+
gitlab_check = check_gitlab_config(config)
26+
if gitlab_check['passed']:
27+
results.append(["Gitlab configuration", "Passed", "", "✅ Code review function can be used.\n✅ Comment function can be used."])
28+
else:
29+
results.append(["Gitlab configuration", "Failed",
30+
"\n".join(gitlab_check['errors']),
31+
"❌ Code review function cannot be used.\n❌ Comment function cannot be used."])
32+
33+
except ImportError:
34+
results.append(["Configuration file", "Failed", "config.py not found",
35+
"❌ Cannot run any Service, please create a config.py file"])
36+
return print_results(results)
37+
except Exception as e:
38+
results.append(["Configuration file", "Failed", f"Error loading config.py: {e}",
39+
"❌ Cannot run any Service, please check config.py file"])
40+
return print_results(results)
41+
42+
return print_results(results)
43+
44+
def check_gitlab_config(config):
45+
"""
46+
Check the gitlab configuration
47+
:return: dict
48+
"""
49+
result = {'passed': True, 'errors': []}
50+
try:
51+
response = requests.get(config.gitlab_server_url)
52+
if response.status_code != 200:
53+
error_msg = f"Gitlab server URL {config.gitlab_server_url} is not available"
54+
result['errors'].append(error_msg)
55+
result['passed'] = False
56+
57+
response = requests.get(f"{config.gitlab_server_url}/api/v4/projects",
58+
headers={"PRIVATE-TOKEN": config.gitlab_private_token})
59+
if response.status_code != 200:
60+
error_msg = "Gitlab private token is invalid"
61+
result['errors'].append(error_msg)
62+
result['passed'] = False
63+
64+
except Exception as e:
65+
result['errors'].append(str(e))
66+
result['passed'] = False
67+
68+
return result
69+
70+
def check_api_config(config):
71+
"""
72+
Check the API configuration
73+
:return: dict
74+
"""
75+
result = {'passed': True, 'errors': []}
76+
try:
77+
from llm_api.load_api import create_llm_api_instance
78+
api = create_llm_api_instance()
79+
api.set_config(config.api_config)
80+
api.generate_text([
81+
{"role": "system",
82+
"content": "你是一个有用的助手"
83+
},
84+
{"role": "user",
85+
"content": "请输出ok两个小写字母,不要输出其他任何内容",
86+
}
87+
])
88+
res_str = api.get_respond_content()
89+
if not res_str or res_str == "":
90+
error_msg = "Model interface check failed: Please check if the model call related configuration is correct"
91+
result['errors'].append(error_msg)
92+
result['passed'] = False
93+
elif "ok" not in res_str:
94+
warning_msg = "Model interface check failed: The model did not return the expected result, but may still be available"
95+
result['errors'].append(warning_msg)
96+
result['passed'] = False
97+
98+
except Exception as e:
99+
result['errors'].append(str(e))
100+
result['passed'] = False
101+
102+
return result
103+
104+
def check_exist(config, arg_names):
105+
"""
106+
Check if the variable is defined
107+
:param arg_names: variable name list
108+
:return: bool
109+
"""
110+
res = True
111+
errors = []
112+
for arg_name in arg_names:
113+
if not hasattr(config, arg_name):
114+
errors.append(f"{arg_name} not found in config.py")
115+
res = False
116+
if errors:
117+
print("\n".join(errors))
118+
return res
119+
120+
def wrap_text(text, width):
121+
"""
122+
Wrap text to a specified width.
123+
:param text: The text to wrap.
124+
:param width: The maximum width of each line.
125+
:return: The wrapped text.
126+
"""
127+
if not text:
128+
return ""
129+
lines = []
130+
while len(text) > width:
131+
# Find the last space within the width limit
132+
wrap_at = text.rfind(' ', 0, width)
133+
if wrap_at == -1:
134+
wrap_at = width
135+
lines.append(text[:wrap_at])
136+
text = text[wrap_at:].lstrip()
137+
lines.append(text)
138+
return "\n".join(lines)
139+
140+
def print_results(results):
141+
"""
142+
Print the results in a tabulated format
143+
:param results: list of lists containing the check results
144+
"""
145+
wrapped_results = []
146+
for result in results:
147+
wrapped_result = [wrap_text(result[0], 30), wrap_text(result[1], 10),
148+
wrap_text(result[2], 50), result[3]]
149+
wrapped_results.append(wrapped_result)
150+
table = tabulate(wrapped_results, headers=["Check", "Status", "Details", "Influence Service"], tablefmt="grid", stralign="left")
151+
print(table)
152+
return all(result[1] == "Passed" for result in results)
153+
154+
# 示例调用
155+
if __name__ == "__main__":
156+
if check_config():
157+
print("All configuration checks passed")
158+
else:
159+
print("Some configuration checks failed")

0 commit comments

Comments
 (0)