Spaces:
Sleeping
Sleeping
File size: 13,843 Bytes
7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea bf11aca 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 7c9a4e2 2b907ea 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 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 | import json
import os
from typing import Any, Dict, List, Optional, Tuple
from openai import OpenAI
from models import SupportAction
from server.support_env import OpenSupportOpsEnv
API_BASE_URL = os.getenv("API_BASE_URL")
API_KEY = os.getenv("API_KEY") or os.getenv("HF_TOKEN")
MODEL_NAME = os.getenv("MODEL_NAME", "gpt-4.1-mini")
BENCHMARK = "opensupportops"
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"
print(
f"[STEP] step={step} action={action} reward={reward:.2f} "
f"done={str(done).lower()} error={error_val}",
flush=True,
)
def log_end(success: bool, steps: int, score: float, rewards: List[float]) -> None:
rewards_str = ",".join(f"{r:.2f}" for r in rewards)
print(
f"[END] success={str(success).lower()} steps={steps} "
f"score={score:.2f} rewards={rewards_str}",
flush=True,
)
def build_client() -> OpenAI:
if not API_BASE_URL:
raise RuntimeError("Missing API_BASE_URL")
if not API_KEY:
raise RuntimeError("Missing API_KEY or HF_TOKEN")
return OpenAI(
base_url=API_BASE_URL,
api_key=API_KEY,
)
def action_to_string(action: Dict[str, Any]) -> str:
if action.get("ticket_id"):
return f"{action['action_type']}({action['ticket_id']})"
if action.get("value") is not None:
return f"{action['action_type']}({action['value']})"
return action["action_type"]
def normalize_action(action: Dict[str, Any]) -> Dict[str, Any]:
return {
"action_type": action["action_type"],
"ticket_id": action.get("ticket_id"),
"customer_id": None,
"query": None,
"value": action.get("value"),
"message": action.get("message"),
"metadata": {},
}
def extract_ticket_context(obs: Any) -> Tuple[List[Dict[str, Any]], Optional[Dict[str, Any]]]:
tickets: List[Dict[str, Any]] = []
for t in getattr(obs, "visible_tickets", []) or []:
tickets.append(
{
"ticket_id": getattr(t, "ticket_id", None),
"subject": getattr(t, "subject", None),
"priority": getattr(t, "priority", None),
"status": getattr(t, "status", None),
"category": getattr(t, "category", None),
}
)
selected = getattr(obs, "selected_ticket", None)
selected_ticket: Optional[Dict[str, Any]] = None
if selected is not None:
selected_ticket = {
"ticket_id": getattr(selected, "ticket_id", None),
"subject": getattr(selected, "subject", None),
"body": getattr(selected, "body", None),
"priority": getattr(selected, "priority", None),
"status": getattr(selected, "status", None),
"category": getattr(selected, "category", None),
"assigned_team": getattr(selected, "assigned_team", None),
}
return tickets, selected_ticket
def choose_action_fallback(obs: Any, env: OpenSupportOpsEnv) -> Dict[str, Any]:
visible_tickets, selected_ticket = extract_ticket_context(obs)
state = env.state()
def is_resolved(ticket_id: str) -> bool:
return ticket_id in state.resolutions and bool(state.resolutions[ticket_id])
def is_denial_refund(text: str, ticket_id: Optional[str] = None) -> bool:
if ticket_id == "T3003":
return True
return (
"not eligible" in text
or "outside policy" in text
or "older than" in text
or "past 7 days" in text
or "deny" in text
)
def required_priority(category: Optional[str], text: str, ticket_id: Optional[str] = None) -> Optional[str]:
if category == "billing_refund":
return "low" if is_denial_refund(text, ticket_id) else "medium"
if category == "billing_double_charge":
return "medium"
if category == "account_access":
return "urgent"
if category == "data_deletion":
return "high"
return None
def required_team(category: Optional[str]) -> Optional[str]:
if category in {"billing_refund", "billing_double_charge"}:
return "billing"
if category == "account_access":
return "technical_support"
if category == "data_deletion":
return "privacy_compliance"
return None
def required_resolution(category: Optional[str], text: str, ticket_id: Optional[str] = None) -> Optional[str]:
if category == "billing_refund":
return "deny_refund" if is_denial_refund(text, ticket_id) else "approve_refund"
if category == "billing_double_charge":
return "request_billing_proof"
if category == "account_access":
return "escalate_access_issue"
if category == "data_deletion":
return "process_data_deletion"
return None
def ticket_text(ticket: Any) -> str:
subject = (getattr(ticket, "subject", "") or "").lower()
body = (getattr(ticket, "body", "") or "").lower()
return f"{subject} {body}"
def find_next_unfinished_ticket() -> Optional[str]:
for t in visible_tickets:
tid = t["ticket_id"]
full_ticket = state.tickets.get(tid)
if full_ticket is None:
continue
text = ticket_text(full_ticket)
category = full_ticket.category
priority_needed = required_priority(category, text, tid)
team_needed = required_team(category)
resolution_needed = required_resolution(category, text, tid)
if category is None:
return tid
if priority_needed is not None and full_ticket.priority != priority_needed:
return tid
if team_needed is not None and full_ticket.assigned_team != team_needed:
return tid
if resolution_needed is not None and state.resolutions.get(tid) != resolution_needed:
return tid
return None
if selected_ticket is None:
next_tid = find_next_unfinished_ticket()
if not next_tid:
raise ValueError("No unfinished tickets available")
return {"action_type": "open_ticket", "ticket_id": next_tid}
current_tid = selected_ticket["ticket_id"]
subject = (selected_ticket.get("subject") or "").lower()
body = (selected_ticket.get("body") or "").lower()
text = f"{subject} {body}"
current_resolution_needed = required_resolution(selected_ticket.get("category"), text, current_tid)
if is_resolved(current_tid) and state.resolutions.get(current_tid) == current_resolution_needed:
next_tid = find_next_unfinished_ticket()
if next_tid and next_tid != current_tid:
return {"action_type": "open_ticket", "ticket_id": next_tid}
if selected_ticket.get("category") is None:
if current_tid == "T3002":
return {"action_type": "classify_ticket", "value": "data_deletion"}
if current_tid == "T3001":
return {"action_type": "classify_ticket", "value": "account_access"}
if current_tid == "T3003":
return {"action_type": "classify_ticket", "value": "billing_refund"}
if "delete" in text or "deletion" in text or "remove my data" in text or "gdpr" in text or "privacy" in text:
return {"action_type": "classify_ticket", "value": "data_deletion"}
if "login" in text or "access" in text or "locked" in text or "cannot sign in" in text:
return {"action_type": "classify_ticket", "value": "account_access"}
if "double charge" in text or "charged twice" in text or "duplicate charge" in text:
return {"action_type": "classify_ticket", "value": "billing_double_charge"}
if "refund" in text or "duplicate purchase" in text:
return {"action_type": "classify_ticket", "value": "billing_refund"}
return {"action_type": "classify_ticket", "value": "billing_refund"}
category = selected_ticket.get("category")
current_priority = selected_ticket.get("priority")
target_priority = required_priority(category, text, current_tid)
if target_priority is not None and current_priority != target_priority:
return {"action_type": "set_priority", "value": target_priority}
target_team = required_team(category)
if target_team is not None and selected_ticket.get("assigned_team") != target_team:
return {"action_type": "route_ticket", "value": target_team}
target_resolution = required_resolution(category, text, current_tid)
if target_resolution is not None and state.resolutions.get(current_tid) != target_resolution:
return {"action_type": "apply_resolution", "value": target_resolution}
next_tid = find_next_unfinished_ticket()
if next_tid and next_tid != current_tid:
return {"action_type": "open_ticket", "ticket_id": next_tid}
return {"action_type": "apply_resolution", "value": "approve_refund"}
def choose_action_via_llm(client: OpenAI, obs: Any) -> Dict[str, Any]:
visible_tickets, selected_ticket = extract_ticket_context(obs)
payload = {
"screen": getattr(obs, "screen", None),
"visible_tickets": visible_tickets,
"selected_ticket": selected_ticket,
"visible_policy_hits": getattr(obs, "visible_policy_hits", []),
"last_action_result": getattr(obs, "last_action_result", None),
"valid_next_actions": getattr(obs, "valid_next_actions", []),
"remaining_steps": getattr(obs, "remaining_steps", None),
"trajectory_score": getattr(obs, "trajectory_score", None),
}
system_prompt = (
"You are solving a customer support environment. "
"Return exactly one compact JSON object with keys: action_type, ticket_id, value, message. "
"Choose only one next action. "
"Valid action types include open_ticket, classify_ticket, set_priority, route_ticket, apply_resolution. "
"Rules:\n"
"- If no ticket is selected, choose open_ticket with a ticket_id from visible_tickets.\n"
"- For duplicate purchase / refund issues: classify billing_refund, priority medium, route billing, "
"resolution approve_refund unless the text clearly says refund should be denied.\n"
"- For double-charge issues: classify billing_double_charge, priority medium, route billing, "
"resolution request_billing_proof.\n"
"- For access/login/locked account issues: classify account_access, priority urgent, "
"route technical_support, resolution escalate_access_issue.\n"
"- For deletion/privacy/GDPR issues: classify data_deletion, priority high, "
"route privacy_compliance, resolution process_data_deletion.\n"
"- For refund-denial situations, use priority low and resolution deny_refund.\n"
"- Return JSON only, with no markdown and no explanation."
)
response = client.chat.completions.create(
model=MODEL_NAME,
temperature=0,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": json.dumps(payload, ensure_ascii=False)},
],
)
content = (response.choices[0].message.content or "").strip()
start = content.find("{")
end = content.rfind("}")
if start == -1 or end == -1:
raise ValueError("model did not return JSON")
data = json.loads(content[start:end + 1])
return {
"action_type": data["action_type"],
"ticket_id": data.get("ticket_id"),
"value": data.get("value"),
"message": data.get("message"),
}
def run_task(client: OpenAI, task_file: str) -> None:
env = OpenSupportOpsEnv(task_file)
obs = env.reset()
rewards: List[float] = []
steps_taken = 0
score = 0.0
success = False
task_name = task_file.replace(".json", "")
log_start(task=task_name, env=BENCHMARK, model=MODEL_NAME)
try:
max_steps = 25
for step_num in range(1, max_steps + 1):
try:
raw_action = choose_action_via_llm(client, obs)
except Exception:
raw_action = choose_action_fallback(obs, env)
action = SupportAction(**normalize_action(raw_action))
obs, reward, done, info = env.step(action)
reward_value = float(reward.value)
rewards.append(reward_value)
steps_taken = step_num
error = reward.reason if info.get("invalid_action") else None
log_step(
step=step_num,
action=action_to_string(raw_action),
reward=reward_value,
done=done,
error=error,
)
if done:
break
raw_score = float(getattr(obs, "trajectory_score", 0.0))
# clamp score strictly inside (0,1)
score = min(max(raw_score, 0.01), 0.99)
success = raw_score >= 1.0
except Exception as exc:
log_step(
step=steps_taken + 1,
action="exception",
reward=0.00,
done=True,
error=str(exc),
)
success = False
finally:
log_end(success=success, steps=steps_taken, score=score, rewards=rewards)
def main() -> None:
client = build_client()
for task_file in [
"easy_refund.json",
"medium_double_charge.json",
"hard_backlog.json",
]:
run_task(client, task_file)
if __name__ == "__main__":
main() |