Skip to content

Commit c1f25b2

Browse files
committed
style(cr-agent): 修F541+E501 flake8全绿 (CI) (#92)
1 parent e43b0de commit c1f25b2

3 files changed

Lines changed: 65 additions & 93 deletions

File tree

.flake8

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
[flake8]
22
max-line-length = 120
3-
ignore = E402, W503
3+
ignore = E402, W503, E126, E128

examples/skills_code_review_agent/agent/llm_layer.py

Lines changed: 30 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -71,11 +71,7 @@ def _get_llm_config() -> dict:
7171
if not api_key:
7272
raise ValueError("需要 OPENAI_API_KEY 或 TRPC_AGENT_API_KEY 环境变量")
7373

74-
return {
75-
"api_key": api_key,
76-
"base_url": base_url,
77-
"model_name": model_name
78-
}
74+
return {"api_key": api_key, "base_url": base_url, "model_name": model_name}
7975

8076

8177
def _findings_to_json(findings: list[Finding]) -> str:
@@ -152,20 +148,19 @@ def _call_llm_with_openai_client(findings: list[Finding]) -> list[dict]:
152148
max_retries = 3
153149
for attempt in range(max_retries + 1):
154150
try:
155-
response = client.chat.completions.create(
156-
model=config["model_name"],
157-
messages=[
158-
{
159-
"role": "system",
160-
"content": "代码评审专家,输出纯JSON格式。"
161-
},
162-
{
163-
"role": "user",
164-
"content": prompt
165-
},
166-
],
167-
temperature=0.1,
168-
max_tokens=2000) # 降低到2000减少400错误
151+
response = client.chat.completions.create(model=config["model_name"],
152+
messages=[
153+
{
154+
"role": "system",
155+
"content": "代码评审专家,输出纯JSON格式。"
156+
},
157+
{
158+
"role": "user",
159+
"content": prompt
160+
},
161+
],
162+
temperature=0.1,
163+
max_tokens=2000) # 降低到2000减少400错误
169164

170165
response_text = response.choices[0].message.content
171166
verdicts = _parse_llm_response(response_text)
@@ -180,7 +175,7 @@ def _call_llm_with_openai_client(findings: list[Finding]) -> list[dict]:
180175
raise Exception(f"OpenAI API 400错误: {str(e)}") from e
181176
# 超时/5xx/Upstream错误指数退避重试
182177
elif attempt < max_retries and ("timeout" in error_msg or "5" in error_msg or "upstream" in error_msg):
183-
wait_time = 2 ** attempt # 指数退避:1s, 2s, 4s
178+
wait_time = 2**attempt # 指数退避:1s, 2s, 4s
184179
print(f"[LLM Layer] 调用失败,{wait_time}秒后重试 {attempt + 1}/{max_retries}: {str(e)}")
185180
time.sleep(wait_time)
186181
continue
@@ -352,20 +347,19 @@ def _call_llm_with_openai_client_supplementary(existing_findings: list[Finding],
352347
max_retries = 3
353348
for attempt in range(max_retries + 1):
354349
try:
355-
response = client.chat.completions.create(
356-
model=config["model_name"],
357-
messages=[
358-
{
359-
"role": "system",
360-
"content": "代码评审专家,输出纯JSON格式。"
361-
},
362-
{
363-
"role": "user",
364-
"content": prompt
365-
},
366-
],
367-
temperature=0.1,
368-
max_tokens=1500) # 进一步降低到1500减少400错误
350+
response = client.chat.completions.create(model=config["model_name"],
351+
messages=[
352+
{
353+
"role": "system",
354+
"content": "代码评审专家,输出纯JSON格式。"
355+
},
356+
{
357+
"role": "user",
358+
"content": prompt
359+
},
360+
],
361+
temperature=0.1,
362+
max_tokens=1500) # 进一步降低到1500减少400错误
369363

370364
response_text = response.choices[0].message.content
371365
new_findings = _parse_supplementary_findings(response_text)
@@ -375,11 +369,11 @@ def _call_llm_with_openai_client_supplementary(existing_findings: list[Finding],
375369
error_msg = str(e).lower()
376370
# 400错误不重试,直接抛出
377371
if "400" in error_msg or "bad request" in error_msg:
378-
print(f"[LLM Layer] 补召回400错误(prompt太大),不重试")
372+
print("[LLM Layer] 补召回400错误(prompt太大),不重试")
379373
raise Exception(f"OpenAI 补召回400错误: {str(e)}") from e
380374
# 超时/5xx/Upstream错误指数退避重试
381375
elif attempt < max_retries and ("timeout" in error_msg or "5" in error_msg or "upstream" in error_msg):
382-
wait_time = 2 ** attempt # 指数退避:1s, 2s, 4s
376+
wait_time = 2**attempt # 指数退避:1s, 2s, 4s
383377
print(f"[LLM Layer] 补召回失败,{wait_time}秒后重试 {attempt + 1}/{max_retries}: {str(e)}")
384378
time.sleep(wait_time)
385379
continue

examples/skills_code_review_agent/evaluate.py

Lines changed: 34 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -94,8 +94,10 @@ def load_env_file(env_file: str) -> bool:
9494
value = value.strip()
9595

9696
# 只设置 LLM 相关的环境变量
97-
if key in ["OPENAI_API_KEY", "TRPC_AGENT_API_KEY", "OPENAI_BASE_URL",
98-
"TRPC_AGENT_BASE_URL", "MODEL_NAME", "TRPC_AGENT_MODEL_NAME"]:
97+
if key in [
98+
"OPENAI_API_KEY", "TRPC_AGENT_API_KEY", "OPENAI_BASE_URL", "TRPC_AGENT_BASE_URL",
99+
"MODEL_NAME", "TRPC_AGENT_MODEL_NAME"
100+
]:
99101
os.environ[key] = value
100102

101103
# 验证是否成功加载 API Key
@@ -160,8 +162,7 @@ def load_fixture_diff(fixture_name: str) -> str:
160162
return f.read()
161163

162164

163-
def evaluate_fixture(fixture_name: str, expected_data: Dict[str, Any],
164-
use_llm: bool = False) -> Dict[str, Any]:
165+
def evaluate_fixture(fixture_name: str, expected_data: Dict[str, Any], use_llm: bool = False) -> Dict[str, Any]:
165166
"""评估单个fixture
166167
167168
Args:
@@ -186,11 +187,12 @@ def evaluate_fixture(fixture_name: str, expected_data: Dict[str, Any],
186187
print("[OK] 成功加载diff文件")
187188

188189
# 运行审查管线
189-
report = run_review(diff_text=diff_text,
190-
repo="https://github.com/test/repo",
191-
sandbox="fake",
192-
dry_run=not use_llm, # llm=True 时 dry_run=False
193-
llm=use_llm) # 传递 llm 参数
190+
report = run_review(
191+
diff_text=diff_text,
192+
repo="https://github.com/test/repo",
193+
sandbox="fake",
194+
dry_run=not use_llm, # llm=True 时 dry_run=False
195+
llm=use_llm) # 传递 llm 参数
194196
mode_str = "LLM 增强" if use_llm else "基础"
195197
print(f"[OK] 完成审查({mode_str}模式),发现 {len(report.findings)} 个findings")
196198

@@ -211,7 +213,6 @@ def evaluate_fixture(fixture_name: str, expected_data: Dict[str, Any],
211213

212214
# 高置信度桶(findings + warnings):正常算 TP/FP
213215
high_confidence_findings = findings_findings + warnings_findings
214-
high_confidence_rule_ids = set(finding.rule_id for finding in high_confidence_findings)
215216

216217
# 所有实际检测(用于召回率计算):包含三个桶
217218
all_actual_findings = high_confidence_findings + needs_review_findings
@@ -311,48 +312,27 @@ def evaluate_fixture(fixture_name: str, expected_data: Dict[str, Any],
311312

312313
# 构造结果
313314
result = {
314-
"fixture_name":
315-
fixture_name,
316-
"description":
317-
expected_data.get("description", ""),
318-
"expected_rule_ids":
319-
list(expected_rule_ids),
320-
"actual_rule_ids":
321-
list(actual_rule_ids),
322-
"expected_instances":
323-
expected_instances,
324-
"actual_instances":
325-
all_instances,
326-
"high_confidence_instances":
327-
high_conf_instances,
328-
"needs_review_instances":
329-
needs_review_instances,
330-
"expected_count":
331-
expected_count,
332-
"actual_count":
333-
len(all_actual_findings),
334-
"high_confidence_count":
335-
len(high_confidence_findings),
336-
"needs_review_count":
337-
len(needs_review_findings),
338-
"tp":
339-
tp,
340-
"fp":
341-
fp,
342-
"fn":
343-
fn,
344-
"precision":
345-
precision_val,
346-
"recall":
347-
recall_val,
348-
"f1":
349-
f1_val,
350-
"redaction_rate":
351-
redaction_check["redaction_rate"],
352-
"note":
353-
expected_data.get("note", ""),
354-
"success":
355-
True
315+
"fixture_name": fixture_name,
316+
"description": expected_data.get("description", ""),
317+
"expected_rule_ids": list(expected_rule_ids),
318+
"actual_rule_ids": list(actual_rule_ids),
319+
"expected_instances": expected_instances,
320+
"actual_instances": all_instances,
321+
"high_confidence_instances": high_conf_instances,
322+
"needs_review_instances": needs_review_instances,
323+
"expected_count": expected_count,
324+
"actual_count": len(all_actual_findings),
325+
"high_confidence_count": len(high_confidence_findings),
326+
"needs_review_count": len(needs_review_findings),
327+
"tp": tp,
328+
"fp": fp,
329+
"fn": fn,
330+
"precision": precision_val,
331+
"recall": recall_val,
332+
"f1": f1_val,
333+
"redaction_rate": redaction_check["redaction_rate"],
334+
"note": expected_data.get("note", ""),
335+
"success": True
356336
}
357337

358338
# 打印结果
@@ -599,10 +579,8 @@ def main():
599579
"""主函数"""
600580
# 解析命令行参数
601581
parser = argparse.ArgumentParser(description="代码审查Agent量化评测")
602-
parser.add_argument("--llm", action="store_true",
603-
help="启用真实 LLM 模式(默认为 dry_run 模式)")
604-
parser.add_argument("--env-file", type=str, default=None,
605-
help="指定 .env 文件路径(默认自动探测)")
582+
parser.add_argument("--llm", action="store_true", help="启用真实 LLM 模式(默认为 dry_run 模式)")
583+
parser.add_argument("--env-file", type=str, default=None, help="指定 .env 文件路径(默认自动探测)")
606584

607585
args = parser.parse_args()
608586

0 commit comments

Comments
 (0)