""" 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 """ RL Documentation Parser

🤖 RL Documentation Parser

An OpenEnv-compatible Gymnasium environment where an agent learns to navigate a mock file system to answer user queries using technical documentation.

Quick Links

Actions

Rewards

""" @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"}