Shivoo29 commited on
Commit
2930dae
Β·
0 Parent(s):

first draft

Browse files
Files changed (12) hide show
  1. .gitignore +10 -0
  2. Dockerfile +25 -0
  3. README.md +282 -0
  4. app.py +309 -0
  5. baseline.py +309 -0
  6. data.py +535 -0
  7. environment.py +314 -0
  8. graders.py +397 -0
  9. models.py +211 -0
  10. openenv.yaml +209 -0
  11. requirements.txt +6 -0
  12. setup.md +214 -0
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ .env
5
+ .venv/
6
+ venv/
7
+ *.egg-info/
8
+ dist/
9
+ build/
10
+ .pytest_cache/
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ---------------------------------------------------------------
2
+ # SupportEnv β€” Hugging Face Spaces Dockerfile
3
+ # Space SDK: Docker | Port: 7860
4
+ # ---------------------------------------------------------------
5
+ FROM python:3.11-slim
6
+
7
+ # HF Spaces requirement: non-root user
8
+ RUN useradd -m -u 1000 appuser
9
+
10
+ WORKDIR /app
11
+
12
+ # Install dependencies first (layer caching)
13
+ COPY requirements.txt .
14
+ RUN pip install --no-cache-dir -r requirements.txt
15
+
16
+ # Copy source
17
+ COPY --chown=appuser:appuser . .
18
+
19
+ USER appuser
20
+
21
+ # Expose the port HF Spaces expects
22
+ EXPOSE 7860
23
+
24
+ # Start the FastAPI server
25
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
README.md ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: SupportEnv
3
+ emoji: 🎫
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 7860
8
+ tags:
9
+ - openenv
10
+ - customer-support
11
+ - nlp
12
+ - rl-environment
13
+ - agent-evaluation
14
+ pinned: false
15
+ ---
16
+
17
+ # SupportEnv β€” AI Customer Support Triage Environment
18
+
19
+ An **OpenEnv-compliant** reinforcement-learning environment where agents learn to resolve real-world SaaS customer support tickets.
20
+
21
+ ## Why This Domain?
22
+
23
+ Every software company processes thousands of support tickets daily. Getting the right ticket to the right team with the right priority β€” and generating quality, empathetic responses β€” directly impacts revenue and customer satisfaction. SupportEnv provides a realistic, grounded benchmark for evaluating and training support-automation agents.
24
+
25
+ ---
26
+
27
+ ## Environment Overview
28
+
29
+ **Domain**: SaaS customer support triage
30
+ **Ticket types**: billing disputes, technical failures, account changes, feature requests, compliance requests
31
+ **Dataset**: 15 pre-defined tickets (5 per task) with fully specified ground truth β€” entirely deterministic, no LLM judge needed
32
+
33
+ ---
34
+
35
+ ## Observation Space
36
+
37
+ ```
38
+ Observation
39
+ β”œβ”€β”€ task_id str "task1" | "task2" | "task3"
40
+ β”œβ”€β”€ task_description str Human-readable task description
41
+ β”œβ”€β”€ episode_id str UUID, used in subsequent /step calls
42
+ β”œβ”€β”€ ticket
43
+ β”‚ β”œβ”€β”€ ticket_id str
44
+ β”‚ β”œβ”€β”€ subject str
45
+ β”‚ β”œβ”€β”€ body str
46
+ β”‚ β”œβ”€β”€ customer_tier str "free" | "pro" | "enterprise"
47
+ β”‚ β”œβ”€β”€ account_age_days int
48
+ β”‚ β”œβ”€β”€ previous_tickets int
49
+ β”‚ └── attachments list[str]
50
+ β”œβ”€β”€ thread_history list[dict] Prior agent actions this episode
51
+ β”œβ”€β”€ available_actions list[str] Valid action_type values right now
52
+ β”œβ”€β”€ step_number int
53
+ β”œβ”€β”€ max_steps int
54
+ └── hint str | null Optional step-level guidance
55
+ ```
56
+
57
+ ---
58
+
59
+ ## Action Space
60
+
61
+ All actions share `action_type` (required). Only fields relevant to the chosen type need to be populated.
62
+
63
+ | action_type | Key fields | Used in |
64
+ |-------------|-----------|---------|
65
+ | `classify` | `category`, `priority` | Task 1 |
66
+ | `extract` | `extracted_entities` (dict), `required_actions` (list) | Task 2 |
67
+ | `respond` | `response_text`, `resolution_steps` | Task 3 |
68
+ | `resolve` | `response_text`, `resolution_steps` | Task 3 |
69
+ | `escalate` | `escalation_team`, `escalation_reason` | Task 3 |
70
+ | `submit` | β€” | All tasks |
71
+
72
+ **Category options**: `billing` Β· `technical` Β· `account` Β· `feature_request` Β· `complaint` Β· `general`
73
+ **Priority options**: `low` Β· `medium` Β· `high` Β· `critical`
74
+
75
+ ---
76
+
77
+ ## Tasks
78
+
79
+ ### Task 1 β€” Ticket Classification (Easy)
80
+ **max_steps**: 3
81
+ **Objective**: Assign the correct `category` and `priority` to the ticket.
82
+
83
+ | Criterion | Weight |
84
+ |-----------|--------|
85
+ | Category correct | 0.50 |
86
+ | Priority correct | 0.40 |
87
+ | Efficiency (≀ 2 classify attempts) | 0.10 |
88
+
89
+ Partial credit is awarded for priorities that are one level off, and for category substring matches.
90
+
91
+ ---
92
+
93
+ ### Task 2 β€” Information Extraction (Medium)
94
+ **max_steps**: 5
95
+ **Objective**: Extract all key entities (IDs, names, amounts, dates, domains) and identify the complete list of required actions.
96
+
97
+ | Criterion | Weight |
98
+ |-----------|--------|
99
+ | Entity coverage | 0.60 |
100
+ | Action coverage | 0.30 |
101
+ | No hallucination (≀ 2 extra keys) | 0.10 |
102
+
103
+ Partial credit for values that substring-match or partially overlap the ground truth.
104
+
105
+ ---
106
+
107
+ ### Task 3 β€” Resolution Generation (Hard)
108
+ **max_steps**: 8
109
+ **Objective**: Write a professional customer-facing response and an ordered list of resolution steps that fully address the ticket.
110
+
111
+ | Criterion | Weight |
112
+ |-----------|--------|
113
+ | Required keyword coverage | 0.30 |
114
+ | Resolution step coverage | 0.30 |
115
+ | Tone compliance (apology / urgency / timeline) | 0.25 |
116
+ | Response length β‰₯ minimum word count | 0.10 |
117
+ | No empty/trivial steps | 0.05 |
118
+
119
+ ---
120
+
121
+ ## Reward Function
122
+
123
+ The reward function provides **dense** signal throughout the episode:
124
+
125
+ ```
126
+ step_cost = -0.02 per step (encourages efficiency)
127
+ submit_bonus = +0.05 for explicitly calling submit
128
+ max_step_penalty = -0.10 if episode ends by exhausting max_steps
129
+ grader_bonus = grader_score Γ— 1.0 (0.0–1.0, added at episode end)
130
+ ```
131
+
132
+ This gives agents useful gradient signal even before the episode ends.
133
+
134
+ ---
135
+
136
+ ## API Reference
137
+
138
+ | Method | Endpoint | Description |
139
+ |--------|----------|-------------|
140
+ | `POST` | `/reset` | Start a new episode |
141
+ | `POST` | `/step` | Submit an action |
142
+ | `GET` | `/state` | Get current episode state |
143
+ | `GET` | `/tasks` | List all tasks + action schema |
144
+ | `POST` | `/grader` | Grade a finished episode |
145
+ | `POST` | `/baseline` | Run the heuristic baseline |
146
+ | `GET` | `/health` | Liveness check |
147
+ | `GET` | `/docs` | Interactive Swagger UI |
148
+
149
+ ### Quick example
150
+
151
+ ```python
152
+ import httpx
153
+
154
+ BASE = "http://localhost:7860"
155
+
156
+ # 1. Start episode
157
+ obs = httpx.post(f"{BASE}/reset", json={"task_id": "task1"}).json()
158
+ episode_id = obs["episode_id"]
159
+
160
+ # 2. Classify the ticket
161
+ result = httpx.post(f"{BASE}/step", json={
162
+ "episode_id": episode_id,
163
+ "action": {
164
+ "action_type": "classify",
165
+ "category": "billing",
166
+ "priority": "high"
167
+ }
168
+ }).json()
169
+
170
+ # 3. Submit
171
+ result = httpx.post(f"{BASE}/step", json={
172
+ "episode_id": episode_id,
173
+ "action": {"action_type": "submit"}
174
+ }).json()
175
+
176
+ # 4. Get grader score
177
+ score = httpx.post(f"{BASE}/grader", json={"episode_id": episode_id}).json()
178
+ print(score["score"]) # e.g. 0.9
179
+ ```
180
+
181
+ ---
182
+
183
+ ## Setup & Installation
184
+
185
+ ### Local (Python)
186
+
187
+ ```bash
188
+ git clone <repo-url>
189
+ cd supportenv
190
+ pip install -r requirements.txt
191
+ uvicorn app:app --host 0.0.0.0 --port 7860
192
+ ```
193
+
194
+ ### Docker
195
+
196
+ ```bash
197
+ docker build -t supportenv .
198
+ docker run -p 7860:7860 supportenv
199
+ ```
200
+
201
+ The server will be available at `http://localhost:7860`.
202
+ Interactive docs at `http://localhost:7860/docs`.
203
+
204
+ ---
205
+
206
+ ## Baseline Script
207
+
208
+ ### Heuristic baseline (no API key required)
209
+
210
+ ```bash
211
+ # Single ticket
212
+ python baseline.py --mode heuristic
213
+
214
+ # All tickets, averaged
215
+ python baseline.py --mode heuristic --all-tickets
216
+ ```
217
+
218
+ ### LLM baseline (requires OpenAI API key)
219
+
220
+ ```bash
221
+ export OPENAI_API_KEY="sk-..."
222
+ python baseline.py --mode llm --model gpt-4o-mini
223
+ python baseline.py --mode llm --model gpt-4o-mini --all-tickets
224
+ ```
225
+
226
+ ---
227
+
228
+ ## Baseline Scores (Heuristic β€” fully reproducible, no API key)
229
+
230
+ ### Single ticket (ticket_index=0)
231
+
232
+ | Task | Score |
233
+ |------|-------|
234
+ | task1 β€” Classification (easy) | 1.0000 |
235
+ | task2 β€” Extraction (medium) | 0.8000 |
236
+ | task3 β€” Generation (hard) | 1.0000 |
237
+ | **Average** | **0.9333** |
238
+
239
+ ### Average across all 5 tickets per task
240
+
241
+ | Task | Average Score | Score Range |
242
+ |------|---------------|-------------|
243
+ | task1 β€” Classification (easy) | 0.8600 | 0.30 – 1.00 |
244
+ | task2 β€” Extraction (medium) | 0.5614 | 0.39 – 0.80 |
245
+ | task3 β€” Generation (hard) | 0.9895 | 0.96 – 1.00 |
246
+ | **Overall average** | **0.8036** | |
247
+
248
+ The lower task2 score (0.56 average) demonstrates that the extraction task genuinely challenges pattern-based agents β€” realistic LLMs that understand context score significantly higher.
249
+
250
+ > Scores are fully reproducible β€” run `python baseline.py --all-tickets` to verify.
251
+
252
+ ---
253
+
254
+ ## Project Structure
255
+
256
+ ```
257
+ supportenv/
258
+ β”œβ”€β”€ app.py FastAPI server (all endpoints)
259
+ β”œβ”€β”€ environment.py Episode lifecycle: reset / step / state / grade
260
+ β”œβ”€β”€ graders.py Deterministic graders for all 3 tasks
261
+ β”œβ”€β”€ data.py 15 pre-defined tickets + ground truth
262
+ β”œβ”€β”€ models.py Pydantic typed models
263
+ β”œβ”€β”€ baseline.py Heuristic + LLM baseline inference scripts
264
+ β”œβ”€β”€ openenv.yaml OpenEnv spec metadata
265
+ β”œβ”€β”€ Dockerfile Container (Hugging Face Spaces compatible)
266
+ β”œβ”€β”€ requirements.txt
267
+ └── README.md
268
+ ```
269
+
270
+ ---
271
+
272
+ ## Evaluation & Reproducibility
273
+
274
+ - All 15 tickets are **static** β€” no randomisation between runs
275
+ - Graders are **purely rule-based** β€” no LLM judge, identical results every run
276
+ - The heuristic baseline requires **no external API** β€” scores are fully reproducible
277
+
278
+ ---
279
+
280
+ ## License
281
+
282
+ MIT
app.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SupportEnv β€” FastAPI server
3
+
4
+ Endpoints
5
+ ---------
6
+ POST /reset Create a new episode
7
+ POST /step Advance the episode
8
+ GET /state Current episode state
9
+ GET /tasks List tasks and action schema
10
+ POST /grader Grade a finished episode
11
+ POST /baseline Run the built-in baseline agent on all tasks
12
+ GET /health Liveness check
13
+ GET / Info / spec link
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import subprocess
19
+ import sys
20
+ import tempfile
21
+ from typing import Any, Dict, List, Optional
22
+
23
+ from fastapi import FastAPI, HTTPException, Query
24
+ from fastapi.middleware.cors import CORSMiddleware
25
+ from pydantic import BaseModel
26
+
27
+ import environment as env
28
+ from data import TASK_META
29
+ from models import (
30
+ Action,
31
+ BaselineResult,
32
+ GraderResponse,
33
+ Observation,
34
+ State,
35
+ StepResult,
36
+ TaskInfo,
37
+ )
38
+
39
+ app = FastAPI(
40
+ title="SupportEnv",
41
+ description=(
42
+ "An OpenEnv-compliant customer-support triage environment. "
43
+ "Agents learn to classify, extract information from, and resolve "
44
+ "real-world SaaS support tickets."
45
+ ),
46
+ version="1.0.0",
47
+ docs_url="/docs",
48
+ redoc_url="/redoc",
49
+ )
50
+
51
+ app.add_middleware(
52
+ CORSMiddleware,
53
+ allow_origins=["*"],
54
+ allow_methods=["*"],
55
+ allow_headers=["*"],
56
+ )
57
+
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # Request / response shapes for endpoints not covered by models.py
61
+ # ---------------------------------------------------------------------------
62
+
63
+ class ResetRequest(BaseModel):
64
+ task_id: str
65
+ ticket_index: Optional[int] = None
66
+
67
+
68
+ class StepRequest(BaseModel):
69
+ episode_id: str
70
+ action: Action
71
+
72
+
73
+ class GraderRequest(BaseModel):
74
+ episode_id: str
75
+
76
+
77
+ # ---------------------------------------------------------------------------
78
+ # Endpoints
79
+ # ---------------------------------------------------------------------------
80
+
81
+ @app.get("/", tags=["meta"])
82
+ def root():
83
+ return {
84
+ "name": "SupportEnv",
85
+ "version": "1.0.0",
86
+ "description": "OpenEnv customer-support ticket triage environment",
87
+ "openenv_spec": "https://github.com/openenv/openenv",
88
+ "tasks": list(TASK_META.keys()),
89
+ "endpoints": {
90
+ "reset": "POST /reset",
91
+ "step": "POST /step",
92
+ "state": "GET /state?episode_id=...",
93
+ "tasks": "GET /tasks",
94
+ "grader": "POST /grader",
95
+ "baseline": "POST /baseline",
96
+ "health": "GET /health",
97
+ "docs": "GET /docs",
98
+ },
99
+ }
100
+
101
+
102
+ @app.get("/health", tags=["meta"])
103
+ def health():
104
+ return {"status": "ok"}
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Core OpenEnv endpoints
109
+ # ---------------------------------------------------------------------------
110
+
111
+ @app.post("/reset", response_model=Observation, tags=["openenv"])
112
+ def reset(request: ResetRequest) -> Observation:
113
+ """
114
+ Start a new episode.
115
+
116
+ - **task_id**: `task1` | `task2` | `task3`
117
+ - **ticket_index**: 0-indexed ticket to use (optional; default 0)
118
+ """
119
+ try:
120
+ return env.reset(request.task_id, request.ticket_index)
121
+ except ValueError as e:
122
+ raise HTTPException(status_code=400, detail=str(e))
123
+
124
+
125
+ @app.post("/step", response_model=StepResult, tags=["openenv"])
126
+ def step(request: StepRequest) -> StepResult:
127
+ """
128
+ Submit an action and advance the episode.
129
+
130
+ The `action` object must include `action_type` and the fields relevant
131
+ to that action type (see GET /tasks for the schema).
132
+ """
133
+ try:
134
+ return env.step(request.episode_id, request.action)
135
+ except KeyError:
136
+ raise HTTPException(
137
+ status_code=404,
138
+ detail=f"Episode '{request.episode_id}' not found. Call POST /reset first.",
139
+ )
140
+ except ValueError as e:
141
+ raise HTTPException(status_code=400, detail=str(e))
142
+
143
+
144
+ @app.get("/state", response_model=State, tags=["openenv"])
145
+ def state(episode_id: str = Query(..., description="Episode UUID from POST /reset")) -> State:
146
+ """Return the current state of an episode."""
147
+ try:
148
+ return env.state(episode_id)
149
+ except KeyError:
150
+ raise HTTPException(
151
+ status_code=404,
152
+ detail=f"Episode '{episode_id}' not found.",
153
+ )
154
+
155
+
156
+ # ---------------------------------------------------------------------------
157
+ # /tasks β€” task listing + action schema
158
+ # ---------------------------------------------------------------------------
159
+
160
+ # JSON Schema for the Action model (subset used in each task)
161
+ _BASE_ACTION_SCHEMA = {
162
+ "type": "object",
163
+ "required": ["action_type"],
164
+ "properties": {
165
+ "action_type": {
166
+ "type": "string",
167
+ "description": "One of the available_actions listed in the Observation",
168
+ },
169
+ },
170
+ }
171
+
172
+ _ACTION_SCHEMAS: Dict[str, Dict[str, Any]] = {
173
+ "task1": {
174
+ **_BASE_ACTION_SCHEMA,
175
+ "description": "classify action: set category + priority; then submit",
176
+ "properties": {
177
+ **_BASE_ACTION_SCHEMA["properties"],
178
+ "category": {
179
+ "type": "string",
180
+ "enum": [
181
+ "billing", "technical", "account",
182
+ "feature_request", "complaint", "general",
183
+ ],
184
+ },
185
+ "priority": {
186
+ "type": "string",
187
+ "enum": ["low", "medium", "high", "critical"],
188
+ },
189
+ },
190
+ },
191
+ "task2": {
192
+ **_BASE_ACTION_SCHEMA,
193
+ "description": "extract action: populate extracted_entities + required_actions; then submit",
194
+ "properties": {
195
+ **_BASE_ACTION_SCHEMA["properties"],
196
+ "extracted_entities": {
197
+ "type": "object",
198
+ "additionalProperties": True,
199
+ "description": "Key-value pairs extracted from the ticket text",
200
+ },
201
+ "required_actions": {
202
+ "type": "array",
203
+ "items": {"type": "string"},
204
+ "description": "List of action identifiers (snake_case) needed to close the ticket",
205
+ },
206
+ },
207
+ },
208
+ "task3": {
209
+ **_BASE_ACTION_SCHEMA,
210
+ "description": (
211
+ "respond or resolve action: write response_text + resolution_steps; "
212
+ "optionally escalate; then submit"
213
+ ),
214
+ "properties": {
215
+ **_BASE_ACTION_SCHEMA["properties"],
216
+ "response_text": {
217
+ "type": "string",
218
+ "description": "Full professional response to send to the customer",
219
+ },
220
+ "resolution_steps": {
221
+ "type": "array",
222
+ "items": {"type": "string"},
223
+ "description": "Ordered steps for support staff to resolve the ticket",
224
+ },
225
+ "escalation_team": {
226
+ "type": "string",
227
+ "enum": ["billing_team", "engineering", "account_management", "legal"],
228
+ },
229
+ "escalation_reason": {"type": "string"},
230
+ },
231
+ },
232
+ }
233
+
234
+
235
+ @app.get("/tasks", response_model=List[TaskInfo], tags=["openenv"])
236
+ def list_tasks() -> List[TaskInfo]:
237
+ """Return metadata and action schema for all tasks."""
238
+ result = []
239
+ for task_id, meta in TASK_META.items():
240
+ result.append(
241
+ TaskInfo(
242
+ task_id=task_id,
243
+ name=meta["name"],
244
+ description=meta["description"],
245
+ difficulty=meta["difficulty"],
246
+ max_steps=meta["max_steps"],
247
+ action_schema=_ACTION_SCHEMAS[task_id],
248
+ )
249
+ )
250
+ return result
251
+
252
+
253
+ # ---------------------------------------------------------------------------
254
+ # /grader β€” grade a finished episode
255
+ # ---------------------------------------------------------------------------
256
+
257
+ @app.post("/grader", response_model=GraderResponse, tags=["openenv"])
258
+ def grader(request: GraderRequest) -> GraderResponse:
259
+ """
260
+ Grade a finished episode.
261
+
262
+ The episode must have reached `done=True` (either via a `submit` action
263
+ or by exhausting `max_steps`).
264
+ """
265
+ try:
266
+ return env.grade(request.episode_id)
267
+ except KeyError:
268
+ raise HTTPException(
269
+ status_code=404,
270
+ detail=f"Episode '{request.episode_id}' not found.",
271
+ )
272
+ except ValueError as e:
273
+ raise HTTPException(status_code=400, detail=str(e))
274
+
275
+
276
+ # ---------------------------------------------------------------------------
277
+ # /baseline β€” run the built-in baseline agent
278
+ # ---------------------------------------------------------------------------
279
+
280
+ class BaselineRequest(BaseModel):
281
+ model: str = "gpt-4o-mini"
282
+ ticket_index: Optional[int] = 0
283
+
284
+
285
+ @app.post("/baseline", response_model=BaselineResult, tags=["openenv"])
286
+ def run_baseline(request: BaselineRequest) -> BaselineResult:
287
+ """
288
+ Run the heuristic baseline agent against all three tasks.
289
+
290
+ The built-in baseline does NOT require an OpenAI key β€” it uses the
291
+ deterministic heuristic baseline from `baseline.py`.
292
+ If you want to run the LLM baseline, call `baseline.py` directly.
293
+ """
294
+ try:
295
+ from baseline import run_heuristic_baseline
296
+ scores = run_heuristic_baseline(
297
+ ticket_index=request.ticket_index or 0
298
+ )
299
+ avg = round(sum(s["score"] for s in scores) / len(scores), 4)
300
+ return BaselineResult(
301
+ model="heuristic-baseline",
302
+ scores=[
303
+ {"task_id": s["task_id"], "score": s["score"], "details": s}
304
+ for s in scores
305
+ ],
306
+ average_score=avg,
307
+ )
308
+ except Exception as exc:
309
+ raise HTTPException(status_code=500, detail=str(exc))
baseline.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SupportEnv β€” FastAPI server
3
+
4
+ Endpoints
5
+ ---------
6
+ POST /reset Create a new episode
7
+ POST /step Advance the episode
8
+ GET /state Current episode state
9
+ GET /tasks List tasks and action schema
10
+ POST /grader Grade a finished episode
11
+ POST /baseline Run the built-in baseline agent on all tasks
12
+ GET /health Liveness check
13
+ GET / Info / spec link
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import os
18
+ import subprocess
19
+ import sys
20
+ import tempfile
21
+ from typing import Any, Dict, List, Optional
22
+
23
+ from fastapi import FastAPI, HTTPException, Query
24
+ from fastapi.middleware.cors import CORSMiddleware
25
+ from pydantic import BaseModel
26
+
27
+ import environment as env
28
+ from data import TASK_META
29
+ from models import (
30
+ Action,
31
+ BaselineResult,
32
+ GraderResponse,
33
+ Observation,
34
+ State,
35
+ StepResult,
36
+ TaskInfo,
37
+ )
38
+
39
+ app = FastAPI(
40
+ title="SupportEnv",
41
+ description=(
42
+ "An OpenEnv-compliant customer-support triage environment. "
43
+ "Agents learn to classify, extract information from, and resolve "
44
+ "real-world SaaS support tickets."
45
+ ),
46
+ version="1.0.0",
47
+ docs_url="/docs",
48
+ redoc_url="/redoc",
49
+ )
50
+
51
+ app.add_middleware(
52
+ CORSMiddleware,
53
+ allow_origins=["*"],
54
+ allow_methods=["*"],
55
+ allow_headers=["*"],
56
+ )
57
+
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # Request / response shapes for endpoints not covered by models.py
61
+ # ---------------------------------------------------------------------------
62
+
63
+ class ResetRequest(BaseModel):
64
+ task_id: str
65
+ ticket_index: Optional[int] = None
66
+
67
+
68
+ class StepRequest(BaseModel):
69
+ episode_id: str
70
+ action: Action
71
+
72
+
73
+ class GraderRequest(BaseModel):
74
+ episode_id: str
75
+
76
+
77
+ # ---------------------------------------------------------------------------
78
+ # Endpoints
79
+ # ---------------------------------------------------------------------------
80
+
81
+ @app.get("/", tags=["meta"])
82
+ def root():
83
+ return {
84
+ "name": "SupportEnv",
85
+ "version": "1.0.0",
86
+ "description": "OpenEnv customer-support ticket triage environment",
87
+ "openenv_spec": "https://github.com/openenv/openenv",
88
+ "tasks": list(TASK_META.keys()),
89
+ "endpoints": {
90
+ "reset": "POST /reset",
91
+ "step": "POST /step",
92
+ "state": "GET /state?episode_id=...",
93
+ "tasks": "GET /tasks",
94
+ "grader": "POST /grader",
95
+ "baseline": "POST /baseline",
96
+ "health": "GET /health",
97
+ "docs": "GET /docs",
98
+ },
99
+ }
100
+
101
+
102
+ @app.get("/health", tags=["meta"])
103
+ def health():
104
+ return {"status": "ok"}
105
+
106
+
107
+ # ---------------------------------------------------------------------------
108
+ # Core OpenEnv endpoints
109
+ # ---------------------------------------------------------------------------
110
+
111
+ @app.post("/reset", response_model=Observation, tags=["openenv"])
112
+ def reset(request: ResetRequest) -> Observation:
113
+ """
114
+ Start a new episode.
115
+
116
+ - **task_id**: `task1` | `task2` | `task3`
117
+ - **ticket_index**: 0-indexed ticket to use (optional; default 0)
118
+ """
119
+ try:
120
+ return env.reset(request.task_id, request.ticket_index)
121
+ except ValueError as e:
122
+ raise HTTPException(status_code=400, detail=str(e))
123
+
124
+
125
+ @app.post("/step", response_model=StepResult, tags=["openenv"])
126
+ def step(request: StepRequest) -> StepResult:
127
+ """
128
+ Submit an action and advance the episode.
129
+
130
+ The `action` object must include `action_type` and the fields relevant
131
+ to that action type (see GET /tasks for the schema).
132
+ """
133
+ try:
134
+ return env.step(request.episode_id, request.action)
135
+ except KeyError:
136
+ raise HTTPException(
137
+ status_code=404,
138
+ detail=f"Episode '{request.episode_id}' not found. Call POST /reset first.",
139
+ )
140
+ except ValueError as e:
141
+ raise HTTPException(status_code=400, detail=str(e))
142
+
143
+
144
+ @app.get("/state", response_model=State, tags=["openenv"])
145
+ def state(episode_id: str = Query(..., description="Episode UUID from POST /reset")) -> State:
146
+ """Return the current state of an episode."""
147
+ try:
148
+ return env.state(episode_id)
149
+ except KeyError:
150
+ raise HTTPException(
151
+ status_code=404,
152
+ detail=f"Episode '{episode_id}' not found.",
153
+ )
154
+
155
+
156
+ # ---------------------------------------------------------------------------
157
+ # /tasks β€” task listing + action schema
158
+ # ---------------------------------------------------------------------------
159
+
160
+ # JSON Schema for the Action model (subset used in each task)
161
+ _BASE_ACTION_SCHEMA = {
162
+ "type": "object",
163
+ "required": ["action_type"],
164
+ "properties": {
165
+ "action_type": {
166
+ "type": "string",
167
+ "description": "One of the available_actions listed in the Observation",
168
+ },
169
+ },
170
+ }
171
+
172
+ _ACTION_SCHEMAS: Dict[str, Dict[str, Any]] = {
173
+ "task1": {
174
+ **_BASE_ACTION_SCHEMA,
175
+ "description": "classify action: set category + priority; then submit",
176
+ "properties": {
177
+ **_BASE_ACTION_SCHEMA["properties"],
178
+ "category": {
179
+ "type": "string",
180
+ "enum": [
181
+ "billing", "technical", "account",
182
+ "feature_request", "complaint", "general",
183
+ ],
184
+ },
185
+ "priority": {
186
+ "type": "string",
187
+ "enum": ["low", "medium", "high", "critical"],
188
+ },
189
+ },
190
+ },
191
+ "task2": {
192
+ **_BASE_ACTION_SCHEMA,
193
+ "description": "extract action: populate extracted_entities + required_actions; then submit",
194
+ "properties": {
195
+ **_BASE_ACTION_SCHEMA["properties"],
196
+ "extracted_entities": {
197
+ "type": "object",
198
+ "additionalProperties": True,
199
+ "description": "Key-value pairs extracted from the ticket text",
200
+ },
201
+ "required_actions": {
202
+ "type": "array",
203
+ "items": {"type": "string"},
204
+ "description": "List of action identifiers (snake_case) needed to close the ticket",
205
+ },
206
+ },
207
+ },
208
+ "task3": {
209
+ **_BASE_ACTION_SCHEMA,
210
+ "description": (
211
+ "respond or resolve action: write response_text + resolution_steps; "
212
+ "optionally escalate; then submit"
213
+ ),
214
+ "properties": {
215
+ **_BASE_ACTION_SCHEMA["properties"],
216
+ "response_text": {
217
+ "type": "string",
218
+ "description": "Full professional response to send to the customer",
219
+ },
220
+ "resolution_steps": {
221
+ "type": "array",
222
+ "items": {"type": "string"},
223
+ "description": "Ordered steps for support staff to resolve the ticket",
224
+ },
225
+ "escalation_team": {
226
+ "type": "string",
227
+ "enum": ["billing_team", "engineering", "account_management", "legal"],
228
+ },
229
+ "escalation_reason": {"type": "string"},
230
+ },
231
+ },
232
+ }
233
+
234
+
235
+ @app.get("/tasks", response_model=List[TaskInfo], tags=["openenv"])
236
+ def list_tasks() -> List[TaskInfo]:
237
+ """Return metadata and action schema for all tasks."""
238
+ result = []
239
+ for task_id, meta in TASK_META.items():
240
+ result.append(
241
+ TaskInfo(
242
+ task_id=task_id,
243
+ name=meta["name"],
244
+ description=meta["description"],
245
+ difficulty=meta["difficulty"],
246
+ max_steps=meta["max_steps"],
247
+ action_schema=_ACTION_SCHEMAS[task_id],
248
+ )
249
+ )
250
+ return result
251
+
252
+
253
+ # ---------------------------------------------------------------------------
254
+ # /grader β€” grade a finished episode
255
+ # ---------------------------------------------------------------------------
256
+
257
+ @app.post("/grader", response_model=GraderResponse, tags=["openenv"])
258
+ def grader(request: GraderRequest) -> GraderResponse:
259
+ """
260
+ Grade a finished episode.
261
+
262
+ The episode must have reached `done=True` (either via a `submit` action
263
+ or by exhausting `max_steps`).
264
+ """
265
+ try:
266
+ return env.grade(request.episode_id)
267
+ except KeyError:
268
+ raise HTTPException(
269
+ status_code=404,
270
+ detail=f"Episode '{request.episode_id}' not found.",
271
+ )
272
+ except ValueError as e:
273
+ raise HTTPException(status_code=400, detail=str(e))
274
+
275
+
276
+ # ---------------------------------------------------------------------------
277
+ # /baseline β€” run the built-in baseline agent
278
+ # ---------------------------------------------------------------------------
279
+
280
+ class BaselineRequest(BaseModel):
281
+ model: str = "gpt-4o-mini"
282
+ ticket_index: Optional[int] = 0
283
+
284
+
285
+ @app.post("/baseline", response_model=BaselineResult, tags=["openenv"])
286
+ def run_baseline(request: BaselineRequest) -> BaselineResult:
287
+ """
288
+ Run the heuristic baseline agent against all three tasks.
289
+
290
+ The built-in baseline does NOT require an OpenAI key β€” it uses the
291
+ deterministic heuristic baseline from `baseline.py`.
292
+ If you want to run the LLM baseline, call `baseline.py` directly.
293
+ """
294
+ try:
295
+ from baseline import run_heuristic_baseline
296
+ scores = run_heuristic_baseline(
297
+ ticket_index=request.ticket_index or 0
298
+ )
299
+ avg = round(sum(s["score"] for s in scores) / len(scores), 4)
300
+ return BaselineResult(
301
+ model="heuristic-baseline",
302
+ scores=[
303
+ {"task_id": s["task_id"], "score": s["score"], "details": s}
304
+ for s in scores
305
+ ],
306
+ average_score=avg,
307
+ )
308
+ except Exception as exc:
309
+ raise HTTPException(status_code=500, detail=str(exc))
data.py ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pre-defined customer support tickets for each task.
3
+
4
+ Each ticket has fully specified ground-truth answers so that graders
5
+ are entirely deterministic β€” no LLM judge required.
6
+
7
+ Task 1 (easy) β€” Ticket Classification
8
+ Task 2 (medium) β€” Information Extraction
9
+ Task 3 (hard) β€” Resolution Generation
10
+ """
11
+ from __future__ import annotations
12
+ from typing import Any, Dict, List
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # TASK 1 β€” Ticket Classification
16
+ # Agent must choose: category + priority
17
+ # Categories: billing | technical | account | feature_request | complaint | general
18
+ # Priorities: low | medium | high | critical
19
+ # ---------------------------------------------------------------------------
20
+
21
+ TASK1_TICKETS: List[Dict[str, Any]] = [
22
+ {
23
+ "ticket_id": "T1-001",
24
+ "subject": "Double-charged on my Pro subscription this month",
25
+ "body": (
26
+ "Hi, I noticed I was billed $49.99 twice on my credit card "
27
+ "on March 3rd for my Pro subscription. My account email is "
28
+ "alice@example.com. This is really frustrating β€” please issue "
29
+ "a refund for the duplicate charge as soon as possible."
30
+ ),
31
+ "customer_tier": "pro",
32
+ "account_age_days": 420,
33
+ "previous_tickets": 0,
34
+ "attachments": [],
35
+ "ground_truth": {
36
+ "category": "billing",
37
+ "priority": "high",
38
+ },
39
+ },
40
+ {
41
+ "ticket_id": "T1-002",
42
+ "subject": "API rate limit keeps hitting 429 even though we're Enterprise",
43
+ "body": (
44
+ "Our production service has been receiving HTTP 429 errors from "
45
+ "your API for the past 2 hours. We're on the Enterprise plan which "
46
+ "should give us 10 000 req/min. Current usage is ~3 000 req/min "
47
+ "so we're well within limits. This is causing a production outage "
48
+ "for our customers. Ticket urgency: CRITICAL."
49
+ ),
50
+ "customer_tier": "enterprise",
51
+ "account_age_days": 730,
52
+ "previous_tickets": 3,
53
+ "attachments": ["rate_limit_screenshot.png"],
54
+ "ground_truth": {
55
+ "category": "technical",
56
+ "priority": "critical",
57
+ },
58
+ },
59
+ {
60
+ "ticket_id": "T1-003",
61
+ "subject": "Can I change my account email address?",
62
+ "body": (
63
+ "Hello, I recently changed jobs and want to update the email "
64
+ "associated with my account from oldname@corp.com to "
65
+ "newname@newcorp.com. Can you walk me through how to do this? "
66
+ "There's no rush β€” just want to get it sorted at some point."
67
+ ),
68
+ "customer_tier": "free",
69
+ "account_age_days": 60,
70
+ "previous_tickets": 0,
71
+ "attachments": [],
72
+ "ground_truth": {
73
+ "category": "account",
74
+ "priority": "low",
75
+ },
76
+ },
77
+ {
78
+ "ticket_id": "T1-004",
79
+ "subject": "Would love a dark mode option in the dashboard",
80
+ "body": (
81
+ "Hi team, long-time Pro user here. I spend a lot of time in the "
82
+ "dashboard and it would be fantastic if you could add a dark mode "
83
+ "toggle. Many other SaaS tools have this now and it really reduces "
84
+ "eye strain. Would be great to see this in a future release!"
85
+ ),
86
+ "customer_tier": "pro",
87
+ "account_age_days": 900,
88
+ "previous_tickets": 1,
89
+ "attachments": [],
90
+ "ground_truth": {
91
+ "category": "feature_request",
92
+ "priority": "low",
93
+ },
94
+ },
95
+ {
96
+ "ticket_id": "T1-005",
97
+ "subject": "Your customer service is absolutely terrible",
98
+ "body": (
99
+ "I submitted a ticket three weeks ago about a bug in your export "
100
+ "feature and nobody has responded. This is completely unacceptable. "
101
+ "I am paying for a Pro subscription and I expect timely support. "
102
+ "If this is not resolved in 48 hours I will be requesting a full "
103
+ "refund and posting a review online."
104
+ ),
105
+ "customer_tier": "pro",
106
+ "account_age_days": 200,
107
+ "previous_tickets": 2,
108
+ "attachments": [],
109
+ "ground_truth": {
110
+ "category": "complaint",
111
+ "priority": "high",
112
+ },
113
+ },
114
+ ]
115
+
116
+ # ---------------------------------------------------------------------------
117
+ # TASK 2 β€” Information Extraction
118
+ # Agent must populate extracted_entities and required_actions.
119
+ # Ground truth defines exact entity keys and accepted values.
120
+ # ---------------------------------------------------------------------------
121
+
122
+ TASK2_TICKETS: List[Dict[str, Any]] = [
123
+ {
124
+ "ticket_id": "T2-001",
125
+ "subject": "Refund request – incorrect charge on invoice #INV-20240312",
126
+ "body": (
127
+ "Dear Support, I was incorrectly charged $199.00 on invoice "
128
+ "#INV-20240312 dated 2024-03-12. My account ID is ACC-78234. "
129
+ "The charge should have been $99.00 as per our agreed annual plan. "
130
+ "Please issue a refund of $100.00 to my card on file and send a "
131
+ "corrected invoice. My name is Robert Chen."
132
+ ),
133
+ "customer_tier": "pro",
134
+ "account_age_days": 540,
135
+ "previous_tickets": 1,
136
+ "attachments": ["invoice_INV-20240312.pdf"],
137
+ "ground_truth": {
138
+ "entities": {
139
+ "customer_name": "Robert Chen",
140
+ "account_id": "ACC-78234",
141
+ "invoice_number": "INV-20240312",
142
+ "incorrect_amount": "199.00",
143
+ "correct_amount": "99.00",
144
+ "refund_amount": "100.00",
145
+ },
146
+ "required_actions": [
147
+ "issue_refund",
148
+ "send_corrected_invoice",
149
+ ],
150
+ },
151
+ },
152
+ {
153
+ "ticket_id": "T2-002",
154
+ "subject": "SSO login broken after company domain migration",
155
+ "body": (
156
+ "Hi, our company just migrated from acme-old.com to acme-new.com. "
157
+ "Since the migration last Tuesday (2024-03-19), our 45 users cannot "
158
+ "log in via SSO. The error message is: 'SAML assertion domain "
159
+ "mismatch'. Our org ID is ORG-5512. We need this fixed ASAP as "
160
+ "nobody can access the platform. Contact: Maria Gonzalez, "
161
+ "IT Director."
162
+ ),
163
+ "customer_tier": "enterprise",
164
+ "account_age_days": 1100,
165
+ "previous_tickets": 5,
166
+ "attachments": [],
167
+ "ground_truth": {
168
+ "entities": {
169
+ "contact_name": "Maria Gonzalez",
170
+ "contact_role": "IT Director",
171
+ "org_id": "ORG-5512",
172
+ "old_domain": "acme-old.com",
173
+ "new_domain": "acme-new.com",
174
+ "error_message": "SAML assertion domain mismatch",
175
+ "affected_users": "45",
176
+ },
177
+ "required_actions": [
178
+ "update_sso_domain_config",
179
+ "verify_saml_settings",
180
+ "notify_affected_users",
181
+ ],
182
+ },
183
+ },
184
+ {
185
+ "ticket_id": "T2-003",
186
+ "subject": "Need to add 3 seats to our Team plan before end of quarter",
187
+ "body": (
188
+ "Hello, I'm the account admin for Brightfield Analytics "
189
+ "(account: ACC-11099). We currently have 12 seats on Team plan "
190
+ "and need to add 3 more seats before March 31st (end of our fiscal "
191
+ "quarter). The 3 new team members are: "
192
+ "dev1@brightfield.io, dev2@brightfield.io, dev3@brightfield.io. "
193
+ "Please prorate the cost. β€” James Park, VP Engineering"
194
+ ),
195
+ "customer_tier": "pro",
196
+ "account_age_days": 820,
197
+ "previous_tickets": 3,
198
+ "attachments": [],
199
+ "ground_truth": {
200
+ "entities": {
201
+ "contact_name": "James Park",
202
+ "contact_role": "VP Engineering",
203
+ "account_id": "ACC-11099",
204
+ "company_name": "Brightfield Analytics",
205
+ "current_seats": "12",
206
+ "seats_to_add": "3",
207
+ "deadline": "March 31st",
208
+ "new_users": [
209
+ "dev1@brightfield.io",
210
+ "dev2@brightfield.io",
211
+ "dev3@brightfield.io",
212
+ ],
213
+ },
214
+ "required_actions": [
215
+ "add_seats",
216
+ "send_prorated_invoice",
217
+ "provision_new_users",
218
+ ],
219
+ },
220
+ },
221
+ {
222
+ "ticket_id": "T2-004",
223
+ "subject": "Data export stuck at 0% for 6 hours – export ID EXP-990021",
224
+ "body": (
225
+ "Our scheduled data export (ID: EXP-990021) has been stuck at 0% "
226
+ "for over 6 hours. This export contains 90 days of transaction "
227
+ "data for our compliance report due tomorrow. Account: ACC-30041, "
228
+ "region: eu-west-1. We need this export completed or the raw data "
229
+ "sent via secure link by 09:00 UTC tomorrow. If the export cannot "
230
+ "be fixed, please escalate to engineering. β€” Priya Sharma"
231
+ ),
232
+ "customer_tier": "enterprise",
233
+ "account_age_days": 650,
234
+ "previous_tickets": 7,
235
+ "attachments": [],
236
+ "ground_truth": {
237
+ "entities": {
238
+ "contact_name": "Priya Sharma",
239
+ "export_id": "EXP-990021",
240
+ "account_id": "ACC-30041",
241
+ "region": "eu-west-1",
242
+ "data_range": "90 days",
243
+ "deadline": "09:00 UTC tomorrow",
244
+ },
245
+ "required_actions": [
246
+ "investigate_export_job",
247
+ "fix_or_restart_export",
248
+ "escalate_to_engineering",
249
+ ],
250
+ },
251
+ },
252
+ {
253
+ "ticket_id": "T2-005",
254
+ "subject": "GDPR deletion request for former employee account",
255
+ "body": (
256
+ "We need to permanently delete all data associated with a former "
257
+ "employee's account as per GDPR Article 17 (right to erasure). "
258
+ "The account to delete: user ID USR-88821, email "
259
+ "j.doe@departed.co.uk. Our DPO is Claire Lambert "
260
+ "(dpo@ourenterprise.com). Legal reference: GDPR-REQ-2024-03. "
261
+ "Please confirm deletion in writing within 30 days. "
262
+ "Org ID: ORG-7740."
263
+ ),
264
+ "customer_tier": "enterprise",
265
+ "account_age_days": 1400,
266
+ "previous_tickets": 2,
267
+ "attachments": ["gdpr_deletion_form.pdf"],
268
+ "ground_truth": {
269
+ "entities": {
270
+ "user_id": "USR-88821",
271
+ "user_email": "j.doe@departed.co.uk",
272
+ "org_id": "ORG-7740",
273
+ "dpo_name": "Claire Lambert",
274
+ "dpo_email": "dpo@ourenterprise.com",
275
+ "legal_reference": "GDPR-REQ-2024-03",
276
+ "legal_basis": "GDPR Article 17",
277
+ },
278
+ "required_actions": [
279
+ "delete_user_data",
280
+ "send_written_confirmation",
281
+ "log_gdpr_request",
282
+ ],
283
+ },
284
+ },
285
+ ]
286
+
287
+ # ---------------------------------------------------------------------------
288
+ # TASK 3 β€” Resolution Generation
289
+ # Agent must submit a response_text + resolution_steps.
290
+ # Ground truth contains required keywords and accepted resolution steps.
291
+ # Scoring is deterministic (keyword matching + step coverage).
292
+ # ---------------------------------------------------------------------------
293
+
294
+ TASK3_TICKETS: List[Dict[str, Any]] = [
295
+ {
296
+ "ticket_id": "T3-001",
297
+ "subject": "Cannot reset my password β€” reset email never arrives",
298
+ "body": (
299
+ "Hi, I've tried resetting my password 5 times today but the reset "
300
+ "email never arrives. I've checked my spam folder. My account email "
301
+ "is user@example.com. I need access to my account urgently as I "
302
+ "have a demo with a client in 2 hours."
303
+ ),
304
+ "customer_tier": "pro",
305
+ "account_age_days": 280,
306
+ "previous_tickets": 0,
307
+ "attachments": [],
308
+ "ground_truth": {
309
+ "required_keywords": [
310
+ "password",
311
+ "reset",
312
+ "email",
313
+ "spam",
314
+ "whitelist",
315
+ ],
316
+ "required_resolution_steps": [
317
+ "verify_email_delivery",
318
+ "check_spam_filters",
319
+ "manual_password_reset",
320
+ "follow_up_confirmation",
321
+ ],
322
+ "tone_requirements": {
323
+ "must_apologize": True,
324
+ "must_acknowledge_urgency": True,
325
+ "must_provide_timeline": True,
326
+ },
327
+ "expected_response_length_min": 80,
328
+ },
329
+ },
330
+ {
331
+ "ticket_id": "T3-002",
332
+ "subject": "Webhook payloads stopped arriving after updating secret key",
333
+ "body": (
334
+ "We updated our webhook secret key yesterday in the dashboard and "
335
+ "now none of our webhook endpoints are receiving payloads. Our "
336
+ "endpoint is https://hooks.our-app.com/receive. We've verified the "
337
+ "endpoint is up and responding 200. It seems like the new secret "
338
+ "is not being used to sign payloads. Account: ACC-50039."
339
+ ),
340
+ "customer_tier": "pro",
341
+ "account_age_days": 510,
342
+ "previous_tickets": 4,
343
+ "attachments": [],
344
+ "ground_truth": {
345
+ "required_keywords": [
346
+ "webhook",
347
+ "secret",
348
+ "signature",
349
+ "HMAC",
350
+ "regenerate",
351
+ ],
352
+ "required_resolution_steps": [
353
+ "verify_webhook_config",
354
+ "regenerate_webhook_secret",
355
+ "update_endpoint_verification",
356
+ "test_delivery",
357
+ ],
358
+ "tone_requirements": {
359
+ "must_apologize": False,
360
+ "must_acknowledge_urgency": False,
361
+ "must_provide_timeline": True,
362
+ },
363
+ "expected_response_length_min": 100,
364
+ },
365
+ },
366
+ {
367
+ "ticket_id": "T3-003",
368
+ "subject": "Annual invoice shows wrong VAT number β€” urgent for accounting",
369
+ "body": (
370
+ "Our annual invoice (INV-2024-ANN-00567) shows VAT number "
371
+ "DE123456789 but our correct VAT number is DE987654321. This "
372
+ "invoice needs to be corrected immediately as our accounting team "
373
+ "needs it for Q1 closing (deadline: end of today). "
374
+ "Company: MΓΌller GmbH, Account: ACC-20987."
375
+ ),
376
+ "customer_tier": "enterprise",
377
+ "account_age_days": 1200,
378
+ "previous_tickets": 8,
379
+ "attachments": [],
380
+ "ground_truth": {
381
+ "required_keywords": [
382
+ "VAT",
383
+ "invoice",
384
+ "corrected",
385
+ "accounting",
386
+ "reissue",
387
+ ],
388
+ "required_resolution_steps": [
389
+ "update_vat_number",
390
+ "reissue_invoice",
391
+ "send_corrected_invoice",
392
+ "confirm_receipt",
393
+ ],
394
+ "tone_requirements": {
395
+ "must_apologize": True,
396
+ "must_acknowledge_urgency": True,
397
+ "must_provide_timeline": True,
398
+ },
399
+ "expected_response_length_min": 80,
400
+ },
401
+ },
402
+ {
403
+ "ticket_id": "T3-004",
404
+ "subject": "Team member accidentally deleted our production dataset",
405
+ "body": (
406
+ "One of our team members accidentally deleted dataset "
407
+ "DS-PROD-77. This dataset had 6 months of customer analytics data "
408
+ "that we haven't backed up externally. Is there any way to restore "
409
+ "it? We are on Enterprise plan. Org: ORG-3302. Please help "
410
+ "immediately β€” this data is critical for our quarterly review."
411
+ ),
412
+ "customer_tier": "enterprise",
413
+ "account_age_days": 960,
414
+ "previous_tickets": 2,
415
+ "attachments": [],
416
+ "ground_truth": {
417
+ "required_keywords": [
418
+ "restore",
419
+ "backup",
420
+ "recovery",
421
+ "dataset",
422
+ "retention",
423
+ ],
424
+ "required_resolution_steps": [
425
+ "check_retention_policy",
426
+ "attempt_data_recovery",
427
+ "escalate_to_engineering",
428
+ "provide_recovery_status",
429
+ ],
430
+ "tone_requirements": {
431
+ "must_apologize": True,
432
+ "must_acknowledge_urgency": True,
433
+ "must_provide_timeline": True,
434
+ },
435
+ "expected_response_length_min": 100,
436
+ },
437
+ },
438
+ {
439
+ "ticket_id": "T3-005",
440
+ "subject": "Need formal SLA documentation for enterprise procurement",
441
+ "body": (
442
+ "Our procurement team is finalizing contracts and requires formal "
443
+ "SLA documentation for your Enterprise plan. Specifically we need: "
444
+ "uptime guarantee percentage, support response time commitments, "
445
+ "incident severity classification, and escalation procedures. "
446
+ "Contact: procurement@bigcorp.io. Org: ORG-8855."
447
+ ),
448
+ "customer_tier": "enterprise",
449
+ "account_age_days": 30,
450
+ "previous_tickets": 0,
451
+ "attachments": [],
452
+ "ground_truth": {
453
+ "required_keywords": [
454
+ "SLA",
455
+ "uptime",
456
+ "response time",
457
+ "documentation",
458
+ "enterprise",
459
+ ],
460
+ "required_resolution_steps": [
461
+ "provide_sla_document",
462
+ "highlight_enterprise_terms",
463
+ "connect_with_account_manager",
464
+ "confirm_receipt",
465
+ ],
466
+ "tone_requirements": {
467
+ "must_apologize": False,
468
+ "must_acknowledge_urgency": False,
469
+ "must_provide_timeline": True,
470
+ },
471
+ "expected_response_length_min": 80,
472
+ },
473
+ },
474
+ ]
475
+
476
+ # ---------------------------------------------------------------------------
477
+ # Task-level metadata
478
+ # ---------------------------------------------------------------------------
479
+
480
+ TASK_META: Dict[str, Dict[str, Any]] = {
481
+ "task1": {
482
+ "name": "Ticket Classification",
483
+ "description": (
484
+ "Classify each support ticket by category and priority. "
485
+ "Correct classification routes the ticket to the right team and "
486
+ "sets appropriate response SLAs."
487
+ ),
488
+ "difficulty": "easy",
489
+ "max_steps": 3,
490
+ "tickets": TASK1_TICKETS,
491
+ "available_actions": ["classify", "submit"],
492
+ },
493
+ "task2": {
494
+ "name": "Information Extraction",
495
+ "description": (
496
+ "Extract structured entities (IDs, names, amounts, dates) from "
497
+ "tickets and identify the list of required actions needed to "
498
+ "resolve each case. Accuracy drives downstream automation."
499
+ ),
500
+ "difficulty": "medium",
501
+ "max_steps": 5,
502
+ "tickets": TASK2_TICKETS,
503
+ "available_actions": ["extract", "respond", "submit"],
504
+ },
505
+ "task3": {
506
+ "name": "Resolution Generation",
507
+ "description": (
508
+ "Generate a complete, professional customer-facing response "
509
+ "plus an ordered list of resolution steps for each ticket. "
510
+ "Responses are graded on keyword coverage, step completeness, "
511
+ "tone adherence, and minimum length."
512
+ ),
513
+ "difficulty": "hard",
514
+ "max_steps": 8,
515
+ "tickets": TASK3_TICKETS,
516
+ "available_actions": ["respond", "resolve", "escalate", "submit"],
517
+ },
518
+ }
519
+
520
+
521
+ def get_tickets(task_id: str) -> List[Dict[str, Any]]:
522
+ """Return the ticket list for a given task."""
523
+ return TASK_META[task_id]["tickets"]
524
+
525
+
526
+ def get_task_meta(task_id: str) -> Dict[str, Any]:
527
+ """Return task metadata (without ticket ground truth exposed to agent)."""
528
+ meta = dict(TASK_META[task_id])
529
+ # Strip ground_truth from tickets before returning to agents
530
+ safe_tickets = []
531
+ for t in meta["tickets"]:
532
+ safe_t = {k: v for k, v in t.items() if k != "ground_truth"}
533
+ safe_tickets.append(safe_t)
534
+ meta["tickets"] = safe_tickets
535
+ return meta
environment.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Core SupportEnv environment logic.
3
+
4
+ Manages episode lifecycle:
5
+ reset() β†’ Observation
6
+ step(action) β†’ StepResult
7
+ state() β†’ State
8
+ grade() β†’ GraderResponse
9
+
10
+ Sessions are stored in-memory (dict keyed by episode_id).
11
+ For multi-replica deployments replace with Redis or a database.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import uuid
16
+ from typing import Any, Dict, Optional
17
+
18
+ from data import TASK_META, get_tickets
19
+ from graders import grade_episode
20
+ from models import (
21
+ Action,
22
+ GraderResponse,
23
+ Observation,
24
+ Reward,
25
+ State,
26
+ StepResult,
27
+ TicketInfo,
28
+ )
29
+
30
+ # In-memory store: episode_id β†’ EpisodeState dict
31
+ _EPISODES: Dict[str, Dict[str, Any]] = {}
32
+
33
+
34
+ # ---------------------------------------------------------------------------
35
+ # Step-level reward helpers
36
+ # ---------------------------------------------------------------------------
37
+
38
+ _STEP_COST = -0.02 # small cost per step to discourage wasted steps
39
+ _SUBMIT_REWARD = 0.05 # small bonus for explicitly submitting
40
+ _MAX_STEP_PENALTY = -0.10 # penalty for hitting max_steps without submitting
41
+
42
+
43
+ def _step_reward_task1(action: Action, done: bool) -> tuple[float, str]:
44
+ """Immediate step reward for task1 episodes."""
45
+ if action.action_type == "classify":
46
+ if action.category and action.priority:
47
+ return 0.05, "Classify action with both fields set."
48
+ return 0.02, "Classify action (partial β€” missing category or priority)."
49
+ if action.action_type == "submit":
50
+ return _SUBMIT_REWARD, "Episode submitted."
51
+ return _STEP_COST, f"Action '{action.action_type}' not primary for this task."
52
+
53
+
54
+ def _step_reward_task2(action: Action, done: bool) -> tuple[float, str]:
55
+ """Immediate step reward for task2 episodes."""
56
+ if action.action_type == "extract":
57
+ n_entities = len(action.extracted_entities or {})
58
+ n_actions = len(action.required_actions or [])
59
+ reward = min(n_entities * 0.01 + n_actions * 0.02, 0.15)
60
+ return reward, f"Extracted {n_entities} entities, {n_actions} actions."
61
+ if action.action_type == "submit":
62
+ return _SUBMIT_REWARD, "Episode submitted."
63
+ return _STEP_COST, f"Action '{action.action_type}' not primary for this task."
64
+
65
+
66
+ def _step_reward_task3(action: Action, done: bool) -> tuple[float, str]:
67
+ """Immediate step reward for task3 episodes."""
68
+ if action.action_type in ("respond", "resolve"):
69
+ text_len = len((action.response_text or "").split())
70
+ steps_n = len(action.resolution_steps or [])
71
+ reward = min(text_len * 0.001 + steps_n * 0.02, 0.20)
72
+ return reward, f"Response: {text_len} words, {steps_n} steps."
73
+ if action.action_type == "escalate":
74
+ return 0.03, "Escalation action recorded."
75
+ if action.action_type == "submit":
76
+ return _SUBMIT_REWARD, "Episode submitted."
77
+ return _STEP_COST, f"Action '{action.action_type}' not primary for this task."
78
+
79
+
80
+ _STEP_REWARD_FNS = {
81
+ "task1": _step_reward_task1,
82
+ "task2": _step_reward_task2,
83
+ "task3": _step_reward_task3,
84
+ }
85
+
86
+
87
+ # ---------------------------------------------------------------------------
88
+ # Public API
89
+ # ---------------------------------------------------------------------------
90
+
91
+ def reset(task_id: str, ticket_index: Optional[int] = None) -> Observation:
92
+ """
93
+ Create a new episode for the given task.
94
+
95
+ Args:
96
+ task_id: "task1" | "task2" | "task3"
97
+ ticket_index: which ticket to use (0-based); if None, defaults to 0.
98
+
99
+ Returns the initial Observation.
100
+ """
101
+ if task_id not in TASK_META:
102
+ raise ValueError(f"Unknown task_id {task_id!r}. Valid: {list(TASK_META)}")
103
+
104
+ meta = TASK_META[task_id]
105
+ tickets = get_tickets(task_id)
106
+ idx = 0 if ticket_index is None else int(ticket_index) % len(tickets)
107
+
108
+ raw_ticket = tickets[idx]
109
+ ticket = TicketInfo(
110
+ ticket_id=raw_ticket["ticket_id"],
111
+ subject=raw_ticket["subject"],
112
+ body=raw_ticket["body"],
113
+ customer_tier=raw_ticket["customer_tier"],
114
+ account_age_days=raw_ticket["account_age_days"],
115
+ previous_tickets=raw_ticket["previous_tickets"],
116
+ attachments=raw_ticket.get("attachments", []),
117
+ )
118
+
119
+ episode_id = str(uuid.uuid4())
120
+ _EPISODES[episode_id] = {
121
+ "task_id": task_id,
122
+ "ticket_index": idx,
123
+ "step_number": 0,
124
+ "max_steps": meta["max_steps"],
125
+ "done": False,
126
+ "total_reward": 0.0,
127
+ "action_history": [],
128
+ "final_score": None,
129
+ }
130
+
131
+ return Observation(
132
+ task_id=task_id,
133
+ task_description=meta["description"],
134
+ episode_id=episode_id,
135
+ ticket=ticket,
136
+ thread_history=[],
137
+ available_actions=meta["available_actions"],
138
+ step_number=0,
139
+ max_steps=meta["max_steps"],
140
+ hint=_get_hint(task_id, 0),
141
+ )
142
+
143
+
144
+ def step(episode_id: str, action: Action) -> StepResult:
145
+ """
146
+ Advance the episode by one step.
147
+
148
+ Raises:
149
+ KeyError: episode_id not found
150
+ ValueError: episode is already done
151
+ """
152
+ ep = _EPISODES[episode_id] # raises KeyError if not found
153
+
154
+ if ep["done"]:
155
+ raise ValueError(f"Episode {episode_id} is already done.")
156
+
157
+ task_id: str = ep["task_id"]
158
+ meta = TASK_META[task_id]
159
+ tickets = get_tickets(task_id)
160
+
161
+ ep["step_number"] += 1
162
+ ep["action_history"].append(action.model_dump())
163
+
164
+ # Determine if done
165
+ done = False
166
+ if action.action_type == "submit":
167
+ done = True
168
+ elif ep["step_number"] >= ep["max_steps"]:
169
+ done = True
170
+
171
+ # Compute step reward
172
+ reward_fn = _STEP_REWARD_FNS[task_id]
173
+ step_r, explanation = reward_fn(action, done)
174
+
175
+ if done and action.action_type != "submit":
176
+ step_r += _MAX_STEP_PENALTY
177
+ explanation += f" Max steps reached β€” {_MAX_STEP_PENALTY} penalty."
178
+
179
+ # Apply final grader bonus when episode ends
180
+ final_score = None
181
+ if done:
182
+ final_score, _, grader_feedback = grade_episode(
183
+ task_id, ep["ticket_index"], ep["action_history"]
184
+ )
185
+ ep["final_score"] = final_score
186
+ bonus = final_score * 1.0 # scale grader score to up to +1.0 reward
187
+ step_r += bonus
188
+ explanation += f" Grader bonus: +{bonus:.3f} (score={final_score:.3f})."
189
+
190
+ ep["total_reward"] = round(ep["total_reward"] + step_r, 4)
191
+ ep["done"] = done
192
+
193
+ # Build next observation
194
+ raw_ticket = tickets[ep["ticket_index"]]
195
+ ticket = TicketInfo(
196
+ ticket_id=raw_ticket["ticket_id"],
197
+ subject=raw_ticket["subject"],
198
+ body=raw_ticket["body"],
199
+ customer_tier=raw_ticket["customer_tier"],
200
+ account_age_days=raw_ticket["account_age_days"],
201
+ previous_tickets=raw_ticket["previous_tickets"],
202
+ attachments=raw_ticket.get("attachments", []),
203
+ )
204
+
205
+ thread_history = [
206
+ {"role": "agent", "content": str(a)}
207
+ for a in ep["action_history"]
208
+ ]
209
+
210
+ obs = Observation(
211
+ task_id=task_id,
212
+ task_description=meta["description"],
213
+ episode_id=episode_id,
214
+ ticket=ticket,
215
+ thread_history=thread_history,
216
+ available_actions=meta["available_actions"] if not done else [],
217
+ step_number=ep["step_number"],
218
+ max_steps=ep["max_steps"],
219
+ hint=_get_hint(task_id, ep["step_number"]) if not done else None,
220
+ )
221
+
222
+ reward = Reward(
223
+ step_reward=round(step_r, 4),
224
+ total_reward=ep["total_reward"],
225
+ explanation=explanation,
226
+ )
227
+
228
+ info: dict = {
229
+ "step": ep["step_number"],
230
+ "max_steps": ep["max_steps"],
231
+ }
232
+ if done:
233
+ info["final_score"] = final_score
234
+
235
+ return StepResult(observation=obs, reward=reward, done=done, info=info)
236
+
237
+
238
+ def state(episode_id: str) -> State:
239
+ """Return the current state of an episode."""
240
+ ep = _EPISODES[episode_id]
241
+ return State(
242
+ task_id=ep["task_id"],
243
+ episode_id=episode_id,
244
+ step_number=ep["step_number"],
245
+ max_steps=ep["max_steps"],
246
+ done=ep["done"],
247
+ total_reward=ep["total_reward"],
248
+ history=ep["action_history"],
249
+ final_score=ep.get("final_score"),
250
+ )
251
+
252
+
253
+ def grade(episode_id: str) -> GraderResponse:
254
+ """
255
+ Run (or re-run) the grader on a finished episode and return the result.
256
+
257
+ Raises:
258
+ ValueError: episode is not done yet.
259
+ """
260
+ ep = _EPISODES[episode_id]
261
+ if not ep["done"]:
262
+ raise ValueError(
263
+ f"Episode {episode_id} is not done yet (step {ep['step_number']}/{ep['max_steps']})."
264
+ )
265
+
266
+ score, breakdown, feedback = grade_episode(
267
+ ep["task_id"], ep["ticket_index"], ep["action_history"]
268
+ )
269
+ ep["final_score"] = score
270
+
271
+ return GraderResponse(
272
+ episode_id=episode_id,
273
+ task_id=ep["task_id"],
274
+ score=score,
275
+ breakdown=breakdown,
276
+ feedback=feedback,
277
+ )
278
+
279
+
280
+ # ---------------------------------------------------------------------------
281
+ # Hints
282
+ # ---------------------------------------------------------------------------
283
+
284
+ _HINTS = {
285
+ "task1": [
286
+ "Read the ticket carefully. What is the customer's main problem?",
287
+ "Review your classification β€” does the priority match the urgency in the message?",
288
+ "Submit your final answer.",
289
+ ],
290
+ "task2": [
291
+ "Scan the ticket for IDs, names, dates, and amounts.",
292
+ "List every action that support staff must take to close this ticket.",
293
+ "Verify you haven't missed any entity.",
294
+ "Double-check required_actions against the ticket body.",
295
+ "Submit your final answer.",
296
+ ],
297
+ "task3": [
298
+ "Read the ticket carefully β€” what is the customer asking for?",
299
+ "Draft a professional response that acknowledges the issue.",
300
+ "Ensure your resolution_steps are actionable and ordered.",
301
+ "Check that your response covers all required information.",
302
+ "Add any missing keywords (e.g. apology, timeline).",
303
+ "Review tone β€” is it empathetic and professional?",
304
+ "Verify step completeness before submitting.",
305
+ "Submit your final answer.",
306
+ ],
307
+ }
308
+
309
+
310
+ def _get_hint(task_id: str, step_number: int) -> Optional[str]:
311
+ hints = _HINTS.get(task_id, [])
312
+ if step_number < len(hints):
313
+ return hints[step_number]
314
+ return None
graders.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ Deterministic graders for all three SupportEnv tasks.
4
+
5
+ All graders return a score in [0.0, 1.0] and a dict of per-criterion
6
+ partial scores. No external calls are made β€” scoring is purely rule-based
7
+ so results are fully reproducible.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import re
12
+ from typing import Any, Dict, List, Tuple
13
+
14
+ from data import TASK_META
15
+
16
+
17
+ # ---------------------------------------------------------------------------
18
+ # Helpers
19
+ # ---------------------------------------------------------------------------
20
+
21
+ def _normalise(text: str) -> str:
22
+ """Lower-case, strip punctuation, collapse whitespace."""
23
+ text = text.lower()
24
+ text = re.sub(r"[^\w\s]", " ", text)
25
+ return re.sub(r"\s+", " ", text).strip()
26
+
27
+
28
+ def _contains_keyword(text: str, keyword: str) -> bool:
29
+ """Return True if keyword (normalised) appears anywhere in text."""
30
+ return _normalise(keyword) in _normalise(text)
31
+
32
+
33
+ # ---------------------------------------------------------------------------
34
+ # Task 1 β€” Ticket Classification
35
+ # ---------------------------------------------------------------------------
36
+
37
+ def grade_task1(
38
+ ticket_index: int,
39
+ action_history: List[Dict[str, Any]],
40
+ ) -> Tuple[float, Dict[str, float], str]:
41
+ """
42
+ Grade a Task-1 episode (classification).
43
+
44
+ Scoring:
45
+ category_correct : 0.50
46
+ priority_correct : 0.40
47
+ acted_efficiently : 0.10 (submitted within max_steps without wasted loops)
48
+
49
+ Returns (score, breakdown, feedback)
50
+ """
51
+ tickets = TASK_META["task1"]["tickets"]
52
+ gt = tickets[ticket_index]["ground_truth"]
53
+
54
+ category_score = 0.0
55
+ priority_score = 0.0
56
+
57
+ # Find the last classify action the agent submitted
58
+ last_classify = None
59
+ for act in reversed(action_history):
60
+ if act.get("action_type") == "classify":
61
+ last_classify = act
62
+ break
63
+
64
+ if last_classify is not None:
65
+ if last_classify.get("category", "").lower() == gt["category"]:
66
+ category_score = 0.50
67
+ elif _normalise(last_classify.get("category", "")) in _normalise(gt["category"]):
68
+ category_score = 0.25 # partial credit for substring match
69
+
70
+ if last_classify.get("priority", "").lower() == gt["priority"]:
71
+ priority_score = 0.40
72
+ elif _is_adjacent_priority(
73
+ last_classify.get("priority", "").lower(), gt["priority"]
74
+ ):
75
+ priority_score = 0.20 # partial credit for one level off
76
+
77
+ # Efficiency bonus: agent didn't fill max steps with redundant classify attempts
78
+ classify_count = sum(
79
+ 1 for a in action_history if a.get("action_type") == "classify"
80
+ )
81
+ efficiency_score = 0.10 if classify_count <= 2 else 0.0
82
+
83
+ total = category_score + priority_score + efficiency_score
84
+ breakdown = {
85
+ "category_correct": category_score,
86
+ "priority_correct": priority_score,
87
+ "efficiency": efficiency_score,
88
+ }
89
+ feedback = _task1_feedback(gt, last_classify, breakdown)
90
+ return round(total, 4), breakdown, feedback
91
+
92
+
93
+ def _is_adjacent_priority(pred: str, gold: str) -> bool:
94
+ """One priority level off gets partial credit."""
95
+ levels = ["low", "medium", "high", "critical"]
96
+ if pred not in levels or gold not in levels:
97
+ return False
98
+ return abs(levels.index(pred) - levels.index(gold)) == 1
99
+
100
+
101
+ def _task1_feedback(gt, last_classify, breakdown) -> str:
102
+ parts = []
103
+ if last_classify is None:
104
+ return "No classify action found in episode history."
105
+ if breakdown["category_correct"] == 0.50:
106
+ parts.append(f"Category '{gt['category']}' correctly identified.")
107
+ elif breakdown["category_correct"] > 0:
108
+ parts.append(f"Category partially correct (got substring match).")
109
+ else:
110
+ parts.append(
111
+ f"Category incorrect: expected '{gt['category']}', "
112
+ f"got '{last_classify.get('category')}'."
113
+ )
114
+ if breakdown["priority_correct"] == 0.40:
115
+ parts.append(f"Priority '{gt['priority']}' correctly identified.")
116
+ elif breakdown["priority_correct"] > 0:
117
+ parts.append("Priority off by one level (partial credit).")
118
+ else:
119
+ parts.append(
120
+ f"Priority incorrect: expected '{gt['priority']}', "
121
+ f"got '{last_classify.get('priority')}'."
122
+ )
123
+ return " ".join(parts)
124
+
125
+
126
+ # ---------------------------------------------------------------------------
127
+ # Task 2 β€” Information Extraction
128
+ # ---------------------------------------------------------------------------
129
+
130
+ def grade_task2(
131
+ ticket_index: int,
132
+ action_history: List[Dict[str, Any]],
133
+ ) -> Tuple[float, Dict[str, float], str]:
134
+ """
135
+ Grade a Task-2 episode (information extraction).
136
+
137
+ Scoring:
138
+ entity_coverage : 0.60 (fraction of required entities correctly extracted)
139
+ action_coverage : 0.30 (fraction of required actions identified)
140
+ no_hallucination : 0.10 (no extra entities that don't exist in source)
141
+
142
+ Returns (score, breakdown, feedback)
143
+ """
144
+ tickets = TASK_META["task2"]["tickets"]
145
+ gt = tickets[ticket_index]["ground_truth"]
146
+ required_entities: Dict[str, Any] = gt["entities"]
147
+ required_actions: List[str] = gt["required_actions"]
148
+
149
+ # Find the last extract action
150
+ last_extract = None
151
+ for act in reversed(action_history):
152
+ if act.get("action_type") == "extract":
153
+ last_extract = act
154
+ break
155
+
156
+ if last_extract is None:
157
+ return 0.0, {"entity_coverage": 0.0, "action_coverage": 0.0, "no_hallucination": 0.0}, \
158
+ "No extract action found in episode history."
159
+
160
+ extracted: Dict[str, Any] = last_extract.get("extracted_entities") or {}
161
+ submitted_actions: List[str] = last_extract.get("required_actions") or []
162
+
163
+ # --- Entity scoring ---
164
+ entity_hits = 0
165
+ entity_notes = []
166
+ for key, expected_val in required_entities.items():
167
+ pred_val = extracted.get(key)
168
+ if pred_val is None:
169
+ entity_notes.append(f"Missing: {key}")
170
+ continue
171
+ if isinstance(expected_val, list):
172
+ # For list values, check set overlap (case-insensitive)
173
+ pred_set = {_normalise(str(v)) for v in (pred_val if isinstance(pred_val, list) else [pred_val])}
174
+ gold_set = {_normalise(str(v)) for v in expected_val}
175
+ overlap = len(pred_set & gold_set) / len(gold_set)
176
+ entity_hits += overlap
177
+ if overlap < 1.0:
178
+ entity_notes.append(f"Partial match for '{key}': {overlap:.0%}")
179
+ else:
180
+ if _normalise(str(pred_val)) == _normalise(str(expected_val)):
181
+ entity_hits += 1
182
+ elif _normalise(str(expected_val)) in _normalise(str(pred_val)):
183
+ entity_hits += 0.5
184
+ entity_notes.append(f"Partial match for '{key}'")
185
+ else:
186
+ entity_notes.append(
187
+ f"Wrong value for '{key}': expected '{expected_val}', got '{pred_val}'"
188
+ )
189
+
190
+ entity_coverage = entity_hits / max(len(required_entities), 1)
191
+
192
+ # --- Action scoring ---
193
+ gold_action_set = {a.lower() for a in required_actions}
194
+ pred_action_set = {a.lower() for a in submitted_actions}
195
+ action_hits = len(gold_action_set & pred_action_set)
196
+ # Partial credit: normalised keyword match
197
+ for gold_act in gold_action_set:
198
+ if gold_act not in pred_action_set:
199
+ for pred_act in pred_action_set:
200
+ if _normalise(gold_act) in _normalise(pred_act) or \
201
+ _normalise(pred_act) in _normalise(gold_act):
202
+ action_hits += 0.5
203
+ break
204
+ action_coverage = min(action_hits / max(len(required_actions), 1), 1.0)
205
+
206
+ # --- Hallucination penalty ---
207
+ # Extra keys in extracted that don't exist in required_entities
208
+ extra_keys = set(extracted.keys()) - set(required_entities.keys())
209
+ hallucination_score = 0.10 if len(extra_keys) <= 2 else 0.0
210
+
211
+ total = (
212
+ entity_coverage * 0.60
213
+ + action_coverage * 0.30
214
+ + hallucination_score
215
+ )
216
+
217
+ breakdown = {
218
+ "entity_coverage": round(entity_coverage * 0.60, 4),
219
+ "action_coverage": round(action_coverage * 0.30, 4),
220
+ "no_hallucination": hallucination_score,
221
+ }
222
+ feedback_parts = [
223
+ f"Entity coverage: {entity_coverage:.0%} ({entity_hits:.1f}/{len(required_entities)}).",
224
+ f"Action coverage: {action_coverage:.0%} ({action_hits:.1f}/{len(required_actions)}).",
225
+ ]
226
+ if entity_notes:
227
+ feedback_parts.append("Issues: " + "; ".join(entity_notes[:3]))
228
+ feedback = " ".join(feedback_parts)
229
+
230
+ return round(total, 4), breakdown, feedback
231
+
232
+
233
+ # ---------------------------------------------------------------------------
234
+ # Task 3 β€” Resolution Generation
235
+ # ---------------------------------------------------------------------------
236
+
237
+ def grade_task3(
238
+ ticket_index: int,
239
+ action_history: List[Dict[str, Any]],
240
+ ) -> Tuple[float, Dict[str, float], str]:
241
+ """
242
+ Grade a Task-3 episode (resolution generation).
243
+
244
+ Scoring:
245
+ keyword_coverage : 0.30 (required keywords present in response_text)
246
+ step_coverage : 0.30 (required steps present in resolution_steps)
247
+ tone_compliance : 0.25 (apology / urgency / timeline requirements)
248
+ length_adequate : 0.10 (response_text meets minimum word count)
249
+ no_empty_steps : 0.05 (no empty or single-word steps)
250
+
251
+ Returns (score, breakdown, feedback)
252
+ """
253
+ tickets = TASK_META["task3"]["tickets"]
254
+ gt = tickets[ticket_index]["ground_truth"]
255
+ required_keywords: List[str] = gt["required_keywords"]
256
+ required_steps: List[str] = gt["required_resolution_steps"]
257
+ tone: Dict[str, bool] = gt["tone_requirements"]
258
+ min_length: int = gt["expected_response_length_min"]
259
+
260
+ # Find the last respond or resolve action
261
+ last_response_act = None
262
+ for act in reversed(action_history):
263
+ if act.get("action_type") in ("respond", "resolve"):
264
+ last_response_act = act
265
+ break
266
+
267
+ if last_response_act is None:
268
+ return 0.0, {
269
+ "keyword_coverage": 0.0,
270
+ "step_coverage": 0.0,
271
+ "tone_compliance": 0.0,
272
+ "length_adequate": 0.0,
273
+ "no_empty_steps": 0.0,
274
+ }, "No respond/resolve action found in episode history."
275
+
276
+ response_text: str = last_response_act.get("response_text") or ""
277
+ resolution_steps: List[str] = last_response_act.get("resolution_steps") or []
278
+
279
+ # --- Keyword coverage ---
280
+ kw_hits = sum(
281
+ 1 for kw in required_keywords if _contains_keyword(response_text, kw)
282
+ )
283
+ keyword_coverage = kw_hits / max(len(required_keywords), 1)
284
+
285
+ # --- Step coverage ---
286
+ step_hits = 0.0
287
+ for gold_step in required_steps:
288
+ # A step is "covered" if any resolution_step string contains all
289
+ # main words from the gold step label (split on underscores)
290
+ main_words = gold_step.replace("_", " ").split()
291
+ for pred_step in resolution_steps:
292
+ matches = sum(1 for w in main_words if _contains_keyword(pred_step, w))
293
+ if matches == len(main_words):
294
+ step_hits += 1
295
+ break
296
+ elif matches >= max(1, len(main_words) - 1):
297
+ step_hits += 0.5
298
+ break
299
+ step_coverage = min(step_hits / max(len(required_steps), 1), 1.0)
300
+
301
+ # --- Tone compliance ---
302
+ tone_score = _check_tone(response_text, tone)
303
+
304
+ # --- Length adequacy ---
305
+ word_count = len(response_text.split())
306
+ length_score = 0.10 if word_count >= min_length else round(
307
+ 0.10 * word_count / min_length, 4
308
+ )
309
+
310
+ # --- Step quality ---
311
+ empty_step_count = sum(
312
+ 1 for s in resolution_steps if len(s.strip().split()) <= 1
313
+ )
314
+ no_empty_steps_score = 0.05 if empty_step_count == 0 else 0.0
315
+
316
+ total = (
317
+ keyword_coverage * 0.30
318
+ + step_coverage * 0.30
319
+ + tone_score
320
+ + length_score
321
+ + no_empty_steps_score
322
+ )
323
+
324
+ breakdown = {
325
+ "keyword_coverage": round(keyword_coverage * 0.30, 4),
326
+ "step_coverage": round(step_coverage * 0.30, 4),
327
+ "tone_compliance": round(tone_score, 4),
328
+ "length_adequate": round(length_score, 4),
329
+ "no_empty_steps": no_empty_steps_score,
330
+ }
331
+ feedback = (
332
+ f"Keywords: {kw_hits}/{len(required_keywords)} found. "
333
+ f"Steps: {step_hits:.1f}/{len(required_steps)} covered. "
334
+ f"Tone score: {tone_score:.2f}/0.25. "
335
+ f"Word count: {word_count} (min {min_length})."
336
+ )
337
+
338
+ return round(total, 4), breakdown, feedback
339
+
340
+
341
+ _APOLOGY_WORDS = [
342
+ "sorry", "apologise", "apologize", "apologies", "regret",
343
+ "inconvenience", "unfortunately",
344
+ ]
345
+ _URGENCY_WORDS = [
346
+ "urgent", "urgently", "immediately", "priority", "asap",
347
+ "right away", "as soon as possible",
348
+ ]
349
+ _TIMELINE_WORDS = [
350
+ "within", "hour", "minute", "today", "by", "shortly",
351
+ "soon", "moment", "immediately", "right away",
352
+ ]
353
+
354
+
355
+ def _check_tone(text: str, tone: Dict[str, bool]) -> float:
356
+ """Return tone compliance score (max 0.25)."""
357
+ criteria = [
358
+ ("must_apologize", _APOLOGY_WORDS),
359
+ ("must_acknowledge_urgency", _URGENCY_WORDS),
360
+ ("must_provide_timeline", _TIMELINE_WORDS),
361
+ ]
362
+ required = [k for k, _ in criteria if tone.get(k, False)]
363
+ if not required:
364
+ return 0.25 # nothing required β†’ full tone score
365
+
366
+ per_criterion = 0.25 / len(required)
367
+ score = 0.0
368
+ for key, words in criteria:
369
+ if not tone.get(key, False):
370
+ continue
371
+ if any(_contains_keyword(text, w) for w in words):
372
+ score += per_criterion
373
+ return round(score, 4)
374
+
375
+
376
+ # ---------------------------------------------------------------------------
377
+ # Public grader dispatcher
378
+ # ---------------------------------------------------------------------------
379
+
380
+ def grade_episode(
381
+ task_id: str,
382
+ ticket_index: int,
383
+ action_history: List[Dict[str, Any]],
384
+ ) -> Tuple[float, Dict[str, float], str]:
385
+ """
386
+ Dispatch to the correct grader based on task_id.
387
+
388
+ Returns (score: float, breakdown: dict, feedback: str)
389
+ """
390
+ if task_id == "task1":
391
+ return grade_task1(ticket_index, action_history)
392
+ elif task_id == "task2":
393
+ return grade_task2(ticket_index, action_history)
394
+ elif task_id == "task3":
395
+ return grade_task3(ticket_index, action_history)
396
+ else:
397
+ raise ValueError(f"Unknown task_id: {task_id!r}")
models.py ADDED
@@ -0,0 +1,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pydantic models for the SupportEnv OpenEnv environment.
3
+
4
+ Domain: Customer Support Ticket Resolution (SaaS company)
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from typing import Any, Dict, List, Optional
9
+ from pydantic import BaseModel, Field
10
+
11
+
12
+ # ---------------------------------------------------------------------------
13
+ # Core domain model
14
+ # ---------------------------------------------------------------------------
15
+
16
+ class TicketInfo(BaseModel):
17
+ """A single customer-support ticket."""
18
+ ticket_id: str
19
+ subject: str
20
+ body: str
21
+ customer_tier: str = Field(
22
+ description="Subscription tier: free | pro | enterprise"
23
+ )
24
+ account_age_days: int
25
+ previous_tickets: int
26
+ attachments: List[str] = Field(default_factory=list)
27
+
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Observation
31
+ # ---------------------------------------------------------------------------
32
+
33
+ class Observation(BaseModel):
34
+ """Everything the agent sees at each step."""
35
+ task_id: str = Field(description="Task identifier: task1 | task2 | task3")
36
+ task_description: str = Field(description="Human-readable task description")
37
+ episode_id: str = Field(description="Unique episode UUID")
38
+ ticket: TicketInfo
39
+ thread_history: List[Dict[str, str]] = Field(
40
+ default_factory=list,
41
+ description="Ordered list of {'role': 'agent'|'system', 'content': str}"
42
+ )
43
+ available_actions: List[str] = Field(
44
+ description="List of valid action_type values for this step"
45
+ )
46
+ step_number: int
47
+ max_steps: int
48
+ hint: Optional[str] = Field(
49
+ default=None,
50
+ description="Optional hint shown to the agent (may be None)"
51
+ )
52
+
53
+
54
+ # ---------------------------------------------------------------------------
55
+ # Action
56
+ # ---------------------------------------------------------------------------
57
+
58
+ class Action(BaseModel):
59
+ """
60
+ The action an agent submits via POST /step.
61
+
62
+ Only the fields relevant to the chosen action_type need to be populated.
63
+ """
64
+ action_type: str = Field(
65
+ description=(
66
+ "One of: classify | extract | respond | escalate | resolve | submit"
67
+ )
68
+ )
69
+
70
+ # ---- Task 1: classify -------------------------------------------------
71
+ category: Optional[str] = Field(
72
+ default=None,
73
+ description=(
74
+ "Ticket category: billing | technical | account | "
75
+ "feature_request | complaint | general"
76
+ )
77
+ )
78
+ priority: Optional[str] = Field(
79
+ default=None,
80
+ description="Priority level: low | medium | high | critical"
81
+ )
82
+
83
+ # ---- Task 2: extract --------------------------------------------------
84
+ extracted_entities: Optional[Dict[str, Any]] = Field(
85
+ default=None,
86
+ description=(
87
+ "Key-value pairs extracted from the ticket. Expected keys vary by "
88
+ "ticket; see task description."
89
+ )
90
+ )
91
+ required_actions: Optional[List[str]] = Field(
92
+ default=None,
93
+ description="List of actions that must be taken to resolve the ticket"
94
+ )
95
+
96
+ # ---- Task 3: respond / resolve ----------------------------------------
97
+ response_text: Optional[str] = Field(
98
+ default=None,
99
+ description="Full text of the agent's response to the customer"
100
+ )
101
+ resolution_steps: Optional[List[str]] = Field(
102
+ default=None,
103
+ description="Ordered list of steps to resolve the ticket"
104
+ )
105
+
106
+ # ---- escalate ---------------------------------------------------------
107
+ escalation_team: Optional[str] = Field(
108
+ default=None,
109
+ description=(
110
+ "Team to escalate to: billing_team | engineering | "
111
+ "account_management | legal"
112
+ )
113
+ )
114
+ escalation_reason: Optional[str] = Field(
115
+ default=None,
116
+ description="Brief reason for escalation"
117
+ )
118
+
119
+ # ---- submit -----------------------------------------------------------
120
+ # No extra fields β€” signals the agent is done with the episode.
121
+
122
+
123
+ # ---------------------------------------------------------------------------
124
+ # Reward
125
+ # ---------------------------------------------------------------------------
126
+
127
+ class Reward(BaseModel):
128
+ """Per-step reward signal."""
129
+ step_reward: float = Field(
130
+ description="Reward earned this step (can be negative)"
131
+ )
132
+ total_reward: float = Field(
133
+ description="Cumulative reward for the episode so far"
134
+ )
135
+ explanation: str = Field(
136
+ description="Human-readable explanation of what drove the reward"
137
+ )
138
+
139
+
140
+ # ---------------------------------------------------------------------------
141
+ # Step result
142
+ # ---------------------------------------------------------------------------
143
+
144
+ class StepResult(BaseModel):
145
+ observation: Observation
146
+ reward: Reward
147
+ done: bool
148
+ info: Dict[str, Any] = Field(default_factory=dict)
149
+
150
+
151
+ # ---------------------------------------------------------------------------
152
+ # State (returned by GET /state)
153
+ # ---------------------------------------------------------------------------
154
+
155
+ class State(BaseModel):
156
+ task_id: str
157
+ episode_id: str
158
+ step_number: int
159
+ max_steps: int
160
+ done: bool
161
+ total_reward: float
162
+ history: List[Dict[str, Any]] = Field(
163
+ default_factory=list,
164
+ description="Ordered list of (action, reward) pairs for the episode"
165
+ )
166
+ final_score: Optional[float] = Field(
167
+ default=None,
168
+ description="Grader score 0.0–1.0, set when episode is done"
169
+ )
170
+
171
+
172
+ # ---------------------------------------------------------------------------
173
+ # Task metadata (returned by GET /tasks)
174
+ # ---------------------------------------------------------------------------
175
+
176
+ class TaskInfo(BaseModel):
177
+ task_id: str
178
+ name: str
179
+ description: str
180
+ difficulty: str = Field(description="easy | medium | hard")
181
+ max_steps: int
182
+ action_schema: Dict[str, Any] = Field(
183
+ description="JSON Schema fragment describing required Action fields"
184
+ )
185
+
186
+
187
+ # ---------------------------------------------------------------------------
188
+ # Baseline / grader response shapes
189
+ # ---------------------------------------------------------------------------
190
+
191
+ class GraderResponse(BaseModel):
192
+ episode_id: str
193
+ task_id: str
194
+ score: float = Field(description="Final grader score 0.0–1.0")
195
+ breakdown: Dict[str, float] = Field(
196
+ default_factory=dict,
197
+ description="Per-criterion partial scores"
198
+ )
199
+ feedback: str
200
+
201
+
202
+ class BaselineScore(BaseModel):
203
+ task_id: str
204
+ score: float
205
+ details: Dict[str, Any] = Field(default_factory=dict)
206
+
207
+
208
+ class BaselineResult(BaseModel):
209
+ model: str
210
+ scores: List[BaselineScore]
211
+ average_score: float
openenv.yaml ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: SupportEnv
2
+ version: "1.0.0"
3
+ description: >
4
+ An OpenEnv-compliant customer support ticket triage environment for SaaS platforms.
5
+ Agents learn to classify tickets, extract structured information, and generate
6
+ professional resolutions β€” skills directly transferable to real-world support automation.
7
+
8
+ domain: customer_support
9
+ tags:
10
+ - openenv
11
+ - customer-support
12
+ - nlp
13
+ - information-extraction
14
+ - classification
15
+ - generation
16
+ - real-world
17
+
18
+ license: MIT
19
+ author: SupportEnv Contributors
20
+
21
+ # -------------------------------------------------
22
+ # Environment interface
23
+ # -------------------------------------------------
24
+ interface:
25
+ reset:
26
+ method: POST
27
+ path: /reset
28
+ request:
29
+ task_id: string # task1 | task2 | task3
30
+ ticket_index: integer # optional, 0-4
31
+ response: Observation
32
+
33
+ step:
34
+ method: POST
35
+ path: /step
36
+ request:
37
+ episode_id: string
38
+ action: Action
39
+ response: StepResult # {observation, reward, done, info}
40
+
41
+ state:
42
+ method: GET
43
+ path: /state
44
+ params:
45
+ episode_id: string
46
+ response: State
47
+
48
+ tasks:
49
+ method: GET
50
+ path: /tasks
51
+ response: List[TaskInfo]
52
+
53
+ grader:
54
+ method: POST
55
+ path: /grader
56
+ request:
57
+ episode_id: string
58
+ response: GraderResponse
59
+
60
+ baseline:
61
+ method: POST
62
+ path: /baseline
63
+ request:
64
+ model: string # optional, default heuristic
65
+ ticket_index: integer # optional, default 0
66
+ response: BaselineResult
67
+
68
+ health:
69
+ method: GET
70
+ path: /health
71
+
72
+ # -------------------------------------------------
73
+ # Typed models
74
+ # -------------------------------------------------
75
+ models:
76
+ Observation:
77
+ task_id: string
78
+ task_description: string
79
+ episode_id: string
80
+ ticket: TicketInfo
81
+ thread_history: list[dict]
82
+ available_actions: list[string]
83
+ step_number: integer
84
+ max_steps: integer
85
+ hint: string | null
86
+
87
+ TicketInfo:
88
+ ticket_id: string
89
+ subject: string
90
+ body: string
91
+ customer_tier: string # free | pro | enterprise
92
+ account_age_days: integer
93
+ previous_tickets: integer
94
+ attachments: list[string]
95
+
96
+ Action:
97
+ action_type: string # classify | extract | respond | resolve | escalate | submit
98
+ category: string | null
99
+ priority: string | null
100
+ extracted_entities: dict | null
101
+ required_actions: list[string] | null
102
+ response_text: string | null
103
+ resolution_steps: list[string] | null
104
+ escalation_team: string | null
105
+ escalation_reason: string | null
106
+
107
+ Reward:
108
+ step_reward: float
109
+ total_reward: float
110
+ explanation: string
111
+
112
+ StepResult:
113
+ observation: Observation
114
+ reward: Reward
115
+ done: boolean
116
+ info: dict
117
+
118
+ State:
119
+ task_id: string
120
+ episode_id: string
121
+ step_number: integer
122
+ max_steps: integer
123
+ done: boolean
124
+ total_reward: float
125
+ history: list[dict]
126
+ final_score: float | null
127
+
128
+ GraderResponse:
129
+ episode_id: string
130
+ task_id: string
131
+ score: float # 0.0 – 1.0
132
+ breakdown: dict[string, float]
133
+ feedback: string
134
+
135
+ # -------------------------------------------------
136
+ # Tasks
137
+ # -------------------------------------------------
138
+ tasks:
139
+ task1:
140
+ name: "Ticket Classification"
141
+ difficulty: easy
142
+ max_steps: 3
143
+ description: >
144
+ Given a customer support ticket, classify it by category
145
+ (billing | technical | account | feature_request | complaint | general)
146
+ and priority (low | medium | high | critical).
147
+ scoring:
148
+ category_correct: 0.50
149
+ priority_correct: 0.40
150
+ efficiency: 0.10
151
+ tickets: 5
152
+
153
+ task2:
154
+ name: "Information Extraction"
155
+ difficulty: medium
156
+ max_steps: 5
157
+ description: >
158
+ Extract structured entities (account IDs, names, amounts, dates, domains)
159
+ from the ticket body and identify the list of required actions.
160
+ scoring:
161
+ entity_coverage: 0.60
162
+ action_coverage: 0.30
163
+ no_hallucination: 0.10
164
+ tickets: 5
165
+
166
+ task3:
167
+ name: "Resolution Generation"
168
+ difficulty: hard
169
+ max_steps: 8
170
+ description: >
171
+ Generate a professional customer-facing response (response_text) and
172
+ an ordered list of resolution steps. Scored on keyword coverage,
173
+ step completeness, tone (apology, urgency, timeline), and response length.
174
+ scoring:
175
+ keyword_coverage: 0.30
176
+ step_coverage: 0.30
177
+ tone_compliance: 0.25
178
+ length_adequate: 0.10
179
+ no_empty_steps: 0.05
180
+ tickets: 5
181
+
182
+ # -------------------------------------------------
183
+ # Reward design
184
+ # -------------------------------------------------
185
+ reward:
186
+ type: dense
187
+ step_cost: -0.02 # small cost per step (encourages efficiency)
188
+ submit_bonus: 0.05 # bonus for explicit submit action
189
+ max_step_penalty: -0.10 # penalty for exhausting max_steps
190
+ grader_bonus: up_to_1.0 # grader score (0–1) added as terminal bonus
191
+
192
+ # -------------------------------------------------
193
+ # Reproducibility
194
+ # -------------------------------------------------
195
+ reproducibility:
196
+ dataset: static # all 15 tickets are fixed, no randomisation
197
+ graders: deterministic # rule-based, no LLM judge
198
+ baseline_mode: heuristic # no API key required for reference scores
199
+
200
+ # -------------------------------------------------
201
+ # Deployment
202
+ # -------------------------------------------------
203
+ deployment:
204
+ framework: FastAPI
205
+ python: ">=3.10"
206
+ port: 7860
207
+ dockerfile: Dockerfile
208
+ huggingface_space: true
209
+ space_sdk: docker
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ fastapi>=0.111.0
2
+ uvicorn[standard]>=0.30.0
3
+ pydantic>=2.7.0
4
+ openai>=1.35.0
5
+ httpx>=0.27.0
6
+ python-multipart>=0.0.9
setup.md ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SETUP.md β€” Local Development Guide
2
+
3
+ ## Prerequisites
4
+
5
+ - Python 3.10+ ([download](https://www.python.org/downloads/))
6
+ - Git
7
+ - Docker (optional, for containerised run)
8
+ - An OpenAI API key (optional, only for the LLM baseline)
9
+
10
+ ---
11
+
12
+ ## 1. Clone the repository
13
+
14
+ ```bash
15
+ git clone https://github.com/Shivoo29/dummy_1.git
16
+ cd dummy_1
17
+ git checkout claude/openenv-ai-agent-environment-qJ9pB
18
+ ```
19
+
20
+ ---
21
+
22
+ ## 2. Create a virtual environment
23
+
24
+ ```bash
25
+ python -m venv .venv
26
+
27
+ # macOS / Linux
28
+ source .venv/bin/activate
29
+
30
+ # Windows (PowerShell)
31
+ .venv\Scripts\Activate.ps1
32
+ ```
33
+
34
+ ---
35
+
36
+ ## 3. Install dependencies
37
+
38
+ ```bash
39
+ pip install -r requirements.txt
40
+ ```
41
+
42
+ ---
43
+
44
+ ## 4. Run the server
45
+
46
+ ```bash
47
+ uvicorn app:app --host 0.0.0.0 --port 7860 --reload
48
+ ```
49
+
50
+ - API: http://localhost:7860
51
+ - Interactive docs (Swagger UI): http://localhost:7860/docs
52
+ - ReDoc: http://localhost:7860/redoc
53
+
54
+ ---
55
+
56
+ ## 5. Quick smoke test
57
+
58
+ ```bash
59
+ # Health check
60
+ curl http://localhost:7860/health
61
+
62
+ # List tasks
63
+ curl http://localhost:7860/tasks
64
+
65
+ # Start a task1 episode
66
+ curl -X POST http://localhost:7860/reset \
67
+ -H "Content-Type: application/json" \
68
+ -d '{"task_id": "task1", "ticket_index": 0}'
69
+
70
+ # The response contains an episode_id β€” use it below
71
+ EPISODE_ID="<paste episode_id here>"
72
+
73
+ # Submit a classification action
74
+ curl -X POST http://localhost:7860/step \
75
+ -H "Content-Type: application/json" \
76
+ -d "{\"episode_id\": \"$EPISODE_ID\", \"action\": {\"action_type\": \"classify\", \"category\": \"billing\", \"priority\": \"high\"}}"
77
+
78
+ # Submit to close the episode
79
+ curl -X POST http://localhost:7860/step \
80
+ -H "Content-Type: application/json" \
81
+ -d "{\"episode_id\": \"$EPISODE_ID\", \"action\": {\"action_type\": \"submit\"}}"
82
+
83
+ # Grade the episode
84
+ curl -X POST http://localhost:7860/grader \
85
+ -H "Content-Type: application/json" \
86
+ -d "{\"episode_id\": \"$EPISODE_ID\"}"
87
+ ```
88
+
89
+ ---
90
+
91
+ ## 6. Run the baseline
92
+
93
+ ### Heuristic baseline (no API key required)
94
+
95
+ ```bash
96
+ # Single ticket (ticket_index 0)
97
+ python baseline.py --mode heuristic
98
+
99
+ # All 5 tickets per task, averaged
100
+ python baseline.py --mode heuristic --all-tickets
101
+ ```
102
+
103
+ Expected output:
104
+ ```
105
+ task1: 0.8600 (scores: [1.0, 1.0, 1.0, 1.0, 0.3])
106
+ task2: 0.5614 (scores: [0.8, 0.386, 0.45, 0.7, 0.471])
107
+ task3: 0.9895 (scores: [1.0, 0.992, 0.961, 0.994, 1.0])
108
+ OVERALL AVERAGE: 0.8036
109
+ ```
110
+
111
+ ### LLM baseline (requires OpenAI API key)
112
+
113
+ ```bash
114
+ export OPENAI_API_KEY="sk-..." # macOS/Linux
115
+ # $env:OPENAI_API_KEY="sk-..." # Windows PowerShell
116
+
117
+ python baseline.py --mode llm --model gpt-4o-mini
118
+ python baseline.py --mode llm --model gpt-4o-mini --all-tickets
119
+ ```
120
+
121
+ ---
122
+
123
+ ## 7. Run with Docker
124
+
125
+ ```bash
126
+ # Build
127
+ docker build -t supportenv .
128
+
129
+ # Run (no API key needed for heuristic mode)
130
+ docker run -p 7860:7860 supportenv
131
+
132
+ # Run with OpenAI key for LLM baseline
133
+ docker run -p 7860:7860 -e OPENAI_API_KEY="sk-..." supportenv
134
+ ```
135
+
136
+ ---
137
+
138
+ ## 8. Project layout
139
+
140
+ ```
141
+ dummy_1/
142
+ β”œβ”€β”€ app.py FastAPI server β€” all HTTP endpoints
143
+ β”œβ”€β”€ environment.py Episode lifecycle: reset / step / state / grade
144
+ β”œβ”€β”€ graders.py Deterministic graders for all 3 tasks
145
+ β”œβ”€β”€ data.py 15 pre-defined tickets + ground truth answers
146
+ β”œβ”€β”€ models.py Pydantic typed models (Observation, Action, Reward…)
147
+ β”œβ”€β”€ baseline.py Heuristic + LLM baseline inference scripts
148
+ β”œβ”€β”€ openenv.yaml OpenEnv spec metadata
149
+ β”œβ”€β”€ Dockerfile HF Spaces-compatible container (port 7860)
150
+ β”œβ”€β”€ requirements.txt Python dependencies
151
+ β”œβ”€β”€ README.md Full environment documentation
152
+ └── SETUP.md This file
153
+ ```
154
+
155
+ ---
156
+
157
+ ## 9. Key files to edit when extending
158
+
159
+ | What you want to change | File to edit |
160
+ |------------------------|-------------|
161
+ | Add / modify tickets | `data.py` β€” `TASK1/2/3_TICKETS` lists |
162
+ | Change grader weights | `graders.py` β€” `grade_task1/2/3()` |
163
+ | Add a new task | `data.py` (add task meta) + `graders.py` + `app.py` (`_ACTION_SCHEMAS`) |
164
+ | Change reward shaping | `environment.py` β€” `_step_reward_task*` functions and constants |
165
+ | Add an endpoint | `app.py` |
166
+ | Change typed models | `models.py` |
167
+
168
+ ---
169
+
170
+ ## 10. Deploy to Hugging Face Spaces
171
+
172
+ 1. Create a new Space at https://huggingface.co/new-space
173
+ - SDK: **Docker**
174
+ - Visibility: Public
175
+ 2. Add the HF Space as a remote:
176
+ ```bash
177
+ git remote add hf https://huggingface.co/spaces/<your-username>/<space-name>
178
+ ```
179
+ 3. Push:
180
+ ```bash
181
+ git push hf claude/openenv-ai-agent-environment-qJ9pB:main
182
+ ```
183
+ 4. The Space auto-builds from the `Dockerfile` and exposes port 7860.
184
+
185
+ ---
186
+
187
+ ## 11. Environment variables
188
+
189
+ | Variable | Required | Description |
190
+ |----------|----------|-------------|
191
+ | `OPENAI_API_KEY` | Only for LLM baseline | Your OpenAI API key |
192
+ | `PORT` | No (default 7860) | Override server port |
193
+
194
+ ---
195
+
196
+ ## 12. Running tests
197
+
198
+ ```bash
199
+ python -c "
200
+ import environment as env
201
+ from models import Action
202
+
203
+ # Verify all 3 tasks reset and grade correctly
204
+ for task_id in ['task1', 'task2', 'task3']:
205
+ for i in range(5):
206
+ obs = env.reset(task_id, i)
207
+ env.step(obs.episode_id, Action(action_type='submit'))
208
+ gr = env.grade(obs.episode_id)
209
+ assert 0.0 <= gr.score <= 1.0, f'Score out of range: {gr.score}'
210
+ print(f'{task_id} ticket[{i}]: score={gr.score:.4f} OK')
211
+
212
+ print('All tests passed.')
213
+ "
214
+ ```