Spaces:
Configuration error
Configuration error
Download app.py from ManojR19/scalarhackathon: direct link, hf CLI and curl.
- Browser
- Download file 5.46 kB
-
https://huggingface.co/spaces/ManojR19/scalarhackathon/resolve/main/app.py
- Command line
-
hf download hf://spaces/ManojR19/scalarhackathon/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ManojR19/scalarhackathon/resolve/main/app.py
5.46 kB
| """ | |
| 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 ββββββββββββββββββββββββ | |
| 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", | |
| } | |
| def health(): | |
| return {"status": "ok", "environment": "EmailTriageEnv", "version": "1.0.0"} | |
| def get_tasks(): | |
| """List all available tasks with descriptions and grader weights.""" | |
| return {"tasks": env.get_tasks()} | |
| 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)) | |
| 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, | |
| } | |
| 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() | |
| 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() | |
| def action_schema(): | |
| """Return JSON schema for the Action model.""" | |
| return Action.model_json_schema() | |
| 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="/") | |