tech-trans-rag / README.md
phaethon-order's picture
Implement retrieval text and embedding utilities, evaluation scripts, and regression tests
34d9afb
|
Raw History Blame Contribute Delete
14.2 kB
---
title: Technology Transactions RAG
emoji: πŸ“ƒ
colorFrom: blue
colorTo: indigo
sdk: docker
sdk_version: "0.1.0"
app_file: app.py
pinned: false
---
# Technology Transactions RAG
A Flask-based Retrieval-Augmented Generation (RAG) application for document processing, embedding generation, and semantic search specific to technology transactions use cases in the legal domain.
Available at: [tech-trans-rag](https://huggingface.co/spaces/phaethon-order/tech-trans-rag "Hugging Face Spaces: phaethon-order/tech-trans-rag")
## Features
- **Document Processing**: Upload and process PDF, DOCX, and text files
- **Smart Chunking**: Intelligent document segmentation for optimal retrieval
- **Vector Embeddings**: Generate embeddings using Hugging Face models
- **Hybrid Search**: Neon Postgres full-text ranking fused with pgvector cosine search
- **Dynamic Corpus**: Corpus can be updated to increase knowledge base and customize responses to user preferences, including best practices, jurisdictions, and governing laws.
- **Web UI**: Clean, responsive interface for document management and search
- **REST API**: Full API access for programmatic integration
- **Durable Storage**: Raw uploads live in Neon Object Storage; metadata, text,
chunks, and embeddings live in Neon Postgres
- **Docker Support**: Containerized deployment with external database storage
## Architecture
```
β”œβ”€β”€ app.py # Main Flask application
β”œβ”€β”€ config.py # Configuration management
β”œβ”€β”€ pyproject.toml # Python dependencies and tool configuration
β”œβ”€β”€ uv.lock # Reproducible dependency lockfile
β”œβ”€β”€ Dockerfile # Container configuration
β”œβ”€β”€ infrastructure/ # Core processing modules
β”‚ β”œβ”€β”€ chunker.py # Document chunking logic
β”‚ β”œβ”€β”€ database.py # Neon Postgres and pgvector interface
β”‚ β”œβ”€β”€ document_processor.py # File processing
β”‚ β”œβ”€β”€ embeddings.py # Embedding generation
β”‚ β”œβ”€β”€ logger.py # Logging configuration
β”‚ β”œβ”€β”€ object_storage.py # Neon Object Storage document uploads
β”‚ └── vector_search.py # Search functionality
β”œβ”€β”€ routes/ # Flask route handlers
β”‚ β”œβ”€β”€ api.py # REST API endpoints
β”‚ └── web.py # Web interface routes
β”œβ”€β”€ static/ # Frontend HTML templates
β”‚ β”œβ”€β”€ index.html # Main search interface
β”‚ β”œβ”€β”€ upload.html # Document upload page
β”‚ β”œβ”€β”€ chunks.html # Document chunks viewer
β”‚ β”œβ”€β”€ manifest.html # Document manifest viewer
β”‚ └── dbviewer.html # Raw database viewer
└── services/ # GPT services
└── gpt_service.py # Query response enrichment
```
## Quick Start
### Environment Setup
1. **Clone the repository**
```bash
git clone <repository-url>
cd hfs-techtx-rag
```
2. **Set up environment variables** (create `.env` file)
```bash
# Required API Keys
OPENAI_API_KEY=your_openai_api_key_here
DATABASE_URL=postgresql://user:password@host/database?sslmode=require
AWS_ACCESS_KEY_ID=nak_live_your_access_key
AWS_SECRET_ACCESS_KEY=nsk_live_your_secret_key
AWS_ENDPOINT_URL_S3=https://your-branch.storage.example.neon.tech
AWS_REGION=us-east-2
CLAUDE_KEY=your_claude_api_key_here
# Optional Configuration
EMBEDDING_MODEL=text-embedding-3-small
CHAT_MODEL=gpt-5.6-luna
OPENAI_BASE_URL=https://api.openai.com/v1
MAX_CONTEXT_LENGTH=4000
TOP_K_RESULTS=5
MAX_QUERY_LENGTH=1000
REQUEST_TIMEOUT=30
SECRET_KEY=your_secret_key_here
# Security (optional)
RESET_PASSWORD=change-me
```
### Local Development
Install `uv`, then use the checked-in lockfile for the local environment.
1. **Install dependencies**
```bash
uv sync --locked
```
2. **Run the application**
```bash
uv run python app.py
```
3. **Access the application**
- Web Interface: http://localhost:5000
- Upload Documents: http://localhost:5000/upload
- API Documentation: http://localhost:5000/api
### Docker Deployment
1. **Build the image**
```bash
docker build -t tech-trans-rag .
```
2. **Run the container**
```bash
docker run -p 5000:5000 \
-e OPENAI_API_KEY=your_key_here \
-e DATABASE_URL='postgresql://user:password@host/database?sslmode=require' \
-e AWS_ACCESS_KEY_ID='nak_live_your_access_key' \
-e AWS_SECRET_ACCESS_KEY='nsk_live_your_secret_key' \
-e AWS_ENDPOINT_URL_S3='https://your-branch.storage.example.neon.tech' \
-e AWS_REGION='us-east-2' \
tech-trans-rag
```
## API Endpoints
### Document Management
- `POST /api/upload` β€” Upload and process documents
- `GET /api/manifest` β€” List processed documents (document manifest)
- `PATCH /api/manifest` β€” Update manifest fields
- `DELETE /api/manifest` β€” Delete from manifest
- `GET /api/documents` β€” List documents (DB viewer optimized)
- `GET /api/chunks?doc_id=<id>` β€” List chunks for a given document ID
- `GET /api/chunks/all` β€” List chunks across all documents (paginated in UI)
- `GET /api/chunks/jsonl` β€” Download chunks as JSONL
- `PATCH /api/chunks` β€” Update chunk metadata (e.g., flags or annotations)
### Search & Health
- `POST /api/query` β€” Perform semantic search and response generation
- `GET /api/healthz` β€” Health check endpoint
### Admin
- `POST /api/reset` β€” Delete all application records and objects from Neon and reset identities
- If `RESET_PASSWORD` is set, provide `{"password": "<value>"}` in the JSON body or pass header `X-Reset-Password: <value>`
## Configuration
### Environment Variables
| Variable | Description | Default |
|----------|-------------|---------|
| `OPENAI_API_KEY` | OpenAI API key for chat models | Required |
| `DATABASE_URL` | Neon pooled Postgres connection string, including `sslmode=require` | Required |
| `DATABASE_CONNECT_TIMEOUT` | Database connection timeout in seconds | `10` |
| `AWS_ACCESS_KEY_ID` | Neon branch credential token ID for Object Storage | Required |
| `AWS_SECRET_ACCESS_KEY` | Neon branch credential secret for Object Storage | Required |
| `AWS_ENDPOINT_URL_S3` | Neon branch S3-compatible endpoint | Required |
| `AWS_REGION` | Neon Object Storage region | Required |
| `CLAUDE_KEY` | Anthropic Claude API key | Optional |
| `EMBEDDING_MODEL` | OpenAI embedding model | `text-embedding-3-small` |
| `CHAT_MODEL` | OpenAI chat model | `gpt-5.6-luna` |
| `MAX_CONTEXT_LENGTH` | Conservative token budget for retrieved chat context | `4000` |
| `TOP_K_RESULTS` | Default number of final hybrid search results (maximum `20`) | `5` |
| `MAX_QUERY_LENGTH` | Maximum accepted query length in characters | `1000` |
| `RESET_PASSWORD` | Password for reset operations | None |
### API Field Notes
- Chunk responses include rich metadata when available: `section_number`, `section_title`, `clause_type`, `page_start`, `page_end`, `path`, `numbers_present`, `definition_terms`, along with operational fields like `chunk_index`, `token_count`, `tok_ver`, `seg_ver`, and `embedding_count`.
- Chunk responses also expose `embedding_input_version` and
`embedding_input_sha256` so enriched-embedding backfills are auditable.
- When querying by `doc_id` (`GET /api/chunks?doc_id=<id>`), the response shape matches the global chunks listing so UIs can render consistently.
`POST /api/query` validates `top_k` from 1 through 20 and accepts an optional
`filters` object with `doc_id`, `doc_type`, `jurisdiction`, `governing_law`, or
`industry`. Text filter values use case-insensitive exact matching against the
comma-delimited document metadata values. Results preserve the prior fields and
add final rank, vector rank, lexical rank, reciprocal-rank-fusion score, section
metadata, and selection reason.
### Neon Data Persistence
Create a Neon project in a region that supports Object Storage, copy its pooled
Postgres connection string, and provision a private bucket named `documents`:
```bash
neon buckets create documents
neon credentials create --scope storage:read --scope storage:write
```
Add `DATABASE_URL`, `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`,
`AWS_ENDPOINT_URL_S3`, and `AWS_REGION` to the Hugging Face Space as secrets.
Do not add credentials as public Space variables or commit them to `.env`.
At startup, the application enables the `vector` extension and creates the
`documents` and `chunks` tables when absent. Neon is the source of truth for:
- document metadata and the manifest;
- original uploaded file metadata and extracted clean text;
- chunks and editable chunk metadata; and
- OpenAI embeddings stored in a pgvector column.
Original uploaded file bytes are stored in the private Neon Object Storage
bucket named `documents`. Postgres stores only the object key, filename, media
type, size, and the existing `/api/raw/...` download route. Existing rows that
still contain legacy `raw_content` bytes remain readable, but all new uploads
use Object Storage.
Only model caches are written to `/tmp`; they are disposable and may be cleared
on every Space restart. No persistent volume is required.
For an existing Space, add `DATABASE_URL` before deploying this revision. The
automatic schema initialization is idempotent, but it does not import records
from an old ChromaDB or `/data` directory.
## Security Features
### Reset Protection
You can protect the dangerous Reset operation by setting the `RESET_PASSWORD` environment variable:
```bash
export RESET_PASSWORD="change-me"
uv run python app.py
```
The Reset button in the web interface will prompt for this password before allowing database wipes.
### Try the API quickly
Optional cURL snippets you can run locally:
```bash
# Health
curl -s http://localhost:5000/api/healthz | jq
# Manifest
curl -s http://localhost:5000/api/manifest | jq
# Chunks for a document (replace 1 with a real ID from manifest)
curl -s "http://localhost:5000/api/chunks?doc_id=1" | jq '.chunks[0]'
# Query with hybrid search
curl -s -X POST http://localhost:5000/api/query \
-H 'Content-Type: application/json' \
-d '{"query": "What does the indemnity clause cover?", "top_k": 5, "filters": {"jurisdiction": "US-DE"}}' | jq
# Admin reset (if password required)
# Update a chunk's metadata (example: set clause_type)
curl -s -X PATCH http://localhost:5000/api/chunks \
-H 'Content-Type: application/json' \
-d '{"chunk_id": 123, "updates": {"clause_type": "Indemnification"}}' | jq
# Get all chunks (paginated)
curl -s "http://localhost:5000/api/chunks/all?limit=200&offset=0" | jq '.chunks | length'
curl -s -X POST http://localhost:5000/api/reset \
-H 'Content-Type: application/json' \
-d '{"password": "change-me"}' | jq
```
## Development
Install the locked development environment and run the test suite with:
```bash
uv sync --locked
uv run pytest
```
### Embedding backfill
New chunks embed canonical retrieval text containing the original chunk plus its
section, clause, path, and defined-term metadata. Existing chunks can be scanned
without mutation:
```bash
uv run python -m scripts.reindex_embeddings
```
Run the same command with `--apply` only against an explicitly selected Neon
branch after reviewing the dry-run count. The command updates successful batches
atomically, exits nonzero on a failed batch, and reports the last safe
`--after-chunk-id` checkpoint for resumption. It is never invoked during app
startup.
The reviewed relevance-benchmark format and acceptance criteria are documented
in `evals/retrieval/README.md`. The repository supplies the harness but does not
fabricate expert relevance labels.
### Project Structure
- **Infrastructure Layer**: Core processing modules for documents, embeddings, and search
- **Route Layer**: Flask blueprints for web and API endpoints
- **Static Layer**: Frontend templates and assets
- **Configuration**: Environment-based configuration management
### Key Components
- **Document Processor**: Handles PDF, DOCX, and text file processing with OCR support
- **Chunker**: Intelligent text segmentation for optimal retrieval
- **Embeddings**: Hugging Face model integration for vector generation
- **Hybrid Search**: weighted Postgres full-text search plus exact pgvector
cosine candidates, fused with reciprocal-rank fusion and diversified with MMR
- **Database**: Neon Postgres storage with automatic schema initialization
### Troubleshooting
- Health endpoint returns 404: Ensure you are calling `/api/healthz` (not `/api/health`).
- No chunks returned for `doc_id`: Verify the document ID from `/api/manifest`. Chunks are only created after successful processing.
- Reset not permitted: Provide the correct password in JSON body (`{"password": "..."}`) or `X-Reset-Password` header and ensure `RESET_PASSWORD` is set in the server environment.
- Database connection errors: confirm `DATABASE_URL` is the Neon connection string, includes TLS settings, and is configured as a Hugging Face secret.
- Missing API keys: Set `OPENAI_API_KEY` (and optional `CLAUDE_KEY`) before starting the app.
- `/api/chunks/jsonl` is retained for UI compatibility but now reads chunks from Neon rather than a local JSONL file.
- Object Storage errors: confirm the private `documents` bucket exists and all
four `AWS_*` Object Storage secrets belong to the same Neon branch as the
database.
- Large uploads: PDFs with many pages can take time to process; their original
bytes are retained in Neon Object Storage rather than the Space filesystem or
a Postgres `BYTEA` value.
## License
This repository is publicly viewable for portfolio purposes only. The code is proprietary.
Copyright Β© 2026 Phaethon Order LLC. All rights reserved.
Contact [support@phaethon.llc](mailto:support@phaethon.llc) for licensing or reuse requests.
See [LICENSE](LICENSE)
Note: `package.json` may list a different license string; the authoritative license for this repository is proprietary.
---
## Contact
Questions or support: [support@phaethon.llc](mailto:support@phaethon.llc).