Spaces:
Sleeping
Sleeping
File size: 13,325 Bytes
317d3e1 a76b278 | 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 | import json
import uuid
from pathlib import Path
from typing import Any, Dict, Tuple
from models import (
RewardModel,
SupportAction,
SupportObservation,
SupportState,
TicketDetail,
TicketSummary,
)
TASKS_DIR = Path(__file__).resolve().parent.parent / "tasks"
class OpenSupportOpsEnv:
def __init__(self, task_file: str = "easy_refund.json"):
self.task_file = task_file
self.task_data: Dict[str, Any] = {}
self._state: SupportState | None = None
def _load_task(self) -> Dict[str, Any]:
with open(TASKS_DIR / self.task_file, "r", encoding="utf-8") as f:
return json.load(f)
def reset(self) -> SupportObservation:
self.task_data = self._load_task()
tickets = {
t["ticket_id"]: TicketDetail(**t)
for t in self.task_data["visible"]["tickets"]
}
self._state = SupportState(
task_id=self.task_data["task_id"],
episode_id=str(uuid.uuid4()),
step_count=0,
max_steps=self.task_data.get("max_steps", 10),
done=False,
active_ticket_id=None,
tickets=tickets,
customers=self.task_data["visible"].get("customers", {}),
policy_snippets=self.task_data["visible"].get("policy_snippets", []),
internal_notes={k: [] for k in tickets.keys()},
draft_replies={},
resolutions={},
audit_log=[],
hidden_score=0.0,
)
return self._build_observation("reset_done")
def state(self) -> SupportState:
if self._state is None:
raise RuntimeError("Call reset() first")
return self._state
def step(
self, action: SupportAction
) -> Tuple[SupportObservation, RewardModel, bool, Dict[str, Any]]:
if self._state is None:
raise RuntimeError("Call reset() first")
if self._state.done:
obs = self._build_observation("episode_already_done")
reward = RewardModel(value=0.0, reason="episode_already_done")
return obs, reward, True, {"invalid_action": True}
self._state.step_count += 1
info: Dict[str, Any] = {"invalid_action": False}
self._state.audit_log.append(
{
"step": self._state.step_count,
"action": action.model_dump(),
}
)
reward = RewardModel(value=0.0, reason="step")
if action.action_type == "open_ticket":
if action.ticket_id and action.ticket_id in self._state.tickets:
self._state.active_ticket_id = action.ticket_id
reward = RewardModel(value=0.1, reason="opened_ticket")
else:
reward = RewardModel(value=-0.1, reason="invalid_ticket")
info["invalid_action"] = True
elif action.action_type == "view_customer":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
else:
reward = RewardModel(value=0.02, reason="customer_viewed")
elif action.action_type == "search_policy":
reward = RewardModel(value=0.02, reason="policy_searched")
elif action.action_type == "classify_ticket":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
else:
ticket = self._state.tickets[self._state.active_ticket_id]
ticket.category = action.value
expected = self.task_data.get("gold", {}).get("classification", {}).get(ticket.ticket_id)
if expected is not None:
if action.value == expected:
reward = RewardModel(value=0.1, reason="classification_correct")
else:
reward = RewardModel(value=-0.02, reason="classification_wrong")
else:
reward = RewardModel(value=0.05, reason="ticket_classified")
elif action.action_type == "set_priority":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
elif action.value not in {"low", "medium", "high", "urgent"}:
reward = RewardModel(value=-0.05, reason="invalid_priority")
info["invalid_action"] = True
else:
ticket = self._state.tickets[self._state.active_ticket_id]
ticket.priority = action.value
expected = self.task_data.get("gold", {}).get("priority", {}).get(ticket.ticket_id)
if expected is not None:
if action.value == expected:
reward = RewardModel(value=0.1, reason="priority_correct")
else:
reward = RewardModel(value=-0.02, reason="priority_wrong")
else:
reward = RewardModel(value=0.05, reason="priority_updated")
elif action.action_type == "route_ticket":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
else:
ticket = self._state.tickets[self._state.active_ticket_id]
ticket.assigned_team = action.value
expected = self.task_data.get("gold", {}).get("routing", {}).get(ticket.ticket_id)
if expected is not None:
if action.value == expected:
reward = RewardModel(value=0.15, reason="routing_correct")
else:
reward = RewardModel(value=-0.03, reason="routing_wrong")
else:
reward = RewardModel(value=0.05, reason="ticket_routed")
elif action.action_type == "request_more_info":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
else:
ticket = self._state.tickets[self._state.active_ticket_id]
ticket.status = "pending"
reward = RewardModel(value=0.08, reason="more_info_requested")
elif action.action_type == "draft_reply":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
else:
self._state.draft_replies[self._state.active_ticket_id] = action.message or ""
reward = RewardModel(value=0.08, reason="reply_drafted")
elif action.action_type == "add_internal_note":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
else:
ticket_id = self._state.active_ticket_id
self._state.internal_notes.setdefault(ticket_id, []).append(action.message or "")
reward = RewardModel(value=0.02, reason="internal_note_added")
elif action.action_type == "apply_resolution":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
else:
ticket_id = self._state.active_ticket_id
self._state.resolutions[ticket_id] = action.value or ""
expected = self.task_data.get("gold", {}).get("resolution", {}).get(ticket_id)
if expected is not None:
if action.value == expected:
reward = RewardModel(value=0.2, reason="resolution_correct")
else:
reward = RewardModel(value=-0.05, reason="resolution_wrong")
else:
reward = RewardModel(value=0.1, reason="resolution_applied")
elif action.action_type == "close_ticket":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
else:
ticket = self._state.tickets[self._state.active_ticket_id]
ticket.status = "closed"
reward = RewardModel(value=0.1, reason="ticket_closed")
elif action.action_type == "escalate":
if self._state.active_ticket_id is None:
reward = RewardModel(value=-0.05, reason="no_active_ticket")
info["invalid_action"] = True
else:
ticket = self._state.tickets[self._state.active_ticket_id]
ticket.assigned_team = action.value or "escalations"
ticket.status = "pending"
reward = RewardModel(value=0.05, reason="ticket_escalated")
else:
reward = RewardModel(value=-0.1, reason="unsupported_action")
info["invalid_action"] = True
self._update_progress_score()
self._state.done = (
self._is_task_complete() or
self._state.step_count >= self._state.max_steps
)
obs = self._build_observation(reward.reason)
return obs, reward, self._state.done, info
def _is_task_complete(self) -> bool:
if self._state is None:
return False
gold = self.task_data.get("gold", {})
classification = gold.get("classification", {})
for tid, expected in classification.items():
if tid not in self._state.tickets:
return False
if self._state.tickets[tid].category != expected:
return False
priority = gold.get("priority", {})
for tid, expected in priority.items():
if tid not in self._state.tickets:
return False
if self._state.tickets[tid].priority != expected:
return False
routing = gold.get("routing", {})
for tid, expected in routing.items():
if tid not in self._state.tickets:
return False
if self._state.tickets[tid].assigned_team != expected:
return False
resolution = gold.get("resolution", {})
for tid, expected in resolution.items():
if self._state.resolutions.get(tid) != expected:
return False
return True
def _update_progress_score(self) -> None:
if self._state is None:
return
gold = self.task_data.get("gold", {})
score = 0.0
classification = gold.get("classification", {})
priority = gold.get("priority", {})
routing = gold.get("routing", {})
resolution = gold.get("resolution", {})
for tid, expected in classification.items():
if tid in self._state.tickets and self._state.tickets[tid].category == expected:
score += 0.25
for tid, expected in priority.items():
if tid in self._state.tickets and self._state.tickets[tid].priority == expected:
score += 0.25
for tid, expected in routing.items():
if tid in self._state.tickets and self._state.tickets[tid].assigned_team == expected:
score += 0.25
for tid, expected in resolution.items():
if self._state.resolutions.get(tid) == expected:
score += 0.25
self._state.hidden_score = round(min(score, 1.0), 2)
def _build_observation(self, last_action_result: str) -> SupportObservation:
s = self._state
assert s is not None
selected = s.tickets.get(s.active_ticket_id) if s.active_ticket_id else None
return SupportObservation(
screen="ticket" if selected else "inbox",
visible_tickets=[
TicketSummary(
ticket_id=t.ticket_id,
subject=t.subject,
customer_tier=t.metadata.get("customer_tier", "free"),
priority=t.priority,
status=t.status,
category=t.category,
)
for t in s.tickets.values()
],
selected_ticket=selected,
visible_policy_hits=s.policy_snippets[:3],
last_action_result=last_action_result,
valid_next_actions=[
"open_ticket",
"view_customer",
"search_policy",
"classify_ticket",
"set_priority",
"route_ticket",
"request_more_info",
"draft_reply",
"add_internal_note",
"apply_resolution",
"close_ticket",
"escalate",
],
remaining_steps=max(0, s.max_steps - s.step_count),
trajectory_score=s.hidden_score,
) |