Build an Agent Pipeline to Revise Contracts Against Rule Sets
Machine LearningModel answerLast updated
Design a system that uses LLMs to automatically rewrite a contract so it satisfies dozens of compliance rules, handling overlaps, conflicts, verification, and cost.
You're building an automated compliance system. The input consists of a contract document and a set of dozens of compliance rules. Each rule specifies a requirement the contract must meet. Your task is to design an LLM-powered agent architecture that modifies the contract to satisfy all the rules and produces a compliant output.
Walk through your architecture: how you structure the processing pipeline, how you represent and coordinate edits when multiple rules target overlapping sections, how you validate that all rules are met, and the trade-offs in terms of API cost and response time.
What You Should Address
- Work decomposition: How do you break the problem across LLM calls?
- Edit representation: What format captures each proposed change and which rule triggered it?
- Conflict handling: What happens when two rules affect the same clause in incompatible ways?
- Validation: How do you confirm every rule is satisfied and no unintended edits were made?
- Practical constraints: Latency, token cost, failure modes, and observability.
Clarifying Assumptions
Before diving in, consider asking:
- What is the contract length relative to the model context window?
- Can rules contradict each other, and is there a priority ordering?
- Should the output include change tracking and justifications, or just the final text?
- What latency and cost budget is acceptable per contract?
- Is a human lawyer reviewing the result before it's finalized?
- Must sections unaffected by any rule remain byte-for-byte identical?
Hints
Hint 1
Don't try to apply all rules in a single prompt—think about parallelism, attribution, and retry granularity.
Hint 2
Consider how you'll represent proposed edits so they can be merged, prioritized, or rejected without corrupting the document.
Hint 3
Verification is separate from generation: use a different prompt or model call to check whether each rule is satisfied in the final draft.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture
A strong design decomposes the task into rule analysis, parallel edit proposal, conflict resolution, merge, and verification, with observability at each stage.
1. Rule Analysis and Chunking
Decompose by rule, not by applying everything at once.
Sending all dozens of rules in one prompt reduces traceability, makes retries all-or-nothing, and increases the risk of the model missing a rule or hallucinating edits.
- Per-rule agents: Spawn one LLM call per rule (or small batches of 3–5 related rules). Each call receives the original contract and one rule, and proposes the minimal edit required to satisfy that rule.
- Parallel execution: Rules are independent in the first pass, so calls run concurrently. This cuts latency from n sequential calls to one round-trip.
- Chunking for long contracts: If the contract exceeds the context window, split it into overlapping chunks (e.g., by section with 10% overlap). Each per-rule agent processes only the chunks relevant to that rule, determined by keyword or embedding similarity.
2. Edit Representation
Each agent returns a structured edit proposal, not raw revised text. A clean format is:
{
"rule_id": "R14",
"rule_text": "Indemnification cap must not exceed $1M",
"location": {"section": "7.3", "start_char": 1024, "end_char": 1087},
"original_text": "liable for damages without limit",
"proposed_text": "liable for damages up to $1,000,000",
"justification": "Inserted cap at $1M per rule R14"
}
This enables:
- Traceability: Every change cites the rule that required it.
- Conflict detection: Two edits with overlapping character ranges signal a conflict.
- Granular retries: If one edit fails validation, re-run only that rule's agent.
3. Conflict Detection and Resolution
Overlaps are common: two rules may both revise the same liability clause.
- Detect overlaps: Sort edits by
start_charand flag pairs with[start_A, end_A)intersecting[start_B, end_B). - Resolution strategies:
- Priority ordering: If rules have explicit precedence (e.g., statutory rules override boilerplate preferences), apply the higher-priority edit and re-validate the lower-priority rule against the result.
- Sequential composition: Apply edit A, then re-run the agent for rule B against the updated text. Repeat until both rules pass verification.
- Merge prompt: Send both conflicting edits and both rules to a dedicated LLM call that produces one combined edit satisfying both. This is expensive but necessary when rules genuinely interact.
- Human escalation: If the model cannot resolve the conflict after two attempts, flag it for human review.
4. Merging Edits into the Contract
Once conflicts are resolved, apply edits in reverse document order (highest start_char first) so earlier offsets remain valid. Construct the final draft by replacing each [start, end) span with the proposed_text.
Track which sections were untouched: this is key for validating that the system didn't introduce spurious changes.
5. Verification
Generation and verification should be separate.
After merging, run a verification pass for each rule:
- Per-rule validator: Send the final contract and one rule to a fresh LLM call with the prompt: "Does this contract satisfy the following rule? Answer yes or no, and cite the relevant clause."
- Parallel validation: These calls are independent and run concurrently.
- Failure handling: If rule R fails verification, log it, re-run the edit agent for R (possibly with the validator's feedback as context), re-merge, and re-validate. Cap retries at 2–3 per rule.
Check for unintended edits: Diff the final contract against the original. Any changed spans not covered by an edit proposal indicate model drift or hallucination; flag these for review.
6. Latency and Cost Trade-offs
| Strategy | Latency | Cost | Trade-off |
|---|---|---|---|
| Single prompt, all rules | 1 call | Low tokens | High failure rate, no traceability |
| Sequential per-rule | n × latency | n calls | Prohibitively slow |
| Parallel per-rule + parallel validation | 2 rounds | ~2n calls | Recommended: fast, traceable, retryable |
| Batch rules (3–5 per call) | 2 rounds | ~0.4n calls | Saves cost, slightly less traceable |
Concrete example: 50 rules, 10-page contract.
- Parallel per-rule: 50 edit calls + 50 validation calls = 100 calls, ~2 rounds → 20–30 seconds end-to-end, ~$5–10 at GPT-4 pricing.
- Sequential: 100 calls in series → 5–10 minutes.
Use a cheaper model (GPT-3.5, Claude Haiku) for straightforward rules and reserve expensive models (GPT-4, Claude Opus) for complex legal reasoning or conflict resolution.
7. Observability and Failure Modes
- Logging: Record every edit proposal, conflict resolution decision, and validation result. Store the provenance graph: which rules triggered which edits.
- Partial failures: If 48 of 50 rules pass, return the best-effort draft with a report of the 2 failures and let a human address them.
- Retries: Retry transient API failures (rate limits, timeouts) with exponential backoff. Retry validation failures by regenerating the edit, not by blindly retrying the same API call.
- Human-in-the-loop: For high-stakes contracts, always include a final human review. The system should produce a tracked-changes document (Word, PDF with annotations) showing what changed and why.
Common Mistakes
- Single mega-prompt: Trying to apply all rules in one call. This is brittle, opaque, and can't recover from partial failures.
- Ignoring conflicts: Naively applying overlapping edits in arbitrary order produces malformed text.
- No verification loop: Trusting the model's edits without checking. Generation and validation must be decoupled.
- Character offsets in mutable text: Applying edits in forward order invalidates later offsets. Always apply in reverse.
- Overfitting to success: Not planning for retries, API failures, or unsatisfiable rule combinations.
Summary
A production system uses parallel per-rule agents that emit structured, traceable edits, a conflict resolver that handles overlaps via priority or composition, a separate verification pass for each rule, and robust retry and logging. This balances speed (30s for 50 rules), cost ($5–10), and reliability, while keeping a human in the loop for final sign-off.