contractguardian 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,35 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ${{ matrix.os }}
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ os: [ubuntu-latest, windows-latest]
16
+ python-version: ["3.10", "3.11", "3.12"]
17
+
18
+ steps:
19
+ - uses: actions/checkout@v6
20
+
21
+ - name: Set up Python ${{ matrix.python-version }}
22
+ uses: actions/setup-python@v6
23
+ with:
24
+ python-version: ${{ matrix.python-version }}
25
+
26
+ - name: Install dependencies
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ pip install -e ".[dev]"
30
+
31
+ - name: Lint with ruff
32
+ run: ruff check .
33
+
34
+ - name: Run tests
35
+ run: pytest tests/ -v
@@ -0,0 +1,15 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *$py.class
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .eggs/
8
+ *.egg
9
+ .env
10
+ .venv/
11
+ venv/
12
+ .ruff_cache/
13
+ .pytest_cache/
14
+ .mypy_cache/
15
+ .tmp/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yufeng He
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,280 @@
1
+ Metadata-Version: 2.4
2
+ Name: contractguardian
3
+ Version: 0.2.0
4
+ Summary: AI-powered contract review agent — scan any contract for red flags, unfair terms, and missing protections
5
+ Project-URL: Homepage, https://github.com/he-yufeng/ContractGuard
6
+ Project-URL: Repository, https://github.com/he-yufeng/ContractGuard
7
+ Project-URL: Issues, https://github.com/he-yufeng/ContractGuard/issues
8
+ Author-email: Yufeng He <40085740+he-yufeng@users.noreply.github.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: agent,ai,contract,guard,legal,llm,red-flag,review
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: End Users/Desktop
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Office/Business
20
+ Classifier: Topic :: Text Processing :: General
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: click>=8.0
23
+ Requires-Dist: openai>=1.0
24
+ Requires-Dist: pdfplumber>=0.10
25
+ Requires-Dist: pydantic>=2.0
26
+ Requires-Dist: python-docx>=1.0
27
+ Requires-Dist: rich>=13.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
30
+ Requires-Dist: pytest>=7.0; extra == 'dev'
31
+ Requires-Dist: ruff>=0.4; extra == 'dev'
32
+ Provides-Extra: ocr
33
+ Requires-Dist: pytesseract>=0.3; extra == 'ocr'
34
+ Provides-Extra: web
35
+ Requires-Dist: gradio>=4.0; extra == 'web'
36
+ Description-Content-Type: text/markdown
37
+
38
+ <div align="center">
39
+
40
+ <img src="docs/banner.png" alt="ContractGuard — never sign a bad contract again" width="100%">
41
+
42
+ Upload any contract → get red flags, unfair terms, and plain-English explanations in seconds.
43
+
44
+ [![PyPI](https://img.shields.io/pypi/v/contractguardian.svg)](https://pypi.org/project/contractguardian/)
45
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
46
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
47
+ [![CI](https://github.com/he-yufeng/ContractGuard/actions/workflows/ci.yml/badge.svg)](https://github.com/he-yufeng/ContractGuard/actions)
48
+
49
+ **[English](README.md) · [中文](README_CN.md)** &nbsp;·&nbsp; [Demo](#demo) · [Quick Start](#quick-start) · [How It Works](#how-it-works)
50
+
51
+ </div>
52
+
53
+ ---
54
+
55
+ ## Why ContractGuard?
56
+
57
+ Every year, millions of people sign contracts they don't fully understand — apartment leases with hidden penalties, employment agreements with overly broad non-competes, NDAs that silently strip away your rights. Hiring a lawyer costs $300-500/hour. Most people just sign and hope for the best.
58
+
59
+ **ContractGuard** changes that. It's an open-source AI agent that reads every clause of your contract, flags problems in plain language, and tells you exactly what to negotiate — all in under 30 seconds.
60
+
61
+ **What makes it different from ChatGPT?**
62
+ - **Structured analysis**, not a wall of text — you get categorized red flags, warnings, protections, and a fairness score
63
+ - **Actionable suggestions** for every issue found — not just "this is bad" but "change it to this"
64
+ - **Consistent output format** via Pydantic models — easy to integrate into other tools
65
+ - **CLI-first design** — one command, beautiful terminal output, no browser needed
66
+ - **Works with any LLM** — OpenRouter, OpenAI, Ollama (fully local/private)
67
+
68
+ ## Demo
69
+
70
+ ```bash
71
+ contractguard scan my-lease.pdf
72
+ ```
73
+
74
+ ```
75
+ ✔ Parsed my-lease.pdf (4,521 characters)
76
+
77
+ ⬤ RED FLAGS (5 found)
78
+ ==================================================
79
+
80
+ 1. Non-refundable security deposit
81
+ Clause: Section 3
82
+ "The security deposit is non-refundable and shall
83
+ be retained by Landlord upon termination"
84
+ Most states require deposits to be refundable.
85
+ This clause is likely illegal in California.
86
+ Suggestion: Remove "non-refundable" language.
87
+
88
+ 2. Unlimited landlord access without notice
89
+ Clause: Section 5
90
+ "Landlord shall have the right to enter the Property
91
+ at any time, with or without notice"
92
+ California law requires 24-hour written notice.
93
+ Suggestion: Add "with 24 hours written notice"
94
+
95
+ … 3 more red flags, 3 warnings, 2 protections, 4 missing protections …
96
+
97
+ FAIRNESS SCORE: D (28/100)
98
+ 5 red flags 3 warnings 2 protections 4 missing
99
+ ```
100
+
101
+ ## Quick Start
102
+
103
+ ### 1. Install
104
+
105
+ ```bash
106
+ pip install contractguardian
107
+ ```
108
+
109
+ ### 2. Set up your API key
110
+
111
+ ContractGuard works with any OpenAI-compatible API. Pick one:
112
+
113
+ **Option A: OpenRouter (recommended)** — access to Claude, GPT-4, DeepSeek, Gemini, and 100+ models through a single API key:
114
+
115
+ ```bash
116
+ export OPENROUTER_API_KEY=sk-or-...
117
+ ```
118
+
119
+ **Option B: OpenAI directly:**
120
+
121
+ ```bash
122
+ export OPENAI_API_KEY=sk-...
123
+ export OPENAI_BASE_URL=https://api.openai.com/v1
124
+ ```
125
+
126
+ **Option C: Local models via Ollama** — your contract data never leaves your machine:
127
+
128
+ ```bash
129
+ export OPENAI_BASE_URL=http://localhost:11434/v1
130
+ export OPENAI_API_KEY=ollama
131
+ ```
132
+
133
+ ### 3. Scan a contract
134
+
135
+ ```bash
136
+ contractguard scan my-contract.pdf
137
+ ```
138
+
139
+ That's it. Three steps, under 60 seconds.
140
+
141
+ ## Usage
142
+
143
+ ```bash
144
+ # Scan a PDF, DOCX, or TXT
145
+ contractguard scan lease.pdf
146
+
147
+ # Pick any OpenRouter / OpenAI / Ollama model
148
+ contractguard scan contract.pdf --model openai/gpt-4o
149
+
150
+ # Export a markdown report, or structured JSON for scripting
151
+ contractguard scan contract.pdf --output report.md
152
+ contractguard scan contract.pdf --json --output report.json
153
+
154
+ # Scan a whole folder, or diff two versions of a contract
155
+ contractguard batch ./contracts/ --output-dir reports/
156
+ contractguard compare lease-v1.pdf lease-v2.pdf
157
+ ```
158
+
159
+ ### Python API
160
+
161
+ ```python
162
+ from contractguard.analyzer import analyze_contract
163
+ from contractguard.parser import extract_text
164
+
165
+ result = analyze_contract(extract_text("my-lease.pdf"))
166
+ print(f"{result.fairness_grade} ({result.fairness_score}/100)")
167
+ for flag in result.red_flags:
168
+ print(f"- {flag.title} ({flag.clause}): {flag.suggestion}")
169
+ ```
170
+
171
+ `--json` emits the full structured result — contract type, parties, key terms, red flags, warnings, protections, and fairness score — as a Pydantic-backed object ready to pipe into other tools.
172
+
173
+ ## Supported File Formats
174
+
175
+ | Format | Extension | Notes |
176
+ |--------|-----------|-------|
177
+ | PDF | `.pdf` | Text-based PDFs. Scanned/image-based PDFs require OCR (coming soon). |
178
+ | Word | `.docx` | Microsoft Word documents |
179
+ | Plain Text | `.txt` | Plain text files |
180
+ | Markdown | `.md` | Markdown files |
181
+ | Rich Text | `.rtf` | Rich Text Format files |
182
+
183
+ ## Supported Contract Types
184
+
185
+ ContractGuard automatically detects the contract type and tailors its analysis accordingly. Each type has specific red flags and industry-standard protections it checks for:
186
+
187
+ | Contract Type | What ContractGuard Checks |
188
+ |---|---|
189
+ | **Residential Leases** | Rent increases, deposit refundability, maintenance obligations, landlord access rights, early termination penalties, habitability guarantees |
190
+ | **NDAs / Confidentiality** | Scope of "confidential information" (too broad?), duration, non-solicitation, non-compete, carve-outs for prior knowledge, return/destruction of materials |
191
+ | **Employment Contracts** | Non-compete scope & duration, IP assignment (does employer own your side projects?), termination notice period, severance, at-will vs. for-cause, benefits |
192
+ | **Freelance / Contractor** | Payment terms & schedule, kill fees, IP ownership, indemnification, scope creep protections, late payment penalties |
193
+ | **SaaS Terms of Service** | Data ownership & portability, auto-renewal & cancellation, SLA guarantees, limitation of liability, unilateral modification rights |
194
+ | **Loan Agreements** | Interest rate (fixed vs. variable), prepayment penalties, default triggers, personal guarantee scope, collateral requirements |
195
+ | **Purchase Agreements** | Warranty terms, return/refund policy, liability limits, dispute resolution (arbitration vs. court), force majeure |
196
+
197
+ ## How It Works
198
+
199
+ ![ContractGuard pipeline](docs/architecture.png)
200
+
201
+ 1. **Parse** — Extracts text from your document (PDF, DOCX, TXT). For PDFs, uses `pdfplumber` to handle complex layouts. For DOCX, uses `python-docx` to read all paragraphs.
202
+
203
+ 2. **Detect** — Sends the extracted text to the LLM, which automatically identifies the contract type (lease, NDA, employment, etc.) and adjusts its analysis strategy.
204
+
205
+ 3. **Analyze** — The AI agent reviews every clause and categorizes findings into four groups:
206
+ - **Red Flags** — Serious issues that could cause financial harm, legal liability, or loss of rights. These are things you should push back on before signing.
207
+ - **Warnings** — Moderate concerns that are worth discussing but aren't necessarily deal-breakers. Common in many contracts but still worth knowing about.
208
+ - **Protections** — Good clauses that protect your interests. These are things the contract got right.
209
+ - **Missing Protections** — Standard clauses that are absent from the contract. Their absence may leave you exposed.
210
+
211
+ 4. **Score** — Generates an overall fairness grade from A+ (excellent, fair to both parties) to F (heavily one-sided, many red flags). The score is based on the number and severity of issues found, balanced against protections present.
212
+
213
+ 5. **Report** — Outputs results as a beautiful Rich-formatted terminal report, or exports to Markdown/JSON for sharing or further processing.
214
+
215
+ ## Configuration
216
+
217
+ ### LLM Providers
218
+
219
+ ContractGuard uses the OpenAI-compatible API format, so it works with virtually any LLM provider:
220
+
221
+ | Provider | Setup | Best For |
222
+ |----------|-------|----------|
223
+ | **OpenRouter** | `export OPENROUTER_API_KEY=sk-or-...` | Access to 100+ models through one API key |
224
+ | **OpenAI** | `export OPENAI_API_KEY=sk-...` + `export OPENAI_BASE_URL=https://api.openai.com/v1` | Direct access to GPT-4o, o1, etc. |
225
+ | **Anthropic (via OpenRouter)** | Use `--model anthropic/claude-sonnet-4` | Best reasoning for complex contracts |
226
+ | **Ollama (local)** | `export OPENAI_BASE_URL=http://localhost:11434/v1` | Maximum privacy — data never leaves your machine |
227
+ | **Azure OpenAI** | Set `OPENAI_BASE_URL` to your Azure endpoint | Enterprise compliance |
228
+ | **Any OpenAI-compatible API** | Set `OPENAI_BASE_URL` and `OPENAI_API_KEY` | Self-hosted models, vLLM, etc. |
229
+
230
+ Default model is `anthropic/claude-sonnet-4`. `google/gemini-2.5-pro` handles very long contracts (1M context), `deepseek/deepseek-chat` is the budget pick, and any Ollama model keeps your data local.
231
+
232
+ ## FAQ
233
+
234
+ **Is this legal advice?**
235
+ No. ContractGuard is an educational tool for understanding contract terms in plain language, not a substitute for a licensed attorney.
236
+
237
+ **Is my contract data sent to the cloud?**
238
+ Only to the LLM provider you configure. For full privacy, use a local model via Ollama — the text never leaves your machine. ContractGuard itself stores and logs nothing.
239
+
240
+ **What's the maximum contract length?**
241
+ About 30,000 tokens (~60 pages); longer documents are truncated. Use a large-context model like `google/gemini-2.5-pro` for very long contracts.
242
+
243
+ **Can I use it in CI/CD?**
244
+ Yes. `--json` gives parseable output; exit code is 0 on success, 1 on error. E.g. `contractguard scan contract.pdf --json | jq '.red_flags | length'`.
245
+
246
+ ## Roadmap
247
+
248
+ **Shipped:** batch scanning (analyze many contracts in one run) and contract comparison (diff two versions and surface what changed, clause by clause).
249
+
250
+ **Planned:**
251
+
252
+ - **OCR for scanned PDFs** — handle image-only contracts, not just text PDFs, which is where a lot of real paperwork actually lives.
253
+ - **Jurisdiction-aware analysis** — judge clauses against a chosen jurisdiction (US state law, EU, China), since whether a term is risky depends on where it's enforced.
254
+ - **Clause-by-clause negotiation drafts** — for each red flag, draft suggested replacement language, turning the report into the start of a redline.
255
+ - **A web UI** — a Streamlit/Gradio front end for people who won't touch a CLI, with the same local-only handling.
256
+ - **Pre-built contract templates** — a few common contract types with known red flags, useful both as a starting point and as a test corpus.
257
+
258
+ ## Related Projects
259
+
260
+ ContractGuard is one of my applied agent projects. A few others worth a look:
261
+
262
+ - **[CoreCoder](https://github.com/he-yufeng/CoreCoder)** — want to understand how a coding agent really works? Read the whole ~1k-line engine end to end, not a black box.
263
+ - **[RepoWiki](https://github.com/he-yufeng/RepoWiki)** — dropped into an unfamiliar codebase? It gives you a guided wiki and a where-to-start reading path, a self-hostable DeepWiki alternative.
264
+ - **[FindJobs-Agent](https://github.com/he-yufeng/FindJobs-Agent)** — stop sifting job boards by hand: it ranks postings against your resume and runs mock interviews.
265
+ - **[GitSense](https://github.com/he-yufeng/GitSense)** — want to contribute to open source? It finds issues worth your time and gauges whether your PR will get merged.
266
+ - **[CodeABC](https://github.com/he-yufeng/CodeABC)** — understand any codebase even if you don't code, built for non-programmers.
267
+
268
+ ## Contributing
269
+
270
+ Contributions are welcome! Here's how you can help:
271
+
272
+ - **Report bugs** — Open an [issue](https://github.com/he-yufeng/ContractGuard/issues) with the contract type and expected behavior
273
+ - **Add contract samples** — More sample contracts for testing (with intentional red flags)
274
+ - **Improve prompts** — Better LLM prompts for more accurate analysis
275
+ - **Add languages** — Test with contracts in different languages and report results
276
+ - **Build integrations** — MCP server, VS Code extension, Slack bot, etc.
277
+
278
+ ## License
279
+
280
+ [MIT](LICENSE) — use it however you want.
@@ -0,0 +1,243 @@
1
+ <div align="center">
2
+
3
+ <img src="docs/banner.png" alt="ContractGuard — never sign a bad contract again" width="100%">
4
+
5
+ Upload any contract → get red flags, unfair terms, and plain-English explanations in seconds.
6
+
7
+ [![PyPI](https://img.shields.io/pypi/v/contractguardian.svg)](https://pypi.org/project/contractguardian/)
8
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
9
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
10
+ [![CI](https://github.com/he-yufeng/ContractGuard/actions/workflows/ci.yml/badge.svg)](https://github.com/he-yufeng/ContractGuard/actions)
11
+
12
+ **[English](README.md) · [中文](README_CN.md)** &nbsp;·&nbsp; [Demo](#demo) · [Quick Start](#quick-start) · [How It Works](#how-it-works)
13
+
14
+ </div>
15
+
16
+ ---
17
+
18
+ ## Why ContractGuard?
19
+
20
+ Every year, millions of people sign contracts they don't fully understand — apartment leases with hidden penalties, employment agreements with overly broad non-competes, NDAs that silently strip away your rights. Hiring a lawyer costs $300-500/hour. Most people just sign and hope for the best.
21
+
22
+ **ContractGuard** changes that. It's an open-source AI agent that reads every clause of your contract, flags problems in plain language, and tells you exactly what to negotiate — all in under 30 seconds.
23
+
24
+ **What makes it different from ChatGPT?**
25
+ - **Structured analysis**, not a wall of text — you get categorized red flags, warnings, protections, and a fairness score
26
+ - **Actionable suggestions** for every issue found — not just "this is bad" but "change it to this"
27
+ - **Consistent output format** via Pydantic models — easy to integrate into other tools
28
+ - **CLI-first design** — one command, beautiful terminal output, no browser needed
29
+ - **Works with any LLM** — OpenRouter, OpenAI, Ollama (fully local/private)
30
+
31
+ ## Demo
32
+
33
+ ```bash
34
+ contractguard scan my-lease.pdf
35
+ ```
36
+
37
+ ```
38
+ ✔ Parsed my-lease.pdf (4,521 characters)
39
+
40
+ ⬤ RED FLAGS (5 found)
41
+ ==================================================
42
+
43
+ 1. Non-refundable security deposit
44
+ Clause: Section 3
45
+ "The security deposit is non-refundable and shall
46
+ be retained by Landlord upon termination"
47
+ Most states require deposits to be refundable.
48
+ This clause is likely illegal in California.
49
+ Suggestion: Remove "non-refundable" language.
50
+
51
+ 2. Unlimited landlord access without notice
52
+ Clause: Section 5
53
+ "Landlord shall have the right to enter the Property
54
+ at any time, with or without notice"
55
+ California law requires 24-hour written notice.
56
+ Suggestion: Add "with 24 hours written notice"
57
+
58
+ … 3 more red flags, 3 warnings, 2 protections, 4 missing protections …
59
+
60
+ FAIRNESS SCORE: D (28/100)
61
+ 5 red flags 3 warnings 2 protections 4 missing
62
+ ```
63
+
64
+ ## Quick Start
65
+
66
+ ### 1. Install
67
+
68
+ ```bash
69
+ pip install contractguardian
70
+ ```
71
+
72
+ ### 2. Set up your API key
73
+
74
+ ContractGuard works with any OpenAI-compatible API. Pick one:
75
+
76
+ **Option A: OpenRouter (recommended)** — access to Claude, GPT-4, DeepSeek, Gemini, and 100+ models through a single API key:
77
+
78
+ ```bash
79
+ export OPENROUTER_API_KEY=sk-or-...
80
+ ```
81
+
82
+ **Option B: OpenAI directly:**
83
+
84
+ ```bash
85
+ export OPENAI_API_KEY=sk-...
86
+ export OPENAI_BASE_URL=https://api.openai.com/v1
87
+ ```
88
+
89
+ **Option C: Local models via Ollama** — your contract data never leaves your machine:
90
+
91
+ ```bash
92
+ export OPENAI_BASE_URL=http://localhost:11434/v1
93
+ export OPENAI_API_KEY=ollama
94
+ ```
95
+
96
+ ### 3. Scan a contract
97
+
98
+ ```bash
99
+ contractguard scan my-contract.pdf
100
+ ```
101
+
102
+ That's it. Three steps, under 60 seconds.
103
+
104
+ ## Usage
105
+
106
+ ```bash
107
+ # Scan a PDF, DOCX, or TXT
108
+ contractguard scan lease.pdf
109
+
110
+ # Pick any OpenRouter / OpenAI / Ollama model
111
+ contractguard scan contract.pdf --model openai/gpt-4o
112
+
113
+ # Export a markdown report, or structured JSON for scripting
114
+ contractguard scan contract.pdf --output report.md
115
+ contractguard scan contract.pdf --json --output report.json
116
+
117
+ # Scan a whole folder, or diff two versions of a contract
118
+ contractguard batch ./contracts/ --output-dir reports/
119
+ contractguard compare lease-v1.pdf lease-v2.pdf
120
+ ```
121
+
122
+ ### Python API
123
+
124
+ ```python
125
+ from contractguard.analyzer import analyze_contract
126
+ from contractguard.parser import extract_text
127
+
128
+ result = analyze_contract(extract_text("my-lease.pdf"))
129
+ print(f"{result.fairness_grade} ({result.fairness_score}/100)")
130
+ for flag in result.red_flags:
131
+ print(f"- {flag.title} ({flag.clause}): {flag.suggestion}")
132
+ ```
133
+
134
+ `--json` emits the full structured result — contract type, parties, key terms, red flags, warnings, protections, and fairness score — as a Pydantic-backed object ready to pipe into other tools.
135
+
136
+ ## Supported File Formats
137
+
138
+ | Format | Extension | Notes |
139
+ |--------|-----------|-------|
140
+ | PDF | `.pdf` | Text-based PDFs. Scanned/image-based PDFs require OCR (coming soon). |
141
+ | Word | `.docx` | Microsoft Word documents |
142
+ | Plain Text | `.txt` | Plain text files |
143
+ | Markdown | `.md` | Markdown files |
144
+ | Rich Text | `.rtf` | Rich Text Format files |
145
+
146
+ ## Supported Contract Types
147
+
148
+ ContractGuard automatically detects the contract type and tailors its analysis accordingly. Each type has specific red flags and industry-standard protections it checks for:
149
+
150
+ | Contract Type | What ContractGuard Checks |
151
+ |---|---|
152
+ | **Residential Leases** | Rent increases, deposit refundability, maintenance obligations, landlord access rights, early termination penalties, habitability guarantees |
153
+ | **NDAs / Confidentiality** | Scope of "confidential information" (too broad?), duration, non-solicitation, non-compete, carve-outs for prior knowledge, return/destruction of materials |
154
+ | **Employment Contracts** | Non-compete scope & duration, IP assignment (does employer own your side projects?), termination notice period, severance, at-will vs. for-cause, benefits |
155
+ | **Freelance / Contractor** | Payment terms & schedule, kill fees, IP ownership, indemnification, scope creep protections, late payment penalties |
156
+ | **SaaS Terms of Service** | Data ownership & portability, auto-renewal & cancellation, SLA guarantees, limitation of liability, unilateral modification rights |
157
+ | **Loan Agreements** | Interest rate (fixed vs. variable), prepayment penalties, default triggers, personal guarantee scope, collateral requirements |
158
+ | **Purchase Agreements** | Warranty terms, return/refund policy, liability limits, dispute resolution (arbitration vs. court), force majeure |
159
+
160
+ ## How It Works
161
+
162
+ ![ContractGuard pipeline](docs/architecture.png)
163
+
164
+ 1. **Parse** — Extracts text from your document (PDF, DOCX, TXT). For PDFs, uses `pdfplumber` to handle complex layouts. For DOCX, uses `python-docx` to read all paragraphs.
165
+
166
+ 2. **Detect** — Sends the extracted text to the LLM, which automatically identifies the contract type (lease, NDA, employment, etc.) and adjusts its analysis strategy.
167
+
168
+ 3. **Analyze** — The AI agent reviews every clause and categorizes findings into four groups:
169
+ - **Red Flags** — Serious issues that could cause financial harm, legal liability, or loss of rights. These are things you should push back on before signing.
170
+ - **Warnings** — Moderate concerns that are worth discussing but aren't necessarily deal-breakers. Common in many contracts but still worth knowing about.
171
+ - **Protections** — Good clauses that protect your interests. These are things the contract got right.
172
+ - **Missing Protections** — Standard clauses that are absent from the contract. Their absence may leave you exposed.
173
+
174
+ 4. **Score** — Generates an overall fairness grade from A+ (excellent, fair to both parties) to F (heavily one-sided, many red flags). The score is based on the number and severity of issues found, balanced against protections present.
175
+
176
+ 5. **Report** — Outputs results as a beautiful Rich-formatted terminal report, or exports to Markdown/JSON for sharing or further processing.
177
+
178
+ ## Configuration
179
+
180
+ ### LLM Providers
181
+
182
+ ContractGuard uses the OpenAI-compatible API format, so it works with virtually any LLM provider:
183
+
184
+ | Provider | Setup | Best For |
185
+ |----------|-------|----------|
186
+ | **OpenRouter** | `export OPENROUTER_API_KEY=sk-or-...` | Access to 100+ models through one API key |
187
+ | **OpenAI** | `export OPENAI_API_KEY=sk-...` + `export OPENAI_BASE_URL=https://api.openai.com/v1` | Direct access to GPT-4o, o1, etc. |
188
+ | **Anthropic (via OpenRouter)** | Use `--model anthropic/claude-sonnet-4` | Best reasoning for complex contracts |
189
+ | **Ollama (local)** | `export OPENAI_BASE_URL=http://localhost:11434/v1` | Maximum privacy — data never leaves your machine |
190
+ | **Azure OpenAI** | Set `OPENAI_BASE_URL` to your Azure endpoint | Enterprise compliance |
191
+ | **Any OpenAI-compatible API** | Set `OPENAI_BASE_URL` and `OPENAI_API_KEY` | Self-hosted models, vLLM, etc. |
192
+
193
+ Default model is `anthropic/claude-sonnet-4`. `google/gemini-2.5-pro` handles very long contracts (1M context), `deepseek/deepseek-chat` is the budget pick, and any Ollama model keeps your data local.
194
+
195
+ ## FAQ
196
+
197
+ **Is this legal advice?**
198
+ No. ContractGuard is an educational tool for understanding contract terms in plain language, not a substitute for a licensed attorney.
199
+
200
+ **Is my contract data sent to the cloud?**
201
+ Only to the LLM provider you configure. For full privacy, use a local model via Ollama — the text never leaves your machine. ContractGuard itself stores and logs nothing.
202
+
203
+ **What's the maximum contract length?**
204
+ About 30,000 tokens (~60 pages); longer documents are truncated. Use a large-context model like `google/gemini-2.5-pro` for very long contracts.
205
+
206
+ **Can I use it in CI/CD?**
207
+ Yes. `--json` gives parseable output; exit code is 0 on success, 1 on error. E.g. `contractguard scan contract.pdf --json | jq '.red_flags | length'`.
208
+
209
+ ## Roadmap
210
+
211
+ **Shipped:** batch scanning (analyze many contracts in one run) and contract comparison (diff two versions and surface what changed, clause by clause).
212
+
213
+ **Planned:**
214
+
215
+ - **OCR for scanned PDFs** — handle image-only contracts, not just text PDFs, which is where a lot of real paperwork actually lives.
216
+ - **Jurisdiction-aware analysis** — judge clauses against a chosen jurisdiction (US state law, EU, China), since whether a term is risky depends on where it's enforced.
217
+ - **Clause-by-clause negotiation drafts** — for each red flag, draft suggested replacement language, turning the report into the start of a redline.
218
+ - **A web UI** — a Streamlit/Gradio front end for people who won't touch a CLI, with the same local-only handling.
219
+ - **Pre-built contract templates** — a few common contract types with known red flags, useful both as a starting point and as a test corpus.
220
+
221
+ ## Related Projects
222
+
223
+ ContractGuard is one of my applied agent projects. A few others worth a look:
224
+
225
+ - **[CoreCoder](https://github.com/he-yufeng/CoreCoder)** — want to understand how a coding agent really works? Read the whole ~1k-line engine end to end, not a black box.
226
+ - **[RepoWiki](https://github.com/he-yufeng/RepoWiki)** — dropped into an unfamiliar codebase? It gives you a guided wiki and a where-to-start reading path, a self-hostable DeepWiki alternative.
227
+ - **[FindJobs-Agent](https://github.com/he-yufeng/FindJobs-Agent)** — stop sifting job boards by hand: it ranks postings against your resume and runs mock interviews.
228
+ - **[GitSense](https://github.com/he-yufeng/GitSense)** — want to contribute to open source? It finds issues worth your time and gauges whether your PR will get merged.
229
+ - **[CodeABC](https://github.com/he-yufeng/CodeABC)** — understand any codebase even if you don't code, built for non-programmers.
230
+
231
+ ## Contributing
232
+
233
+ Contributions are welcome! Here's how you can help:
234
+
235
+ - **Report bugs** — Open an [issue](https://github.com/he-yufeng/ContractGuard/issues) with the contract type and expected behavior
236
+ - **Add contract samples** — More sample contracts for testing (with intentional red flags)
237
+ - **Improve prompts** — Better LLM prompts for more accurate analysis
238
+ - **Add languages** — Test with contracts in different languages and report results
239
+ - **Build integrations** — MCP server, VS Code extension, Slack bot, etc.
240
+
241
+ ## License
242
+
243
+ [MIT](LICENSE) — use it however you want.