Spaces:
Sleeping
Sleeping
File size: 6,645 Bytes
9540270 d68d941 9540270 d68d941 9540270 a0969f0 9540270 a0969f0 d68d941 a0969f0 53516a5 a0969f0 d68d941 a0969f0 53516a5 a0969f0 d68d941 a0969f0 53516a5 a0969f0 9540270 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 | """
app.py β FastAPI wrapper for DocParserEnv
Exposes the OpenEnv-compatible step/reset/state API over HTTP.
Runs on port 7860 for HuggingFace Spaces.
"""
import json
import random
from pathlib import Path
from typing import Any, Dict, Optional
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
from rl_doc_parser import DocParserEnv, ACTIONS
app = FastAPI(
title="RL Documentation Parser β OpenEnv API",
description="A Gymnasium environment where an agent navigates a mock filesystem to answer technical queries.",
version="1.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# ββ Global env instance (one session; extend with session IDs for multi-user) ββ
env = DocParserEnv(max_steps=20)
_obs, _info = env.reset()
_current_obs = _obs
_current_info = _info
_episode_reward = 0.0
_done = False
# ββ Pydantic models ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class StepRequest(BaseModel):
action: int # 0=ls, 1=cd, 2=read, 3=submit_answer
target: Optional[str] = None # directory/file name for cd/read/submit
class ResetRequest(BaseModel):
seed: Optional[int] = None
task_id: Optional[int] = None
# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _build_state_response(obs, info, reward=None, done=False):
return {
"observation": obs,
"info": info,
"reward": reward,
"done": done,
"action_space": {"type": "Discrete", "n": 4},
"actions": ACTIONS,
"episode_reward": _episode_reward,
}
# ββ Routes βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/", response_class=HTMLResponse)
def root():
"""Simple landing page with links to the API docs."""
return """
<html>
<head><title>RL Documentation Parser</title></head>
<body style="font-family:sans-serif;max-width:700px;margin:40px auto;padding:0 20px">
<h1>π€ RL Documentation Parser</h1>
<p>
An OpenEnv-compatible Gymnasium environment where an agent learns to navigate
a mock file system to answer user queries using technical documentation.
</p>
<h2>Quick Links</h2>
<ul>
<li><a href="/docs">π Interactive API Docs (Swagger UI)</a></li>
<li><a href="/redoc">π ReDoc</a></li>
<li><a href="/state">π Current Environment State</a></li>
<li><a href="/openenv.yaml">π openenv.yaml metadata</a></li>
</ul>
<h2>Actions</h2>
<ul>
<li><b>0 β ls</b>: List current directory contents</li>
<li><b>1 β cd</b>: Change to a subdirectory (provide <code>target</code>)</li>
<li><b>2 β read</b>: Read a .md file (provide <code>target</code>)</li>
<li><b>3 β submit_answer</b>: Submit final answer (provide <code>target</code> as answer text)</li>
</ul>
<h2>Rewards</h2>
<ul>
<li>+100 Correct answer submitted</li>
<li>-1 Per step (efficiency penalty)</li>
<li>-5 Invalid action</li>
<li>-20 Wrong answer submitted</li>
</ul>
</body>
</html>
"""
@app.post("/reset")
def reset(req: ResetRequest = ResetRequest()):
"""Reset the environment and return the initial observation."""
global _current_obs, _current_info, _episode_reward, _done
_current_obs, _current_info = env.reset(seed=req.seed, options={"task_id": req.task_id} if req.task_id else None)
_episode_reward = 0.0
_done = False
return _build_state_response(_current_obs, _current_info, reward=None, done=False)
@app.post("/step")
def step(req: StepRequest):
"""Take a step in the environment."""
global _current_obs, _current_info, _episode_reward, _done
if _done:
raise HTTPException(
status_code=400,
detail="Episode is done. Call POST /reset to start a new episode.",
)
if req.action not in ACTIONS:
raise HTTPException(status_code=400, detail=f"Invalid action {req.action}. Must be 0β3.")
# Inject the target into the env before stepping
if req.target is not None:
env.target_dir = req.target
else:
env.target_dir = ""
obs, reward, done, truncated, info = env.step(req.action)
_current_obs = obs
_current_info = info
_episode_reward += reward
_done = done or truncated
return _build_state_response(obs, info, reward=reward, done=_done)
@app.get("/state")
def state():
"""Return the current environment state without taking an action."""
return _build_state_response(_current_obs, _current_info, reward=None, done=_done)
@app.get("/openenv.yaml")
def openenv_yaml():
"""Return openenv.yaml metadata for validator compliance."""
from fastapi.responses import PlainTextResponse
yaml_path = Path(__file__).resolve().parents[1] / "openenv.yaml"
yaml_content = yaml_path.read_text(encoding="utf-8")
return PlainTextResponse(yaml_content, media_type="text/yaml")
@app.get("/tasks")
def list_tasks():
"""List the available tasks with their difficulties."""
return {
"tasks": [
{
"id": 1,
"name": "easy",
"description": "Locate SSL configuration details",
"grader": "root.graders:grade_find_ssl_config",
"score_range": [0.01, 0.99],
},
{
"id": 2,
"name": "medium",
"description": "Find PostgreSQL setup instructions",
"grader": "root.graders:grade_find_postgres_setup",
"score_range": [0.01, 0.99],
},
{
"id": 3,
"name": "hard",
"description": "Retrieve OAuth authentication steps",
"grader": "root.graders:grade_find_oauth_guide",
"score_range": [0.01, 0.99],
},
]
}
@app.get("/health")
def health():
return {"status": "ok"}
|