File size: 9,319 Bytes
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
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/env python3
"""
Baseline runner: deterministic heuristic and optional OpenAI policy.

Loads `.env` from the current working directory and from the directory containing
this script (so `legal_contract_env/.env` works). API key: `OPENAI_API_KEY`, then
`HF_TOKEN` as fallback. Strict one JSON object per log line on stderr for tooling.

Usage:
  # Terminal 1
  uvicorn app:app --host 127.0.0.1 --port 8000

  # Terminal 2 (from this directory)
  pip install -e ".[baseline]"
  export BASE_URL=http://127.0.0.1:8000
  python inference.py

  python inference.py --use-openai   # OPENAI_API_KEY in .env or env
  python inference.py --local        # no server; direct env (repro scores)
"""

from __future__ import annotations

import argparse
import asyncio
import json
import logging
import os
import sys
from pathlib import Path
from typing import Any, Dict, List, Literal, Optional

from legal_contract_env.grader import normalize_clause_type
from legal_contract_env.models import ContractAction, ContractObservation

logging.basicConfig(level=logging.INFO)
log = logging.getLogger("legal_contract_baseline")


def _log_event(obj: Dict[str, Any]) -> None:
    sys.stderr.write(json.dumps(obj, sort_keys=True) + "\n")
    sys.stderr.flush()


def _load_dotenv() -> None:
    """Populate os.environ from .env (does not override already-set variables)."""
    try:
        from dotenv import load_dotenv
    except ImportError:
        return
    here = Path(__file__).resolve().parent
    load_dotenv(here / ".env")
    load_dotenv()


Task = Literal["classify", "risk", "fix"]


def _heuristic_classify(clause: str) -> str:
    t = clause.lower()
    if "termination" in t:
        return "termination"
    if "auto-renew" in t or "renews" in t or "renew" in t:
        return "auto_renewal"
    if "liability" in t or "unlimited" in t:
        return "liability"
    return "liability"


def _heuristic_fix(clause_type: str) -> str:
    from legal_contract_env.models import STANDARD_RULES

    key = normalize_clause_type(clause_type) or clause_type
    return STANDARD_RULES.get(key, STANDARD_RULES["liability"])


async def _llm_next_action(
    task: Task,
    obs: ContractObservation,
    model: str,
) -> ContractAction:
    from openai import OpenAI

    api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("HF_TOKEN")
    if not api_key:
        raise RuntimeError(
            "Set OPENAI_API_KEY (e.g. in .env) or HF_TOKEN for --use-openai"
        )

    client = OpenAI(api_key=api_key)
    system = (
        "You are a legal contract reviewer. Reply with a single JSON object only, "
        "no markdown. Fields: action_type (classify_clause|flag_risk|suggest_fix|finish), "
        "clause_index (int|null), clause_type (string|null), risk_flag (bool|null), "
        "suggestion (string|null). "
        f"Current task mode is {task!r}. "
        "For classify_clause you must output the clause type: liability, termination, or auto_renewal. "
        "For flag_risk, risk_flag is whether the clause is risky under vendor/NDA heuristics. "
        "For suggest_fix, suggestion is a short safer replacement. "
        "Call finish only when the task is complete."
    )
    user = json.dumps(
        {
            "task": task,
            "document_text": obs.document_text,
            "clauses": obs.clauses,
            "standard_rules": obs.standard_rules,
            "step_count": obs.step_count,
            "message": obs.message,
        },
        indent=2,
    )

    resp = client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": system},
            {"role": "user", "content": user},
        ],
        response_format={"type": "json_object"},
        temperature=0,
    )
    raw = resp.choices[0].message.content or "{}"
    data = json.loads(raw)
    _log_event({"event": "llm_raw", "task": task, "data": data})
    return ContractAction.model_validate(data)


async def run_episode_remote(
    base_url: str,
    task: Task,
    use_openai: bool,
    model: str,
) -> Dict[str, Any]:
    from legal_contract_env.client import LegalContractEnv

    classified: set[int] = set()
    risked: set[int] = set()
    fixed: set[int] = set()

    async with LegalContractEnv(base_url=base_url) as env:
        result = await env.reset(task=task)
        total_reward = 0.0
        steps = 0
        final_grader: Optional[float] = None

        while not result.done and steps < 64:
            obs = result.observation
            if use_openai:
                action = await _llm_next_action(task, obs, model=model)
            else:
                action = _heuristic_pick(task, obs, classified, risked, fixed)

            _log_event(
                {
                    "event": "step",
                    "task": task,
                    "steps": steps,
                    "action": action.model_dump(mode="json", exclude_none=True),
                }
            )

            result = await env.step(action)
            if result.reward is not None:
                total_reward += float(result.reward)
            steps += 1

            if result.observation.grader_score is not None:
                final_grader = result.observation.grader_score

            _track_action(action, classified, risked, fixed)

        return {
            "task": task,
            "steps": steps,
            "total_reward": total_reward,
            "grader_score": final_grader,
            "done": result.done,
            "episode_return": result.observation.episode_return,
        }


def _heuristic_pick(
    task: Task,
    obs: ContractObservation,
    classified: set[int],
    risked: set[int],
    fixed: set[int],
) -> ContractAction:
    n = len(obs.clauses)
    if task == "classify":
        for i in range(n):
            if i not in classified:
                return ContractAction(
                    action_type="classify_clause",
                    clause_index=i,
                    clause_type=_heuristic_classify(obs.clauses[i]),
                )
        return ContractAction(action_type="finish")
    if task == "risk":
        for i in range(n):
            if i not in risked:
                return ContractAction(
                    action_type="flag_risk", clause_index=i, risk_flag=True
                )
        return ContractAction(action_type="finish")
    risky_indices = [0, 1, 2]
    for i in risky_indices:
        if i < n and i not in fixed:
            ct = _heuristic_classify(obs.clauses[i])
            return ContractAction(
                action_type="suggest_fix",
                clause_index=i,
                suggestion=_heuristic_fix(ct),
            )
    return ContractAction(action_type="finish")


def _track_action(
    action: ContractAction,
    classified: set[int],
    risked: set[int],
    fixed: set[int],
) -> None:
    if action.action_type == "classify_clause" and action.clause_index is not None:
        classified.add(action.clause_index)
    elif action.action_type == "flag_risk" and action.clause_index is not None:
        risked.add(action.clause_index)
    elif action.action_type == "suggest_fix" and action.clause_index is not None:
        fixed.add(action.clause_index)


def run_episode_local(task: Task) -> Dict[str, Any]:
    from legal_contract_env.server.legal_contract_environment import LegalContractEnvironment

    env = LegalContractEnvironment()
    obs = env.reset(task=task)
    total_reward = 0.0
    steps = 0
    classified: set[int] = set()
    risked: set[int] = set()
    fixed: set[int] = set()

    while not obs.done and steps < 64:
        action = _heuristic_pick(task, obs, classified, risked, fixed)
        _log_event(
            {
                "event": "step_local",
                "task": task,
                "action": action.model_dump(mode="json", exclude_none=True),
            }
        )
        obs = env.step(action)
        if obs.reward is not None:
            total_reward += float(obs.reward)
        steps += 1
        _track_action(action, classified, risked, fixed)

    return {
        "task": task,
        "steps": steps,
        "total_reward": total_reward,
        "grader_score": obs.grader_score,
        "episode_return": obs.episode_return,
        "done": obs.done,
    }


async def main_async() -> None:
    _load_dotenv()

    p = argparse.ArgumentParser()
    p.add_argument("--base-url", default=os.environ.get("BASE_URL", "http://127.0.0.1:8000"))
    p.add_argument("--use-openai", action="store_true")
    p.add_argument("--model", default=os.environ.get("OPENAI_MODEL", "gpt-4o-mini"))
    p.add_argument("--local", action="store_true", help="Run LegalContractEnvironment in-process")
    args = p.parse_args()

    tasks: List[Task] = ["classify", "risk", "fix"]
    summary: Dict[str, Any] = {"tasks": {}, "config": vars(args)}

    for task in tasks:
        if args.local:
            summary["tasks"][task] = run_episode_local(task)
        else:
            summary["tasks"][task] = await run_episode_remote(
                args.base_url, task, args.use_openai, args.model
            )

    _log_event({"event": "summary", "data": summary})
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    asyncio.run(main_async())