Spaces:
Running
Download README.md from phaethon-order/tech-trans-rag: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/spaces/phaethon-order/tech-trans-rag/resolve/main/README.md
- Command line
-
hf download hf://spaces/phaethon-order/tech-trans-rag/README.md
-
curl -L -o README.md https://huggingface.co/spaces/phaethon-order/tech-trans-rag/resolve/main/README.md
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
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
Clone the repository
git clone <repository-url> cd hfs-techtx-ragSet up environment variables (create
.envfile)# 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.
Install dependencies
uv sync --lockedRun the application
uv run python app.pyAccess the application
- Web Interface: http://localhost:5000
- Upload Documents: http://localhost:5000/upload
- API Documentation: http://localhost:5000/api
Docker Deployment
Build the image
docker build -t tech-trans-rag .Run the container
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 documentsGET /api/manifestβ List processed documents (document manifest)PATCH /api/manifestβ Update manifest fieldsDELETE /api/manifestβ Delete from manifestGET /api/documentsβ List documents (DB viewer optimized)GET /api/chunks?doc_id=<id>β List chunks for a given document IDGET /api/chunks/allβ List chunks across all documents (paginated in UI)GET /api/chunks/jsonlβ Download chunks as JSONLPATCH /api/chunksβ Update chunk metadata (e.g., flags or annotations)
Search & Health
POST /api/queryβ Perform semantic search and response generationGET /api/healthzβ Health check endpoint
Admin
POST /api/resetβ Delete all application records and objects from Neon and reset identities- If
RESET_PASSWORDis set, provide{"password": "<value>"}in the JSON body or pass headerX-Reset-Password: <value>
- If
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 likechunk_index,token_count,tok_ver,seg_ver, andembedding_count. - Chunk responses also expose
embedding_input_versionandembedding_input_sha256so 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:
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:
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:
# 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:
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:
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": "..."}) orX-Reset-Passwordheader and ensureRESET_PASSWORDis set in the server environment. - Database connection errors: confirm
DATABASE_URLis the Neon connection string, includes TLS settings, and is configured as a Hugging Face secret. - Missing API keys: Set
OPENAI_API_KEY(and optionalCLAUDE_KEY) before starting the app. /api/chunks/jsonlis retained for UI compatibility but now reads chunks from Neon rather than a local JSONL file.- Object Storage errors: confirm the private
documentsbucket exists and all fourAWS_*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
BYTEAvalue.
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 for licensing or reuse requests.
See 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.