File size: 5,798 Bytes
ff399ac
52ec3b0
 
 
 
ff399ac
 
52ec3b0
 
 
ff399ac
 
52ec3b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
---
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)).