Drac0528 commited on
Commit
da33e9d
·
verified ·
1 Parent(s): 9afa300

Delete inference.py

Browse files
Files changed (1) hide show
  1. inference.py +0 -220
inference.py DELETED
@@ -1,220 +0,0 @@
1
- #!/usr/bin/env python3
2
- from __future__ import annotations
3
-
4
- import asyncio
5
- import json
6
- import os
7
- from typing import Any, Dict, List, Optional
8
-
9
- from openai import OpenAI
10
-
11
- try:
12
- from code_security_auditor_env import CodeSecurityAction, CodeSecurityAuditorEnv
13
- except ImportError:
14
- from client import CodeSecurityAuditorEnv
15
- from models import CodeSecurityAction
16
-
17
- API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
18
- MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
19
- API_KEY = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
20
- LOCAL_IMAGE_NAME = os.getenv("LOCAL_IMAGE_NAME")
21
- ENV_BASE_URL = os.getenv("ENV_BASE_URL")
22
- TASK_IDS = [t.strip() for t in os.getenv("TASK_IDS", "easy,medium,hard").split(",") if t.strip()]
23
- MAX_STEPS = int(os.getenv("MAX_STEPS", "12"))
24
- TEMPERATURE = 0.0
25
- MAX_TOKENS = 260
26
- BENCHMARK = "code_security_auditor_env"
27
-
28
- SYSTEM_PROMPT = (
29
- "You are a senior application security reviewer. Produce strictly valid JSON for the next action. "
30
- "Allowed action_type values: inspect_file, submit_finding, submit_final_report. "
31
- "Do not include markdown fences. Keep fields concise and accurate."
32
- )
33
-
34
-
35
- def log_start(task: str, env: str, model: str) -> None:
36
- print(f"[START] task={task} env={env} model={model}", flush=True)
37
-
38
-
39
- def log_step(step: int, action: str, reward: float, done: bool, error: Optional[str]) -> None:
40
- err = error if error else "null"
41
- print(
42
- f"[STEP] step={step} action={action} reward={reward:.2f} done={str(done).lower()} error={err}",
43
- flush=True,
44
- )
45
-
46
-
47
- def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
48
- rewards_str = ",".join(f"{r:.2f}" for r in rewards)
49
- print(
50
- f"[END] success={str(success).lower()} steps={steps} score={score:.3f} rewards={rewards_str}",
51
- flush=True,
52
- )
53
-
54
-
55
- def _compact_action_str(action: Dict[str, Any]) -> str:
56
- return json.dumps(action, separators=(",", ":"), ensure_ascii=True)
57
-
58
-
59
- def _default_action() -> Dict[str, Any]:
60
- return {
61
- "action_type": "submit_final_report",
62
- "confidence": 0.5,
63
- "summary": "fallback-finalize",
64
- "evidence": "fallback-finalize",
65
- }
66
-
67
-
68
- def _parse_action(raw: str, available_files: List[str]) -> Dict[str, Any]:
69
- try:
70
- parsed = json.loads(raw)
71
- if not isinstance(parsed, dict):
72
- return _default_action()
73
- except Exception:
74
- return _default_action()
75
-
76
- action_type = parsed.get("action_type")
77
- if action_type not in {"inspect_file", "submit_finding", "submit_final_report"}:
78
- return _default_action()
79
-
80
- action: Dict[str, Any] = {
81
- "action_type": action_type,
82
- "confidence": float(parsed.get("confidence", 0.5)),
83
- "summary": str(parsed.get("summary", ""))[:400],
84
- "evidence": str(parsed.get("evidence", ""))[:700],
85
- }
86
-
87
- if parsed.get("filename"):
88
- filename = str(parsed["filename"])
89
- if filename in available_files:
90
- action["filename"] = filename
91
- if parsed.get("line_start") is not None:
92
- try:
93
- action["line_start"] = max(1, int(parsed["line_start"]))
94
- except Exception:
95
- pass
96
- if parsed.get("line_end") is not None:
97
- try:
98
- action["line_end"] = max(1, int(parsed["line_end"]))
99
- except Exception:
100
- pass
101
- if parsed.get("vuln_type") is not None:
102
- action["vuln_type"] = str(parsed["vuln_type"])
103
- if parsed.get("severity") is not None:
104
- action["severity"] = str(parsed["severity"])
105
-
106
- action["confidence"] = min(1.0, max(0.0, action["confidence"]))
107
-
108
- return action
109
-
110
-
111
- def _build_prompt(obs: Any, step: int) -> str:
112
- findings = obs.findings_so_far[-4:] if obs.findings_so_far else []
113
- snippet = obs.file_excerpt[:1800] if obs.file_excerpt else ""
114
- return (
115
- f"Task: {obs.task_id} ({obs.difficulty})\\n"
116
- f"Objective: {obs.objective}\\n"
117
- f"Step: {step}\\n"
118
- f"Steps remaining: {obs.steps_remaining}\\n"
119
- f"Files: {', '.join(obs.available_files)}\\n"
120
- f"Last feedback: {obs.last_feedback}\\n"
121
- f"Focused file: {obs.focused_file}\\n"
122
- f"Recent findings: {json.dumps(findings)}\\n"
123
- f"Visible snippet:\\n{snippet}\\n"
124
- "Return one JSON object with action_type and required fields."
125
- )
126
-
127
-
128
- def _query_model(client: OpenAI, obs: Any, step: int) -> Dict[str, Any]:
129
- user_prompt = _build_prompt(obs, step)
130
- try:
131
- resp = client.chat.completions.create(
132
- model=MODEL_NAME,
133
- messages=[
134
- {"role": "system", "content": SYSTEM_PROMPT},
135
- {"role": "user", "content": user_prompt},
136
- ],
137
- temperature=TEMPERATURE,
138
- max_tokens=MAX_TOKENS,
139
- stream=False,
140
- )
141
- content = (resp.choices[0].message.content or "").strip()
142
- return _parse_action(content, obs.available_files)
143
- except Exception:
144
- return _default_action()
145
-
146
-
147
- async def _create_env() -> CodeSecurityAuditorEnv:
148
- if LOCAL_IMAGE_NAME:
149
- return await CodeSecurityAuditorEnv.from_docker_image(LOCAL_IMAGE_NAME)
150
- if ENV_BASE_URL:
151
- return CodeSecurityAuditorEnv(base_url=ENV_BASE_URL)
152
- raise RuntimeError(
153
- "Set LOCAL_IMAGE_NAME (docker mode) or ENV_BASE_URL (remote mode) to run inference."
154
- )
155
-
156
-
157
- async def run_task(env: CodeSecurityAuditorEnv, client: OpenAI, task_id: str) -> float:
158
- log_start(task=task_id, env=BENCHMARK, model=MODEL_NAME)
159
-
160
- rewards: List[float] = []
161
- steps_taken = 0
162
- score = 0.0
163
- success = False
164
-
165
- try:
166
- result = await env.reset(task_id=task_id)
167
- obs = result.observation
168
-
169
- for step in range(1, MAX_STEPS + 1):
170
- if result.done:
171
- break
172
-
173
- action_dict = _query_model(client, obs, step)
174
- action_str = _compact_action_str(action_dict)
175
-
176
- action = CodeSecurityAction(**action_dict)
177
- result = await env.step(action)
178
- obs = result.observation
179
-
180
- reward = float(result.reward or 0.0)
181
- done = bool(result.done)
182
- error = obs.metadata.get("last_action_error")
183
-
184
- rewards.append(reward)
185
- steps_taken = step
186
- log_step(step=step, action=action_str, reward=reward, done=done, error=error)
187
-
188
- if done:
189
- break
190
-
191
- score = float(obs.reward or 0.0)
192
- score = min(max(score, 0.0), 1.0)
193
- success = score >= 0.6
194
- finally:
195
- log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
196
-
197
- return score
198
-
199
-
200
- async def main() -> None:
201
- if not API_KEY:
202
- raise RuntimeError("HF_TOKEN (or API_KEY) is required for inference.")
203
-
204
- client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
205
- env = await _create_env()
206
-
207
- try:
208
- scores: List[float] = []
209
- for task_id in TASK_IDS:
210
- score = await run_task(env, client, task_id)
211
- scores.append(score)
212
-
213
- # Keep strict output format requirement: no extra structured tags beyond START/STEP/END.
214
- _ = scores
215
- finally:
216
- await env.close()
217
-
218
-
219
- if __name__ == "__main__":
220
- asyncio.run(main())