File size: 10,607 Bytes
dab441f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9ad6f9
 
dab441f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9ad6f9
 
dab441f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9ad6f9
dab441f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Async baseline inference runner for Supermail."""

from __future__ import annotations

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

from openai import OpenAI

try:
    from dotenv import load_dotenv
except ImportError:  # pragma: no cover
    def load_dotenv() -> bool:
        return False

from client import SupermailEnv
from models import SupportAction, SupportObservation
from server.environment import SupermailEnvironment
from sys_prompt import SYSTEM_PROMPT
from tasks import ALL_TASKS, TASKS_BY_ID

load_dotenv()

API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-72B-Instruct")
HF_TOKEN = os.getenv("HF_TOKEN")
LOCAL_IMAGE_NAME = os.getenv("LOCAL_IMAGE_NAME")

BASE_URL = os.getenv("SUPERMAIL_BASE_URL") or os.getenv("SUPPORT_SIM_BASE_URL")
TASK_NAME = os.getenv("SUPERMAIL_TASK") or os.getenv("SUPPORT_SIM_TASK", "all")
BENCHMARK = os.getenv("SUPERMAIL_BENCHMARK") or os.getenv("SUPPORT_SIM_BENCHMARK", "supermail")

MAX_STEPS = 12
TEMPERATURE = 0.4
MAX_TOKENS = 25000
SUCCESS_SCORE_THRESHOLD = 0.95
MIN_SCORE = 0.01
MAX_SCORE = 0.99

@dataclass
class LocalStepResult:
    """Minimal local stand-in for OpenEnv StepResult."""

    observation: SupportObservation
    reward: float
    done: bool


class LocalSupermailSession:
    """Async adapter for direct local environment usage."""

    def __init__(self, task_id: str):
        self._env = SupermailEnvironment(task_id=task_id)

    async def reset(self) -> LocalStepResult:
        observation = self._env.reset()
        return LocalStepResult(
            observation=observation,
            reward=observation.reward or 0.0,
            done=observation.done,
        )

    async def step(self, action: SupportAction) -> LocalStepResult:
        observation = self._env.step(action)
        return LocalStepResult(
            observation=observation,
            reward=observation.reward or 0.0,
            done=observation.done,
        )

    async def close(self) -> None:
        self._env.close()


def sanitize(value: Any) -> str:
    """Keep log output on a single line."""
    text = str(value)
    return " ".join(text.replace("\r", " ").replace("\n", " ").split())


def clamp_score(score: float) -> float:
    """Clamp score into the open interval (0, 1)."""
    return min(max(score, MIN_SCORE), MAX_SCORE)


def compact_action(action: Optional[SupportAction]) -> str:
    """Serialize an action for the required log format."""
    if action is None:
        return "null"
    payload = {
        field_name: getattr(action, field_name)
        for field_name in ("priority", "category", "action", "notes")
        if getattr(action, field_name, None)
    }
    return json.dumps(payload, separators=(",", ":"), sort_keys=True)


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: Optional[SupportAction],
    reward: float,
    done: bool,
    error: Optional[str],
) -> None:
    error_text = error if error else "null"
    print(
        "[STEP] "
        f"step={step} "
        f"action={sanitize(compact_action(action))} "
        f"reward={reward:.2f} "
        f"done={'true' if done else 'false'} "
        f"error={sanitize(error_text)}",
        flush=True,
    )


def log_end(*, success: bool, steps: int, score: float, rewards: List[float]) -> None:
    reward_text = ",".join(f"{reward:.2f}" for reward in rewards)
    print(
        f"[END] success={'true' if success else 'false'} "
        f"steps={steps} score={score:.2f} rewards={reward_text}",
        flush=True,
    )


def build_client() -> Optional[OpenAI]:
    """Create an OpenAI client when credentials are available."""
    if not HF_TOKEN:
        return None
    return OpenAI(base_url=API_BASE_URL, api_key=HF_TOKEN)


def heuristic_action(observation: SupportObservation) -> SupportAction:
    """Deterministic fallback policy for the bundled tasks."""
    text = f"{observation.email} {json.dumps(observation.context, sort_keys=True)}".lower()

    if any(
        token in text
        for token in (
            "click here",
            "gift card",
            "crypto",
            "lottery",
            "unsubscribe",
            "bypass all metrics",
            "encrypted emergency",
            "decrypt tool",
            "emergency slot",
            "override the normal queue",
            "sender_verified\": \"false",
            "spoofed sender",
        )
    ):
        priority = "spam"
    elif any(
        token in text
        for token in (
            "today",
            "payroll closes",
            "500 error",
            "blocked",
            "backing up",
            "immediately",
            "double",
            "charged again",
        )
    ):
        priority = "urgent"
    else:
        priority = "normal"

    if any(token in text for token in ("charge", "charged", "invoice", "refund", "billing", "subscription")):
        category = "billing"
    elif any(token in text for token in ("tracking", "shipment", "delivery", "delivered", "ship")):
        category = "delivery"
    elif any(token in text for token in ("error", "login", "outage", "crash", "bug", "sign in")):
        category = "technical"
    else:
        category = "general"

    if priority == "spam":
        next_action = "ignore"
    elif category == "technical":
        next_action = "assign_to_team"
    elif priority == "urgent":
        next_action = "respond_immediately"
    elif category == "delivery":
        next_action = "assign_to_team"
    else:
        next_action = "respond_immediately"

    payload: dict[str, str] = {}
    if "priority" in observation.required_fields:
        payload["priority"] = priority
    if "category" in observation.required_fields:
        payload["category"] = category
    if "action" in observation.required_fields:
        payload["action"] = next_action
    return SupportAction(**payload)


def get_model_action(
    client: OpenAI,
    observation: SupportObservation,
    history: List[str],
) -> SupportAction:
    """Use the OpenAI client for the next action."""
    prompt = {
        "task_id": observation.task_id,
        "benchmark": observation.benchmark,
        "objective": observation.objective,
        "required_fields": observation.required_fields,
        "allowed_values": observation.allowed_values,
        "email": observation.email,
        "context": observation.context,
        "history": history,
        "feedback": observation.feedback,
    }

    response = client.chat.completions.create(
        model=MODEL_NAME,
        temperature=TEMPERATURE,
        max_tokens=MAX_TOKENS,
        messages=[
            {"role": "system", "content": SYSTEM_PROMPT},
            {"role": "user", "content": json.dumps(prompt, ensure_ascii=True)},
        ],
    )
    content = (response.choices[0].message.content or "").strip()
    payload = json.loads(content)
    filtered_payload = {
        key: value
        for key, value in payload.items()
        if key in {"priority", "category", "action", "notes"}
    }
    return SupportAction(**filtered_payload)


def choose_action(
    client: Optional[OpenAI],
    observation: SupportObservation,
    history: List[str],
) -> SupportAction:
    """Use the model when available, otherwise fall back to heuristics."""
    if client is None:
        return heuristic_action(observation)
    try:
        return get_model_action(client, observation, history)
    except Exception:
        return heuristic_action(observation)


async def create_env(task_id: str):
    """Create the environment session using docker, base URL, or local fallback."""
    if LOCAL_IMAGE_NAME:
        return await SupermailEnv.from_docker_image(
            LOCAL_IMAGE_NAME,
            env_vars={"SUPERMAIL_TASK": task_id},
        )

    if BASE_URL:
        env = SupermailEnv(base_url=BASE_URL)
        await env.connect()
        return env

    return LocalSupermailSession(task_id=task_id)


async def run_episode(task_id: str, client: Optional[OpenAI]) -> None:
    """Run a single task episode and emit the required logs."""
    if task_id not in TASKS_BY_ID:
        raise ValueError(f"Unknown task: {task_id}")

    env = None
    history: List[str] = []
    rewards: List[float] = []
    steps_taken = 0
    score = MIN_SCORE
    success = False
    action_for_log: Optional[SupportAction] = None

    log_start(task=task_id, env=BENCHMARK, model=MODEL_NAME)

    try:
        env = await create_env(task_id)
        result = await env.reset()
        observation = result.observation

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

            action_for_log = choose_action(client, observation, history)
            result = await env.step(action_for_log)
            observation = result.observation
            reward = result.reward or 0.0
            done = result.done
            error = observation.metadata.get("last_action_error")

            rewards.append(reward)
            steps_taken = step
            score = clamp_score(float(getattr(observation, "score", 0.0)))

            log_step(
                step=step,
                action=action_for_log,
                reward=reward,
                done=done,
                error=error,
            )

            history.append(
                f"step={step} action={compact_action(action_for_log)} "
                f"reward={reward:.2f} score={score:.2f}"
            )

            if done:
                break

        success = score >= SUCCESS_SCORE_THRESHOLD
    except Exception as exc:
        log_step(
            step=steps_taken,
            action=action_for_log,
            reward=0.0,
            done=True,
            error=str(exc),
        )
    finally:
        if env is not None:
            try:
                await env.close()
            except Exception:
                pass
        log_end(success=success, steps=steps_taken, score=score, rewards=rewards)


def task_sequence() -> List[str]:
    """Resolve the requested task selection."""
    if TASK_NAME == "all":
        return [task.task_id for task in ALL_TASKS]
    return [TASK_NAME]


async def main() -> None:
    """Run one or more task episodes."""
    client = build_client()
    for task_id in task_sequence():
        await run_episode(task_id, client)


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