Spaces:
Configuration error

File size: 5,458 Bytes
ff32501
 
 
 
 
 
 
 
 
 
 
4ac0dac
ff32501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ac0dac
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
"""
server/app.py β€” FastAPI server for EmailTriage OpenEnv
Endpoints: /reset /step /grader /tasks /state /health /docs
"""
from __future__ import annotations

import sys
import json
from pathlib import Path
from typing import Optional

import gradio as gr
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field

from environment import EmailTriageEnv
from models import Action

# ─────────────────────────── App Init ─────────────────────────

app = FastAPI(
    title="EmailTriage OpenEnv",
    description=(
        "πŸ† Hackathon OpenEnv: Real-world email support triage benchmark. "
        "Agents classify, prioritize, draft replies, and escalate critical issues. "
        "3 tasks (easy β†’ hard), deterministic graders, shaped rewards."
    ),
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Global environment instance (stateful, single session)
env = EmailTriageEnv()


# ─────────────────────────── Request Models ────────────────────

class ResetRequest(BaseModel):
    task: str = Field(default="easy", description="Task ID: easy | medium | hard")


class StepRequest(BaseModel):
    action: str = Field(
        ...,
        description='JSON string of Action. E.g.: {"type": "label", "email_id": "e1", "value": "spam"}'
    )


class GraderRequest(BaseModel):
    task: Optional[str] = Field(default=None, description="Optional: override task for grading")


# ─────────────────────────── Endpoints ────────────────────────

@app.get("/", tags=["Meta"])
def root():
    return {
        "name": "EmailTriage OpenEnv",
        "version": "1.0.0",
        "description": "Real-world email support triage benchmark for training AI agents.",
        "tasks": ["easy", "medium", "hard"],
        "endpoints": ["/reset", "/step", "/grader", "/tasks", "/state", "/health", "/docs"],
        "hackathon": "OpenEnv Scalar Hackathon 2025",
    }


@app.get("/health", tags=["Meta"])
def health():
    return {"status": "ok", "environment": "EmailTriageEnv", "version": "1.0.0"}


@app.get("/tasks", tags=["Environment"])
def get_tasks():
    """List all available tasks with descriptions and grader weights."""
    return {"tasks": env.get_tasks()}


@app.post("/reset", tags=["Environment"])
def reset(req: ResetRequest):
    """
    Reset environment to a fresh task inbox.

    Returns initial observation with all emails visible.
    """
    try:
        obs = env.reset(task=req.task)
        return {
            "observation": obs.model_dump(),
            "message": f"Environment reset for task '{req.task}'. {obs.stats.total} emails loaded.",
        }
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.post("/step", tags=["Environment"])
def step(req: StepRequest):
    """
    Take one action in the environment.

    Action JSON format:
    - `{"type": "label", "email_id": "e1", "value": "spam"}`
    - `{"type": "delete", "email_id": "e2"}`
    - `{"type": "draft", "email_id": "e3", "value": "Thanks for reaching out..."}`
    - `{"type": "escalate", "email_id": "e4"}`
    - `{"type": "archive", "email_id": "e5"}`
    """
    if env.state is None or not env.state.inbox:
        raise HTTPException(status_code=400, detail="Environment not initialized. Call /reset first.")

    result = env.step(req.action)
    return {
        "observation": result.observation.model_dump(),
        "reward": result.reward,
        "done": result.done,
        "info": result.info,
    }


@app.post("/grader", tags=["Environment"])
def grader(req: GraderRequest = GraderRequest()):
    """
    Score the current episode. Returns 0.0–1.0 with breakdown.

    Call after episode is done (or anytime for partial scoring).
    """
    if env.state is None or not env.state.inbox:
        raise HTTPException(status_code=400, detail="Environment not initialized. Call /reset first.")

    result = env.grader()
    return result.model_dump()


@app.get("/state", tags=["Environment"])
def get_state():
    """Return full internal state (for debugging)."""
    if env.state is None:
        raise HTTPException(status_code=400, detail="Environment not initialized.")
    return env.get_state().model_dump()


@app.get("/action-schema", tags=["Meta"])
def action_schema():
    """Return JSON schema for the Action model."""
    return Action.model_json_schema()


@app.get("/observation-schema", tags=["Meta"])
def observation_schema():
    """Return JSON schema for the Observation model."""
    from models import Observation
    return Observation.model_json_schema()



# ─────────────────────────── Gradio App ────────────────────────

def greet(name):
    return "Hello " + name + "!!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")

# Mount Gradio into FastAPI
app = gr.mount_gradio_app(app, demo, path="/")