Sumitwarrior7 commited on
Commit
01e6bf4
Β·
verified Β·
1 Parent(s): 4696f8d

Upload folder using huggingface_hub

Browse files
client.py CHANGED
@@ -84,7 +84,7 @@ class JobScamEnv(EnvClient[JobScamAction, JobScamObservation, State]):
84
 
85
  # ------------------------------------------------------------------ reset
86
 
87
- async def reset(self, task_name: str = "medium") -> StepResult[JobScamObservation]:
88
  """
89
  Start a new episode on the server.
90
 
@@ -100,6 +100,10 @@ class JobScamEnv(EnvClient[JobScamAction, JobScamObservation, State]):
100
  The initial observation containing query_type, initial_query,
101
  available_context, step_budget, and task_name.
102
  """
 
 
 
 
103
  if task_name not in VALID_TASK_NAMES:
104
  raise ValueError(
105
  f"Unknown task_name '{task_name}'. "
@@ -152,9 +156,6 @@ class JobScamEnv(EnvClient[JobScamAction, JobScamObservation, State]):
152
  available_context=obs_raw.get("available_context"),
153
 
154
  # ── EASY TASK β€” information request fields (placeholders) ──────────
155
- # TODO: add easy-specific field deserialization here when designed
156
- # Example:
157
- # easy_summary=obs_raw.get("easy_summary"),
158
 
159
  # ── HARD TASK β€” information request fields (placeholders) ──────────
160
  # TODO: add hard-specific field deserialization here when designed
 
84
 
85
  # ------------------------------------------------------------------ reset
86
 
87
+ async def reset(self, task_name: str = None) -> StepResult[JobScamObservation]:
88
  """
89
  Start a new episode on the server.
90
 
 
100
  The initial observation containing query_type, initial_query,
101
  available_context, step_budget, and task_name.
102
  """
103
+ if not task_name:
104
+ raise ValueError(
105
+ f"Please provide a task_name."
106
+ )
107
  if task_name not in VALID_TASK_NAMES:
108
  raise ValueError(
109
  f"Unknown task_name '{task_name}'. "
 
156
  available_context=obs_raw.get("available_context"),
157
 
158
  # ── EASY TASK β€” information request fields (placeholders) ──────────
 
 
 
159
 
160
  # ── HARD TASK β€” information request fields (placeholders) ──────────
161
  # TODO: add hard-specific field deserialization here when designed
constants.py CHANGED
@@ -22,14 +22,23 @@ VALID_TASK_NAMES: List[str] = ["easy", "medium", "hard"]
22
  # ===========================================================================
23
  # EASY TASK constants (placeholders β€” fill in when easy task is designed)
24
  # ===========================================================================
25
- # EASY_MAX_STEPS: int = 3
26
- # EASY_TIMEOUT_PENALTY: float = -1.5
27
  EASY_DATASET_FILENAME: str = "data_task_easy.jsonl"
28
 
29
- # EASY_REWARD_MATRIX: Dict[str, Dict[str, float]] = {}
30
- EASY_ACTION_TO_FIELD: Dict[str, str] = {}
31
- # EASY_ALL_CONTEXT_FIELDS: List[str] = []
 
 
 
 
 
 
 
32
 
 
 
33
 
34
  # ===========================================================================
35
  # MEDIUM TASK constants (the original / current task)
@@ -81,7 +90,7 @@ MEDIUM_ALL_CONTEXT_FIELDS: List[str] = list(MEDIUM_ACTION_TO_FIELD.values())
81
  # ===========================================================================
82
  # HARD TASK constants (placeholders β€” fill in when hard task is designed)
83
  # ===========================================================================
84
- # HARD_MAX_STEPS: int = 7
85
  # HARD_TIMEOUT_PENALTY: float = -1.5
86
  HARD_DATASET_FILENAME: str = "data_task_hard.jsonl"
87
 
 
22
  # ===========================================================================
23
  # EASY TASK constants (placeholders β€” fill in when easy task is designed)
24
  # ===========================================================================
25
+ EASY_MAX_STEPS: int = 1
26
+ # EASY_TIMEOUT_PENALTY: float = -1.0
27
  EASY_DATASET_FILENAME: str = "data_task_easy.jsonl"
28
 
29
+ EASY_REWARD_MATRIX: Dict[str, Dict[str, float]] = {
30
+ "legit": {
31
+ "legit": 1.00,
32
+ "scam": -1.00,
33
+ },
34
+ "scam": {
35
+ "legit": -0.60,
36
+ "scam": 1.00,
37
+ },
38
+ }
39
 
40
+ EASY_ACTION_TO_FIELD: Dict[str, str] = {}
41
+ EASY_ALL_CONTEXT_FIELDS: List[str] = []
42
 
43
  # ===========================================================================
44
  # MEDIUM TASK constants (the original / current task)
 
90
  # ===========================================================================
91
  # HARD TASK constants (placeholders β€” fill in when hard task is designed)
92
  # ===========================================================================
93
+ HARD_MAX_STEPS: int = 7
94
  # HARD_TIMEOUT_PENALTY: float = -1.5
95
  HARD_DATASET_FILENAME: str = "data_task_hard.jsonl"
96
 
inference.py CHANGED
@@ -2,41 +2,15 @@
2
  Inference Script β€” Job Scam Detection Environment
3
  ==================================================
4
 
5
- An LLM-driven agent that plays one episode of the JobScamEnvironment by
6
- investigating a job opportunity and submitting a classification label.
7
-
8
- Task selection
9
- --------------
10
- Set the ``TASK_NAME`` variable below to choose which difficulty variant runs.
11
- Allowed values: "easy" | "medium" | "hard". Defaults to "medium".
12
 
13
  Required environment variables
14
  -------------------------------
15
  API_BASE_URL API endpoint for the LLM (e.g. https://router.huggingface.co/v1).
16
  MODEL_NAME Model identifier (e.g. Qwen/Qwen2.5-72B-Instruct).
17
  HF_TOKEN Hugging Face / API key.
18
-
19
- The script uses the OpenAI-compatible client for all LLM calls, as required
20
- by the submission spec.
21
-
22
- Agent strategy (medium task)
23
- -----------------------------
24
- 1. Parse the initial observation (query type + raw query text).
25
- 2. Use the LLM to decide which context field to request next, or to
26
- classify if enough evidence has been gathered.
27
- 3. Parse the LLM response as a JSON action object.
28
- 4. Step the environment, print the reward breakdown.
29
- 5. Repeat until ``done=True``.
30
-
31
- Action JSON format expected from the LLM
32
- -----------------------------------------
33
- Info request (medium)::
34
-
35
- {"action_type": "request_company_profile"}
36
-
37
- Classification (all tasks)::
38
-
39
- {"action_type": "classify", "label": "scam"}
40
  """
41
 
42
  from __future__ import annotations
@@ -52,173 +26,180 @@ from openai import OpenAI
52
  from dotenv import load_dotenv
53
  from client import JobScamEnv
54
  from models import ActionType, ClassificationLabel, JobScamAction, JobScamObservation
55
- from constants import VALID_TASK_NAMES
56
-
57
- # ---------------------------------------------------------------------------
58
- # Task selection β€” change this variable to switch between task variants
59
- # ---------------------------------------------------------------------------
60
-
61
- # Options: "easy" | "medium" | "hard"
62
- TASK_NAME: str = "medium"
63
 
64
  # ---------------------------------------------------------------------------
65
  # Configuration
66
  # ---------------------------------------------------------------------------
67
  load_dotenv()
68
- API_BASE_URL: str = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
69
- API_KEY: Optional[str] = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
70
- MODEL_NAME: Optional[str] = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
71
- IMAGE_NAME: Optional[str] = os.getenv("IMAGE_NAME", "job_scam_env-env:latest")
72
 
 
73
  TEMPERATURE: float = 0.2
74
  MAX_TOKENS: int = 300
75
 
 
 
 
 
 
 
 
 
 
76
  _VALID_ACTION_TYPES = [a.value for a in ActionType]
77
  _VALID_LABELS = [l.value for l in ClassificationLabel]
78
 
79
  # ---------------------------------------------------------------------------
80
- # Task-specific: max steps
81
  # ---------------------------------------------------------------------------
82
 
83
- if TASK_NAME == "easy":
84
- # TODO: set easy-task max steps when task is designed
85
- # from constants import EASY_MAX_STEPS
86
- # MAX_STEPS: int = EASY_MAX_STEPS
87
- MAX_STEPS: int = 3 # placeholder
88
- elif TASK_NAME == "medium":
89
- from constants import MEDIUM_MAX_STEPS
90
- MAX_STEPS: int = MEDIUM_MAX_STEPS
91
- elif TASK_NAME == "hard":
92
- # TODO: set hard-task max steps when task is designed
93
- # from constants import HARD_MAX_STEPS
94
- # MAX_STEPS: int = HARD_MAX_STEPS
95
- MAX_STEPS: int = 8 # placeholder
96
- else:
97
- raise ValueError(
98
- f"Unknown TASK_NAME '{TASK_NAME}'. Must be one of: {VALID_TASK_NAMES}."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  )
100
 
 
 
 
101
  # ---------------------------------------------------------------------------
102
- # Task-specific: system prompt
103
  # ---------------------------------------------------------------------------
104
- if TASK_NAME == "easy":
105
- # TODO: write an easy-task-specific system prompt when task is designed.
106
- # For now, a placeholder is used.
107
- _SYSTEM_PROMPT = textwrap.dedent("""
108
- You are an expert job-scam investigator.
109
- [EASY TASK β€” system prompt placeholder. Replace with easy-task instructions.]
110
-
111
- Terminal action (must be your last action):
112
- {"action_type": "classify", "label": "<legit|suspicious|scam|insufficient_info>"}
113
-
114
- Output ONLY a valid JSON object. No surrounding text.
115
- """).strip()
116
- elif TASK_NAME == "medium":
117
- _SYSTEM_PROMPT = textwrap.dedent("""
118
- You are an expert job-scam investigator.
119
- Your task is to analyse a job opportunity and classify it as one of:
120
- legit | suspicious | scam | insufficient_info
121
-
122
- You have up to 5 steps per episode. Each step you must output exactly one
123
- JSON object β€” nothing else, no markdown, no explanation.
124
-
125
- AVAILABLE ACTIONS
126
- -----------------
127
- Information requests (use these to gather evidence before classifying):
128
- {"action_type": "request_recruiter_profile"}
129
- {"action_type": "request_company_profile"}
130
- {"action_type": "request_thread_history"}
131
- {"action_type": "request_job_post_comments"}
132
-
133
- Terminal action (must be your last action):
134
- {"action_type": "classify", "label": "<legit|suspicious|scam|insufficient_info>"}
135
-
136
- STRATEGY GUIDELINES
137
- -------------------
138
- - Look for red flags: payment requests, off-platform contact (WhatsApp/Telegram),
139
- government ID requests, urgency pressure, evasion tactics, gmail sender for MNC.
140
- - Look for green flags: official domain, no-fee statements, portal-only hiring,
141
- anti-scam guidance.
142
- - Classify as soon as you have enough evidence β€” earlier correct classification
143
- earns a timing bonus.
144
- - Do NOT request the same field twice β€” it incurs a -0.20 penalty.
145
- - Do NOT use classify before you have enough evidence.
146
- - Output ONLY a valid JSON object. No surrounding text.
147
- """).strip()
148
- elif TASK_NAME == "hard":
149
- # TODO: write a hard-task-specific system prompt when task is designed.
150
- # For now, a placeholder is used.
151
- _SYSTEM_PROMPT = textwrap.dedent("""
152
- You are an expert job-scam investigator.
153
- [HARD TASK β€” system prompt placeholder. Replace with hard-task instructions.]
154
-
155
- Terminal action (must be your last action):
156
- {"action_type": "classify", "label": "<legit|suspicious|scam|insufficient_info>"}
157
-
158
- Output ONLY a valid JSON object. No surrounding text.
159
- """).strip()
160
 
161
  # ---------------------------------------------------------------------------
162
- # Task-specific: fallback action priority
163
  # ---------------------------------------------------------------------------
164
- if TASK_NAME == "easy":
165
- # TODO: define the easy-task fallback priority order when task is designed.
166
- # For now, only classify is available as fallback.
167
- _FALLBACK_PRIORITY: List[ActionType] = []
168
- elif TASK_NAME == "medium":
169
- _FALLBACK_PRIORITY: List[ActionType] = [
170
  ActionType.REQUEST_COMPANY_PROFILE,
171
  ActionType.REQUEST_RECRUITER_PROFILE,
172
  ActionType.REQUEST_THREAD_HISTORY,
173
  ActionType.REQUEST_JOB_POST_COMMENTS,
174
- ]
175
- elif TASK_NAME == "hard":
176
- # TODO: define the hard-task fallback priority order when task is designed.
177
- _FALLBACK_PRIORITY: List[ActionType] = []
178
-
179
 
180
  # ---------------------------------------------------------------------------
181
  # User message builder
182
  # ---------------------------------------------------------------------------
 
183
  def _build_user_message(
184
  step: int,
185
  obs: JobScamObservation,
186
  history: List[str],
 
 
187
  ) -> str:
188
- """Construct the user-turn message for the LLM at each step."""
189
  step_budget = obs.step_budget
190
  if isinstance(step_budget, dict):
191
- remaining = step_budget.get("remaining", MAX_STEPS - step)
192
  else:
193
- remaining = MAX_STEPS - step
194
 
195
  parts: List[str] = [
196
- f"TASK: {obs.task_name or TASK_NAME}",
197
  f"STEP: {step}",
198
  f"STEPS REMAINING: {remaining}",
199
  "",
200
  ]
201
 
202
- # ── Initial query (always present) ──────────────────────────────────────
203
  if obs.query_type:
204
  parts.append(f"QUERY TYPE: {obs.query_type}")
205
  if obs.initial_query:
206
  parts.append(f"INITIAL QUERY:\n{obs.initial_query}")
207
 
208
- # ── Task-specific field content display ──────────────────────────────────
209
- if TASK_NAME == "easy":
210
- # TODO: add easy-task-specific field display here when task is designed
211
- pass
212
-
213
- elif TASK_NAME == "medium":
214
  if obs.requested_field and obs.field_content:
215
  parts.append(f"\nFIELD JUST RECEIVED β€” {obs.requested_field.upper()}:")
216
  parts.append(obs.field_content)
217
 
218
- elif TASK_NAME == "hard":
219
- # TODO: add hard-task-specific field display here when task is designed
220
- pass
221
-
222
  if history:
223
  parts.append("\nACTIONS TAKEN SO FAR:")
224
  parts.extend(f" {h}" for h in history)
@@ -236,17 +217,11 @@ def _build_user_message(
236
  # ---------------------------------------------------------------------------
237
  _JSON_RE = re.compile(r"\{.*?\}", re.DOTALL)
238
 
239
- def _parse_action(response_text: str) -> Optional[JobScamAction]:
240
- """
241
- Extract the first JSON object from the LLM response and validate it
242
- as a ``JobScamAction``.
243
 
244
- Returns ``None`` if parsing fails (caller will apply a fallback).
245
- """
246
  match = _JSON_RE.search(response_text)
247
  if not match:
248
  return None
249
-
250
  try:
251
  data = json.loads(match.group(0))
252
  except json.JSONDecodeError:
@@ -258,7 +233,7 @@ def _parse_action(response_text: str) -> Optional[JobScamAction]:
258
 
259
  label_str: Optional[str] = data.get("label")
260
 
261
- if action_type_str == ActionType.CLASSIFY:
262
  if label_str not in _VALID_LABELS:
263
  return None
264
  return JobScamAction(
@@ -271,65 +246,67 @@ def _parse_action(response_text: str) -> Optional[JobScamAction]:
271
 
272
  return JobScamAction(action_type=ActionType(action_type_str))
273
 
274
- def _fallback_action(step: int, requested: List[str]) -> JobScamAction:
275
- """
276
- Heuristic fallback when the LLM produces an unparseable response.
277
-
278
- Requests the next unrequested field in the task-specific priority order,
279
- or defaults to ``insufficient_info`` if all fields have been requested.
280
- """
281
- if TASK_NAME == "easy":
282
- # TODO: implement easy-task fallback logic when task is designed
283
- pass
284
-
285
- elif TASK_NAME == "medium":
286
- for action_type in _FALLBACK_PRIORITY:
287
- field = action_type.value.replace("request_", "")
288
- if field not in requested:
289
- return JobScamAction(action_type=action_type)
290
-
291
- elif TASK_NAME == "hard":
292
- # TODO: implement hard-task fallback logic when task is designed
293
- pass
294
 
295
- # All fields seen or last step β€” safe default
 
 
 
 
296
  return JobScamAction(
297
  action_type=ActionType.CLASSIFY,
298
  label=ClassificationLabel.INSUFFICIENT_INFO,
299
  )
300
 
 
301
  # ---------------------------------------------------------------------------
302
- # Main episode loop
303
  # ---------------------------------------------------------------------------
304
- async def run_episode(env: JobScamEnv, llm_client: OpenAI) -> float:
 
 
 
 
 
 
 
305
  """
306
- Run a single episode to completion and return the total reward.
307
- ``env`` is the live async client, already connected via ``async with``.
 
 
308
  """
309
- # Reset with the chosen task variant
310
- result = await env.reset(task_name=TASK_NAME)
311
  obs = result.observation
312
 
313
- history: List[str] = []
314
- requested_fields: List[str] = []
315
- total_reward: float = 0.0
316
- initial_query_text = obs.initial_query or ""
 
 
317
 
 
318
  print(f"\n{'='*60}")
319
- print(f"NEW EPISODE [task: {TASK_NAME}]")
320
  print(f"Query type : {obs.query_type}")
321
  print(f"Initial : {initial_query_text[:120]}...")
322
  print(f"{'='*60}")
323
 
324
- for step in range(1, MAX_STEPS + 1):
325
- # ── Build LLM messages ────────────────────────────────────────────────
326
- user_msg = _build_user_message(step, obs, history)
 
 
 
 
 
327
  messages: List[Dict[str, Any]] = [
328
- {"role": "system", "content": _SYSTEM_PROMPT},
329
  {"role": "user", "content": user_msg},
330
  ]
331
 
332
- # ── Call LLM ─────────────────────────────────────────────────────────
 
333
  try:
334
  completion = llm_client.chat.completions.create(
335
  model=MODEL_NAME,
@@ -340,35 +317,43 @@ async def run_episode(env: JobScamEnv, llm_client: OpenAI) -> float:
340
  )
341
  response_text = completion.choices[0].message.content or ""
342
  except Exception as exc:
 
343
  print(f" [Step {step}] LLM error: {exc}. Using fallback.")
344
- response_text = ""
345
 
346
- # ── Parse action ──────────────────────────────────────────────────────
347
  action = _parse_action(response_text)
348
  if action is None:
349
  print(
350
  f" [Step {step}] Unparseable response: "
351
  f"{response_text!r:.80}. Using fallback."
352
  )
353
- action = _fallback_action(step, requested_fields)
354
 
355
- print(
356
- f"\n[Step {step}] Action: {action.action_type.value}"
357
- + (f" label={action.label.value}" if action.label else "")
358
- )
359
 
360
- # ── Step environment ──────────────────────────────────────────────────
361
  result = await env.step(action)
362
  obs = result.observation
363
  reward = result.reward or 0.0
364
  total_reward += reward
 
 
365
 
366
- # ── Record history (task-specific field naming) ───────────────────────
367
- if action.action_type != ActionType.CLASSIFY:
368
- if TASK_NAME == "easy":
 
 
 
 
 
 
369
  # TODO: derive field name for easy-task actions when designed
370
- field_name = action.action_type.value.replace("request_", "")
371
- elif TASK_NAME == "medium":
 
372
  field_name = action.action_type.value.replace("request_", "")
373
  requested_fields.append(field_name)
374
  history.append(
@@ -381,59 +366,99 @@ async def run_episode(env: JobScamEnv, llm_client: OpenAI) -> float:
381
  print(f" Breakdown : {info['reward_breakdown']}")
382
  if info.get("cumulative"):
383
  print(f" Cumulative : {info['cumulative']}")
384
- elif TASK_NAME == "hard":
385
  # TODO: derive field name for hard-task actions when designed
386
- field_name = action.action_type.value.replace("request_", "")
387
-
388
-
389
- # ── Handle done ───────────────────────────────────────────────────────
390
- if result.done:
391
- if TASK_NAME == "easy":
 
 
 
 
 
 
 
 
392
  break
393
- elif TASK_NAME == "medium":
 
394
  info = obs.info or {}
395
  if obs.reason == "timeout":
 
396
  print(f"\n TIMEOUT β€” all steps exhausted without classifying.")
397
- print(f" Timeout penalty: {info['reward_breakdown']['timeout_penalty']:+.4f}")
398
- print(f" Step Reward : {reward:+.4f}")
 
399
  else:
 
 
400
  print(f"\n CLASSIFICATION RESULT")
401
  print(f" Step reward : {reward:+.4f}")
402
- print(f" Predicted : {obs.predicted_label}")
403
- print(f" Actual : {obs.actual_label}")
404
- correct = obs.predicted_label == obs.actual_label
405
- print(f" Correct : {correct}\n")
406
  if info.get("reward_breakdown"):
407
- print(f" Breakdown : {info['reward_breakdown']}")
408
  if info.get("cumulative"):
409
- print(f" Episode total : {info['cumulative']}")
410
  break
411
- elif TASK_NAME == "hard":
 
412
  break
413
 
414
- print(f"\nEpisode finished!!")
415
- return total_reward
416
 
 
 
 
 
 
 
 
417
 
418
  async def main() -> None:
419
- """
420
- Entry point: spin up the Docker container, run one episode, then tear down.
421
- """
422
  if not API_KEY:
423
  raise EnvironmentError("HF_TOKEN or API_KEY environment variable must be set.")
424
  if not MODEL_NAME:
425
  raise EnvironmentError("MODEL_NAME environment variable must be set.")
426
- if TASK_NAME not in VALID_TASK_NAMES:
427
- raise ValueError(
428
- f"Invalid TASK_NAME '{TASK_NAME}'. Must be one of: {VALID_TASK_NAMES}."
429
- )
430
 
431
  llm_client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
432
 
433
- env = await JobScamEnv.from_docker_image(IMAGE_NAME)
434
 
435
  async with env:
436
- await run_episode(env, llm_client)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
 
438
 
439
  if __name__ == "__main__":
 
2
  Inference Script β€” Job Scam Detection Environment
3
  ==================================================
4
 
5
+ An LLM-driven agent that plays episodes of the JobScamEnvironment for ALL
6
+ task variants (easy, medium, hard) in a single invocation, emitting
7
+ structured [START] / [STEP] / [END] logs that the validator parses.
 
 
 
 
8
 
9
  Required environment variables
10
  -------------------------------
11
  API_BASE_URL API endpoint for the LLM (e.g. https://router.huggingface.co/v1).
12
  MODEL_NAME Model identifier (e.g. Qwen/Qwen2.5-72B-Instruct).
13
  HF_TOKEN Hugging Face / API key.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  """
15
 
16
  from __future__ import annotations
 
26
  from dotenv import load_dotenv
27
  from client import JobScamEnv
28
  from models import ActionType, ClassificationLabel, JobScamAction, JobScamObservation
29
+ from constants import VALID_TASK_NAMES, EASY_MAX_STEPS, MEDIUM_MAX_STEPS, HARD_MAX_STEPS
 
 
 
 
 
 
 
30
 
31
  # ---------------------------------------------------------------------------
32
  # Configuration
33
  # ---------------------------------------------------------------------------
34
  load_dotenv()
35
+ API_BASE_URL: str = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
36
+ API_KEY: Optional[str] = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
37
+ MODEL_NAME: Optional[str] = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
38
+ LOCAL_IMAGE_NAME: Optional[str] = os.getenv("LOCAL_IMAGE_NAME", "job_scam_env:latest")
39
 
40
+ BENCHMARK: str = "job_scam_detection"
41
  TEMPERATURE: float = 0.2
42
  MAX_TOKENS: int = 300
43
 
44
+ # ---------------------------------------------------------------------------
45
+ # All tasks to run β€” validator requires one [START]/[END] pair per task
46
+ # ---------------------------------------------------------------------------
47
+ TASKS: List[tuple[str, str, int]] = [
48
+ ("task_easy", "easy", EASY_MAX_STEPS),
49
+ ("task_medium", "medium", MEDIUM_MAX_STEPS),
50
+ # ("task_hard", "hard", HARD_MAX_STEPS),
51
+ ]
52
+
53
  _VALID_ACTION_TYPES = [a.value for a in ActionType]
54
  _VALID_LABELS = [l.value for l in ClassificationLabel]
55
 
56
  # ---------------------------------------------------------------------------
57
+ # Structured log helpers (validator-required stdout format)
58
  # ---------------------------------------------------------------------------
59
 
60
+ def log_start(task: str, env: str, model: str) -> None:
61
+ print(f"[START] task={task} env={env} model={model}", flush=True)
62
+
63
+
64
+ def log_step(
65
+ step: int,
66
+ action: str,
67
+ reward: float,
68
+ done: bool,
69
+ error: Optional[str] = None,
70
+ ) -> None:
71
+ done_str = "true" if done else "false"
72
+ error_str = error if error is not None else "null"
73
+ print(
74
+ f"[STEP] step={step} action={action} "
75
+ f"done={done_str} error={error_str}",
76
+ flush=True,
77
+ )
78
+
79
+
80
+ def log_end(
81
+ task: str,
82
+ success: bool,
83
+ steps: int,
84
+ score: float,
85
+ ) -> None:
86
+ success_str = "true" if success else "false"
87
+ print(
88
+ f"[END] task={task} success={success_str} steps={steps} "
89
+ f"score={score:.4f}",
90
+ flush=True,
91
  )
92
 
93
+ def normalize_one(x):
94
+ return int(x) if float(x) == 1.0 else x
95
+
96
  # ---------------------------------------------------------------------------
97
+ # System prompts (per task)
98
  # ---------------------------------------------------------------------------
99
+ _SYSTEM_PROMPTS: Dict[str, str] = {
100
+ "easy": textwrap.dedent("""
101
+ You are an expert job scam detector.
102
+
103
+ For this easy task, read the message and classify it as either:
104
+ legit | scam
105
+
106
+ Output exactly one JSON object and nothing else.
107
+
108
+ Format:
109
+ {"action_type": "classify", "label": "<legit|scam>"}
110
+ """).strip(),
111
+
112
+ "medium": textwrap.dedent("""
113
+ You are an expert job-scam investigator.
114
+ Your task is to analyse a job opportunity and classify it as one of:
115
+ legit | suspicious | scam | insufficient_info
116
+
117
+ You have up to 5 steps per episode. Each step you must output exactly one
118
+ JSON object β€” nothing else, no markdown, no explanation.
119
+
120
+ AVAILABLE ACTIONS
121
+ -----------------
122
+ Information requests (use these to gather evidence before classifying):
123
+ {"action_type": "request_recruiter_profile"}
124
+ {"action_type": "request_company_profile"}
125
+ {"action_type": "request_thread_history"}
126
+ {"action_type": "request_job_post_comments"}
127
+
128
+ Terminal action (must be your last action):
129
+ {"action_type": "classify", "label": "<legit|suspicious|scam|insufficient_info>"}
130
+
131
+ STRATEGY GUIDELINES
132
+ -------------------
133
+ - Look for red flags: payment requests, off-platform contact (WhatsApp/Telegram),
134
+ government ID requests, urgency pressure, evasion tactics, gmail sender for MNC.
135
+ - Look for green flags: official domain, no-fee statements, portal-only hiring,
136
+ anti-scam guidance.
137
+ - Classify as soon as you have enough evidence β€” earlier correct classification
138
+ earns a timing bonus.
139
+ - Do NOT request the same field twice β€” it incurs a -0.20 penalty.
140
+ - Do NOT use classify before you have enough evidence.
141
+ - Output ONLY a valid JSON object. No surrounding text.
142
+ """).strip(),
143
+
144
+ "hard": textwrap.dedent("""
145
+ You are an expert job-scam investigator.
146
+ [HARD TASK β€” system prompt placeholder. Replace with hard-task instructions.]
147
+
148
+ Terminal action (must be your last action):
149
+ {"action_type": "classify", "label": "<legit|suspicious|scam|insufficient_info>"}
150
+
151
+ Output ONLY a valid JSON object. No surrounding text.
152
+ """).strip(),
153
+ }
 
154
 
155
  # ---------------------------------------------------------------------------
156
+ # Fallback action priority (per task)
157
  # ---------------------------------------------------------------------------
158
+ _FALLBACK_PRIORITY: Dict[str, List[ActionType]] = {
159
+ "easy": [],
160
+ "medium": [
 
 
 
161
  ActionType.REQUEST_COMPANY_PROFILE,
162
  ActionType.REQUEST_RECRUITER_PROFILE,
163
  ActionType.REQUEST_THREAD_HISTORY,
164
  ActionType.REQUEST_JOB_POST_COMMENTS,
165
+ ],
166
+ "hard": [],
167
+ }
 
 
168
 
169
  # ---------------------------------------------------------------------------
170
  # User message builder
171
  # ---------------------------------------------------------------------------
172
+
173
  def _build_user_message(
174
  step: int,
175
  obs: JobScamObservation,
176
  history: List[str],
177
+ task_name: str,
178
+ max_steps: int,
179
  ) -> str:
 
180
  step_budget = obs.step_budget
181
  if isinstance(step_budget, dict):
182
+ remaining = step_budget.get("remaining", max_steps - step)
183
  else:
184
+ remaining = max_steps - step
185
 
186
  parts: List[str] = [
187
+ f"TASK: {obs.task_name or task_name}",
188
  f"STEP: {step}",
189
  f"STEPS REMAINING: {remaining}",
190
  "",
191
  ]
192
 
 
193
  if obs.query_type:
194
  parts.append(f"QUERY TYPE: {obs.query_type}")
195
  if obs.initial_query:
196
  parts.append(f"INITIAL QUERY:\n{obs.initial_query}")
197
 
198
+ if task_name == "medium":
 
 
 
 
 
199
  if obs.requested_field and obs.field_content:
200
  parts.append(f"\nFIELD JUST RECEIVED β€” {obs.requested_field.upper()}:")
201
  parts.append(obs.field_content)
202
 
 
 
 
 
203
  if history:
204
  parts.append("\nACTIONS TAKEN SO FAR:")
205
  parts.extend(f" {h}" for h in history)
 
217
  # ---------------------------------------------------------------------------
218
  _JSON_RE = re.compile(r"\{.*?\}", re.DOTALL)
219
 
 
 
 
 
220
 
221
+ def _parse_action(response_text: str) -> Optional[JobScamAction]:
 
222
  match = _JSON_RE.search(response_text)
223
  if not match:
224
  return None
 
225
  try:
226
  data = json.loads(match.group(0))
227
  except json.JSONDecodeError:
 
233
 
234
  label_str: Optional[str] = data.get("label")
235
 
236
+ if action_type_str in (ActionType.CLASSIFY, ActionType.CLASSIFY_EASY):
237
  if label_str not in _VALID_LABELS:
238
  return None
239
  return JobScamAction(
 
246
 
247
  return JobScamAction(action_type=ActionType(action_type_str))
248
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
249
 
250
+ def _fallback_action(task_name: str, requested: List[str]) -> JobScamAction:
251
+ for action_type in _FALLBACK_PRIORITY.get(task_name, []):
252
+ field = action_type.value.replace("request_", "")
253
+ if field not in requested:
254
+ return JobScamAction(action_type=action_type)
255
  return JobScamAction(
256
  action_type=ActionType.CLASSIFY,
257
  label=ClassificationLabel.INSUFFICIENT_INFO,
258
  )
259
 
260
+
261
  # ---------------------------------------------------------------------------
262
+ # Single episode runner
263
  # ---------------------------------------------------------------------------
264
+
265
+ async def run_episode(
266
+ env: JobScamEnv,
267
+ llm_client: OpenAI,
268
+ task_id: str,
269
+ task_name: str,
270
+ max_steps: int,
271
+ ) -> tuple[bool, int, float, List[float]]:
272
  """
273
+ Run one episode for the given task variant.
274
+
275
+ Returns (success, steps_taken, total_reward, per_step_rewards).
276
+ Emits [STEP] lines to stdout.
277
  """
278
+ result = await env.reset(task_name=task_name)
 
279
  obs = result.observation
280
 
281
+ history: List[str] = []
282
+ requested_fields: List[str] = []
283
+ per_step_rewards: List[float] = []
284
+ total_reward: float = 0.0
285
+ success: bool = False
286
+ steps_taken: int = 0
287
 
288
+ initial_query_text = obs.initial_query or ""
289
  print(f"\n{'='*60}")
290
+ print(f"NEW EPISODE [task_id={task_id} task_name={task_name}]")
291
  print(f"Query type : {obs.query_type}")
292
  print(f"Initial : {initial_query_text[:120]}...")
293
  print(f"{'='*60}")
294
 
295
+ system_prompt = _SYSTEM_PROMPTS[task_name]
296
+
297
+ for step in range(1, max_steps + 1):
298
+ steps_taken = step
299
+ step_error: Optional[str] = None
300
+
301
+ # ── Build LLM messages ──────────────────────────────────────────────
302
+ user_msg = _build_user_message(step, obs, history, task_name, max_steps)
303
  messages: List[Dict[str, Any]] = [
304
+ {"role": "system", "content": system_prompt},
305
  {"role": "user", "content": user_msg},
306
  ]
307
 
308
+ # ── Call LLM ───────────────────────────────────────────────────────
309
+ response_text = ""
310
  try:
311
  completion = llm_client.chat.completions.create(
312
  model=MODEL_NAME,
 
317
  )
318
  response_text = completion.choices[0].message.content or ""
319
  except Exception as exc:
320
+ step_error = str(exc)
321
  print(f" [Step {step}] LLM error: {exc}. Using fallback.")
 
322
 
323
+ # ── Parse action ────────────────────────────────────────────────────
324
  action = _parse_action(response_text)
325
  if action is None:
326
  print(
327
  f" [Step {step}] Unparseable response: "
328
  f"{response_text!r:.80}. Using fallback."
329
  )
330
+ action = _fallback_action(task_name, requested_fields)
331
 
332
+ action_str = action.action_type.value
333
+ if action.label:
334
+ action_str += f":{action.label.value}"
 
335
 
336
+ # ── Step environment ────────────────────────────────────────────────
337
  result = await env.step(action)
338
  obs = result.observation
339
  reward = result.reward or 0.0
340
  total_reward += reward
341
+ per_step_rewards.append(reward)
342
+ normalised_reward = 0
343
 
344
+ is_done = bool(result.done)
345
+
346
+ # ── Emit structured [STEP] log ──────────────────────────────────────
347
+ log_step(step=step, action=action_str, reward=reward, done=is_done, error=step_error)
348
+
349
+ # ── Track history for info-request actions ──────────────────────────
350
+ is_classify = action.action_type in (ActionType.CLASSIFY, ActionType.CLASSIFY_EASY)
351
+ if not is_classify:
352
+ if task_name == "easy":
353
  # TODO: derive field name for easy-task actions when designed
354
+ # field_name = action.action_type.value.replace("request_", "")
355
+ pass
356
+ elif task_name == "medium":
357
  field_name = action.action_type.value.replace("request_", "")
358
  requested_fields.append(field_name)
359
  history.append(
 
366
  print(f" Breakdown : {info['reward_breakdown']}")
367
  if info.get("cumulative"):
368
  print(f" Cumulative : {info['cumulative']}")
369
+ elif task_name == "hard":
370
  # TODO: derive field name for hard-task actions when designed
371
+ # field_name = action.action_type.value.replace("request_", "")
372
+ pass
373
+
374
+ # ── Handle done ─────────────────────────────────────────────────────
375
+ if is_done:
376
+ if task_name == "easy":
377
+ normalised_reward = reward
378
+ correct = obs.predicted_label == obs.actual_label
379
+ success = bool(correct)
380
+ print(f"\n CLASSIFICATION RESULT")
381
+ print(f" Step reward : {reward:+.4f}")
382
+ print(f" Predicted : {obs.predicted_label}")
383
+ print(f" Actual : {obs.actual_label}")
384
+ print(f" Correct : {correct}\n")
385
  break
386
+ elif task_name == "medium":
387
+ normalised_reward = reward
388
  info = obs.info or {}
389
  if obs.reason == "timeout":
390
+ success = False
391
  print(f"\n TIMEOUT β€” all steps exhausted without classifying.")
392
+ print(f" Timeout penalty: {info['reward_breakdown']['timeout_penalty']:+.4f}")
393
+ print(f" Step Reward : {reward:+.4f}")
394
+ print(f" Correct : False")
395
  else:
396
+ correct = obs.predicted_label == obs.actual_label
397
+ success = bool(correct)
398
  print(f"\n CLASSIFICATION RESULT")
399
  print(f" Step reward : {reward:+.4f}")
400
+ print(f" Predicted : {obs.predicted_label}")
401
+ print(f" Actual : {obs.actual_label}")
402
+ print(f" Correct : {correct}")
 
403
  if info.get("reward_breakdown"):
404
+ print(f" Breakdown : {info['reward_breakdown']}")
405
  if info.get("cumulative"):
406
+ print(f" Cumulative : {info['cumulative']}")
407
  break
408
+ elif task_name == "hard":
409
+ normalised_reward = 0
410
  break
411
 
 
 
412
 
413
+ print(f"\nEpisode finished β€” task={task_id}")
414
+ return success, steps_taken, normalised_reward, per_step_rewards
415
+
416
+
417
+ # ---------------------------------------------------------------------------
418
+ # Main β€” iterate over ALL tasks in a single invocation
419
+ # ---------------------------------------------------------------------------
420
 
421
  async def main() -> None:
 
 
 
422
  if not API_KEY:
423
  raise EnvironmentError("HF_TOKEN or API_KEY environment variable must be set.")
424
  if not MODEL_NAME:
425
  raise EnvironmentError("MODEL_NAME environment variable must be set.")
 
 
 
 
426
 
427
  llm_client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
428
 
429
+ env = await JobScamEnv.from_docker_image(LOCAL_IMAGE_NAME)
430
 
431
  async with env:
432
+ for task_id, task_name, max_steps in TASKS:
433
+ # Emit [START] before the episode
434
+ log_start(task=task_id, env=BENCHMARK, model=MODEL_NAME)
435
+
436
+ success = False
437
+ steps_taken = 0
438
+ # total_reward = 0.0
439
+ # rewards_list: List[float] = []
440
+ try:
441
+ success, steps_taken, normalised_reward, rewards_list = await run_episode(
442
+ env=env,
443
+ llm_client=llm_client,
444
+ task_id=task_id,
445
+ task_name=task_name,
446
+ max_steps=max_steps,
447
+ )
448
+ except Exception as exc:
449
+ # Log the crash but always emit [END]
450
+ print(f" [FATAL] task={task_id} crashed: {exc}", flush=True)
451
+ # if not rewards_list:
452
+ # rewards_list = [0.0]
453
+ finally:
454
+ log_end(
455
+ task=task_id,
456
+ success=success,
457
+ steps=steps_taken,
458
+ score=normalize_one(normalised_reward),
459
+ # rewards=rewards_list if rewards_list else [0.0],
460
+ )
461
+ print("\n\n")
462
 
463
 
464
  if __name__ == "__main__":
inference_copy.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Inference Script β€” Job Scam Detection Environment
3
+ ==================================================
4
+
5
+ An LLM-driven agent that plays one episode of the JobScamEnvironment by
6
+ investigating a job opportunity and submitting a classification label.
7
+
8
+ Task selection
9
+ --------------
10
+ Set the ``TASK_NAME`` variable below to choose which difficulty variant runs.
11
+ Allowed values: "easy" | "medium" | "hard". Defaults to "medium".
12
+
13
+ Required environment variables
14
+ -------------------------------
15
+ API_BASE_URL API endpoint for the LLM (e.g. https://router.huggingface.co/v1).
16
+ MODEL_NAME Model identifier (e.g. Qwen/Qwen2.5-72B-Instruct).
17
+ HF_TOKEN Hugging Face / API key.
18
+
19
+ The script uses the OpenAI-compatible client for all LLM calls, as required
20
+ by the submission spec.
21
+
22
+ Agent strategy (medium task)
23
+ -----------------------------
24
+ 1. Parse the initial observation (query type + raw query text).
25
+ 2. Use the LLM to decide which context field to request next, or to
26
+ classify if enough evidence has been gathered.
27
+ 3. Parse the LLM response as a JSON action object.
28
+ 4. Step the environment, print the reward breakdown.
29
+ 5. Repeat until ``done=True``.
30
+
31
+ Action JSON format expected from the LLM
32
+ -----------------------------------------
33
+ Info request (medium)::
34
+
35
+ {"action_type": "request_company_profile"}
36
+
37
+ Classification (all tasks)::
38
+
39
+ {"action_type": "classify", "label": "scam"}
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import asyncio
45
+ import json
46
+ import random
47
+ import os
48
+ import re
49
+ import textwrap
50
+ from typing import Any, Dict, List, Optional
51
+
52
+ from openai import OpenAI
53
+ from dotenv import load_dotenv
54
+ from client import JobScamEnv
55
+ from models import ActionType, ClassificationLabel, JobScamAction, JobScamObservation
56
+ from constants import VALID_TASK_NAMES
57
+
58
+ # ---------------------------------------------------------------------------
59
+ # Task selection β€” change this variable to switch between task variants
60
+ # ---------------------------------------------------------------------------
61
+
62
+ # Options: "easy" | "medium" | "hard"
63
+ tasks = ["easy", "medium", "hard"]
64
+ TASK_NAME: str = random.choice(tasks)
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Configuration
68
+ # ---------------------------------------------------------------------------
69
+ load_dotenv()
70
+ API_BASE_URL: str = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
71
+ API_KEY: Optional[str] = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
72
+ MODEL_NAME: Optional[str] = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
73
+ LOCAL_IMAGE_NAME: Optional[str] = os.getenv("LOCAL_IMAGE_NAME", "job_scam_env:latest")
74
+
75
+ TEMPERATURE: float = 0.2
76
+ MAX_TOKENS: int = 300
77
+
78
+ _VALID_ACTION_TYPES = [a.value for a in ActionType]
79
+ _VALID_LABELS = [l.value for l in ClassificationLabel]
80
+
81
+ # ---------------------------------------------------------------------------
82
+ # Task-specific: max steps
83
+ # ---------------------------------------------------------------------------
84
+
85
+ if TASK_NAME == "easy":
86
+ # TODO: set easy-task max steps when task is designed
87
+ # from constants import EASY_MAX_STEPS
88
+ from constants import EASY_MAX_STEPS
89
+ MAX_STEPS: int = EASY_MAX_STEPS
90
+ elif TASK_NAME == "medium":
91
+ from constants import MEDIUM_MAX_STEPS
92
+ MAX_STEPS: int = MEDIUM_MAX_STEPS
93
+ elif TASK_NAME == "hard":
94
+ # TODO: set hard-task max steps when task is designed
95
+ # from constants import HARD_MAX_STEPS
96
+ # MAX_STEPS: int = HARD_MAX_STEPS
97
+ MAX_STEPS: int = 8 # placeholder
98
+ else:
99
+ raise ValueError(
100
+ f"Unknown TASK_NAME '{TASK_NAME}'. Must be one of: {VALID_TASK_NAMES}."
101
+ )
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # Task-specific: system prompt
105
+ # ---------------------------------------------------------------------------
106
+ if TASK_NAME == "easy":
107
+ # TODO: write an easy-task-specific system prompt when task is designed.
108
+ # For now, a placeholder is used.
109
+ _SYSTEM_PROMPT = textwrap.dedent("""
110
+ You are an expert job scam detector.
111
+
112
+ For this easy task,
113
+ read the message and classify it as either:
114
+ legit |scam
115
+
116
+ Output exactly one JSON object and nothing else.
117
+
118
+ Format:
119
+ {"action_type": "classify", "label": "<legit|scam>"}
120
+ """).strip()
121
+ elif TASK_NAME == "medium":
122
+ _SYSTEM_PROMPT = textwrap.dedent("""
123
+ You are an expert job-scam investigator.
124
+ Your task is to analyse a job opportunity and classify it as one of:
125
+ legit | suspicious | scam | insufficient_info
126
+
127
+ You have up to 5 steps per episode. Each step you must output exactly one
128
+ JSON object β€” nothing else, no markdown, no explanation.
129
+
130
+ AVAILABLE ACTIONS
131
+ -----------------
132
+ Information requests (use these to gather evidence before classifying):
133
+ {"action_type": "request_recruiter_profile"}
134
+ {"action_type": "request_company_profile"}
135
+ {"action_type": "request_thread_history"}
136
+ {"action_type": "request_job_post_comments"}
137
+
138
+ Terminal action (must be your last action):
139
+ {"action_type": "classify", "label": "<legit|suspicious|scam|insufficient_info>"}
140
+
141
+ STRATEGY GUIDELINES
142
+ -------------------
143
+ - Look for red flags: payment requests, off-platform contact (WhatsApp/Telegram),
144
+ government ID requests, urgency pressure, evasion tactics, gmail sender for MNC.
145
+ - Look for green flags: official domain, no-fee statements, portal-only hiring,
146
+ anti-scam guidance.
147
+ - Classify as soon as you have enough evidence β€” earlier correct classification
148
+ earns a timing bonus.
149
+ - Do NOT request the same field twice β€” it incurs a -0.20 penalty.
150
+ - Do NOT use classify before you have enough evidence.
151
+ - Output ONLY a valid JSON object. No surrounding text.
152
+ """).strip()
153
+ elif TASK_NAME == "hard":
154
+ # TODO: write a hard-task-specific system prompt when task is designed.
155
+ # For now, a placeholder is used.
156
+ _SYSTEM_PROMPT = textwrap.dedent("""
157
+ You are an expert job-scam investigator.
158
+ [HARD TASK β€” system prompt placeholder. Replace with hard-task instructions.]
159
+
160
+ Terminal action (must be your last action):
161
+ {"action_type": "classify", "label": "<legit|suspicious|scam|insufficient_info>"}
162
+
163
+ Output ONLY a valid JSON object. No surrounding text.
164
+ """).strip()
165
+
166
+ # ---------------------------------------------------------------------------
167
+ # Task-specific: fallback action priority
168
+ # ---------------------------------------------------------------------------
169
+ if TASK_NAME == "easy":
170
+ # TODO: define the easy-task fallback priority order when task is designed.
171
+ # For now, only classify is available as fallback.
172
+ _FALLBACK_PRIORITY: List[ActionType] = []
173
+ elif TASK_NAME == "medium":
174
+ _FALLBACK_PRIORITY: List[ActionType] = [
175
+ ActionType.REQUEST_COMPANY_PROFILE,
176
+ ActionType.REQUEST_RECRUITER_PROFILE,
177
+ ActionType.REQUEST_THREAD_HISTORY,
178
+ ActionType.REQUEST_JOB_POST_COMMENTS,
179
+ ]
180
+ elif TASK_NAME == "hard":
181
+ # TODO: define the hard-task fallback priority order when task is designed.
182
+ _FALLBACK_PRIORITY: List[ActionType] = []
183
+
184
+
185
+ # ---------------------------------------------------------------------------
186
+ # User message builder
187
+ # ---------------------------------------------------------------------------
188
+ def _build_user_message(
189
+ step: int,
190
+ obs: JobScamObservation,
191
+ history: List[str],
192
+ ) -> str:
193
+ """Construct the user-turn message for the LLM at each step."""
194
+ step_budget = obs.step_budget
195
+ if isinstance(step_budget, dict):
196
+ remaining = step_budget.get("remaining", MAX_STEPS - step)
197
+ else:
198
+ remaining = MAX_STEPS - step
199
+
200
+ parts: List[str] = [
201
+ f"TASK: {obs.task_name or TASK_NAME}",
202
+ f"STEP: {step}",
203
+ f"STEPS REMAINING: {remaining}",
204
+ "",
205
+ ]
206
+
207
+ # ── Initial query (always present) ──────────────────────────────────────
208
+ if obs.query_type:
209
+ parts.append(f"QUERY TYPE: {obs.query_type}")
210
+ if obs.initial_query:
211
+ parts.append(f"INITIAL QUERY:\n{obs.initial_query}")
212
+
213
+ # ── Task-specific field content display ──────────────────────────────────
214
+ if TASK_NAME == "easy":
215
+ # TODO: add easy-task-specific field display here when task is designed
216
+ pass
217
+
218
+ elif TASK_NAME == "medium":
219
+ if obs.requested_field and obs.field_content:
220
+ parts.append(f"\nFIELD JUST RECEIVED β€” {obs.requested_field.upper()}:")
221
+ parts.append(obs.field_content)
222
+
223
+ elif TASK_NAME == "hard":
224
+ # TODO: add hard-task-specific field display here when task is designed
225
+ pass
226
+
227
+ if history:
228
+ parts.append("\nACTIONS TAKEN SO FAR:")
229
+ parts.extend(f" {h}" for h in history)
230
+
231
+ parts.append(
232
+ "\nOutput exactly one JSON action object. "
233
+ "Classify only when you have sufficient evidence."
234
+ )
235
+
236
+ return "\n".join(parts)
237
+
238
+
239
+ # ---------------------------------------------------------------------------
240
+ # Action parsing
241
+ # ---------------------------------------------------------------------------
242
+ _JSON_RE = re.compile(r"\{.*?\}", re.DOTALL)
243
+
244
+ def _parse_action(response_text: str) -> Optional[JobScamAction]:
245
+ """
246
+ Extract the first JSON object from the LLM response and validate it
247
+ as a ``JobScamAction``.
248
+
249
+ Returns ``None`` if parsing fails (caller will apply a fallback).
250
+ """
251
+ match = _JSON_RE.search(response_text)
252
+ if not match:
253
+ return None
254
+
255
+ try:
256
+ data = json.loads(match.group(0))
257
+ except json.JSONDecodeError:
258
+ return None
259
+
260
+ action_type_str: str = data.get("action_type", "")
261
+ if action_type_str not in _VALID_ACTION_TYPES:
262
+ return None
263
+
264
+ label_str: Optional[str] = data.get("label")
265
+
266
+ if action_type_str == ActionType.CLASSIFY or action_type_str == ActionType.CLASSIFY_EASY:
267
+ if label_str not in _VALID_LABELS:
268
+ return None
269
+ return JobScamAction(
270
+ action_type=ActionType(action_type_str),
271
+ label=ClassificationLabel(label_str),
272
+ )
273
+
274
+ if label_str is not None:
275
+ return None # label must not be present for non-classify actions
276
+
277
+ return JobScamAction(action_type=ActionType(action_type_str))
278
+
279
+ def _fallback_action(step: int, requested: List[str]) -> JobScamAction:
280
+ """
281
+ Heuristic fallback when the LLM produces an unparseable response.
282
+
283
+ Requests the next unrequested field in the task-specific priority order,
284
+ or defaults to ``insufficient_info`` if all fields have been requested.
285
+ """
286
+ if TASK_NAME == "easy":
287
+ # TODO: implement easy-task fallback logic when task is designed
288
+ pass
289
+
290
+ elif TASK_NAME == "medium":
291
+ for action_type in _FALLBACK_PRIORITY:
292
+ field = action_type.value.replace("request_", "")
293
+ if field not in requested:
294
+ return JobScamAction(action_type=action_type)
295
+
296
+ elif TASK_NAME == "hard":
297
+ # TODO: implement hard-task fallback logic when task is designed
298
+ pass
299
+
300
+ # All fields seen or last step β€” safe default
301
+ return JobScamAction(
302
+ action_type=ActionType.CLASSIFY,
303
+ label=ClassificationLabel.INSUFFICIENT_INFO,
304
+ )
305
+
306
+ # ---------------------------------------------------------------------------
307
+ # Main episode loop
308
+ # ---------------------------------------------------------------------------
309
+ async def run_episode(env: JobScamEnv, llm_client: OpenAI) -> float:
310
+ """
311
+ Run a single episode to completion and return the total reward.
312
+ ``env`` is the live async client, already connected via ``async with``.
313
+ """
314
+ # Reset with the chosen task variant
315
+ result = await env.reset(task_name=TASK_NAME)
316
+ obs = result.observation
317
+
318
+ history: List[str] = []
319
+ requested_fields: List[str] = []
320
+ total_reward: float = 0.0
321
+ initial_query_text = obs.initial_query or ""
322
+
323
+ print(f"\n{'='*60}")
324
+ print(f"NEW EPISODE [task: {TASK_NAME}]")
325
+ print(f"Query type : {obs.query_type}")
326
+ print(f"Initial : {initial_query_text[:120]}...")
327
+ print(f"{'='*60}")
328
+
329
+ for step in range(1, MAX_STEPS + 1):
330
+ # ── Build LLM messages ────────────────────────────────────────────────
331
+ user_msg = _build_user_message(step, obs, history)
332
+ messages: List[Dict[str, Any]] = [
333
+ {"role": "system", "content": _SYSTEM_PROMPT},
334
+ {"role": "user", "content": user_msg},
335
+ ]
336
+
337
+ # ── Call LLM ─────────────────────────────────────────────────────────
338
+ try:
339
+ completion = llm_client.chat.completions.create(
340
+ model=MODEL_NAME,
341
+ messages=messages,
342
+ temperature=TEMPERATURE,
343
+ max_tokens=MAX_TOKENS,
344
+ stream=False,
345
+ )
346
+ response_text = completion.choices[0].message.content or ""
347
+ except Exception as exc:
348
+ print(f" [Step {step}] LLM error: {exc}. Using fallback.")
349
+ response_text = ""
350
+
351
+ # ── Parse action ──────────────────────────────────────────────────────
352
+ action = _parse_action(response_text)
353
+ if action is None:
354
+ print(
355
+ f" [Step {step}] Unparseable response: "
356
+ f"{response_text!r:.80}. Using fallback."
357
+ )
358
+ action = _fallback_action(step, requested_fields)
359
+
360
+ print(
361
+ f"\n[Step {step}] Action: {action.action_type.value}"
362
+ + (f" label={action.label.value}" if action.label else "")
363
+ )
364
+
365
+ # ── Step environment ──────────────────────────────────────────────────
366
+ result = await env.step(action)
367
+ obs = result.observation
368
+ reward = result.reward or 0.0
369
+ total_reward += reward
370
+
371
+ # ── Record history (task-specific field naming) ───────────────────────
372
+ if action.action_type != ActionType.CLASSIFY and action.action_type != ActionType.CLASSIFY_EASY:
373
+ if TASK_NAME == "easy":
374
+ # TODO: derive field name for easy-task actions when designed
375
+ # field_name = action.action_type.value.replace("request_", "")
376
+ pass
377
+ elif TASK_NAME == "medium":
378
+ field_name = action.action_type.value.replace("request_", "")
379
+ requested_fields.append(field_name)
380
+ history.append(
381
+ f"Step {step}: {action.action_type.value} β†’ reward {reward:+.4f}"
382
+ )
383
+
384
+ info = obs.info or {}
385
+ print(f" Step Reward : {reward:+.4f}")
386
+ if info.get("reward_breakdown"):
387
+ print(f" Breakdown : {info['reward_breakdown']}")
388
+ if info.get("cumulative"):
389
+ print(f" Cumulative : {info['cumulative']}")
390
+ elif TASK_NAME == "hard":
391
+ # TODO: derive field name for hard-task actions when designed
392
+ field_name = action.action_type.value.replace("request_", "")
393
+
394
+
395
+ # ── Handle done ───────────────────────────────────────────────────────
396
+ success = False
397
+ if result.done:
398
+ if TASK_NAME == "easy":
399
+ info = obs.info or {}
400
+ print(f"\n CLASSIFICATION RESULT")
401
+ print(f" Step reward : {reward:+.4f}")
402
+ print(f" Predicted : {obs.predicted_label}")
403
+ print(f" Actual : {obs.actual_label}")
404
+ correct = obs.predicted_label == obs.actual_label
405
+ success = correct
406
+ print(f" Correct : {correct}\n")
407
+
408
+
409
+ elif TASK_NAME == "medium":
410
+ info = obs.info or {}
411
+ if obs.reason == "timeout":
412
+ print(f"\n TIMEOUT β€” all steps exhausted without classifying.")
413
+ print(f" Timeout penalty: {info['reward_breakdown']['timeout_penalty']:+.4f}")
414
+ print(f" Step Reward : {reward:+.4f}")
415
+ else:
416
+ print(f"\n CLASSIFICATION RESULT")
417
+ print(f" Step reward : {reward:+.4f}")
418
+ print(f" Predicted : {obs.predicted_label}")
419
+ print(f" Actual : {obs.actual_label}")
420
+ correct = obs.predicted_label == obs.actual_label
421
+ success = correct
422
+ print(f" Correct : {correct}\n")
423
+ if info.get("reward_breakdown"):
424
+ print(f" Breakdown : {info['reward_breakdown']}")
425
+ if info.get("cumulative"):
426
+ print(f" Episode total : {info['cumulative']}")
427
+ break
428
+ elif TASK_NAME == "hard":
429
+ break
430
+
431
+ print(f"\nEpisode finished!!")
432
+ return total_reward
433
+
434
+
435
+ async def main() -> None:
436
+ """
437
+ Entry point: spin up the Docker container, run one episode, then tear down.
438
+ """
439
+ if not API_KEY:
440
+ raise EnvironmentError("HF_TOKEN or API_KEY environment variable must be set.")
441
+ if not MODEL_NAME:
442
+ raise EnvironmentError("MODEL_NAME environment variable must be set.")
443
+ if TASK_NAME not in VALID_TASK_NAMES:
444
+ raise ValueError(
445
+ f"Invalid TASK_NAME '{TASK_NAME}'. Must be one of: {VALID_TASK_NAMES}."
446
+ )
447
+
448
+ llm_client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
449
+
450
+ env = await JobScamEnv.from_docker_image(LOCAL_IMAGE_NAME)
451
+
452
+ async with env:
453
+ await run_episode(env, llm_client)
454
+
455
+
456
+ if __name__ == "__main__":
457
+ asyncio.run(main())
models.py CHANGED
@@ -52,6 +52,7 @@ class ActionType(str, Enum):
52
  # ── EASY TASK ────────────
53
  # TODO: uncomment / add when easy task is designed
54
  # REQUEST_EASY_FIELD_A = "request_easy_field_a"
 
55
 
56
  # ── HARD TASK ────────────
57
  # TODO: uncomment / add when hard task is designed
@@ -75,6 +76,8 @@ class ClassificationLabel(str, Enum):
75
 
76
  # ── EASY TASK labels (placeholders) ─────────────────────────────────────
77
  # TODO: add easy-specific labels here if needed
 
 
78
 
79
  # ── HARD TASK labels (placeholders) ─────────────────────────────────────
80
  # TODO: add hard-specific labels here if needed
 
52
  # ── EASY TASK ────────────
53
  # TODO: uncomment / add when easy task is designed
54
  # REQUEST_EASY_FIELD_A = "request_easy_field_a"
55
+ CLASSIFY_EASY = "classify"
56
 
57
  # ── HARD TASK ────────────
58
  # TODO: uncomment / add when hard task is designed
 
76
 
77
  # ── EASY TASK labels (placeholders) ─────────────────────────────────────
78
  # TODO: add easy-specific labels here if needed
79
+ SCAM_EASY = "scam" # example only β€” replace with actual easy-task labels when designed
80
+ LEGIT_EASY = "legit" # example only β€” replace with actual easy-task labels when designed
81
 
82
  # ── HARD TASK labels (placeholders) ─────────────────────────────────────
83
  # TODO: add hard-specific labels here if needed
openenv.yaml CHANGED
@@ -5,3 +5,24 @@ runtime: fastapi
5
  app: server.app:app
6
  port: 8000
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  app: server.app:app
6
  port: 8000
7
 
8
+ tasks:
9
+ - id: task_easy
10
+ difficulty: easy
11
+ grader:
12
+ type: deterministic
13
+ description: >
14
+ A task for easy job scam detection with 1 step message classification.
15
+
16
+ - id: task_medium
17
+ difficulty: medium
18
+ grader:
19
+ type: deterministic
20
+ description: >
21
+ A task for medium job scam detection with upto 5 steps message classification.
22
+
23
+ - id: task_hard
24
+ difficulty: hard
25
+ grader:
26
+ type: deterministic
27
+ description: >
28
+ A task for hard job scam detection with upto 8 steps message classification.
server/data_task_easy.jsonl ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"sample_id":"easy_001","query_type":"email","initial_query":"Dear Akshay, we are excited to announce that you have been selected for Software Engineering Intern at Microsoft. Please fill the application form to complete your onboarding. Regards, Namrita, HR Recruiter","ground_truth":"legit"}
2
+ {"sample_id":"easy_002","query_type":"whatsapp","initial_query":"Hello Colin, We have a great opportunity at Lite Media for the position of Digital Marketing Manager. Please click the link below to apply and pay a one-time processing fee of 500 rupees: http://litmedia/2334/ip6kj","ground_truth":"scam"}
3
+ {"sample_id":"easy_003","query_type":"telegram","initial_query":"Hi, I'm Hannah from HR Recruitment at Digi-Soln Tech. The job is to subscribe to YouTube channels and send screenshots. Earn β‚Ή100 per task and up to β‚Ή15000-20000 monthly.","ground_truth":"scam"}
4
+ {"sample_id":"easy_004","query_type":"email","initial_query":"Dear Akshay, Thank you for applying to the Software Engineering Intern role. We would like to invite you for the next round. Please log in to your candidate portal to select an interview slot.","ground_truth":"legit"}
5
+ {"sample_id":"easy_005","query_type":"whatsapp","initial_query":"Hi Rohan, this is Priya from TechNova HR. We received your application for the Data Analyst role. Are you available for a screening call tomorrow?","ground_truth":"legit"}
6
+ {"sample_id":"easy_006","query_type":"telegram","initial_query":"Hello, this is the official hiring channel for Digi-Soln Tech. Please apply through our website www.digisoln.in/careers.","ground_truth":"legit"}
7
+ {"sample_id":"easy_007","query_type":"whatsapp","initial_query":"Hello Ankit, we came across your profile on LinkedIn and thought you might be a good fit for a Backend Developer role. Please apply through our official website.","ground_truth":"legit"}
8
+ {"sample_id":"easy_008","query_type":"email","initial_query":"Hi Neha, thanks for completing your assessment. We will get back to you within 5-7 business days.","ground_truth":"legit"}
9
+ {"sample_id":"easy_009","query_type":"email","initial_query":"Dear Rahul, Congratulations! You have been selected for the HR Intern role. Please pay a refundable onboarding fee of β‚Ή750 today to confirm your position.","ground_truth":"scam"}
10
+ {"sample_id":"easy_010","query_type":"whatsapp","initial_query":"Hello Aman, we are offering a remote data entry job with a salary of β‚Ή40,000 per week. No experience needed. Message us on WhatsApp to start immediately.","ground_truth":"scam"}
11
+ {"sample_id":"easy_011","query_type":"sms","initial_query":"Hi, this is from QuickHire Solutions. To verify your application, please share the OTP sent to your phone.","ground_truth":"scam"}
12
+ {"sample_id":"easy_012","query_type":"email","initial_query":"Dear Candidate, you must complete a mandatory training program. Training fee is β‚Ή2000, after which job placement is guaranteed.","ground_truth":"scam"}
13
+ {"sample_id":"easy_013","query_type":"telegram","initial_query":"Earn β‚Ή5000 daily by liking Instagram posts. No skills required. Pay β‚Ή299 to register.","ground_truth":"scam"}
14
+ {"sample_id":"easy_014","query_type":"email","initial_query":"Dear Applicant, your profile has been selected for a government job. Pay β‚Ή1500 processing fee to secure your position.","ground_truth":"scam"}
15
+ {"sample_id":"easy_015","query_type":"whatsapp","initial_query":"Please send your resume along with Aadhaar card and bank details to proceed with hiring.","ground_truth":"scam"}
16
+ {"sample_id":"easy_016","query_type":"telegram","initial_query":"Urgent hiring today. Salary β‚Ή25,000 per week. Pay β‚Ή500 to reserve your slot immediately.","ground_truth":"scam"}
17
+ {"sample_id":"easy_017","query_type":"email","initial_query":"Earn β‚Ή20,000 weekly from home. Pay β‚Ή999 for registration kit and start today.","ground_truth":"scam"}
18
+ {"sample_id":"easy_018","query_type":"whatsapp","initial_query":"You have been referred for a job. Please pay β‚Ή600 referral fee to activate your application.","ground_truth":"scam"}
19
+ {"sample_id":"easy_019","query_type":"whatsapp","initial_query":"You have been referred for a role at JPMConst. Please register via our official portal and share your registration ID.","ground_truth":"legit"}
20
+ {"sample_id":"easy_020","query_type":"telegram","initial_query":"Work from home and earn up to β‚Ή50K per month. No degree, no interview. Limited seats available.","ground_truth":"scam"}
21
+ {"sample_id":"easy_021","query_type":"email","initial_query":"Good evening Rakesh, you have cleared the screening round. Please share your availability for the next interview round.","ground_truth":"legit"}
22
+ {"sample_id":"easy_022","query_type":"email","initial_query":"Meta in collaboration with Scaler is conducting a hackathon. Top teams may get interview opportunities. Visit the official page for details.","ground_truth":"legit"}
23
+ {"sample_id":"easy_023","query_type":"job_board","initial_query":"Our company is hiring for a Data Engineer role (0-2 years experience). Please apply through our official careers page.","ground_truth":"legit"}
24
+ {"sample_id":"easy_024","query_type":"whatsapp","initial_query":"Hi Arjun, are you open to Backend roles? Let me know if you'd like more details.","ground_truth":"legit"}
25
+ {"sample_id":"easy_025","query_type":"email","initial_query":"Reminder: Your interview is scheduled tomorrow at 11 AM. Please join using the link shared earlier.","ground_truth":"legit"}
26
+ {"sample_id":"easy_026","query_type":"job_board","initial_query":"We are hiring a Frontend Developer with 1–3 years experience. Apply via our careers page.","ground_truth":"legit"}
27
+ {"sample_id":"easy_027","query_type":"whatsapp","initial_query":"Hi, we got your resume from LinkedIn. Role is QA Engineer. Send updated CV if interested.","ground_truth":"legit"}
28
+ {"sample_id":"easy_028","query_type":"email","initial_query":"Please complete the online assessment within 3 days. The link has been sent to your email.","ground_truth":"legit"}
29
+ {"sample_id":"easy_029","query_type":"telegram","initial_query":"Earn guaranteed crypto profits daily. Join by paying β‚Ή1500 training fee.","ground_truth":"scam"}
30
+ {"sample_id":"easy_030","query_type":"whatsapp","initial_query":"Your interview is confirmed. Pay β‚Ή300 security deposit to receive the interview link.","ground_truth":"scam"}
31
+ {"sample_id":"easy_031","query_type":"email","initial_query":"Share PAN card, Aadhaar, and bank details to proceed with your job application.","ground_truth":"scam"}
32
+ {"sample_id":"easy_032","query_type":"telegram","initial_query":"Get internship certificates from top companies without working. Pay β‚Ή499 now.","ground_truth":"scam"}
server/data_task_hard.jsonl ADDED
@@ -0,0 +1 @@
 
 
1
+ {"ground_truth": "scam", "query_type": "email", "initial_query": "placeholder", "fields": {}}
server/job_scam_env_environment.py CHANGED
@@ -61,7 +61,8 @@ try:
61
  from ..constants import (
62
  VALID_TASK_NAMES,
63
  # Easy
64
- EASY_DATASET_FILENAME, EASY_ACTION_TO_FIELD,
 
65
  # Medium
66
  MEDIUM_REWARD_MATRIX, MEDIUM_ACTION_TO_FIELD, MEDIUM_ALL_CONTEXT_FIELDS,
67
  MEDIUM_MAX_STEPS, MEDIUM_TIMEOUT_PENALTY, MEDIUM_DATASET_FILENAME,
@@ -159,16 +160,13 @@ class JobScamEnvironment(Environment):
159
  self._task_name: str = "medium"
160
 
161
  # ── Datasets β€” loaded once per process ──────────────────────────────
162
- # Medium dataset is always loaded (it ships with the package).
163
  self._MEDIUM_DATASET: List[Dict[str, Any]] = _load_dataset(MEDIUM_DATASET_FILENAME)
164
-
165
- # Easy / hard datasets are loaded lazily on first use so the server
166
- # starts even when those JSONL files are not yet present.
167
- self._EASY_DATASET: Optional[List[Dict[str, Any]]] = None
168
- self._HARD_DATASET: Optional[List[Dict[str, Any]]] = None
169
 
170
  # ---------------------------------------------------------------- reset
171
- def reset(self, task_name: str = "medium") -> JobScamObservation:
 
172
  """
173
  Start a new episode with a randomly selected dataset sample.
174
 
@@ -178,6 +176,11 @@ class JobScamEnvironment(Environment):
178
  Which task variant to run. Must be one of: easy, medium, hard.
179
  Defaults to "medium" for backward compatibility.
180
  """
 
 
 
 
 
181
  if task_name not in VALID_TASK_NAMES:
182
  raise ValueError(
183
  f"Unknown task_name '{task_name}'. "
@@ -215,8 +218,8 @@ class JobScamEnvironment(Environment):
215
 
216
  # ── Dispatch to task-specific step logic ─────────────────────────────
217
  if self._task_name == "easy":
218
- ## Implement your own logic ##
219
- pass
220
 
221
  elif self._task_name == "medium":
222
  if action.action_type == ActionType.CLASSIFY:
@@ -246,7 +249,7 @@ class JobScamEnvironment(Environment):
246
  Raise ValueError if the action_type does not belong to the active task
247
  (and is not the universal CLASSIFY action).
248
  """
249
- if action.action_type == ActionType.CLASSIFY:
250
  return # always valid
251
 
252
  if self._task_name == "easy":
@@ -269,54 +272,89 @@ class JobScamEnvironment(Environment):
269
  # EASY TASK implementation
270
  # =========================================================================
271
  def _easy_reset(self) -> JobScamObservation:
272
- """
273
- Reset the environment for an easy-task episode.
274
 
275
- TODO: Implement when the easy task design is finalised.
276
- Replace the NotImplementedError with the actual logic,
277
- following the same pattern as _medium_reset().
278
- """
279
- # Lazy-load the easy dataset on first use
280
- if self._EASY_DATASET is None:
281
- self._EASY_DATASET = _load_dataset(EASY_DATASET_FILENAME)
282
 
283
- # TODO: implement easy reset logic here
284
- raise NotImplementedError(
285
- "Easy task is not yet implemented. "
286
- "Add the reset logic in _easy_reset() and update constants.py."
 
 
 
 
 
 
 
 
 
287
  )
288
 
289
- def _easy_handle_field_request(self, action: JobScamAction) -> JobScamObservation:
290
- """
291
- Handle an information-gathering action for the easy task.
292
 
293
- TODO: Implement when the easy task design is finalised.
294
- """
295
- raise NotImplementedError("Easy task field request not yet implemented.")
296
 
297
- def _easy_handle_classify(self, action: JobScamAction) -> JobScamObservation:
298
- """
299
- Handle the terminal classify action for the easy task.
300
 
301
- TODO: Implement when the easy task design is finalised.
302
- """
303
- raise NotImplementedError("Easy task classify not yet implemented.")
304
 
305
- def _easy_handle_timeout(self) -> JobScamObservation:
306
- """
307
- Handle step-budget exhaustion for the easy task.
308
 
309
- TODO: Implement when the easy task design is finalised.
310
- """
311
- raise NotImplementedError("Easy task timeout not yet implemented.")
 
312
 
313
- def _easy_compute_field_scores(self, sample: Dict[str, Any]) -> Dict[str, float]:
314
- """
315
- Compute signal scores for each field in an easy-task sample.
 
 
 
 
 
 
 
 
 
 
316
 
317
- TODO: Implement when the easy task design is finalised.
318
- """
319
- raise NotImplementedError("Easy task field score computation not yet implemented.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
 
321
  # =========================================================================
322
  # MEDIUM TASK implementation (original logic, now under _medium_* names)
@@ -552,9 +590,6 @@ class JobScamEnvironment(Environment):
552
  Replace the NotImplementedError with the actual logic,
553
  following the same pattern as _medium_reset().
554
  """
555
- # Lazy-load the hard dataset on first use
556
- if self._HARD_DATASET is None:
557
- self._HARD_DATASET = _load_dataset(HARD_DATASET_FILENAME)
558
 
559
  # TODO: implement hard reset logic here
560
  raise NotImplementedError(
 
61
  from ..constants import (
62
  VALID_TASK_NAMES,
63
  # Easy
64
+ EASY_DATASET_FILENAME, EASY_MAX_STEPS, EASY_REWARD_MATRIX,
65
+ EASY_ACTION_TO_FIELD, EASY_ALL_CONTEXT_FIELDS,
66
  # Medium
67
  MEDIUM_REWARD_MATRIX, MEDIUM_ACTION_TO_FIELD, MEDIUM_ALL_CONTEXT_FIELDS,
68
  MEDIUM_MAX_STEPS, MEDIUM_TIMEOUT_PENALTY, MEDIUM_DATASET_FILENAME,
 
160
  self._task_name: str = "medium"
161
 
162
  # ── Datasets β€” loaded once per process ──────────────────────────────
 
163
  self._MEDIUM_DATASET: List[Dict[str, Any]] = _load_dataset(MEDIUM_DATASET_FILENAME)
164
+ self._EASY_DATASET: List[Dict[str, Any]] = _load_dataset(EASY_DATASET_FILENAME)
165
+ self._HARD_DATASET: List[Dict[str, Any]] = _load_dataset(HARD_DATASET_FILENAME)
 
 
 
166
 
167
  # ---------------------------------------------------------------- reset
168
+
169
+ def reset(self, task_name: str = None) -> JobScamObservation:
170
  """
171
  Start a new episode with a randomly selected dataset sample.
172
 
 
176
  Which task variant to run. Must be one of: easy, medium, hard.
177
  Defaults to "medium" for backward compatibility.
178
  """
179
+ # Select a random task if None is provided
180
+ if not task_name:
181
+ random_task = random.choice(VALID_TASK_NAMES)
182
+ task_name = random_task
183
+
184
  if task_name not in VALID_TASK_NAMES:
185
  raise ValueError(
186
  f"Unknown task_name '{task_name}'. "
 
218
 
219
  # ── Dispatch to task-specific step logic ─────────────────────────────
220
  if self._task_name == "easy":
221
+ if action.action_type == ActionType.CLASSIFY_EASY:
222
+ return self._easy_handle_classify(action)
223
 
224
  elif self._task_name == "medium":
225
  if action.action_type == ActionType.CLASSIFY:
 
249
  Raise ValueError if the action_type does not belong to the active task
250
  (and is not the universal CLASSIFY action).
251
  """
252
+ if action.action_type == ActionType.CLASSIFY or action.action_type == ActionType.CLASSIFY_EASY:
253
  return # always valid
254
 
255
  if self._task_name == "easy":
 
272
  # EASY TASK implementation
273
  # =========================================================================
274
  def _easy_reset(self) -> JobScamObservation:
275
+ sample = random.choice(self._EASY_DATASET)
 
276
 
277
+ self._episode = {
278
+ "sample": sample,
279
+ "used_steps": 0,
280
+ "max_steps": EASY_MAX_STEPS,
281
+ "reward": 0.0,
282
+ "done": False,
283
+ }
284
 
285
+ return JobScamObservation(
286
+ task_name=self._task_name,
287
+ query_type=sample["query_type"],
288
+ initial_query=sample["initial_query"],
289
+ step_budget={
290
+ "total": EASY_MAX_STEPS,
291
+ "used": 0,
292
+ "remaining": EASY_MAX_STEPS,
293
+ },
294
+ episode_done=False,
295
+ done=False,
296
+ reward=0.0,
297
+ info={},
298
  )
299
 
300
+ def _easy_handle_classify(self, action: JobScamAction) -> JobScamObservation:
 
 
301
 
302
+ predicted = action.label.value
303
+ ground_truth = self._episode["sample"]["ground_truth"]
 
304
 
305
+ if predicted not in EASY_REWARD_MATRIX:
306
+ raise ValueError(f"Invalid easy-task label: {predicted}")
 
307
 
308
+ if ground_truth not in EASY_REWARD_MATRIX[predicted]:
309
+ raise ValueError(f"Invalid easy-task ground truth: {ground_truth}")
 
310
 
311
+ reward = EASY_REWARD_MATRIX[predicted][ground_truth]
 
 
312
 
313
+ self._episode["reward"] = round(
314
+ self._episode["reward"] + reward, 4
315
+ )
316
+ self._episode["done"] = True
317
 
318
+ return JobScamObservation(
319
+ task_name=self._task_name,
320
+ predicted_label=predicted,
321
+ actual_label=ground_truth,
322
+ step_budget=self._budget_dict(),
323
+ done=True,
324
+ episode_done=True,
325
+ reason="classification",
326
+ reward=reward,
327
+ info={
328
+ "reward": reward,
329
+ },
330
+ )
331
 
332
+ # def _easy_handle_timeout(self) -> JobScamObservation:
333
+
334
+ # self._episode["total_reward"] = round(
335
+ # self._episode["total_reward"] + EASY_TIMEOUT_PENALTY, 4
336
+ # )
337
+ # self._episode["done"] = True
338
+
339
+ # return JobScamObservation(
340
+ # task_name=self._task_name,
341
+ # episode_done=True,
342
+ # reason="timeout",
343
+ # step_budget=self._budget_dict(),
344
+ # done=True,
345
+ # reward=EASY_TIMEOUT_PENALTY,
346
+ # info={
347
+ # "reward_breakdown": {
348
+ # "classification_reward": 0.0,
349
+ # "timeout_penalty": EASY_TIMEOUT_PENALTY,
350
+ # },
351
+ # "cumulative": {
352
+ # "info_reward_total": self._episode["info_reward_total"],
353
+ # "classification_reward_total": self._episode["classification_reward_total"],
354
+ # "total_reward": self._episode["total_reward"],
355
+ # },
356
+ # },
357
+ # )
358
 
359
  # =========================================================================
360
  # MEDIUM TASK implementation (original logic, now under _medium_* names)
 
590
  Replace the NotImplementedError with the actual logic,
591
  following the same pattern as _medium_reset().
592
  """
 
 
 
593
 
594
  # TODO: implement hard reset logic here
595
  raise NotImplementedError(