Spaces:
Sleeping
Sleeping
Deploy ProfillyBot: Gradio ZeroGPU + CV RAG (Qwen2.5-3B)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+48
- .env.templateAdded+55
- .gitattributes+8
- .github/workflows/README.mdAdded+207
- .github/workflows/code-quality.ymlAdded+38
- .github/workflows/dependency-review.ymlAdded+22
- .github/workflows/lint.ymlAdded+38
- .github/workflows/pre-commit.ymlAdded+38
- .github/workflows/security-scan.ymlAdded+55
- .github/workflows/test-docker.ymlAdded+28
- .github/workflows/test-python-reusable.ymlAdded+48
- .github/workflows/test-python310.ymlAdded+14
- .github/workflows/test-python311.ymlAdded+15
- .github/workflows/test-python312.ymlAdded+14
- .gitignoreAdded+207
- .hfignoreAdded+19
- .pre-commit-config.yamlAdded+40
- .streamlit/config.tomlAdded+16
- .venv/.gitignoreAdded+1
- .venv/CACHEDIR.TAGAdded+1
- .venv/Lib/site-packages/_virtualenv.pthAdded+3
- .venv/Lib/site-packages/_virtualenv.pyAdded+101
- .venv/Scripts/activateAdded+116
- .venv/Scripts/activate.batAdded+71
- .venv/Scripts/activate.cshAdded+76
- .venv/Scripts/activate.fishAdded+124
- .venv/Scripts/activate.nuAdded+117
- .venv/Scripts/activate.ps1Added+82
- .venv/Scripts/activate_this.pyAdded+59
- .venv/Scripts/deactivate.batAdded+39
- .venv/Scripts/pydoc.batAdded+22
- .venv/Scripts/python.exeAdded+3
- .venv/Scripts/pythonw.exeAdded+3
- .venv/pyvenv.cfgAdded+5
- ARCHITECTURE.mdAdded+815
- DockerfileAdded+68
- Dockerfile.appAdded+80
- LICENSEAdded+21
- MakefileAdded+146
- README.md+417-7
- SETUP_GUIDE.mdAdded+371
- app.pyAdded+585
- bm25_index/bm25_index.pklAdded+3
- bm25_index/documents.pklAdded+3
- bm25_index/metadata.jsonAdded+5
- bm25_index/tokenized_corpus.pklAdded+3
- chroma_db/ae1acac2-515c-4deb-b9d0-675bd72bab8b/data_level0.binAdded+3
- chroma_db/ae1acac2-515c-4deb-b9d0-675bd72bab8b/header.binAdded+3
- chroma_db/ae1acac2-515c-4deb-b9d0-675bd72bab8b/length.binAdded+3
- chroma_db/ae1acac2-515c-4deb-b9d0-675bd72bab8b/link_lists.binAdded
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# Python__pycache__/*.py[cod]*$py.class*.so.Pythonbuild/dist/*.egg-info/.venv/venv/env/
# UV.uv/uv.lock
# IDE.vscode/.idea/*.swp*.swo
# Git.git/.gitignore
# Logs*.loglogs/
# Vector database and indexes (will be built in container)chroma_db/bm25_index/
# Testing.pytest_cache/.coveragehtmlcov/
# OS.DS_StoreThumbs.db
# Documentation*.md!README_HF.mddocs/12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# Environment Configuration# Copy this file to .env and fill in your values
# Application SettingsAPP_NAME="Profile Chatbot"APP_PORT=7860DEBUG=false
# =============================================================================# Ollama Configuration (Local LLM)# =============================================================================OLLAMA_BASE_URL=http://localhost:11434OLLAMA_HOST=http://localhost:11434
# Model to use with Ollama (pulled automatically on first run with Docker Compose)# Options: llama3.2:3b (default), phi3:mini, gemma2:2b, llama3.2:1b (smaller)OLLAMA_MODEL=llama3.2:3b
# =============================================================================# Groq API Configuration (Cloud LLM - Optional)# =============================================================================# If set, Groq will be used as the default LLM provider instead of Ollama# Get your API key at: https://console.groq.com/GROQ_API_KEY=
# Optional: Other API Keys for alternative LLM providers# OPENAI_API_KEY=your_openai_api_key_here# ANTHROPIC_API_KEY=your_anthropic_api_key_here
# =============================================================================# Storage Configuration# =============================================================================# Vector DatabaseCHROMA_PERSIST_DIR=./chroma_db
# Document ProcessingDOCUMENTS_DIR=./data/documents
# =============================================================================# Logging & Debugging# =============================================================================LOG_LEVEL=INFO
# LangSmith Tracing (get API key at https://smith.langchain.com)# Set LANGCHAIN_TRACING_V2=true to enable tracingLANGCHAIN_TRACING_V2=falseLANGCHAIN_ENDPOINT=https://api.smith.langchain.comLANGCHAIN_API_KEY=LANGCHAIN_PROJECT=profillybot
# =============================================================================# Hugging Face Spaces (Optional - auto-set by HF Spaces)# =============================================================================# SPACE_ID=your_space_id# SPACE_AUTHOR_NAME=your_username32 unmodified lines333435363738394041424332 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text.venv/Scripts/python.exe filter=lfs diff=lfs merge=lfs -text.venv/Scripts/pythonw.exe filter=lfs diff=lfs merge=lfs -textchroma_db/chroma.sqlite3 filter=lfs diff=lfs merge=lfs -textdata/documents/MY_CV_2_0.pdf filter=lfs diff=lfs merge=lfs -textdocs/arch_system_design.png filter=lfs diff=lfs merge=lfs -textdocs/banner_image.png filter=lfs diff=lfs merge=lfs -textdocs/MY_CV_2_0.pdf filter=lfs diff=lfs merge=lfs -textdocs/screenshot-example.png filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207# GitHub Actions Workflows
This directory contains automated CI/CD workflows for the ProfillyBot project.
[](https://codecov.io/gh/Tin-Hoang/slm-profile-rag)
## Workflows Overview
### 🧪 test-python3XX.yml - Unit Tests per Python Version**Triggers:** Push/PR to main, master, develop branches; Manual dispatch
**Purpose:** Runs comprehensive unit tests for specific Python version (separate badges!)
**Workflows:**- **test-python310.yml**: Tests on Python 3.10- **test-python311.yml**: Tests on Python 3.11 (includes Codecov upload)- **test-python312.yml**: Tests on Python 3.12
**Implementation:**- Each workflow calls `test-python-reusable.yml` (DRY principle)- Installs dependencies- Runs ruff linting and formatting checks- Executes pytest with coverage reporting- Provides separate badge per Python version
### 🐳 test-docker.yml - Docker Build Test**Triggers:** Push/PR to main, master, develop branches; Manual dispatch
**Purpose:** Validates Docker image build
**Jobs:**- Builds Docker image to ensure Dockerfile is valid- Uses caching for faster builds
### 🔍 lint.yml - Linting (Existing)**Triggers:** Push/PR to main, develop branches
**Purpose:** Fast linting checks using ruff
**Jobs:**- Runs ruff check on all Python files- Runs ruff format check- Uses UV for fast dependency installation
### 📊 code-quality.yml - Code Quality Analysis**Triggers:** Push/PR to main, master, develop branches
**Purpose:** Advanced code quality checks
**Jobs:**- Python syntax validation- Code complexity analysis using radon- Maintainability index calculation
### ✅ pre-commit.yml - Pre-commit Hooks**Triggers:** Push/PR to main, master, develop branches
**Purpose:** Validates pre-commit hooks configuration
**Jobs:**- Runs all pre-commit hooks defined in `.pre-commit-config.yaml`- Ensures code formatting and quality standards
### 📦 dependency-review.yml - Dependency Security**Triggers:** Pull requests only
**Purpose:** Reviews dependency changes for security issues
**Jobs:**- Scans for vulnerable dependencies- Checks for problematic licenses (GPL-3.0, AGPL-3.0)- Fails on moderate or higher severity vulnerabilities
### 🔒 security-scan.yml - Security Scanning**Triggers:** Push/PR to main, master, develop branches; Weekly schedule (Mondays)
**Purpose:** Comprehensive security vulnerability scanning
**Jobs:**- **Safety**: Scans Python dependencies for known vulnerabilities- **Bandit**: Static security analysis of Python code- **pip-audit**: Audits Python packages for known vulnerabilities- Uploads security reports as artifacts
## Local Development
### Running Tests Locally
```bash# Install development dependenciespip install -e ".[dev]"
# Run all testspytest tests/ -v
# Run tests with coveragepytest tests/ -v --cov=src --cov-report=term-missing --cov-report=html
# Run specific test filepytest tests/test_main_document_loader.py -v```
### Running Linting Locally
```bash# Install ruffpip install ruff
# Check coderuff check src tests app.py
# Format coderuff format src tests app.py```
### Running Pre-commit Hooks Locally
```bash# Install pre-commitpip install pre-commit
# Install hookspre-commit install
# Run on all filespre-commit run --all-files```
### Running Security Scans Locally
```bash# Install security toolspip install safety bandit pip-audit
# Run safety checksafety check
# Run banditbandit -r src/
# Run pip-auditpip-audit```
## Continuous Integration Matrix
| Workflow | Python Versions | OS | Caching | Coverage ||----------|----------------|-----|---------|----------|| test-python310.yml | 3.10 | Ubuntu | ✅ pip | ❌ || test-python311.yml | 3.11 | Ubuntu | ✅ pip | ✅ Codecov || test-python312.yml | 3.12 | Ubuntu | ✅ pip | ❌ || test-docker.yml | N/A | Ubuntu | ✅ Docker | ❌ || lint.yml | 3.11 | Ubuntu | ✅ UV | ❌ || code-quality.yml | 3.11 | Ubuntu | ✅ pip | ❌ || pre-commit.yml | 3.11 | Ubuntu | ✅ pre-commit | ❌ || security-scan.yml | 3.11 | Ubuntu | ✅ pip | ❌ |
## Troubleshooting
### Tests Failing Locally but Passing in CI (or vice versa)
1. Ensure you're using the correct Python version2. Clear pytest cache: `pytest --cache-clear`3. Reinstall dependencies: `pip install -e ".[dev]" --force-reinstall`
### Codecov Upload Issues
1. Ensure `CODECOV_TOKEN` is set in repository secrets2. Check coverage.xml is generated: `pytest tests/ --cov=src --cov-report=xml`
### Docker Build Failures
1. Test locally: `docker build -t profillybot:test .`2. Check Dockerfile syntax3. Ensure all required files are present
## Contributing
When contributing to this project:
1. Ensure all workflows pass before submitting a PR2. Add tests for new features3. Run pre-commit hooks locally4. Update this README if adding new workflows
## Maintenance
### Updating Dependencies
- GitHub Actions are set to use latest stable versions (v4, v5)- Review and update action versions quarterly- Monitor Dependabot alerts for security updates
### Adding New Workflows
1. Create a new `.yml` file in this directory2. Follow the naming convention: `<purpose>.yml`3. Add appropriate triggers and jobs4. Update this README with workflow documentation5. Add status badge to main README.md1234567891011121314151617181920212223242526272829303132333435363738name: Code Quality
on: push: branches: [ main, master, develop ] pull_request: branches: [ main, master, develop ]
jobs: type-check: name: Type Checking & Complexity Analysis runs-on: ubuntu-latest
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11" cache: 'pip'
- name: Install dependencies run: | python -m pip install --upgrade pip pip install mypy radon
- name: Check for Python syntax errors run: | python -m py_compile app.py find src tests -name "*.py" -exec python -m py_compile {} \;
- name: Run complexity analysis continue-on-error: true run: | radon cc src tests app.py -a -s radon mi src tests app.py -s12345678910111213141516171819202122name: Dependency Review
on: pull_request: branches: [ main, master, develop ]
permissions: contents: read
jobs: dependency-review: name: Review Dependencies runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Dependency Review uses: actions/dependency-review-action@v4 with: fail-on-severity: moderate deny-licenses: GPL-3.0, AGPL-3.01234567891011121314151617181920212223242526272829303132333435363738name: Lint
on: push: branches: [ main, develop ] pull_request: branches: [ main, develop ]
jobs: lint: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: '3.11'
- name: Install UV run: curl -LsSf https://astral.sh/uv/install.sh | sh
- name: Install dependencies run: | uv venv source .venv/bin/activate uv pip install -r requirements.txt uv pip install "ruff>=0.14.6,<0.15.0" pytest pytest-cov
- name: Run Ruff Check run: | source .venv/bin/activate ruff check .
- name: Run Ruff Format Check run: | source .venv/bin/activate ruff format --check .1234567891011121314151617181920212223242526272829303132333435363738name: Pre-commit Checks
on: push: branches: [ main, master, develop ] pull_request: branches: [ main, master, develop ]
jobs: pre-commit: name: Run Pre-commit Hooks runs-on: ubuntu-latest
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.10"
- name: Install pre-commit run: | python -m pip install --upgrade pip pip install pre-commit
- name: Cache pre-commit hooks uses: actions/cache@v4 with: path: ~/.cache/pre-commit key: pre-commit-${{ hashFiles('.pre-commit-config.yaml') }} restore-keys: | pre-commit-
- name: Run pre-commit on all files run: | pre-commit run --all-files --show-diff-on-failure12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455name: Security Scan
on: push: branches: [ main, master, develop ] pull_request: branches: [ main, master, develop ] schedule: # Run weekly on Monday at 00:00 UTC - cron: '0 0 * * 1'
jobs: security-scan: name: Security Vulnerability Scan runs-on: ubuntu-latest
steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11" cache: 'pip'
- name: Install dependencies run: | python -m pip install --upgrade pip pip install safety bandit pip-audit
- name: Run Safety check continue-on-error: true run: | pip install -e . safety check --json || true
- name: Run Bandit security scan continue-on-error: true run: | bandit -r src/ -f json -o bandit-report.json || true bandit -r src/ -f txt || true
- name: Run pip-audit continue-on-error: true run: | pip-audit --desc || true
- name: Upload Bandit report if: always() uses: actions/upload-artifact@v4 with: name: bandit-security-report path: bandit-report.json if-no-files-found: ignore12345678910111213141516171819202122232425262728name: Docker Build Test
on: push: branches: [ main, master, develop ] pull_request: branches: [ main, master, develop ] workflow_dispatch:
jobs: test-docker: name: Test Docker Build runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Docker Buildx uses: docker/setup-buildx-action@v3
- name: Build Docker image uses: docker/build-push-action@v5 with: context: . push: false tags: profillybot:test cache-from: type=gha cache-to: type=gha,mode=max123456789101112131415161718192021222324252627282930313233343536373839404142434445464748name: Test Python (Reusable)
on: workflow_call: inputs: python-version: required: true type: string secrets: CODECOV_TOKEN: required: false
jobs: test: name: Test on Python ${{ inputs.python-version }} runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4
- name: Set up Python ${{ inputs.python-version }} uses: actions/setup-python@v5 with: python-version: ${{ inputs.python-version }} cache: 'pip'
- name: Install dependencies run: | python -m pip install --upgrade pip pip install -e ".[dev]"
- name: Run linting with ruff run: | ruff check src tests ruff format --check src tests
- name: Run tests with pytest run: | pytest tests/ -v --cov=src --cov-report=term-missing --cov-report=xml
- name: Upload coverage to Codecov if: inputs.python-version == '3.11' uses: codecov/codecov-action@v4 with: file: ./coverage.xml token: ${{ secrets.CODECOV_TOKEN }} fail_ci_if_error: false verbose: true1234567891011121314name: Tests Python 3.10
on: push: branches: [ main, master, develop ] pull_request: branches: [ main, master, develop ] workflow_dispatch:
jobs: test: uses: ./.github/workflows/test-python-reusable.yml with: python-version: "3.10"123456789101112131415name: Tests Python 3.11
on: push: branches: [ main, master, develop ] pull_request: branches: [ main, master, develop ] workflow_dispatch:
jobs: test: uses: ./.github/workflows/test-python-reusable.yml with: python-version: "3.11" secrets: inherit1234567891011121314name: Tests Python 3.12
on: push: branches: [ main, master, develop ] pull_request: branches: [ main, master, develop ] workflow_dispatch:
jobs: test: uses: ./.github/workflows/test-python-reusable.yml with: python-version: "3.12"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207# Byte-compiled / optimized / DLL files__pycache__/*.py[codz]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py.cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# UV# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.#uv.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock#poetry.toml
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.# https://pdm-project.org/en/latest/usage/project/#working-with-version-control#pdm.lock#pdm.toml.pdm-python.pdm-build/
# pixi# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.#pixi.lock# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one# in the .venv directory. It is recommended not to include this directory in version control..pixi
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.envrc.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/
# Abstra# Abstra is an AI-powered process automation framework.# Ignore directories containing user credentials, local state, and settings.# Learn more at https://abstra.io/docs.abstra/
# Visual Studio Code# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore# and can be added to the global gitignore or merged into this file. However, if you prefer,# you could uncomment the following to ignore the entire vscode folder# .vscode/
# Ruff stuff:.ruff_cache/
# PyPI configuration file.pypirc
# Cursor# Cursor is an AI-powered code editor. `.cursorignore` specifies files/directories to# exclude from AI features like autocomplete and code analysis. Recommended for sensitive data# refer to https://docs.cursor.com/context/ignore-files.cursorignore.cursorindexingignore
# Marimomarimo/_static/marimo/_lsp/__marimo__/12345678910111213141516171819.venv/venv/.env.env.*.git/__pycache__/**/__pycache__/*.pyc.pytest_cache/.ruff_cache/htmlcov/.coverage.cursor/*.egg-info/.mypy_cache/_cv_preview.txt.idea/.vscode/agent-transcripts/12345678910111213141516171819202122232425262728293031323334353637383940# See https://pre-commit.com for more information# See https://pre-commit.com/hooks.html for more hooksrepos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.5.0 hooks: - id: trailing-whitespace - id: end-of-file-fixer - id: check-yaml - id: check-toml - id: check-added-large-files args: ['--maxkb=6000'] - id: check-merge-conflict - id: check-case-conflict - id: check-docstring-first - id: debug-statements - id: mixed-line-ending args: ['--fix=lf']
- repo: https://github.com/astral-sh/ruff-pre-commit rev: v0.7.4 hooks: # Run the linter - id: ruff args: ['--fix'] # Run the formatter - id: ruff-format
# Uncomment to enable mypy type checking (requires adding mypy and type stubs to dev dependencies) # - repo: https://github.com/pre-commit/mirrors-mypy # rev: v1.11.2 # hooks: # - id: mypy # additional_dependencies: ['types-PyYAML'] # args: ['--ignore-missing-imports', '--no-strict-optional'] # exclude: '^tests/'
# Set this to allow pre-commit to work with uv or other package managersdefault_language_version: python: python3.1012345678910111213141516[theme]primaryColor = "#FF4B4B"backgroundColor = "#FFFFFF"secondaryBackgroundColor = "#F0F2F6"textColor = "#262730"font = "sans serif"
[server]headless = true# port = 8501 # Default Streamlit port (for local dev)# Note: HuggingFace Spaces overrides this to 7860 via DockerfileenableCORS = falseenableXsrfProtection = true
[browser]gatherUsageStats = false1*1Signature: 8a477f597d28d172789f06886806bc55123version https://git-lfs.github.com/spec/v1oid sha256:69ac3d8f27e679c81b94ab30b3b56e9cd138219b1ba94a1fa3606d5a76a1433dsize 18123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101"""Patches that are applied at runtime to the virtual environment."""
import osimport sys
VIRTUALENV_PATCH_FILE = os.path.join(__file__)
def patch_dist(dist): """ Distutils allows user to configure some arguments via a configuration file: https://docs.python.org/3.11/install/index.html#distutils-configuration-files.
Some of this arguments though don't make sense in context of the virtual environment files, let's fix them up. """ # noqa: D205 # we cannot allow some install config as that would get packages installed outside of the virtual environment old_parse_config_files = dist.Distribution.parse_config_files
def parse_config_files(self, *args, **kwargs): result = old_parse_config_files(self, *args, **kwargs) install = self.get_option_dict("install")
if "prefix" in install: # the prefix governs where to install the libraries install["prefix"] = VIRTUALENV_PATCH_FILE, os.path.abspath(sys.prefix) for base in ("purelib", "platlib", "headers", "scripts", "data"): key = f"install_{base}" if key in install: # do not allow global configs to hijack venv paths install.pop(key, None) return result
dist.Distribution.parse_config_files = parse_config_files
# Import hook that patches some modules to ignore configuration values that break package installation in case# of virtual environments._DISTUTILS_PATCH = "distutils.dist", "setuptools.dist"# https://docs.python.org/3/library/importlib.html#setting-up-an-importer
class _Finder: """A meta path finder that allows patching the imported distutils modules."""
fullname = None
# lock[0] is threading.Lock(), but initialized lazily to avoid importing threading very early at startup, # because there are gevent-based applications that need to be first to import threading by themselves. # See https://github.com/pypa/virtualenv/issues/1895 for details. lock = [] # noqa: RUF012
def find_spec(self, fullname, path, target=None): # noqa: ARG002 if fullname in _DISTUTILS_PATCH and self.fullname is None: # initialize lock[0] lazily if len(self.lock) == 0: import threading
lock = threading.Lock() # there is possibility that two threads T1 and T2 are simultaneously running into find_spec, # observing .lock as empty, and further going into hereby initialization. However due to the GIL, # list.append() operation is atomic and this way only one of the threads will "win" to put the lock # - that every thread will use - into .lock[0]. # https://docs.python.org/3/faq/library.html#what-kinds-of-global-value-mutation-are-thread-safe self.lock.append(lock)
from functools import partial from importlib.util import find_spec
with self.lock[0]: self.fullname = fullname try: spec = find_spec(fullname, path) if spec is not None: # https://www.python.org/dev/peps/pep-0451/#how-loading-will-work is_new_api = hasattr(spec.loader, "exec_module") func_name = "exec_module" if is_new_api else "load_module" old = getattr(spec.loader, func_name) func = self.exec_module if is_new_api else self.load_module if old is not func: try: # noqa: SIM105 setattr(spec.loader, func_name, partial(func, old)) except AttributeError: pass # C-Extension loaders are r/o such as zipimporter with <3.7 return spec finally: self.fullname = None return None
@staticmethod def exec_module(old, module): old(module) if module.__name__ in _DISTUTILS_PATCH: patch_dist(module)
@staticmethod def load_module(old, name): module = old(name) if module.__name__ in _DISTUTILS_PATCH: patch_dist(module) return module
sys.meta_path.insert(0, _Finder())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file must be used with "source bin/activate" *from bash*# you cannot run it directly
# Get script path (only used if environment is relocatable).if [ -n "${BASH_VERSION:+x}" ] ; then SCRIPT_PATH="${BASH_SOURCE[0]}" if [ "$SCRIPT_PATH" = "$0" ]; then # Only bash has a reasonably robust check for source'dness. echo "You must source this script: \$ source $0" >&2 exit 33 fielif [ -n "${ZSH_VERSION:+x}" ] ; then SCRIPT_PATH="${(%):-%x}"elif [ -n "${KSH_VERSION:+x}" ] ; then SCRIPT_PATH="${.sh.file}"fi
deactivate () { unset -f pydoc >/dev/null 2>&1 || true
# reset old environment variables # ! [ -z ${VAR+_} ] returns true if VAR is declared at all if ! [ -z "${_OLD_VIRTUAL_PATH:+_}" ] ; then PATH="$_OLD_VIRTUAL_PATH" export PATH unset _OLD_VIRTUAL_PATH fi if ! [ -z "${_OLD_VIRTUAL_PYTHONHOME+_}" ] ; then PYTHONHOME="$_OLD_VIRTUAL_PYTHONHOME" export PYTHONHOME unset _OLD_VIRTUAL_PYTHONHOME fi
# The hash command must be called to get it to forget past # commands. Without forgetting past commands the $PATH changes # we made may not be respected hash -r 2>/dev/null
if ! [ -z "${_OLD_VIRTUAL_PS1+_}" ] ; then PS1="$_OLD_VIRTUAL_PS1" export PS1 unset _OLD_VIRTUAL_PS1 fi
unset VIRTUAL_ENV unset VIRTUAL_ENV_PROMPT if [ ! "${1-}" = "nondestructive" ] ; then # Self destruct! unset -f deactivate fi}
# unset irrelevant variablesdeactivate nondestructive
VIRTUAL_ENV='C:\Users\Admin\Downloads\AIDevMinh\slm-profile-rag\.venv'if ([ "$OSTYPE" = "cygwin" ] || [ "$OSTYPE" = "msys" ]) && $(command -v cygpath &> /dev/null) ; then VIRTUAL_ENV=$(cygpath -u "$VIRTUAL_ENV")fiexport VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"PATH="$VIRTUAL_ENV/Scripts:$PATH"export PATH
if [ "x" != x ] ; then VIRTUAL_ENV_PROMPT="() "else VIRTUAL_ENV_PROMPT="($(basename "$VIRTUAL_ENV")) "fiexport VIRTUAL_ENV_PROMPT
# unset PYTHONHOME if setif ! [ -z "${PYTHONHOME+_}" ] ; then _OLD_VIRTUAL_PYTHONHOME="$PYTHONHOME" unset PYTHONHOMEfi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT-}" ] ; then _OLD_VIRTUAL_PS1="${PS1-}" PS1="${VIRTUAL_ENV_PROMPT}${PS1-}" export PS1fi
# Make sure to unalias pydoc if it's already therealias pydoc 2>/dev/null >/dev/null && unalias pydoc || true
pydoc () { python -m pydoc "$@"}
# The hash command must be called to get it to forget past# commands. Without forgetting past commands the $PATH changes# we made may not be respectedhash -r 2>/dev/null1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071@REM Copyright (c) 2020-202x The virtualenv developers
@REM
@REM Permission is hereby granted, free of charge, to any person obtaining
@REM a copy of this software and associated documentation files (the
@REM "Software"), to deal in the Software without restriction, including
@REM without limitation the rights to use, copy, modify, merge, publish,
@REM distribute, sublicense, and/or sell copies of the Software, and to
@REM permit persons to whom the Software is furnished to do so, subject to
@REM the following conditions:
@REM
@REM The above copyright notice and this permission notice shall be
@REM included in all copies or substantial portions of the Software.
@REM
@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
@REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
@REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
@REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
@REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
@REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@REM This file is UTF-8 encoded, so we need to update the current code page while executing it
@for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @set _OLD_CODEPAGE=%%a
@if defined _OLD_CODEPAGE (
@"%SystemRoot%\System32\chcp.com" 65001 > nul
)
@for %%i in ("C:\Users\Admin\Downloads\AIDevMinh\slm-profile-rag\.venv") do @set "VIRTUAL_ENV=%%~fi"
@set "VIRTUAL_ENV_PROMPT="
@if NOT DEFINED VIRTUAL_ENV_PROMPT (
@for %%d in ("%VIRTUAL_ENV%") do @set "VIRTUAL_ENV_PROMPT=%%~nxd"
)
@if defined _OLD_VIRTUAL_PROMPT (
@set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
) else (
@if not defined PROMPT (
@set "PROMPT=$P$G"
)
@if not defined VIRTUAL_ENV_DISABLE_PROMPT (
@set "_OLD_VIRTUAL_PROMPT=%PROMPT%"
)
)
@if not defined VIRTUAL_ENV_DISABLE_PROMPT (
@set "PROMPT=(%VIRTUAL_ENV_PROMPT%) %PROMPT%"
)
@REM Don't use () to avoid problems with them in %PATH%
@if defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
@set "_OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME%"
:ENDIFVHOME
@set PYTHONHOME=
@REM if defined _OLD_VIRTUAL_PATH (
@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH1
@set "PATH=%_OLD_VIRTUAL_PATH%"
:ENDIFVPATH1
@REM ) else (
@if defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH2
@set "_OLD_VIRTUAL_PATH=%PATH%"
:ENDIFVPATH2
@set "PATH=%VIRTUAL_ENV%\Scripts;%PATH%"
:END
@if defined _OLD_CODEPAGE (
@"%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul
@set _OLD_CODEPAGE=
)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file must be used with "source bin/activate.csh" *from csh*.# You cannot run it directly.# Created by Davide Di Blasi <davidedb@gmail.com>.
set newline='\'
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH:q" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT:q" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate && unalias pydoc'
# Unset irrelevant variables.deactivate nondestructive
setenv VIRTUAL_ENV 'C:\Users\Admin\Downloads\AIDevMinh\slm-profile-rag\.venv'
set _OLD_VIRTUAL_PATH="$PATH:q"setenv PATH "$VIRTUAL_ENV:q/Scripts:$PATH:q"
if ('' != "") then setenv VIRTUAL_ENV_PROMPT ''else setenv VIRTUAL_ENV_PROMPT "$VIRTUAL_ENV:t:q"endif
if ( $?VIRTUAL_ENV_DISABLE_PROMPT ) then if ( $VIRTUAL_ENV_DISABLE_PROMPT == "" ) then set do_prompt = "1" else set do_prompt = "0" endifelse set do_prompt = "1"endif
if ( $do_prompt == "1" ) then # Could be in a non-interactive environment, # in which case, $prompt is undefined and we wouldn't # care about the prompt anyway. if ( $?prompt ) then set _OLD_VIRTUAL_PROMPT="$prompt:q" if ( "$prompt:q" =~ *"$newline:q"* ) then : else set prompt = '('"$VIRTUAL_ENV_PROMPT:q"') '"$prompt:q" endif endifendif
unset env_nameunset do_prompt
alias pydoc python -m pydoc
rehash123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# This file must be used using `source bin/activate.fish` *within a running fish ( http://fishshell.com ) session*.# Do not run it directly.
function _bashify_path -d "Converts a fish path to something bash can recognize" set fishy_path $argv set bashy_path $fishy_path[1] for path_part in $fishy_path[2..-1] set bashy_path "$bashy_path:$path_part" end echo $bashy_pathend
function _fishify_path -d "Converts a bash path to something fish can recognize" echo $argv | tr ':' '\n'end
function deactivate -d 'Exit virtualenv mode and return to the normal environment.' # reset old environment variables if test -n "$_OLD_VIRTUAL_PATH" # https://github.com/fish-shell/fish-shell/issues/436 altered PATH handling if test (echo $FISH_VERSION | head -c 1) -lt 3 set -gx PATH (_fishify_path "$_OLD_VIRTUAL_PATH") else set -gx PATH $_OLD_VIRTUAL_PATH end set -e _OLD_VIRTUAL_PATH end
if test -n "$_OLD_VIRTUAL_PYTHONHOME" set -gx PYTHONHOME "$_OLD_VIRTUAL_PYTHONHOME" set -e _OLD_VIRTUAL_PYTHONHOME end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE" and functions -q _old_fish_prompt # Set an empty local `$fish_function_path` to allow the removal of `fish_prompt` using `functions -e`. set -l fish_function_path
# Erase virtualenv's `fish_prompt` and restore the original. functions -e fish_prompt functions -c _old_fish_prompt fish_prompt functions -e _old_fish_prompt set -e _OLD_FISH_PROMPT_OVERRIDE end
set -e VIRTUAL_ENV set -e VIRTUAL_ENV_PROMPT
if test "$argv[1]" != 'nondestructive' # Self-destruct! functions -e pydoc functions -e deactivate functions -e _bashify_path functions -e _fishify_path endend
# Unset irrelevant variables.deactivate nondestructive
set -gx VIRTUAL_ENV 'C:\Users\Admin\Downloads\AIDevMinh\slm-profile-rag\.venv'
# https://github.com/fish-shell/fish-shell/issues/436 altered PATH handlingif test (echo $FISH_VERSION | head -c 1) -lt 3 set -gx _OLD_VIRTUAL_PATH (_bashify_path $PATH)else set -gx _OLD_VIRTUAL_PATH $PATHendset -gx PATH "$VIRTUAL_ENV"'/Scripts' $PATH
# Prompt override provided?# If not, just use the environment name.if test -n '' set -gx VIRTUAL_ENV_PROMPT ''else set -gx VIRTUAL_ENV_PROMPT (basename "$VIRTUAL_ENV")end
# Unset `$PYTHONHOME` if set.if set -q PYTHONHOME set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME set -e PYTHONHOMEend
function pydoc python -m pydoc $argvend
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT" # Copy the current `fish_prompt` function as `_old_fish_prompt`. functions -c fish_prompt _old_fish_prompt
function fish_prompt # Run the user's prompt first; it might depend on (pipe)status. set -l prompt (_old_fish_prompt)
printf '(%s) ' $VIRTUAL_ENV_PROMPT
string join -- \n $prompt # handle multi-line prompts end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"end123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# virtualenv activation module# Activate with `overlay use activate.nu`# Deactivate with `deactivate`, as usual## To customize the overlay name, you can call `overlay use activate.nu as foo`,# but then simply `deactivate` won't work because it is just an alias to hide# the "activate" overlay. You'd need to call `overlay hide foo` manually.
export-env { def is-string [x] { ($x | describe) == 'string' }
def has-env [...names] { $names | each {|n| $n in $env } | all {|i| $i == true} }
# Emulates a `test -z`, but better as it handles e.g 'false' def is-env-true [name: string] { if (has-env $name) { # Try to parse 'true', '0', '1', and fail if not convertible let parsed = (do -i { $env | get $name | into bool }) if ($parsed | describe) == 'bool' { $parsed } else { not ($env | get -i $name | is-empty) } } else { false } }
let virtual_env = 'C:\Users\Admin\Downloads\AIDevMinh\slm-profile-rag\.venv' let bin = 'Scripts'
let is_windows = ($nu.os-info.family) == 'windows' let path_name = (if (has-env 'Path') { 'Path' } else { 'PATH' } )
let venv_path = ([$virtual_env $bin] | path join) let new_path = ($env | get $path_name | prepend $venv_path)
# If there is no default prompt, then use the env name instead let virtual_env_prompt = (if ('' | is-empty) { ($virtual_env | path basename) } else { '' })
let new_env = { $path_name : $new_path VIRTUAL_ENV : $virtual_env VIRTUAL_ENV_PROMPT : $virtual_env_prompt }
let new_env = (if (is-env-true 'VIRTUAL_ENV_DISABLE_PROMPT') { $new_env } else { # Creating the new prompt for the session let virtual_prefix = $'(char lparen)($virtual_env_prompt)(char rparen) '
# Back up the old prompt builder let old_prompt_command = (if (has-env 'PROMPT_COMMAND') { $env.PROMPT_COMMAND } else { '' })
let new_prompt = (if (has-env 'PROMPT_COMMAND') { if 'closure' in ($old_prompt_command | describe) { {|| $'($virtual_prefix)(do $old_prompt_command)' } } else { {|| $'($virtual_prefix)($old_prompt_command)' } } } else { {|| $'($virtual_prefix)' } })
$new_env | merge { PROMPT_COMMAND : $new_prompt VIRTUAL_PREFIX : $virtual_prefix } })
# Environment variables that will be loaded as the virtual env load-env $new_env}
export alias pydoc = python -m pydocexport alias deactivate = overlay hide activate12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
$script:THIS_PATH = $myinvocation.mycommand.path$script:BASE_DIR = Split-Path (Resolve-Path "$THIS_PATH/..") -Parent
function global:deactivate([switch] $NonDestructive) { if (Test-Path variable:_OLD_VIRTUAL_PATH) { $env:PATH = $variable:_OLD_VIRTUAL_PATH Remove-Variable "_OLD_VIRTUAL_PATH" -Scope global }
if (Test-Path function:_old_virtual_prompt) { $function:prompt = $function:_old_virtual_prompt Remove-Item function:\_old_virtual_prompt }
if ($env:VIRTUAL_ENV) { Remove-Item env:VIRTUAL_ENV -ErrorAction SilentlyContinue }
if ($env:VIRTUAL_ENV_PROMPT) { Remove-Item env:VIRTUAL_ENV_PROMPT -ErrorAction SilentlyContinue }
if (!$NonDestructive) { # Self destruct! Remove-Item function:deactivate Remove-Item function:pydoc }}
function global:pydoc { python -m pydoc $args}
# unset irrelevant variablesdeactivate -nondestructive
$VIRTUAL_ENV = $BASE_DIR$env:VIRTUAL_ENV = $VIRTUAL_ENV
if ("" -ne "") { $env:VIRTUAL_ENV_PROMPT = ""}else { $env:VIRTUAL_ENV_PROMPT = $( Split-Path $env:VIRTUAL_ENV -Leaf )}
New-Variable -Scope global -Name _OLD_VIRTUAL_PATH -Value $env:PATH
$env:PATH = "$env:VIRTUAL_ENV/Scripts;" + $env:PATHif (!$env:VIRTUAL_ENV_DISABLE_PROMPT) { function global:_old_virtual_prompt { "" } $function:_old_virtual_prompt = $function:prompt
function global:prompt { # Add the custom prefix to the existing prompt $previous_prompt_value = & $function:_old_virtual_prompt ("(" + $env:VIRTUAL_ENV_PROMPT + ") " + $previous_prompt_value) }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# Copyright (c) 2020-202x The virtualenv developers## Permission is hereby granted, free of charge, to any person obtaining# a copy of this software and associated documentation files (the# "Software"), to deal in the Software without restriction, including# without limitation the rights to use, copy, modify, merge, publish,# distribute, sublicense, and/or sell copies of the Software, and to# permit persons to whom the Software is furnished to do so, subject to# the following conditions:## The above copyright notice and this permission notice shall be# included in all copies or substantial portions of the Software.## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""Activate virtualenv for current interpreter:
import runpyrunpy.run_path(this_file)
This can be used when you must use an existing Python interpreter, not the virtualenv bin/python.""" # noqa: D415
from __future__ import annotations
import osimport siteimport sys
try: abs_file = os.path.abspath(__file__)except NameError as exc: msg = "You must use import runpy; runpy.run_path(this_file)" raise AssertionError(msg) from exc
bin_dir = os.path.dirname(abs_file)base = bin_dir[: -len("Scripts") - 1] # strip away the bin part from the __file__, plus the path separator
# prepend bin to PATH (this file is inside the bin directory)os.environ["PATH"] = os.pathsep.join([bin_dir, *os.environ.get("PATH", "").split(os.pathsep)])os.environ["VIRTUAL_ENV"] = base # virtual env is right above bin directoryos.environ["VIRTUAL_ENV_PROMPT"] = "" or os.path.basename(base) # noqa: SIM222
# add the virtual environments libraries to the host python import mechanismprev_length = len(sys.path)for lib in "..\\Lib\\site-packages".split(os.pathsep): path = os.path.realpath(os.path.join(bin_dir, lib)) site.addsitedir(path)sys.path[:] = sys.path[prev_length:] + sys.path[0:prev_length]
sys.real_prefix = sys.prefixsys.prefix = base123456789101112131415161718192021222324252627282930313233343536373839@REM Copyright (c) 2020-202x The virtualenv developers
@REM
@REM Permission is hereby granted, free of charge, to any person obtaining
@REM a copy of this software and associated documentation files (the
@REM "Software"), to deal in the Software without restriction, including
@REM without limitation the rights to use, copy, modify, merge, publish,
@REM distribute, sublicense, and/or sell copies of the Software, and to
@REM permit persons to whom the Software is furnished to do so, subject to
@REM the following conditions:
@REM
@REM The above copyright notice and this permission notice shall be
@REM included in all copies or substantial portions of the Software.
@REM
@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
@REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
@REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
@REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
@REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
@REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@set VIRTUAL_ENV=
@set VIRTUAL_ENV_PROMPT=
@REM Don't use () to avoid problems with them in %PATH%
@if not defined _OLD_VIRTUAL_PROMPT @goto ENDIFVPROMPT
@set "PROMPT=%_OLD_VIRTUAL_PROMPT%"
@set _OLD_VIRTUAL_PROMPT=
:ENDIFVPROMPT
@if not defined _OLD_VIRTUAL_PYTHONHOME @goto ENDIFVHOME
@set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%"
@set _OLD_VIRTUAL_PYTHONHOME=
:ENDIFVHOME
@if not defined _OLD_VIRTUAL_PATH @goto ENDIFVPATH
@set "PATH=%_OLD_VIRTUAL_PATH%"
@set _OLD_VIRTUAL_PATH=
:ENDIFVPATH12345678910111213141516171819202122@REM Copyright (c) 2020-202x The virtualenv developers
@REM
@REM Permission is hereby granted, free of charge, to any person obtaining
@REM a copy of this software and associated documentation files (the
@REM "Software"), to deal in the Software without restriction, including
@REM without limitation the rights to use, copy, modify, merge, publish,
@REM distribute, sublicense, and/or sell copies of the Software, and to
@REM permit persons to whom the Software is furnished to do so, subject to
@REM the following conditions:
@REM
@REM The above copyright notice and this permission notice shall be
@REM included in all copies or substantial portions of the Software.
@REM
@REM THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
@REM EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
@REM MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
@REM NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
@REM LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
@REM OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
@REM WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
python.exe -m pydoc %*123version https://git-lfs.github.com/spec/v1oid sha256:8b86e1ee66bac3fe3b998a2586791ef3151d5b7fee9af11f5b1491d2a4a93ff0size 237568123version https://git-lfs.github.com/spec/v1oid sha256:faaa4c9a1c0188a7bb7d648874b68c536db0248ca97b5d863854091864b94b3bsize 23398412345home = C:\Users\Admin\AppData\Roaming\uv\python\cpython-3.13.2-windows-x86_64-noneimplementation = CPythonuv = 0.6.9version_info = 3.13.2include-system-site-packages = false123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815# 🏗️ Architecture Overview
## System Architecture
<p align="center"> <img src="docs/arch_system_design.png" alt="System Architecture Diagram" width="900" /></p><p align="center"><em>High-level system architecture diagram illustrating the complete RAG pipeline flow</em></p>
### Detailed Component View
```┌─────────────────────────────────────────────────────────────┐│ User Interface ││ (Streamlit Web App) ││ app.py │└───────────────────────┬─────────────────────────────────────┘ │ ▼┌─────────────────────────────────────────────────────────────┐│ RAG Pipeline ││ (rag_pipeline.py) ││ ││ ┌────────────────┐ ┌──────────────┐ ││ │ System Prompt │ │ QA Chain │ ││ │ Template │─────▶│ (LangChain) │ ││ └────────────────┘ └──────┬───────┘ │└─────────────────────────────────┼──────────────────────────┘ │ ┌─────────────┴─────────────┐ ▼ ▼ ┌───────────────────────┐ ┌──────────────────────┐ │ Vector Store │ │ LLM Handler │ │ (vectorstore.py) │ │ (llm_handler.py) │ │ │ │ │ │ ┌─────────────────┐ │ │ ┌───────────────┐ │ │ │ ChromaDB │ │ │ │ Ollama │ │ │ │ (Embeddings) │ │ │ │ (llama3.2) │ │ │ └─────────────────┘ │ │ └───────────────┘ │ │ │ │ │ │ ┌─────────────────┐ │ └──────────────────────┘ │ │ HuggingFace │ │ │ │ Embeddings │ │ │ │ (all-MiniLM) │ │ │ └─────────────────┘ │ └───────────────────────┘ ▲ │ ┌───────────┴────────────┐ │ Document Processor │ │ (document_processor.py)│ │ │ │ ┌──────────────────┐ │ │ │ PDF Loader │ │ │ │ DOCX Loader │ │ │ │ HTML Loader │ │ │ │ Text Loader │ │ │ └──────────────────┘ │ │ │ │ ┌──────────────────┐ │ │ │ Text Splitter │ │ │ │ (Chunking) │ │ │ └──────────────────┘ │ └────────────────────────┘ ▲ │ ┌───────────┴────────────┐ │ Source Documents │ │ data/documents/ │ │ │ │ • Resume.pdf │ │ • LinkedIn.html │ │ • Projects.docx │ │ • ... │ └────────────────────────┘
┌──────────────────────────────────────────────────────────────┐│ Configuration Layer │├──────────────────────────────────────────────────────────────┤│ ││ config.yaml env.template (.env) ││ ├─ profile ├─ OLLAMA_BASE_URL ││ ├─ llm ├─ CHROMA_PERSIST_DIR ││ ├─ embeddings ├─ DOCUMENTS_DIR ││ ├─ vectorstore ├─ LOG_LEVEL ││ ├─ document_proc └─ API_KEYS (optional) ││ ├─ rag ││ ├─ ui ││ └─ logging ││ ││ (config_loader.py) │└──────────────────────────────────────────────────────────────┘```
## Data Flow
### 1️⃣ Indexing Phase (One-time Setup)
```Documents → Load → Chunk → Build Indexes ↓ ↓ ↓ ↓resume.pdf PyPDF Split ┌─────────────────────────────┐linkedin.html BS4 into │ BM25 Index (keyword) │projects.docx docx chunks │ ./bm25_index/ │ ├─────────────────────────────┤ │ Vector Index (semantic) │ │ ./chroma_db/ (ChromaDB) │ └─────────────────────────────┘```
**Command:** `python -m src.build_vectorstore`
**Strategy Options:**- `--strategy bm25_vector` - Build both indexes (default, recommended)- `--strategy vector` - Vector index only- `--strategy bm25` - BM25 index only
### 2️⃣ Query Phase (Runtime) - WITH HYBRID SEARCH
```User Question ↓┌─────────────────────────────────────┐│ Extract Chat History (if enabled) ││ • Format previous Q&A pairs ││ • Truncate by turns/tokens ││ • Include in context │└────────────┬────────────────────────┘ ↓┌─────────────────────────────────────┐│ Load Main Document (if enabled) ││ • Check cache validity ││ • Auto-detect format ││ • Count tokens ││ • Summarize if needed │└────────────┬────────────────────────┘ ↓ [Main Doc Content] │ ├─────────────────────────────────────┐ ↓ ↓┌─────────────────────────────────────┐ Main Doc (Priority)│ Hybrid Retrieval Strategy │ ↓│ │ [Always Available]│ ┌─────────────┐ ┌─────────────┐ │ [10k tokens max]│ │ BM25 │ │ Vector │ ││ │ (keyword) │ │ (semantic) │ ││ └──────┬──────┘ └──────┬──────┘ ││ │ │ ││ └───────┬────────┘ ││ ↓ ││ Reciprocal Rank Fusion (RRF) ││ (70% vector, 30% BM25) │└────────────────┬────────────────────┘ ↓ [Retrieved Context] │ └─────────┬───────────────────┘ ↓ Construct Prompt: System Prompt → Chat History → Main Doc → Retrieved Context → Question ↓ Send to LLM (Ollama/Groq) ↓ Generate Answer (streaming) ↓ Response Enhancer • Detect negative phrases • Rewrite positively • Fix markdown formatting • Add forward-looking closings ↓ Display in Streamlit UI (with source citations)```
## Component Details
### 📑 Main Document Integration
The Main Document feature ensures critical profile information is always available in the LLM context, regardless of VectorDB retrieval quality.
```pythonMainDocumentLoader├── Format Auto-Detection│ ├── Markdown (.md) → LangChain TextLoader│ ├── Plain Text (.txt) → LangChain TextLoader│ ├── PDF (.pdf) → Existing PDF loader│ ├── Word (.docx) → Existing DOCX loader│ └── HTML (.html) → Existing HTML loader│├── Token Management│ ├── Counting: tiktoken (cl100k_base encoding)│ ├── Max Limit: 10,000 tokens (configurable)│ ├── Truncation: Smart token-based trimming│ └── Summarization: LLM-based if exceeds limit│├── Caching Strategy│ ├── File hash-based invalidation (MD5)│ ├── Configurable check interval (60s default)│ └── Automatic reload on file changes│└── Integration Point └── Positioned BEFORE VectorDB context (high priority)```
**Architecture Flow:**```Main Document (Priority Context) ↓ [Essential Info Always Available] ↓VectorDB Retrieval (Additional Context) ↓ [Supplementary Information] ↓Combined Context → LLM → Response```
**Benefits:**- ✅ Critical information never missed by retrieval- ✅ Auto-format detection (no manual config)- ✅ Intelligent token management with LLM summarization- ✅ Efficient caching for performance- ✅ Graceful degradation if unavailable
**Note:** The system also supports chat history for conversational context. Previous Q&A pairs are included in the prompt (after system prompt, before main document) with configurable truncation by turns or tokens. Responses are post-processed to improve tone, remove negative language, and fix markdown formatting.
### 📄 Document Processing Pipeline
```pythonDocumentProcessor├── Supported Formats│ ├── PDF → pypdf│ ├── Word → python-docx│ ├── HTML → BeautifulSoup4│ └── Text/MD → LangChain TextLoader│├── Chunking Strategy│ ├── Size: 1000 chars (configurable)│ ├── Overlap: 200 chars (configurable)│ └── Separators: ["\n\n", "\n", ". ", " ", ""]│└── Output: List[Document] └── Each with content + metadata```
### 🔍 Retrieval Strategy System
The retrieval system uses a pluggable strategy pattern for extensibility.
```pythonRetrieverFactory├── Registered Strategies│ ├── "vector" → VectorStrategy (semantic search)│ ├── "bm25" → BM25Strategy (keyword search)│ ├── "bm25_vector" → BM25VectorStrategy (hybrid)│ └── (future: "page_index", "graph_vector")│└── Strategy Interface (BaseRetrieverStrategy) ├── build_index(documents) → Build/update index ├── load_index() → Load from disk ├── retrieve(query, k) → Get relevant docs └── as_retriever() → LangChain compatible```
#### Hybrid Search (BM25 + Vector)
```┌─────────────────────────────────────────────────────────────────┐│ BM25VectorStrategy ││ ││ ┌─────────────────────┐ ┌─────────────────────────┐ ││ │ BM25Retriever │ │ VectorRetriever │ ││ │ (keyword match) │ │ (semantic match) │ ││ │ │ │ │ ││ │ • Exact terms │ │ • Meaning/context │ ││ │ • Abbreviations │ │ • Synonyms │ ││ │ • Proper nouns │ │ • Related concepts │ ││ └──────────┬──────────┘ └───────────┬─────────────┘ ││ │ (k=10) │ (k=10) ││ └───────���──┬───────────────────┘ ││ ↓ ││ Reciprocal Rank Fusion (RRF) ││ weights: {vector: 0.7, bm25: 0.3} ││ ↓ ││ Top K results (k=4) │└─────────────────────────────────────────────────────────────────┘```
**RRF Formula:** `score(d) = Σ (weight × 1/(k + rank(d)))`
### 🧠 Vector Store Architecture
```pythonVectorStoreManager├── Embedding Model│ └── sentence-transformers/all-MiniLM-L6-v2│ ├── Dimension: 384│ ├── Speed: ~2000 sentences/sec (CPU)│ └── Quality: Good for semantic search│├── ChromaDB│ ├── Type: Persistent (SQLite)│ ├── Location: ./chroma_db/│ ├── Collection: profile_documents│ └── Indexing: HNSW (approximate NN)│└── Retrieval ├── Search Type: Similarity (or MMR) ├── Top K: 10 (before fusion) └── Distance: Cosine similarity```
### 📝 BM25 Store Architecture
```pythonBM25Store├── Algorithm: BM25Okapi (rank-bm25)│├── Tokenization│ ├── "simple": Whitespace + punctuation split│ └── "nltk": NLTK word_tokenize (optional)│├── Persistence│ ├── Location: ./bm25_index/│ ├── Format: Pickle (index + documents)│ └── Metadata: JSON (hash, stats)│└── Retrieval ├── Top K: 10 (before fusion) └── Scoring: BM25 term frequency```
### 🤖 LLM Integration
```pythonLLMHandler├── Provider Support│ ├── Ollama (Local)│ │ ├── Base URL: http://localhost:11434│ │ ├── Protocol: HTTP/REST API│ │ └── Auto-detected if no API key│ ││ └── Groq (Cloud)│ ├── Base URL: https://api.groq.com/openai/v1│ ├── Protocol: OpenAI-compatible API│ └── Requires GROQ_API_KEY env var│├── Model Options (Ollama)│ ├── llama3.2:3b (Recommended)│ ├── phi3:mini│ ├── gemma2:2b│ └── llama3.1:8b (with GPU)│├── Model Options (Groq)│ ├── openai/gpt-oss-120b│ ├── llama-3.3-70b-versatile│ ├── llama-3.1-8b-instant│ ├── mixtral-8x7b-32768│ └── gemma2-9b-it│└── Parameters ├── Temperature: 0.7 ├── Max Tokens: 800 (increased for better formatting) ├── Top P: 0.9 └── Context Window: Model-dependent (8192-128k tokens)```
### 🔗 RAG Chain
```pythonRAGPipeline├── Retrieval Strategy│ └── RetrieverFactory.create(strategy_name)│ ├── "vector" → Vector-only retriever│ ├── "bm25" → BM25-only retriever│ └── "bm25_vector" → Fusion retriever (default)│├── Prompt Template Structure│ ├── System Prompt (from config)│ ├── Chat History (formatted previous Q&A pairs)│ ├── Main Document (priority context, always available)│ ├── Retrieved Context (from strategy)│ └── User Question│├── LLM│ └── Ollama or Groq (auto-detected or configured)│└── Output ├── Answer (post-processed for tone/formatting, streaming support) └── Source Documents (citations)```
## Configuration Hierarchy
```1. Environment Variables (.env) ├── Override config.yaml values ├── Secrets (API keys) └── Runtime settings (ports, URLs) ↓2. config.yaml ├── Application defaults ├── Model selection ├── Retrieval strategy (vector, bm25, bm25_vector) └── RAG parameters ↓3. Code Defaults └── Fallback values if config missing```
### Retrieval Configuration
```yamlretrieval: strategy: "bm25_vector" # Which strategy to use final_k: 4 # Documents returned to LLM
vector: search_type: "similarity" # or "mmr" k: 10 # Docs before fusion
bm25: k: 10 # Docs before fusion persist_path: "./bm25_index" tokenizer: "simple"
fusion: algorithm: "rrf" # Reciprocal Rank Fusion rrf_k: 60 # RRF constant weights: vector: 0.7 bm25: 0.3```
### Chat History Configuration
```yamlchat: enable_history: true # Enable conversation context max_history_turns: 10 # Max Q&A pairs to include max_history_tokens: 2000 # Token limit for history```
### RAG Configuration
```yamlrag: enhance_responses: true # Enable post-processing enhancement include_sources: true # Show source citations source_max_length: 150 # Max length of source preview```
## Deployment Architecture
### Local Development
```┌──────────────────┐│ Developer ││ Machine ││ ││ ┌────────────┐ ││ │ Ollama │ │ ← Port 11434 (optional)│ │ Server │ ││ └────────────┘ ││ ││ ┌────────────┐ ││ │ Groq API │ │ ← https://api.groq.com (optional)│ │ (Cloud) │ ││ └────────────┘ ││ ││ ┌────────────┐ ││ │ Streamlit │ │ ← Port 8501│ │ App │ ││ └────────────┘ ││ ││ ┌────────────┐ ││ │ ChromaDB │ │ ← ./chroma_db/│ │ (local) │ ││ └────────────┘ ││ ││ ┌────────────┐ ││ │ BM25 Index │ │ ← ./bm25_index/│ │ (local) │ ││ └────────────┘ │└──────────────────┘```
### Hugging Face Spaces
```┌───────────────────────────────┐│ HF Spaces Container ││ ││ ┌─────────────────────────┐ ││ │ Dockerfile │ ││ │ ├─ Install Ollama │ ││ │ ├─ Pull Model │ ││ │ ├─ Build Indexes │ ││ │ └─ Start Services │ ││ └─────────────────────────┘ ││ ││ ┌──────────┐ ┌──────────┐ ││ │ Ollama │ │Streamlit │ ││ │ Server │ │ App │ ││ └──────────┘ └──────────┘ ││ ││ ┌─────────────────────────┐ ││ │ Persistent Storage │ ││ │ ├─ chroma_db/ │ ││ │ └─ bm25_index/ │ ││ └─────────────────────────┘ │└───────────────────────────────┘ ↑ │ HTTPS │┌────────┴──────────┐│ Public Users ││ (Recruiters) │└───────────────────┘```
## Build & Packaging
### UV + Hatchling + Versioningit
```pyproject.toml├── [build-system]│ ├── requires: ["hatchling", "versioningit"]│ └── build-backend: "hatchling.build"│├── [project]│ ├── name: "profillybot"│ ├── version: <from git tags via versioningit>│ └── dependencies: [...]│├── [tool.versioningit]│ ├── Read git tags (v0.1.0, v0.2.0, etc.)│ ├── Generate version string│ └── Write to src/_version.py│└── [tool.ruff] ├── Linting rules └── Formatting config```
### Version from Git Tags
```bash# Tag releasegit tag v0.1.0git push origin v0.1.0
# Version automatically setpython -c "from src import __version__; print(__version__)"# Output: 0.1.0
# Development version (after tag)# Output: 0.1.0+5.g1a2b3c4 (5 commits after v0.1.0)```
## Code Quality Pipeline
```Developer Writes Code ↓┌───────────────────┐│ Pre-commit ││ (Optional) │└─────────┬─────────┘ ↓┌───────────────────┐│ Ruff Check │ ← Linting│ Ruff Format │ ← Formatting└─────────┬─────────┘ ↓┌───────────────────┐│ Git Commit │└─────────┬─────────┘ ↓┌───────────────────┐│ Push to GitHub │└─────────┬─────────┘ ↓┌───────────────────┐│ GitHub Actions ││ • Lint Check ││ • Format Check ││ • Tests (future) │└───────────────────┘```
## Module Dependencies
```app.py ├─ src.config_loader ├─ src.rag_pipeline ├─ src.llm_handler (provider detection) ├─ src.response_enhancer (post-stream enhancement) ├─ src.main_document_loader (token counting for history) └─ streamlit (UI, chat history management)
src.rag_pipeline ├─ src.config_loader ├─ src.llm_handler ├─ src.retrieval (RetrieverFactory, strategies) ├─ src.main_document_loader ├─ src.response_enhancer └─ langchain (LCEL chains)
src.retrieval ├─ src.retrieval.base (BaseRetrieverStrategy) ├─ src.retrieval.factory (RetrieverFactory) ├─ src.retrieval.fusion (RRF, FusionRetriever) ├─ src.retrieval.stores.bm25_store └─ src.retrieval.strategies.*
src.retrieval.strategies.vector ├─ src.vectorstore └─ src.retrieval.base
src.retrieval.strategies.bm25 ├─ src.retrieval.stores.bm25_store └─ rank_bm25
src.retrieval.strategies.bm25_vector ├─ src.retrieval.strategies.vector ├─ src.retrieval.strategies.bm25 └─ src.retrieval.fusion
src.main_document_loader ├─ src.config_loader ├─ src.document_processor ├─ src.llm_handler ├─ tiktoken └─ pathlib, hashlib, time
src.response_enhancer ├─ src.config_loader └─ re (regex pattern matching)
src.vectorstore ├─ src.config_loader ├─ chromadb └─ langchain_huggingface
src.llm_handler ├─ src.config_loader ├─ langchain_community.llms (Ollama) └─ langchain_groq (Groq support)
src.document_processor ├─ src.config_loader ├─ pypdf ├─ python-docx ├─ beautifulsoup4 └─ langchain
src.config_loader ├─ pyyaml └─ python-dotenv
src.build_vectorstore ├─ src.document_processor ├─ src.retrieval (RetrieverFactory) └─ src.vectorstore```
## Performance Characteristics
### Indexing (One-time)
| Documents | Chunks | Embedding Time | ChromaDB Insert | Total ||-----------|--------|----------------|-----------------|-------|| 5 PDFs | ~100 | ~5 seconds | ~1 second | ~6s || 20 PDFs | ~400 | ~20 seconds | ~2 seconds | ~22s || 50 PDFs | ~1000 | ~50 seconds | ~5 seconds | ~55s |
### Query (Runtime)
| Step | Time (CPU) | Time (GPU) | Notes ||------|------------|------------|-------|| Chat history extraction | <1ms | <1ms | Token counting overhead || Main doc loading | <1ms | <1ms | Cached after first load || Embed query | 50ms | 10ms | Sentence transformers || Vector search | 10-50ms | 10-50ms | ChromaDB HNSW || BM25 search | 5-20ms | 5-20ms | In-memory index || Fusion (RRF) | <1ms | <1ms | Rank combination || LLM inference (Ollama) | 2-5s | 0.5-1s | Local model || LLM inference (Groq) | 0.5-2s | N/A | Cloud API || Response enhancement | <10ms | <10ms | Post-processing || **Total (Ollama)** | **2-5s** | **0.5-1s** | || **Total (Groq)** | **0.6-2s** | **N/A** | Faster cloud option |
### Memory Usage
| Component | RAM | Disk ||-----------|-----|------|| Streamlit | ~200MB | - || Ollama (llama3.2:3b) | ~2GB | ~2GB || ChromaDB | ~100MB | ~50MB per 1k docs || BM25 Index | ~50MB | ~10MB per 1k docs || Embeddings | ~500MB | ~500MB || Chat History | ~1-10MB | - || Response Enhancer | <1MB | - || **Total** | **~3GB** | **~3GB** |
## Security Architecture
```User Input ↓┌─────────────────────┐│ Input Validation │ ← Length limits│ (Streamlit) │ ← Character filtering└─────────┬───────────┘ ↓┌─────────────────────┐│ RAG Pipeline │ ← Context isolation└─────────┬───────────┘ ↓┌─────────────────────┐│ LLM (Local) │ ← No external API calls│ │ ← Data stays local└─────────────────────┘
Secrets Management:├─ .env (local)├─ .gitignore (.env excluded)└─ HF Spaces Secrets (cloud)```
## Extensibility Points
### 🔌 Plugin Architecture
```python# Easy to extend:
# 1. New document typesDocumentProcessor.load_custom_format()
# 2. New LLM providersLLMHandler.get_openai_llm()LLMHandler.get_anthropic_llm()# Already supports: Ollama (local), Groq (cloud)
# 3. New retrieval strategies (extensible system!)@RetrieverFactory.register("page_index")class PageIndexStrategy(BaseRetrieverStrategy): """Vision-based document retrieval (ColPali)""" ...
@RetrieverFactory.register("graph_vector")class GraphVectorStrategy(BaseRetrieverStrategy): """Knowledge graph + vector hybrid""" ...
# 4. New UI featuresapp.py → add_authentication()app.py → add_analytics()# Already supports: Chat history, provider switching, streaming responses
# 5. New embedding modelsVectorStoreManager(embedding_model="...")
# 6. New fusion algorithms# Add to src/retrieval/fusion.pydef custom_fusion(results_list, weights): ...
# 7. New response enhancement patterns# Edit src/response_enhancer.pyResponseEnhancer.negative_patterns.append((pattern, rewrite_func))
# 8. Custom chat history strategies# Modify truncate_chat_history() in app.py# Add custom truncation logic (e.g., importance-based)```
### Adding a New Retrieval Strategy
1. Create `src/retrieval/strategies/my_strategy.py`2. Implement `BaseRetrieverStrategy` interface3. Register with `@RetrieverFactory.register("my_strategy")`4. Add config section in `config.yaml`5. Import in `src/retrieval/strategies/__init__.py`
```pythonfrom src.retrieval import RetrieverFactoryfrom src.retrieval.base import BaseRetrieverStrategy
@RetrieverFactory.register("my_strategy")class MyStrategy(BaseRetrieverStrategy): @property def name(self) -> str: return "my_strategy"
def build_index(self, documents): ... def load_index(self) -> bool: ... def retrieve(self, query, k=4): ... def as_retriever(self, **kwargs): ...```
---
**This architecture prioritizes:**- ✅ Simplicity (easy to understand)- ✅ Modularity (easy to extend)- ✅ Performance (optimized for small-medium datasets)- ✅ Privacy (local processing)- ✅ Deployability (cloud-ready)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# Dockerfile for HuggingFace Spaces with Ollama supportFROM python:3.11-slim
# Set working directoryWORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y \ curl \ build-essential \ zstd \ && rm -rf /var/lib/apt/lists/*
# Install OllamaRUN curl -fsSL https://ollama.ai/install.sh | sh
# Copy requirementsCOPY requirements.txt .
# Install CPU-only PyTorch first (saves ~2GB by avoiding CUDA dependencies)RUN pip install --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu
# Install Python dependenciesRUN pip install --no-cache-dir -r requirements.txt
# Copy application filesCOPY . .
# Create necessary directoriesRUN mkdir -p data/documents chroma_db bm25_index
# Expose Streamlit portEXPOSE 7860
# Expose Ollama portEXPOSE 11434
# Start script that runs both Ollama and StreamlitCOPY <<'EOF' /app/start.sh#!/bin/bashset -e
# Start Ollama in the backgroundollama serve &OLLAMA_PID=$!
# Wait for Ollama to be readyecho "Waiting for Ollama to start..."sleep 5
# Pull the model (use small model for HF Spaces)MODEL=${OLLAMA_MODEL:-llama3.2:3b}echo "Pulling model: $MODEL"ollama pull $MODEL || echo "Model pull failed, will retry on app start"
# Build retrieval indexes if documents exist and indexes don'tif [ -d "data/documents" ] && [ ! -f "chroma_db/chroma.sqlite3" ]; then echo "Building retrieval indexes (BM25 + Vector)..." python -m src.build_vectorstore || echo "Index build failed, will build on first use"fi
# Start Streamlitstreamlit run app.py --server.port=7860 --server.address=0.0.0.0EOF
RUN chmod +x /app/start.sh
CMD ["/app/start.sh"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980# Dockerfile for Streamlit RAG Application (for Docker Compose)# Use with docker-compose.yml - Ollama runs as a separate serviceFROM python:3.11-slim
# Set working directoryWORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y \ curl \ build-essential \ zstd \ && rm -rf /var/lib/apt/lists/*
# Copy requirementsCOPY requirements.txt .
# Install CPU-only PyTorch first (saves ~2GB by avoiding CUDA dependencies)RUN pip install --no-cache-dir torch --index-url https://download.pytorch.org/whl/cpu
# Install Python dependenciesRUN pip install --no-cache-dir -r requirements.txt
# Copy application filesCOPY src/ ./src/COPY app.py .COPY config.yaml .COPY .streamlit/ ./.streamlit/
# Create necessary directoriesRUN mkdir -p data/documents chroma_db bm25_index
# Create startup scriptCOPY <<'EOF' /app/start.sh#!/bin/bashset -e
echo "Starting ProfillyBot Application..."
# Wait for Ollama to be available (if using Ollama)if [ -n "$OLLAMA_HOST" ]; then echo "Waiting for Ollama at $OLLAMA_HOST..." for i in {1..30}; do if curl -sf "$OLLAMA_HOST/api/tags" > /dev/null 2>&1; then echo "Ollama is ready!" break fi echo "Waiting for Ollama... ($i/30)" sleep 2 donefi
# Build retrieval indexes if documents exist and indexes don'tif [ -d "data/documents" ] && [ "$(ls -A data/documents 2>/dev/null)" ]; then if [ ! -f "chroma_db/chroma.sqlite3" ]; then echo "Building retrieval indexes (BM25 + Vector)..." python -m src.build_vectorstore || echo "Index build failed, will build on first use" else echo "Indexes already exist, skipping build" fifi
# Start Streamlitecho "Starting Streamlit on port ${STREAMLIT_SERVER_PORT:-7860}..."exec streamlit run app.py \ --server.port=${STREAMLIT_SERVER_PORT:-7860} \ --server.address=${STREAMLIT_SERVER_ADDRESS:-0.0.0.0} \ --server.headless=trueEOF
RUN chmod +x /app/start.sh
# Expose Streamlit portEXPOSE 7860
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \ CMD curl -f http://localhost:7860/_stcore/health || exit 1
CMD ["/app/start.sh"]123456789101112131415161718192021MIT License
Copyright (c) 2025 Tin-Hoang
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146# Makefile for ProfillyBot# Run 'make help' to see available commands
.PHONY: help install install-dev test test-cov lint format clean \ docker-up docker-down docker-build docker-logs docker-shell \ docker-rebuild docker-ps ollama-pull index-build run
# Default target.DEFAULT_GOAL := help
# VariablesPYTHON := pythonDOCKER_COMPOSE := docker composeAPP_PORT := 7860OLLAMA_MODEL ?= llama3.2:3b
# =============================================================================# Help# =============================================================================help: ## Show this help message @echo "Usage: make [target]" @echo "" @echo "Available targets:" @awk 'BEGIN {FS = ":.*##"; printf ""} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-20s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST)
# =============================================================================# Development Setup# =============================================================================install: ## Install dependencies pip install -r requirements.txt
install-dev: ## Install development dependencies pip install -e ".[dev]"
install-uv: ## Install dependencies using uv (faster) uv pip install -r requirements.txt
install-uv-dev: ## Install dev dependencies using uv uv pip install -e ".[dev]"
# =============================================================================# Testing & Quality# =============================================================================test: ## Run tests pytest tests/ -v
test-cov: ## Run tests with coverage report pytest tests/ -v --cov=src --cov-report=term-missing --cov-report=html
lint: ## Run linter (ruff) ruff check src/ tests/ app.py
lint-fix: ## Run linter and fix issues ruff check src/ tests/ app.py --fix
format: ## Format code (ruff) ruff format src/ tests/ app.py
format-check: ## Check code formatting ruff format src/ tests/ app.py --check
check: lint format-check ## Run all checks (lint + format)
# =============================================================================# Local Development# =============================================================================run: ## Run the Streamlit app locally streamlit run app.py --server.port=$(APP_PORT)
index-build: ## Build vector and BM25 indexes $(PYTHON) -m src.build_vectorstore
index-clean: ## Remove existing indexes rm -rf chroma_db/ bm25_index/
index-rebuild: index-clean index-build ## Rebuild indexes from scratch
# =============================================================================# Docker Compose# =============================================================================docker-up: ## Start all services $(DOCKER_COMPOSE) up -d
docker-down: ## Stop all services $(DOCKER_COMPOSE) down
docker-build: ## Build Docker images $(DOCKER_COMPOSE) build
docker-rebuild: ## Rebuild and restart services $(DOCKER_COMPOSE) up -d --build
docker-logs: ## Show logs (follow mode) $(DOCKER_COMPOSE) logs -f
docker-logs-app: ## Show app logs only $(DOCKER_COMPOSE) logs -f app
docker-ps: ## Show running containers $(DOCKER_COMPOSE) ps
docker-shell: ## Open shell in app container $(DOCKER_COMPOSE) exec app /bin/bash
docker-clean: ## Stop services and remove volumes $(DOCKER_COMPOSE) down -v
docker-restart: docker-down docker-up ## Restart all services
# =============================================================================# Ollama Commands# =============================================================================ollama-pull: ## Pull the configured Ollama model $(DOCKER_COMPOSE) exec ollama ollama pull $(OLLAMA_MODEL)
ollama-list: ## List available Ollama models $(DOCKER_COMPOSE) exec ollama ollama list
ollama-shell: ## Open shell in Ollama container $(DOCKER_COMPOSE) exec ollama /bin/bash
# =============================================================================# Setup & Utilities# =============================================================================setup: ## Initial project setup (copy env, install deps) @if [ ! -f .env ]; then cp .env.template .env && echo "Created .env from template"; fi @echo "Installing dependencies..." @make install-dev @echo "Setup complete! Edit .env if needed, then run 'make run' or 'make docker-up'"
clean: ## Clean up build artifacts and caches rm -rf __pycache__ .pytest_cache .ruff_cache htmlcov .coverage find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true find . -type f -name "*.pyc" -delete 2>/dev/null || true
clean-all: clean index-clean ## Clean everything including indexes rm -rf *.egg-info build dist
# =============================================================================# Pre-commit# =============================================================================pre-commit-install: ## Install pre-commit hooks pre-commit install
pre-commit-run: ## Run pre-commit on all files pre-commit run --all-files12345345678978910111213141315161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423---title: ProfillyBotemoji: 🐨colorFrom: pinkcolorTo: yellowemoji: 🤖colorFrom: bluecolorTo: greensdk: gradiosdk_version: 6.20.0python_version: '3.12'app_file: app.pysdk_version: 5.49.1python_version: "3.11"app_file: gradio_app.pypinned: falselicense: mitshort_description: Cute RAG chatbot for professional profile Q&A on ZeroGPU---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# 🤖 ProfillyBot
<p align="center"> <img src="docs/banner_image.png" alt="ProfillyBot Banner" width="100%" /></p>
<p align="center"> <img src="https://github.com/Tin-Hoang/slm-profile-rag/actions/workflows/test-python310.yml/badge.svg" alt="Python 3.10"/> <img src="https://github.com/Tin-Hoang/slm-profile-rag/actions/workflows/test-python311.yml/badge.svg" alt="Python 3.11"/> <img src="https://github.com/Tin-Hoang/slm-profile-rag/actions/workflows/test-python312.yml/badge.svg" alt="Python 3.12"/> <img src="https://github.com/Tin-Hoang/slm-profile-rag/actions/workflows/test-docker.yml/badge.svg" alt="Docker"/> <img src="https://github.com/Tin-Hoang/slm-profile-rag/actions/workflows/lint.yml/badge.svg" alt="Lint"/> <img src="https://github.com/Tin-Hoang/slm-profile-rag/actions/workflows/code-quality.yml/badge.svg" alt="Code Quality"/> <img src="https://github.com/Tin-Hoang/slm-profile-rag/actions/workflows/security-scan.yml/badge.svg" alt="Security Scan"/> <a href="https://codecov.io/gh/Tin-Hoang/slm-profile-rag"> <img src="https://codecov.io/gh/Tin-Hoang/slm-profile-rag/graph/badge.svg?token=MW4RD9R66J" alt="Codecov"/> </a></p>
**ProfillyBot** is a RAG (Retrieval Augmented Generation) chatbot that answers questions about your professional profile using your resume, project reports, and other documents.
## ✨ Features
- 📄 **Multi-format Support**: Process PDF, Word, HTML, and text documents- 🔍 **Hybrid Search**: Combines BM25 (keyword) + Vector (semantic) search with Reciprocal Rank Fusion- 🧠 **Extensible Retrieval**: Pluggable strategy system - easily add new retrieval methods (PageIndex, GraphRAG, etc.)- 📌 **Main Document Support**: Guaranteed context - critical information always available, auto-format detection- 🦙 **Ollama Integration**: Run small language models locally- 🎨 **Clean UI**: Streamlit-based interface- ⚙️ **Highly Configurable**: YAML-based settings for easy customization- 🚀 **HuggingFace Spaces Ready**: Deploy with one click- ✨ **Smart Response Enhancement**: Automatically removes negative language and adds professional, recruiter-friendly tone
## 🏗️ Architecture
<p align="center"> <img src="docs/arch_system_design.png" alt="System Architecture Diagram" width="800" /></p><p align="center"><em>Overall system design showing the RAG pipeline and component interactions</em></p>
Detailed architecture can be found in [ARCHITECTURE.md](ARCHITECTURE.md).
## 🛠️ Tech Stack
- **Python 3.10+** with UV package manager- **LangChain** for RAG pipeline- **ChromaDB** for vector storage- **rank-bm25** for lexical search- **Ollama** for local LLM serving- **Streamlit** for web interface- **sentence-transformers** for embeddings- **tiktoken** for token counting- **Ruff** for linting/formatting
## 📦 Installation
### Prerequisites
1. **Python 3.10+**2. **UV Package Manager**: Install via: ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ```3. **Ollama**: Install from [ollama.ai](https://ollama.ai)
### Setup
1. **Clone the repository**: ```bash git clone <your-repo-url> cd profillybot ```
2. **Install dependencies with UV**: ```bash uv venv source .venv/bin/activate # On Windows: .venv\Scripts\activate uv pip install -r requirements.txt ```
3. **Set up environment variables**: ```bash cp .env.template .env # Edit .env with your settings ```
4. **Configure the chatbot**: - Edit `config.yaml` to set your name, title, and preferences - Adjust model settings, chunking parameters, and system prompt
5. **Add your documents**: ```bash # Place your PDFs, Word docs, HTML files in: mkdir -p data/documents # Copy your resume, project reports, LinkedIn profile, etc. ```
6. **Create your Main Profile Document** (📌 **Recommended**):
The Main Document feature ensures critical information is **always** included in responses, never missed by vector search.
```bash # Create main profile document (any format: .md, .txt, .pdf, .docx, .html) nano data/documents/main_profile.md ```
**Include essential information:** - Full name, title, contact info - Current role and key responsibilities - Core skills and expertise - Major projects with metrics - Education and certifications
**Example structure:** ```markdown # Your Name **Title**: Your Professional Title **Email**: your.email@example.com
## Professional Summary Brief summary of your experience...
## Core Skills - Skill 1, Skill 2, Skill 3
## Current Role ### Company - Role (Dates) - Achievement 1 with metrics - Achievement 2 with metrics
## Education - Degree, University, Year ```
**Why use this?** - ✅ **Guaranteed Context**: Critical info never missed by vector similarity search - ✅ **Priority Positioning**: Appears BEFORE retrieved chunks (higher LLM attention) - ✅ **Auto-Format Detection**: Supports MD, TXT, PDF, DOCX, HTML automatically - ✅ **Smart Token Management**: LLM-based summarization if content exceeds 10k tokens
The feature is enabled by default in `config.yaml`. See [docs/MAIN_DOCUMENT_GUIDE.md](docs/MAIN_DOCUMENT_GUIDE.md) for advanced configuration.
7. **Pull Ollama model**: ```bash ollama pull llama3.2:3b # Or other small models: phi3:mini, gemma2:2b ```
## 🚀 Usage
### Local Development
1. **Build the retrieval index** (default: hybrid BM25 + Vector): ```bash # Build with default strategy from config (bm25_vector) python -m src.build_vectorstore
# Or specify a strategy explicitly python -m src.build_vectorstore --strategy bm25_vector # Hybrid (recommended) python -m src.build_vectorstore --strategy vector # Vector-only python -m src.build_vectorstore --strategy bm25 # BM25-only ```
2. **Run the Streamlit app**: ```bash streamlit run app.py ```
3. **Open browser**: Navigate to `http://localhost:8501`
**Screenshot Example:**
<p align="center"> <img src="docs/screenshot-example.png" alt="ProfillyBot UI Example" width="800" /></p><p align="center"><em>Streamlit chatbot interface in action</em></p>
### 🐳 Docker Compose
Run the complete stack with Docker Compose (includes Ollama):
```bash# Copy environment templatecp .env.template .env
# Start all services (app + Ollama)docker compose up -d
# View logsdocker compose logs -f
# Stop servicesdocker compose down```
Access the app at `http://localhost:7860`
### 📋 Makefile Commands
Use the Makefile for common development tasks:
```bashmake help # Show all available commands```
| Category | Command | Description ||----------|---------|-------------|| **Setup** | `make setup` | Initial project setup (copy env, install deps) || | `make install` | Install dependencies || | `make install-dev` | Install with dev dependencies || **Development** | `make run` | Run Streamlit app locally || | `make index-build` | Build vector and BM25 indexes || | `make index-rebuild` | Rebuild indexes from scratch || **Quality** | `make test` | Run tests || | `make test-cov` | Run tests with coverage || | `make lint` | Run linter (ruff) || | `make format` | Format code || | `make check` | Run all checks || **Docker** | `make docker-up` | Start all services || | `make docker-down` | Stop all services || | `make docker-rebuild` | Rebuild and restart || | `make docker-logs` | Show logs (follow mode) || | `make docker-clean` | Stop and remove volumes || **Ollama** | `make ollama-pull` | Pull configured model || | `make ollama-list` | List available models || **Cleanup** | `make clean` | Remove build artifacts || | `make clean-all` | Clean everything + indexes |
## 🌐 Deployment to Hugging Face Spaces (ZeroGPU)
ProfillyBot on Spaces uses **Gradio + ZeroGPU** with `Qwen/Qwen2.5-3B-Instruct`(`gradio_app.py`). Streamlit (`app.py`) remains available for local/Ollama/Groq.
### Live Space
- [huggingface.co/spaces/MinhDS/ProfillyBot](https://huggingface.co/spaces/MinhDS/ProfillyBot)
### Deploy / update
1. Create a Gradio Space with **ZeroGPU** hardware (Pro account required to *create* ZeroGPU Spaces).2. Ensure this repo has: - `data/documents/MY_CV_2_0.pdf` (or your profile docs) - Pre-built `chroma_db/` + `bm25_index/` (recommended) — or let the app build on first start3. Push to the Space: ```bash git remote add hf https://huggingface.co/spaces/MinhDS/ProfillyBot git push hf main ```4. Confirm Space Settings: SDK **Gradio**, hardware **ZeroGPU**, app file `gradio_app.py`.
### Important Notes for HF Spaces
- **ZeroGPU is Gradio-only** — do not use the Docker/Ollama `Dockerfile` on ZeroGPU- **SLM**: `Qwen/Qwen2.5-3B-Instruct` via the `transformers` provider- **Embeddings**: `all-MiniLM-L6-v2` on CPU (does not consume GPU quota)- **Vector DB**: Pre-build indexes locally when possible for faster cold start- **Secrets**: optional `HF_TOKEN` only if you switch to a gated model
## ⚙️ Configuration
### `config.yaml` - Main Settings
```yamlprofile: name: "Your Name" # ← Change this! title: "Your Title"
llm: model: "llama3.2:3b" # Choose your model temperature: 0.7
# Retrieval Strategy Configurationretrieval: strategy: "bm25_vector" # Options: vector, bm25, bm25_vector final_k: 4 # Number of documents to return
vector: search_type: "similarity" k: 10 # Docs to retrieve before fusion
bm25: k: 10 # Docs to retrieve before fusion tokenizer: "simple"
fusion: algorithm: "rrf" # Reciprocal Rank Fusion weights: vector: 0.7 # 70% weight on semantic search bm25: 0.3 # 30% weight on keyword search
document_processing: chunk_size: 1000 chunk_overlap: 200```
### `.env` - Environment Variables
```bashOLLAMA_BASE_URL=http://localhost:11434CHROMA_PERSIST_DIR=./chroma_db```
## 📚 Project Structure
```profillybot/├── app.py # Streamlit app entry point├── pyproject.toml # UV/pip dependencies & config├── config.yaml # RAG & LLM settings├── .env.template # Environment variables template├── Makefile # Development commands├── docker-compose.yml # Docker Compose configuration├── Dockerfile # Docker image (standalone with Ollama)├── Dockerfile.app # Docker image (for Compose)├── README.md├── data/│ └── documents/ # Your profile documents├── src/│ ├── __init__.py│ ├── document_processor.py # Load & chunk documents│ ├── vectorstore.py # ChromaDB operations│ ├── llm_handler.py # Ollama/LLM interface│ ├── rag_pipeline.py # RAG chain logic│ ├── main_document_loader.py # Main document management│ ├── response_enhancer.py # Response post-processing│ ├── config_loader.py # Load config.yaml & .env│ ├── build_vectorstore.py # CLI to build indexes│ └── retrieval/ # Extensible retrieval system│ ├── __init__.py│ ├── base.py # BaseRetrieverStrategy ABC│ ├── factory.py # RetrieverFactory│ ├── fusion.py # RRF and fusion algorithms│ ├── stores/│ │ └── bm25_store.py # BM25 index storage│ └── strategies/│ ├── vector.py # Vector-only strategy│ ├── bm25.py # BM25-only strategy│ └── bm25_vector.py # Hybrid BM25+Vector strategy├── chroma_db/ # Vector database (auto-generated)├── bm25_index/ # BM25 index (auto-generated)└── tests/ # Unit tests```
## 🎯 Recommended Models for HF Spaces
| Model | Size | Speed | Quality | HF Spaces Tier ||-------|------|-------|---------|----------------|| `llama3.2:3b` | 3B | Fast | Good | Free ✅ || `phi3:mini` | 3.8B | Fast | Good | Free ✅ || `gemma2:2b` | 2B | Very Fast | Decent | Free ✅ || `llama3.1:8b` | 8B | Medium | Great | Upgraded GPU |
## 🔍 LLM Tracing with LangSmith
Monitor prompts, responses, and latency using [LangSmith](https://smith.langchain.com).
### Setup
1. **Get API Key**: Sign up at [smith.langchain.com](https://smith.langchain.com) (free tier: 5,000 traces/month)
2. **Configure `.env`**: ```bash LANGCHAIN_TRACING_V2=true LANGCHAIN_API_KEY=your_api_key_here LANGCHAIN_PROJECT=profillybot ```
3. **Restart the app**: ```bash streamlit run app.py ```
### What You Can See
- Full prompts sent to LLM (system prompt + context + question)- Complete LLM responses- Latency breakdown per step- Token usage (when available)
## 🔧 Troubleshooting
### Ollama Connection Issues```bash# Check Ollama is runningollama list
# Start Ollama serviceollama serve```
### ChromaDB / Index Errors```bash# Rebuild all indexes from scratchrm -rf chroma_db/ bm25_index/python -m src.build_vectorstore --force-rebuild```
### HuggingFace Spaces Issues- Check logs in the Space's "Logs" tab- Ensure `requirements.txt` is generated: `uv pip compile pyproject.toml -o requirements.txt`- Verify GPU/CPU settings match your model size
## 📄 License
MIT License - see LICENSE file
---
**Note**: Remember to update `config.yaml` with your personal information before deploying!123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371# 🚀 Setup Guide - ProfillyBot
This guide will walk you through setting up ProfillyBot, your personal profile chatbot, from scratch.
## 📋 Prerequisites
### 1. Install Python 3.10+
```bash# Check your Python versionpython --version # Should be 3.10 or higher```
### 2. Install UV Package Manager
```bash# Linux/macOScurl -LsSf https://astral.sh/uv/install.sh | sh
# Windows (PowerShell)irm https://astral.sh/uv/install.ps1 | iex```
### 3. Install Ollama
Download and install from [ollama.ai](https://ollama.ai)
```bash# Verify installationollama --version```
## 🛠️ Local Setup
### Step 1: Clone and Install
```bash# Clone the repositorygit clone https://github.com/Tin-Hoang/slm-profile-rag.gitcd slm-profile-rag # or rename the folder to profillybot if you prefer
# Create virtual environment with UVuv venv
# Activate virtual environment# Linux/macOS:source .venv/bin/activate# Windows:# .venv\Scripts\activate
# Install dependenciesuv pip install -r requirements.txt```
### Step 2: Configuration
#### 2.1 Environment Variables
```bash# Copy environment templatecp env.template .env
# Edit .env file (optional, defaults work for local development)# Update OLLAMA_BASE_URL if needed```
#### 2.2 Configure Your Profile
Edit `config.yaml`:
```yamlprofile: name: "Your Full Name" # ⚠️ CHANGE THIS title: "Your Professional Title" # ⚠️ CHANGE THIS greeting: "Hi! I'm ProfillyBot, trained on {name}'s professional background..."
llm: model: "llama3.2:3b" # Choose based on your hardware temperature: 0.7
# Adjust other settings as needed```
### Step 3: Pull LLM Model
```bash# Pull the model specified in config.yamlollama pull llama3.2:3b
# Or try other models:# ollama pull phi3:mini # Microsoft Phi-3 (3.8B)# ollama pull gemma2:2b # Google Gemma 2 (2B)# ollama pull llama3.1:8b # Larger, better quality (if you have GPU)```
### Step 4: Add Your Documents
```bash# Navigate to documents directorycd data/documents
# Copy your profile documents here# Supported formats: PDF, DOCX, HTML, TXT, MD```
**Recommended Documents:**- ✅ Resume/CV (PDF or DOCX)- ✅ LinkedIn profile (export as PDF)- ✅ Project reports and case studies- ✅ Portfolio descriptions- ✅ Publications, certifications- ✅ Cover letters, personal statements
**Tips:**- Use descriptive filenames- Ensure documents are well-structured with headings- Include detailed information (the more context, the better!)- Remove the sample `SAMPLE_README.md` file
### Step 5: Build Vector Store
```bash# Make sure you're in the project rootcd ../.. # if you're still in data/documents
# Build the vector databasepython -m src.build_vectorstore
# Output should show:# - Processing documents from: ./data/documents# - Successfully processed X document chunks# - ✅ Vector store built successfully!```
**Troubleshooting:**- If no documents found: Check `data/documents/` directory- If import errors: Ensure virtual environment is activated- If memory issues: Reduce chunk_size in `config.yaml`
### Step 6: Start Ollama (if not running)
```bash# Start Ollama serverollama serve```
Keep this terminal running, or run it as a background service.
### Step 7: Run the Application
```bash# In a new terminal (with virtual environment activated)streamlit run app.py
# The app will open at: http://localhost:8501```
## 🎨 Customization
### Change UI Theme
Edit `.streamlit/config.toml`:
```toml[theme]primaryColor = "#FF4B4B" # Change to your colorbackgroundColor = "#FFFFFF"```
### Adjust RAG Settings
Edit `config.yaml`:
```yamldocument_processing: chunk_size: 1000 # Increase for more context per chunk chunk_overlap: 200 # Increase for better continuity
vectorstore: search_kwargs: k: 4 # Number of chunks to retrieve (increase for more context)
llm: temperature: 0.7 # Lower (0.3) for factual, higher (0.9) for creative max_tokens: 512 # Maximum response length```
### Add Example Questions
Edit `config.yaml`:
```yamlui: example_questions: - "What is {name}'s background?" - "What programming languages does {name} know?" - "Tell me about {name}'s biggest project" # Add your own questions```
### Customize System Prompt
Edit `config.yaml`:
```yamlllm: system_prompt: | You are an AI assistant representing {name}. [Customize your instructions here]```
## 🌐 Deployment to Hugging Face Spaces
### Option 1: Direct Upload
1. Go to [Hugging Face Spaces](https://huggingface.co/spaces)2. Click "Create new Space"3. Choose "Streamlit" SDK4. Upload all project files5. Add your documents to `data/documents/`6. Space will automatically build and deploy
### Option 2: Git Integration
```bash# Initialize git (if not already)git initgit add .git commit -m "Initial commit"
# Add Hugging Face as remotegit remote add hf https://huggingface.co/spaces/YOUR_USERNAME/SPACE_NAME
# Push to deploygit push hf main```
### Important for HF Spaces
1. **Pre-build Vector Store**: Build locally and include `chroma_db/` in git
```bash# Build locallypython -m src.build_vectorstore
# Remove chroma_db from .gitignore temporarily# Commit and pushgit add chroma_db/git commit -m "Add pre-built vector store"git push hf main```
2. **Model Size**: Use small models (3B-7B params) for free tier - Recommended: `llama3.2:3b`, `phi3:mini`, `gemma2:2b`
3. **Persistent Storage**: Enable in Space settings for ChromaDB
4. **Secrets**: Add API keys in Space Settings → Repository secrets
## 🧪 Testing
```bash# Install dev dependenciesuv pip install pytest pytest-cov ruff
# Run testspytest
# Run linterruff check .
# Format coderuff format .```
## 🔧 Common Issues
### Issue: "Ollama connection failed"
**Solution:**```bash# Make sure Ollama is runningollama serve
# Check if model is pulledollama list
# Pull model if missingollama pull llama3.2:3b```
### Issue: "Vector store not found"
**Solution:**```bash# Rebuild vector storepython -m src.build_vectorstore --force-rebuild```
### Issue: "No documents found"
**Solution:**- Check `data/documents/` has files- Verify file extensions are supported (.pdf, .docx, .html, .txt, .md)- Check file permissions
### Issue: "Out of memory"
**Solution:**```yaml# Reduce chunk size in config.yamldocument_processing: chunk_size: 500 # Reduced from 1000
# Or use a smaller modelllm: model: "gemma2:2b"```
### Issue: "Slow response times"
**Solution:**- Use smaller model: `gemma2:2b` or `phi3:mini`- Reduce retrieval chunks: `k: 2` instead of `k: 4`- Lower temperature: `temperature: 0.5`- Enable GPU for Ollama (if available)
## 📊 Performance Optimization
### For Local Development
```yaml# config.yamlembeddings: device: "cuda" # If you have GPU
llm: model: "llama3.1:8b" # Better quality with GPU```
### For Production/HF Spaces
```yamlembeddings: device: "cpu" model_name: "sentence-transformers/all-MiniLM-L6-v2" # Fast, lightweight
llm: model: "llama3.2:3b" # Best balance for CPU temperature: 0.6 max_tokens: 384 # Faster responses```
## 🎯 Next Steps
1. ✅ Customize your profile information2. ✅ Add comprehensive documents3. ✅ Test with various questions4. ✅ Deploy to Hugging Face Spaces5. ✅ Share the link with recruiters!
## 📞 Support
- Check [README.md](README.md) for general information- Review [config.yaml](config.yaml) for all options- See [tests/](tests/) for examples- Open an issue for bugs
---
**Happy chatting! 🚀**123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585"""Streamlit app for ProfillyBot."""
import loggingimport osimport sysfrom datetime import datetimefrom pathlib import Path
import streamlit as st
# Add src to pathsys.path.insert(0, str(Path(__file__).parent))
from src.config_loader import get_configfrom src.llm_handler import ( detect_default_provider, get_available_groq_models, get_available_ollama_models, get_default_groq_model, get_default_ollama_model, get_llm_handler,)from src.rag_pipeline import RAGPipeline
# Configure logginglogging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")logger = logging.getLogger(__name__)
# Log LangSmith tracing statusif os.getenv("LANGCHAIN_TRACING_V2", "").lower() == "true": logger.info( f"LangSmith tracing enabled for project: {os.getenv('LANGCHAIN_PROJECT', 'profillybot')}" )
def init_session_state(): """Initialize Streamlit session state.""" if "messages" not in st.session_state: st.session_state.messages = []
if "rag_pipeline" not in st.session_state: st.session_state.rag_pipeline = None
if "config" not in st.session_state: st.session_state.config = None
if "pending_question" not in st.session_state: st.session_state.pending_question = None
# LLM Provider settings if "llm_provider" not in st.session_state: st.session_state.llm_provider = detect_default_provider()
if "groq_api_key" not in st.session_state: st.session_state.groq_api_key = ""
if "groq_model" not in st.session_state: st.session_state.groq_model = get_default_groq_model()
if "ollama_model" not in st.session_state: st.session_state.ollama_model = get_default_ollama_model()
def load_config(): """Load configuration.""" if st.session_state.config is None: try: st.session_state.config = get_config() logger.info("Configuration loaded successfully") except Exception as e: st.error(f"Error loading configuration: {e}") st.stop()
def load_rag_pipeline(force_reload: bool = False): """Load RAG pipeline with current provider settings.
Args: force_reload: Force reload even if pipeline exists """ if st.session_state.rag_pipeline is None or force_reload: with st.spinner("Loading RAG pipeline... This may take a moment."): try: # Get provider settings from session state provider = st.session_state.llm_provider api_key = st.session_state.groq_api_key or None model = None
if provider == "groq": model = st.session_state.groq_model elif provider == "ollama": model = st.session_state.ollama_model
# Create LLM handler with overrides llm_handler = get_llm_handler( provider_override=provider, api_key_override=api_key, model_override=model, )
st.session_state.rag_pipeline = RAGPipeline(llm_handler=llm_handler) logger.info(f"RAG pipeline loaded with provider: {provider}")
except FileNotFoundError: st.error( "❌ Vector store not found! Please build it first:\n\n" "```bash\n" "python -m src.build_vectorstore\n" "```" ) st.info( "Make sure you have:\n" "1. Added your documents to `data/documents/`\n" "2. Run the build command above\n" "3. Started Ollama and pulled the model" ) st.stop()
except Exception as e: error_str = str(e).lower()
# Check if it's a Groq API error - try fallback to Ollama if st.session_state.llm_provider == "groq" and ( "401" in error_str or "invalid" in error_str or "api_key" in error_str or "429" in error_str or "rate" in error_str ): logger.warning(f"Groq API error: {e}. Falling back to Ollama.")
# Show warning to user st.warning( "⚠️ **Groq API Error** - Falling back to Ollama\n\n" "Possible causes:\n" "- Invalid API key\n" "- Rate limit exceeded (free tier cap)\n" "- API key expired\n\n" "**Get a new key at:** https://console.groq.com\n\n" "Using local Ollama instead..." )
# Fallback to Ollama try: st.session_state.llm_provider = "ollama" ollama_model = st.session_state.ollama_model or get_default_ollama_model()
llm_handler = get_llm_handler( provider_override="ollama", model_override=ollama_model, )
st.session_state.rag_pipeline = RAGPipeline(llm_handler=llm_handler) logger.info("Fallback to Ollama successful") st.success(f"✅ Now using Ollama with model: {ollama_model}") return
except Exception as fallback_error: st.error(f"Fallback to Ollama also failed: {fallback_error}") st.info( "Make sure Ollama is running:\n" "- Start Ollama: `ollama serve`\n" "- Pull a model: `ollama pull llama3.2:3b`" ) logger.error(f"Ollama fallback error: {fallback_error}") st.stop()
# Not a Groq error or other error st.error(f"Error loading RAG pipeline: {e}") if st.session_state.llm_provider == "groq": st.info( "Groq issues:\n" "- Check your API key is valid\n" "- Get a free key at https://console.groq.com" ) else: st.info( "Ollama issues:\n" "- Ollama not running: `ollama serve`\n" "- Model not pulled: `ollama pull llama3.2:3b`" ) logger.error(f"RAG pipeline error: {e}", exc_info=True) st.stop()
def configure_page(): """Configure Streamlit page settings.""" config = st.session_state.config
page_title = config.get("ui.page_title", "💬 ProfillyBot") page_icon = config.get("ui.page_icon", "🤖") layout = config.get("ui.layout", "centered")
st.set_page_config(page_title=page_title, page_icon=page_icon, layout=layout)
def display_header(): """Display app header.""" config = st.session_state.config
profile_name = config.get("profile.name", "Candidate") profile_title = config.get("profile.title", "Professional") greeting = config.format_template(config.get("profile.greeting", ""))
st.title(f"💬 ProfillyBot — Chat with {profile_name}'s Profile") st.markdown(f"**{profile_title}**")
if greeting: st.info(greeting)
st.divider()
def display_sidebar(): """Display sidebar with information and controls.""" config = st.session_state.config
with st.sidebar: st.header("ℹ️ About")
profile_name = config.get("profile.name", "the candidate") st.markdown( f"This chatbot can answer questions about **{profile_name}'s** " "professional background, skills, experience, and projects." )
st.divider()
# Example questions st.subheader("💡 Example Questions") example_questions = config.get("ui.example_questions", [])
for question in example_questions: formatted_q = config.format_template(question) if st.button(formatted_q, key=f"example_{hash(formatted_q)}"): st.session_state.pending_question = formatted_q st.rerun()
st.divider()
# LLM Provider Selection st.subheader("🤖 LLM Provider")
# Provider selector providers = ["ollama", "groq"] current_provider_idx = ( providers.index(st.session_state.llm_provider) if st.session_state.llm_provider in providers else 0 )
new_provider = st.radio( "Select Provider", providers, index=current_provider_idx, format_func=lambda x: "🦙 Ollama (Local)" if x == "ollama" else "⚡ Groq (Cloud)", key="provider_radio", help="Ollama runs locally. Groq requires an API key but is faster.", )
# Groq-specific settings if new_provider == "groq": st.markdown("---") groq_key = st.text_input( "Groq API Key", value=st.session_state.groq_api_key, type="password", placeholder="Enter your Groq API key", help="Get a free key at https://console.groq.com", key="groq_key_input", )
groq_models = get_available_groq_models() current_model_idx = ( groq_models.index(st.session_state.groq_model) if st.session_state.groq_model in groq_models else 0 )
new_model = st.selectbox( "Groq Model", groq_models, index=current_model_idx, key="groq_model_select", )
# Check if settings changed settings_changed = ( new_provider != st.session_state.llm_provider or groq_key != st.session_state.groq_api_key or new_model != st.session_state.groq_model )
if settings_changed and st.button("🔄 Apply Changes", type="primary"): st.session_state.llm_provider = new_provider st.session_state.groq_api_key = groq_key st.session_state.groq_model = new_model st.session_state.rag_pipeline = None # Force reload st.rerun() else: # Ollama selected - show model selector st.markdown("---") ollama_models = get_available_ollama_models() current_ollama_idx = ( ollama_models.index(st.session_state.ollama_model) if st.session_state.ollama_model in ollama_models else 0 )
new_ollama_model = st.selectbox( "Ollama Model", ollama_models, index=current_ollama_idx, key="ollama_model_select", help="Make sure the model is pulled: ollama pull <model>", )
settings_changed = ( new_provider != st.session_state.llm_provider or new_ollama_model != st.session_state.ollama_model )
if settings_changed and st.button("🔄 Apply Changes", type="primary"): st.session_state.llm_provider = new_provider st.session_state.ollama_model = new_ollama_model st.session_state.rag_pipeline = None st.rerun()
# Show current active settings st.markdown("---") st.caption(f"**Active:** {st.session_state.llm_provider.upper()}") if st.session_state.llm_provider == "groq": st.caption(f"**Model:** {st.session_state.groq_model}") else: st.caption(f"**Model:** {st.session_state.ollama_model}")
st.divider()
# Clear chat button if st.button("🗑️ Clear Chat History"): st.session_state.messages = [] st.rerun()
# Settings with st.expander("⚙️ Advanced Settings"): st.markdown("**Vector Store**") st.markdown(f"- Collection: {config.get('vectorstore.collection_name', 'N/A')}") st.markdown(f"- Top K: {config.get('vectorstore.search_kwargs.k', 'N/A')}")
st.markdown("**Document Processing**") st.markdown(f"- Chunk Size: {config.get('document_processing.chunk_size', 'N/A')}") st.markdown(f"- Overlap: {config.get('document_processing.chunk_overlap', 'N/A')}")
def extract_chat_history(messages: list, exclude_last: bool = True) -> list[dict]: """Extract and format chat history for LLM.
Args: messages: List of Streamlit message dicts exclude_last: Whether to exclude the last message (usually the current one being processed)
Returns: List of formatted message dicts with 'role' and 'content' keys """ if not messages: return []
# Exclude the last message if requested (current user message being processed) history_messages = messages[:-1] if exclude_last else messages
# Filter to only user and assistant messages, format for LLM formatted_history = [] for msg in history_messages: role = msg.get("role") content = msg.get("content", "")
if role in ("user", "assistant") and content: formatted_history.append({"role": role, "content": content})
return formatted_history
def truncate_chat_history( history: list[dict], max_turns: int | None = None, max_tokens: int | None = None) -> list[dict]: """Truncate chat history based on turn count or token limit.
Args: history: List of message dicts max_turns: Maximum number of Q&A pairs to keep (None = no limit) max_tokens: Maximum tokens allowed (None = no limit)
Returns: Truncated history list """ from src.main_document_loader import get_main_document_loader
if not history: return []
# Apply turn-based truncation first (keep most recent) if max_turns is not None and max_turns > 0: # Each turn = 1 user + 1 assistant message max_messages = max_turns * 2 history = history[-max_messages:] if len(history) > max_messages else history
# Apply token-based truncation if needed if max_tokens is not None and max_tokens > 0: loader = get_main_document_loader() current_tokens = 0 truncated_history = []
# Go through history in reverse, adding messages until we hit token limit for msg in reversed(history): content = msg.get("content", "") msg_tokens = loader.count_tokens(content)
if current_tokens + msg_tokens <= max_tokens: truncated_history.insert(0, msg) current_tokens += msg_tokens else: break
return truncated_history
return history
def display_chat_messages(): """Display chat messages.""" config = st.session_state.config show_timestamps = config.get("ui.show_timestamps", True)
for message in st.session_state.messages: with st.chat_message(message["role"]): st.markdown(message["content"])
# Display timestamp if enabled if show_timestamps and "timestamp" in message: st.caption(f"_{message['timestamp']}_")
# Display sources if available if "sources" in message and message["sources"]: with st.expander("📚 Sources"): st.markdown(message["sources"])
def process_user_input(prompt: str): """Process user input and generate response.
Args: prompt: User's question """ config = st.session_state.config rag_pipeline = st.session_state.rag_pipeline
# Add user message timestamp = datetime.now().strftime("%H:%M:%S") st.session_state.messages.append({"role": "user", "content": prompt, "timestamp": timestamp})
# Display user message with st.chat_message("user"): st.markdown(prompt) if config.get("ui.show_timestamps", True): st.caption(f"_{timestamp}_")
# Extract and prepare chat history chat_history = [] if config.get("chat.enable_history", True): # Extract history excluding the current message we just added raw_history = extract_chat_history(st.session_state.messages, exclude_last=True)
# Truncate based on configuration max_turns = config.get("chat.max_history_turns", 10) max_tokens = config.get("chat.max_history_tokens", 2000)
chat_history = truncate_chat_history( raw_history, max_turns=max_turns if max_turns > 0 else None, max_tokens=max_tokens if max_tokens > 0 else None, )
if chat_history: logger.debug(f"Including {len(chat_history)} messages from chat history")
# Generate streaming response with st.chat_message("assistant"): try: # Create placeholder for streaming content response_placeholder = st.empty()
# Stream the response token by token with spinner streamed_content = "" with st.spinner("Thinking (this may take a few minutes on a free-tier HF space)..."): for chunk in rag_pipeline.stream_answer(prompt, chat_history=chat_history): streamed_content += chunk response_placeholder.markdown(streamed_content + "▌")
# Remove cursor and show final streamed content response_placeholder.markdown(streamed_content)
# Enhance the response for better tone (post-stream enhancement) answer = streamed_content if config.get("rag.enhance_responses", True): from src.response_enhancer import get_response_enhancer
enhancer = get_response_enhancer() enhanced_answer = enhancer.enhance_with_context(streamed_content, prompt) if enhanced_answer != streamed_content: answer = enhanced_answer # Update display with enhanced version response_placeholder.markdown(answer) logger.debug("Response enhanced for better tone")
# Get source documents (after streaming completes) sources = rag_pipeline.get_source_documents(prompt, chat_history=chat_history) sources_text = "" if config.get("rag.include_sources", True) and sources: sources_text = rag_pipeline.format_sources(sources) with st.expander("📚 Sources"): st.markdown(sources_text)
# Add to message history timestamp = datetime.now().strftime("%H:%M:%S") st.session_state.messages.append( { "role": "assistant", "content": answer, "timestamp": timestamp, "sources": sources_text, } )
except Exception as e: error_msg = f"I apologize, but I encountered an error: {e}" st.error(error_msg) logger.error(f"Error generating response: {e}", exc_info=True)
st.session_state.messages.append( {"role": "assistant", "content": error_msg, "timestamp": timestamp} )
def main(): """Main application entry point.""" # Initialize session state init_session_state()
# Load configuration load_config()
# Configure page configure_page()
# Load RAG pipeline load_rag_pipeline()
# Display UI display_header() display_sidebar()
# Display chat messages display_chat_messages()
# Process pending question from example button click if st.session_state.pending_question: pending = st.session_state.pending_question st.session_state.pending_question = None process_user_input(pending) st.rerun()
# Chat input if prompt := st.chat_input("Ask me anything about the profile..."): process_user_input(prompt)
# Limit chat history max_history = st.session_state.config.get("ui.max_chat_history", 50) if len(st.session_state.messages) > max_history: st.session_state.messages = st.session_state.messages[-max_history:]
if __name__ == "__main__": main()123version https://git-lfs.github.com/spec/v1oid sha256:2ae5802b1436443f1b185dc4c4c1b25407932fa7a3a01429f52e766794176495size 25337123version https://git-lfs.github.com/spec/v1oid sha256:fc6e6df6c9c7d9403681d373ad2944e7cf2d774268aba63884a0c5a8cac33a34size 1499512345{
"doc_hash": "cd60d29f92f5390d",
"num_documents": 10,
"tokenizer": "simple"
}123version https://git-lfs.github.com/spec/v1oid sha256:3c4219624d37be72d6ff179b599692006d53bc43f3d4dd03a5b7861ff0e4f567size 16329123version https://git-lfs.github.com/spec/v1oid sha256:8d3b07c5f2f6b3b7e52a35ab5f91bef157094ca463032216b041d6f20e31699csize 167600123version https://git-lfs.github.com/spec/v1oid sha256:a0e81c3b22454233bc12d0762f06dcca48261a75231cf87c79b75e69a6c00150size 100123version https://git-lfs.github.com/spec/v1oid sha256:6ec18261d55fddaecb8c3d38325422e9e8c189edcc7508d0bedb6375ccc174b4size 400.dockerignoreAdded+48
.env.templateAdded+55
.gitattributes+8
.github/workflows/README.mdAdded+207
.github/workflows/code-quality.ymlAdded+38
.github/workflows/dependency-review.ymlAdded+22
.github/workflows/lint.ymlAdded+38
.github/workflows/pre-commit.ymlAdded+38
.github/workflows/security-scan.ymlAdded+55
.github/workflows/test-docker.ymlAdded+28
.github/workflows/test-python-reusable.ymlAdded+48
.github/workflows/test-python310.ymlAdded+14
.github/workflows/test-python311.ymlAdded+15
.github/workflows/test-python312.ymlAdded+14
.gitignoreAdded+207
.hfignoreAdded+19
.pre-commit-config.yamlAdded+40
.streamlit/config.tomlAdded+16
.venv/.gitignoreAdded+1
.venv/CACHEDIR.TAGAdded+1
.venv/Lib/site-packages/_virtualenv.pthAdded+3
.venv/Lib/site-packages/_virtualenv.pyAdded+101
.venv/Scripts/activateAdded+116
.venv/Scripts/activate.batAdded+71
.venv/Scripts/activate.cshAdded+76
.venv/Scripts/activate.fishAdded+124
.venv/Scripts/activate.nuAdded+117
.venv/Scripts/activate.ps1Added+82
.venv/Scripts/activate_this.pyAdded+59
.venv/Scripts/deactivate.batAdded+39
.venv/Scripts/pydoc.batAdded+22
.venv/Scripts/python.exeAdded+3
.venv/Scripts/pythonw.exeAdded+3
.venv/pyvenv.cfgAdded+5
ARCHITECTURE.mdAdded+815
DockerfileAdded+68
Dockerfile.appAdded+80
LICENSEAdded+21
MakefileAdded+146
README.md+417-7
SETUP_GUIDE.mdAdded+371
app.pyAdded+585
bm25_index/bm25_index.pklAdded+3
bm25_index/documents.pklAdded+3
bm25_index/metadata.jsonAdded+5
bm25_index/tokenized_corpus.pklAdded+3
chroma_db/ae1acac2-515c-4deb-b9d0-675bd72bab8b/data_level0.binAdded+3
chroma_db/ae1acac2-515c-4deb-b9d0-675bd72bab8b/header.binAdded+3
chroma_db/ae1acac2-515c-4deb-b9d0-675bd72bab8b/length.binAdded+3
chroma_db/ae1acac2-515c-4deb-b9d0-675bd72bab8b/link_lists.binAdded