#!/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())