File size: 14,858 Bytes
9f1e96e
df67741
 
 
 
 
 
 
9f1e96e
df67741
 
 
9f1e96e
df67741
 
 
9f1e96e
 
 
 
df67741
9f1e96e
 
 
 
df67741
9f1e96e
 
 
 
 
df67741
9f1e96e
 
 
 
df67741
9f1e96e
 
 
df67741
 
9f1e96e
 
 
df67741
9f1e96e
 
df67741
 
9f1e96e
 
df67741
 
9f1e96e
 
 
 
 
 
 
 
 
df67741
9f1e96e
 
 
 
 
 
 
df67741
 
 
 
 
 
 
 
 
9f1e96e
df67741
 
 
 
 
 
 
0d44d80
9f1e96e
df67741
0d44d80
9f1e96e
df67741
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f1e96e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df67741
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f1e96e
df67741
 
 
 
 
 
9f1e96e
df67741
 
 
 
9f1e96e
df67741
 
9f1e96e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df67741
9f1e96e
 
 
 
 
 
 
df67741
 
 
9f1e96e
 
df67741
9f1e96e
 
 
df67741
 
9f1e96e
 
 
 
 
 
 
 
 
 
 
 
 
df67741
 
 
9f1e96e
 
df67741
 
9f1e96e
 
 
 
 
 
 
 
 
 
 
 
 
 
df67741
9f1e96e
 
df67741
 
 
9f1e96e
 
df67741
 
 
9f1e96e
 
df67741
9f1e96e
 
 
 
 
 
 
df67741
 
 
9f1e96e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df67741
9f1e96e
df67741
 
9f1e96e
 
df67741
9f1e96e
 
df67741
9f1e96e
df67741
9f1e96e
df67741
9f1e96e
df67741
 
 
9f1e96e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df67741
 
 
9f1e96e
0d44d80
 
 
 
9f1e96e
 
 
 
 
0d44d80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f1e96e
 
df67741
 
9f1e96e
df67741
9f1e96e
df67741
9f1e96e
df67741
 
9f1e96e
 
 
 
 
df67741
 
9f1e96e
df67741
9f1e96e
df67741
9f1e96e
df67741
 
 
 
9f1e96e
 
df67741
9f1e96e
 
df67741
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f1e96e
 
df67741
 
 
9f1e96e
 
 
 
 
 
 
 
 
df67741
9f1e96e
 
 
df67741
 
 
 
 
 
0d44d80
df67741
9f1e96e
 
 
 
 
 
df67741
 
 
9f1e96e
0d44d80
9f1e96e
 
 
 
 
df67741
9f1e96e
df67741
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
"""Baseline inference runner for the Ecom returns decision environment."""

from __future__ import annotations

import asyncio
import json
import os
import re
import textwrap
from dataclasses import dataclass
from typing import Any, Dict, List, Optional

from openai import OpenAI

from ecom import EcomAction, EcomEnv

BENCHMARK = "ecom_returns_decision"
MAX_STEPS = 5
TEMPERATURE = 0
MAX_TOKENS = 180

SYSTEM_PROMPT = textwrap.dedent(
    """
    You are a returns operations agent.
    Choose exactly one action in JSON only.

    Allowed action_type values:
    - APPROVE
    - REJECT
    - ESCALATE
    - REQUEST_INFO

    If action_type is REJECT, include reason_code with one of:
    - TIME_EXPIRED
    - POLICY_VIOLATION
    - SUSPECTED_FRAUD

    Output JSON only. No prose, no markdown.
    """
).strip()


def _model_name() -> str:
    return os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")


def _image_name() -> Optional[str]:
    return os.getenv("IMAGE_NAME") or os.getenv("LOCAL_IMAGE_NAME")


def _env_base_url() -> Optional[str]:
    return os.getenv("ENV_BASE_URL")


def _task_names() -> List[str]:
    task_name = os.getenv("ECOM_TASK_NAME") or os.getenv("ECOM_TASK")
    if task_name:
        return [task_name]
    return [
        "easy_policy_compliance",
        "medium_balanced_judgment",
        "hard_conflicting_signals",
    ]


@dataclass
class EpisodeOutcome:
    success: bool
    steps: int
    score: float
    rewards: List[float]


def log_start(task: str, env: str, model: str) -> None:
    print(f"[START] task={task} env={env} model={model}", flush=True)


def log_step(
    step: int, action: str, reward: float, done: bool, error: Optional[str]
) -> None:
    error_val = error if error else "null"
    done_val = str(done).lower()
    print(
        f"[STEP] step={step} action={action} reward={reward:.2f} done={done_val} error={error_val}",
        flush=True,
    )


def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
    rewards_str = ",".join(f"{reward:.2f}" for reward in rewards)
    print(
        f"[END] success={str(success).lower()} steps={steps} score={score:.2f} rewards={rewards_str}",
        flush=True,
    )


def format_action(action: EcomAction) -> str:
    if action.reason_code is None:
        return action.action_type
    return f"{action.action_type}({action.reason_code})"


def extract_return_window(policy_summary: str) -> int:
    match = re.search(r"within\s+(\d+)\s+days", policy_summary, flags=re.IGNORECASE)
    if match:
        return int(match.group(1))
    return 30


def exception_applies(observation: Any) -> bool:
    reason = str(observation.return_reason).lower()
    policy_summary = str(observation.policy_summary).lower()

    match = re.search(r"exception:\s*([^.]*)", policy_summary)
    clause = match.group(1) if match else ""

    if reason == "damaged-shipping" and (
        "damage in transit" in clause or "damaged" in clause
    ):
        return True

    if reason == "defective" and "defective" in clause:
        return True

    return False


def is_restricted_class_case(observation: Any) -> bool:
    return "restricted class" in str(observation.product_condition_notes).lower()


def should_reject_time_expired(
    observation: Any, window: int, has_exception: bool
) -> bool:
    if observation.days_since_purchase <= window:
        return False
    if has_exception and not is_restricted_class_case(observation):
        return False
    return True


def _safe_json_parse(text: str) -> Optional[Dict[str, Any]]:
    text = text.strip()
    if not text:
        return None

    try:
        parsed = json.loads(text)
        if isinstance(parsed, dict):
            return parsed
        return None
    except json.JSONDecodeError:
        pass

    start = text.find("{")
    end = text.rfind("}")
    if start == -1 or end == -1 or end <= start:
        return None

    try:
        parsed = json.loads(text[start : end + 1])
        if isinstance(parsed, dict):
            return parsed
    except json.JSONDecodeError:
        return None

    return None


def _extract_last_action_error(observation: Any) -> Optional[str]:
    info = getattr(observation, "info", None)
    if not isinstance(info, dict):
        return None

    for key in ("last_action_error", "invalid_action"):
        value = info.get(key)
        if value is not None:
            return str(value)
    return None


def _extract_available_actions(observation: Any) -> List[str]:
    info = getattr(observation, "info", None)
    if not isinstance(info, dict):
        return []

    raw = info.get("available_actions")
    if not isinstance(raw, list):
        return []
    return [str(value) for value in raw]


def _extract_reject_reason_codes(observation: Any) -> List[str]:
    info = getattr(observation, "info", None)
    if not isinstance(info, dict):
        return []

    raw = info.get("reject_reason_codes")
    if not isinstance(raw, list):
        return []
    return [str(value) for value in raw]


def _enforce_action_contract(
    observation: Any, action: EcomAction
) -> Optional[EcomAction]:
    available_actions = _extract_available_actions(observation)
    if available_actions and action.action_type not in set(available_actions):
        return None

    if action.action_type == "REJECT":
        valid_reasons = set(_extract_reject_reason_codes(observation))
        if valid_reasons and action.reason_code not in valid_reasons:
            return None

    return action


def heuristic_policy(observation: Any, step: int) -> EcomAction:
    available_actions = set(_extract_available_actions(observation))

    window = extract_return_window(observation.policy_summary)
    has_exception = exception_applies(observation)
    notes = str(observation.product_condition_notes).lower()
    reason = str(observation.return_reason)
    return_rate = float(observation.return_rate)

    ambiguous = (
        ("mixed indicators" in notes)
        or ("conflict" in notes)
        or (0.40 <= return_rate <= 0.65)
        or (observation.days_since_purchase > window and has_exception)
    )
    if step == 1 and (not available_actions or "REQUEST_INFO" in available_actions):
        if ambiguous:
            return EcomAction(action_type="REQUEST_INFO")

    if should_reject_time_expired(observation, window, has_exception):
        if available_actions and "REJECT" not in available_actions:
            return EcomAction(action_type="APPROVE")
        return EcomAction(action_type="REJECT", reason_code="TIME_EXPIRED")

    if "restricted class" in notes:
        if available_actions and "REJECT" not in available_actions:
            return EcomAction(action_type="APPROVE")
        return EcomAction(action_type="REJECT", reason_code="POLICY_VIOLATION")

    if (
        step >= 2
        and observation.product_value == "high"
        and return_rate >= 0.50
        and (
            "conflict" in notes
            or "disputed evidence" in notes
            or reason in ("changed-mind", "wrong-item")
        )
    ):
        if available_actions and "REJECT" not in available_actions:
            return EcomAction(action_type="APPROVE")
        return EcomAction(action_type="REJECT", reason_code="SUSPECTED_FRAUD")

    if return_rate >= 0.60 and observation.product_value == "high":
        if available_actions and "REJECT" not in available_actions:
            return EcomAction(action_type="APPROVE")
        return EcomAction(action_type="REJECT", reason_code="SUSPECTED_FRAUD")

    if reason in ("defective", "wrong-item", "damaged-shipping") and return_rate < 0.55:
        if available_actions and "APPROVE" not in available_actions:
            return EcomAction(action_type="ESCALATE")
        return EcomAction(action_type="APPROVE")

    if return_rate >= 0.55:
        if available_actions and "ESCALATE" not in available_actions:
            return EcomAction(action_type="APPROVE")
        return EcomAction(action_type="ESCALATE")

    if available_actions and "APPROVE" not in available_actions:
        if "ESCALATE" in available_actions:
            return EcomAction(action_type="ESCALATE")
        if "REJECT" in available_actions:
            return EcomAction(action_type="REJECT", reason_code="SUSPECTED_FRAUD")

    return EcomAction(action_type="APPROVE")


def build_user_prompt(step: int, observation: Any, history: List[str]) -> str:
    history_block = "\n".join(history[-4:]) if history else "None"
    available_actions = _extract_available_actions(observation)
    reject_reason_codes = _extract_reject_reason_codes(observation)

    prompt = textwrap.dedent(
        f"""
        Step: {step}
        return_reason: {observation.return_reason}
        product_category: {observation.product_category}
        product_value: {observation.product_value}
        days_since_purchase: {observation.days_since_purchase}
        user_account_age_days: {observation.user_account_age_days}
        product_condition_notes: {observation.product_condition_notes}
        return_rate: {float(observation.return_rate):.3f}
        total_orders: {observation.total_orders}
        policy_summary: {observation.policy_summary}
        available_actions: {", ".join(available_actions) if available_actions else "None"}
        available_reject_reason_codes: {", ".join(reject_reason_codes) if reject_reason_codes else "None"}
        Previous steps:
        {history_block}
        """
    ).strip()

    return prompt


def get_model_action(
    client: OpenAI, step: int, observation: Any, history: List[str]
) -> Optional[EcomAction]:
    user_prompt = build_user_prompt(step, observation, history)

    try:
        completion = client.chat.completions.create(
            model=_model_name(),
            messages=[
                {"role": "system", "content": SYSTEM_PROMPT},
                {"role": "user", "content": user_prompt},
            ],
            temperature=TEMPERATURE,
            max_tokens=MAX_TOKENS,
            stream=False,
        )
        text = (completion.choices[0].message.content or "").strip()
    except Exception:
        return None

    data = _safe_json_parse(text)
    if data is None:
        return None

    action_type = str(data.get("action_type", "")).strip().upper()
    reason_code = data.get("reason_code")
    if reason_code is not None:
        reason_code = str(reason_code).strip().upper()

    if action_type == "REJECT":
        if reason_code not in {
            "TIME_EXPIRED",
            "POLICY_VIOLATION",
            "SUSPECTED_FRAUD",
        }:
            return None
        action = EcomAction(action_type="REJECT", reason_code=reason_code)
        return _enforce_action_contract(observation, action)

    if action_type in {"APPROVE", "ESCALATE", "REQUEST_INFO"}:
        action = EcomAction(action_type=action_type)
        return _enforce_action_contract(observation, action)

    return None


def _build_llm_client() -> OpenAI:
    api_base_url = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
    api_key = os.getenv("HF_TOKEN") or os.getenv("API_KEY")
    if not api_key:
        raise RuntimeError("HF_TOKEN or API_KEY environment variable is required.")
    return OpenAI(
        base_url=api_base_url,
        api_key=api_key,
    )


def _probe_llm_proxy(client: OpenAI) -> None:
    try:
        client.chat.completions.create(
            model=_model_name(),
            messages=[
                {"role": "system", "content": "Reply with OK."},
                {"role": "user", "content": "OK"},
            ],
            temperature=0,
            max_tokens=2,
            stream=False,
        )
    except Exception as exc:
        raise RuntimeError(
            "Failed to make an LLM request through API_BASE_URL using HF_TOKEN/API_KEY."
        ) from exc


async def run_task(task_name: str, client: OpenAI) -> EpisodeOutcome:
    history: List[str] = []
    rewards: List[float] = []
    steps_taken = 0
    score = 0.0
    success = False
    env: Optional[EcomEnv] = None

    log_start(task=task_name, env=BENCHMARK, model=_model_name())

    try:
        env_base_url = _env_base_url()
        image_name = _image_name()

        if env_base_url:
            env = EcomEnv(base_url=env_base_url)
            await env.connect()
        else:
            if not image_name:
                raise RuntimeError(
                    "IMAGE_NAME or LOCAL_IMAGE_NAME is required when ENV_BASE_URL is not set"
                )
            env = await EcomEnv.from_docker_image(image_name)

        result = await env.reset(task_name=task_name)

        for step in range(1, MAX_STEPS + 1):
            if result.done:
                break

            observation = result.observation
            action = get_model_action(client, step, observation, history)
            if action is None:
                action = heuristic_policy(observation, step)

            result = await env.step(action)
            reward = float(result.reward or 0.0)
            done = bool(result.done)
            error = _extract_last_action_error(result.observation)

            rewards.append(reward)
            steps_taken = step
            log_step(
                step=step,
                action=format_action(action),
                reward=reward,
                done=done,
                error=error,
            )

            history.append(
                f"Step {step}: {format_action(action)} -> reward {reward:.2f} error={error or 'null'}"
            )

            if done:
                info = result.observation.info
                if isinstance(info, dict):
                    success = bool(info.get("grader_success", False))
                    raw_score = info.get("grader_score", 0.0)
                    try:
                        score = float(raw_score)
                    except (TypeError, ValueError):
                        score = 0.0
                score = max(0.0, min(1.0, score))
                break

    except Exception:
        success = False
    finally:
        if env is not None:
            try:
                await env.close()
            except Exception:
                pass
        log_end(success=success, steps=steps_taken, score=score, rewards=rewards)

    return EpisodeOutcome(
        success=success,
        steps=steps_taken,
        score=score,
        rewards=rewards,
    )


async def main() -> None:
    client = _build_llm_client()
    _probe_llm_proxy(client)

    if not _env_base_url() and not _image_name():
        raise RuntimeError(
            "Set ENV_BASE_URL or IMAGE_NAME/LOCAL_IMAGE_NAME before running inference.py"
        )

    for task_name in _task_names():
        await run_task(task_name, client)


if __name__ == "__main__":
    asyncio.run(main())