--- title: Legal Contract Clause Review emoji: ⚖️ colorFrom: gray colorTo: blue sdk: docker pinned: false app_port: 8000 tags: - openenv --- # Legal Contract Clause Review (`legal_contract_env`) Realistic **vendor / NDA-style** workflow: an agent reviews a short contract with **pre-segmented clauses**, classifies each segment (**liability**, **termination**, **auto_renewal**), flags **policy risks**, and proposes **safer replacement language**. The server exposes the standard OpenEnv **reset / step / state** flow over HTTP and WebSocket with **Pydantic** `Action`, `Observation`, and `State` types. ## Action space (`ContractAction`) | Field | Description | | --- | --- | | `action_type` | `classify_clause`, `flag_risk`, `suggest_fix`, or `finish` | | `clause_index` | Index into `observation.clauses` (required except for `finish`) | | `clause_type` | For classify: `liability` \| `termination` \| `auto_renewal` | | `risk_flag` | For risk task: whether the clause is risky | | `suggestion` | For fix task: proposed replacement text | ## Observation space (`ContractObservation`) | Field | Description | | --- | --- | | `document_text` | Full contract text | | `clauses` | Pre-split clauses (easy mode; no span detection) | | `standard_rules` | Reference “safe” snippets by clause family | | `step_count` | Steps in the current episode | | `task` | Active task: `classify`, `risk`, or `fix` | | `message` | Short status from the environment | | `grader_score` | Set when `done=True`: deterministic score in **[0, 1]** | | `episode_return` | Cumulative reward when the episode ends | ## Tasks (three levels) 1. **Classify (easy)** — Map each clause to the correct type. **Grader:** exact accuracy in `[0, 1]`. **Step rewards:** +0.2 correct, −0.1 wrong type, −0.1 duplicate index, −0.2 invalid index. 2. **Risk (medium)** — Mark risky clauses (unlimited liability, auto-renew without notice, missing termination). **Grader:** `0.6 × recall + 0.4 × precision` on the risky label. **Step rewards:** +0.3 correct, −0.2 false positive / missed risk. 3. **Suggest fix (hard)** — For each **ground-truth risky** clause, propose a concise safer alternative. **Grader:** average keyword coverage in `[0, 1]` (see `grader.py`). **Step rewards:** +0.5 strong match, +0.2 partial, −0.2 weak; −0.2 if the clause is not risky. **Episode termination:** the environment completes automatically when the task’s required work is done, or when the agent sends `finish` (early finish with incomplete work incurs **−0.5** on that step). Wrong action type for the current task costs **−0.2**. Pass **`task`** on reset (WebSocket `reset` payload or HTTP body), e.g. `{"task": "classify"}`. ## Setup ```bash cd legal_contract_env python -m venv .venv && source .venv/bin/activate pip install -e ".[baseline]" ``` ### Run the server (local) ```bash uvicorn app:app --host 0.0.0.0 --port 8000 ``` **Web UI (HTML/CSS/JS):** open [http://127.0.0.1:8000/ui/](http://127.0.0.1:8000/ui/) in your browser (use **`127.0.0.1` or `localhost`**, not `0.0.0.0` — the page auto-fixes `0.0.0.0` to `127.0.0.1` for WebSockets). Click **Connect**, then **Reset**, then use the clause cards. The UI uses `/ws` on the same host. ### Docker ```bash docker build -t legal-contract-env:latest -f server/Dockerfile . docker run --rm -p 8000:8000 legal-contract-env:latest ``` ### OpenEnv validation With `openenv-core[cli]` installed: ```bash openenv validate /path/to/legal_contract_env # optional: against a running server openenv validate /path/to/legal_contract_env --url http://127.0.0.1:8000 ``` ## Baseline inference Deterministic **heuristic** policy (no API key) or **OpenAI**. For `--use-openai`, put **`OPENAI_API_KEY`** in a **`.env`** file next to `inference.py` (or in the process working directory). Copy `.env.example` to `.env`. Variables already set in the shell are not overwritten. `python-dotenv` is included in the **`baseline`** extra (`pip install -e ".[baseline]"`). ```bash export BASE_URL=http://127.0.0.1:8000 python inference.py ``` Structured logs (one JSON object per line) go to **stderr**; the final JSON summary goes to **stdout**. Local smoke test (no server): ```bash python inference.py --local ``` ### Reported baseline scores (heuristic, `--local`) | Task | Grader score | Typical step reward sum | Notes | | --- | ---: | ---: | --- | | classify | 1.0 | 0.6 | 3 × +0.2 | | risk | 1.0 | 0.9 | 3 × +0.3 | | fix | 1.0 | 1.5 | 3 × +0.5 | `episode_return` matches the environment’s internal cumulative reward (same as summing per-step rewards when the episode ends on the last productive step). *Re-run `python inference.py --local` after changes; LLM scores depend on model and temperature.* Lockfile: run `uv lock` in this directory if `openenv validate` reports a missing `uv.lock` (required for multi-mode deployment checks). ## Hugging Face Space - Use **Docker SDK**; this repo includes `server/Dockerfile` and `openenv.yaml`. - Set **`tags: [openenv]`** in Space metadata (see YAML front matter above). - Default port **8000**; health check hits `/health`. ## Layout | Path | Role | | --- | --- | | `models.py` | Pydantic `ContractAction`, `ContractObservation`, `ContractState` | | `grader.py` | Deterministic `[0,1]` graders | | `server/legal_contract_environment.py` | `Environment` implementation | | `app.py` | `create_app` entrypoint (`uvicorn app:app`) | | `server/app.py` | Thin shim (OpenEnv layout); forwards to `app.py` | | `client.py` | `LegalContractEnv` WebSocket client | | `inference.py` | Baseline runner + optional OpenAI | | `web/` | Static HTML/CSS/JS UI at `/ui/` | | `openenv.yaml` | OpenEnv manifest | ## License BSD 3-Clause (aligns with [OpenEnv](https://github.com/meta-pytorch/OpenEnv)).