GautamKishore commited on
Commit
18e58fa
·
verified ·
1 Parent(s): fc79025

Upload folder using huggingface_hub

Browse files
.env.example ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LexRAG Configuration
2
+ # =====================
3
+ # Copy this file to .env and fill in your API keys.
4
+ # NEVER commit the .env file to version control.
5
+
6
+ # LLM Provider API Keys
7
+ GROQ_API_KEY=gsk_your_groq_api_key_here
8
+ OPENROUTER_API_KEY=sk-or-v1-your_openrouter_api_key_here
9
+ INDIANKANOON_TOKEN=your_indian_kanoon_token_here
10
+
11
+ # Default Provider (groq | openrouter | ollama)
12
+ LLM_PROVIDER=groq
13
+
14
+ # Server Configuration
15
+ HOST=0.0.0.0
16
+ PORT=8000
17
+
18
+ # Optional: API Key for external access
19
+ # LEXRAG_API_KEY=your_api_key_here
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ marketing/assets/evolution_core.png filter=lfs diff=lfs merge=lfs -text
37
+ marketing/assets/hero.png filter=lfs diff=lfs merge=lfs -text
.github/workflows/ci.yml ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main, master]
6
+ pull_request:
7
+ branches: [main, master]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.10", "3.11", "3.12"]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - name: Set up Python ${{ matrix.python-version }}
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: ${{ matrix.python-version }}
23
+ cache: pip
24
+
25
+ - name: Install dependencies
26
+ run: |
27
+ python -m pip install --upgrade pip
28
+ pip install -r requirements.txt
29
+ pip install pytest pytest-cov
30
+
31
+ - name: Run tests
32
+ run: |
33
+ pytest -v --tb=short
34
+
35
+ - name: Check import integrity
36
+ run: |
37
+ python -c "
38
+ import sys, os
39
+ sys.path.insert(0, '.')
40
+ from api.utils import parse_citations, format_score
41
+ from api.rag_engine import detect_jurisdiction, auto_context_depth, tier_sources, strip_think_tags
42
+ from embeddings.embedder import LexEmbedder
43
+ print('All imports OK')
44
+ "
45
+
46
+ lint:
47
+ runs-on: ubuntu-latest
48
+ steps:
49
+ - uses: actions/checkout@v4
50
+ - name: Set up Python
51
+ uses: actions/setup-python@v5
52
+ with:
53
+ python-version: "3.11"
54
+ - name: Install ruff
55
+ run: pip install ruff
56
+ - name: Run ruff
57
+ run: ruff check . --ignore=E402,F401,F811 --exit-zero
58
+
59
+ build:
60
+ runs-on: ubuntu-latest
61
+ needs: [test]
62
+ if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/master')
63
+ steps:
64
+ - uses: actions/checkout@v4
65
+ - name: Set up Python
66
+ uses: actions/setup-python@v5
67
+ with:
68
+ python-version: "3.11"
69
+ - name: Install build tools
70
+ run: pip install build
71
+ - name: Build package
72
+ run: python -m build
73
+ - name: Upload artifact
74
+ uses: actions/upload-artifact@v4
75
+ with:
76
+ name: dist
77
+ path: dist/
.github/workflows/publish.yml ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+ inputs:
8
+ dry_run:
9
+ description: 'Dry run (don''t actually publish)'
10
+ type: boolean
11
+ default: true
12
+
13
+ jobs:
14
+ pypi:
15
+ runs-on: ubuntu-latest
16
+ environment: release
17
+ permissions:
18
+ id-token: write
19
+ contents: read
20
+
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+
24
+ - name: Set up Python
25
+ uses: actions/setup-python@v5
26
+ with:
27
+ python-version: "3.11"
28
+ cache: pip
29
+
30
+ - name: Install build deps
31
+ run: pip install build twine
32
+
33
+ - name: Build package
34
+ run: python -m build
35
+
36
+ - name: Check package
37
+ run: twine check dist/*
38
+
39
+ - name: Publish to PyPI
40
+ if: ${{ !inputs.dry_run }}
41
+ uses: pypa/gh-action-pypi-publish@release/v1
42
+ with:
43
+ password: ${{ secrets.PYPI_TOKEN }}
44
+
45
+ huggingface:
46
+ runs-on: ubuntu-latest
47
+ needs: [pypi]
48
+ if: ${{ !inputs.dry_run }}
49
+ steps:
50
+ - uses: actions/checkout@v4
51
+
52
+ - name: Upload to HuggingFace
53
+ env:
54
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
55
+ run: |
56
+ pip install huggingface_hub
57
+ python -c "
58
+ from huggingface_hub import HfApi
59
+ api = HfApi()
60
+ api.upload_folder(
61
+ repo_id='evolucentai/lexrag',
62
+ folder_path='.',
63
+ token='${{ secrets.HF_TOKEN }}'
64
+ )
65
+ print('Uploaded to HuggingFace')
66
+ "
.gitignore ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .env
5
+ qdrant_storage/
6
+ data/raw/*.pdf
7
+ data/processed/*.json
8
+ seen_hashes_*.txt
9
+ .DS_Store
10
+ embeddings_cache/
11
+ scratch/
12
+ .codegraph/
13
+ *.egg-info/
14
+ dist/
15
+ build/
16
+ .pytest_cache/
17
+ scratch/tokens.sh
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment:
12
+
13
+ - Demonstrating empathy and kindness toward other people
14
+ - Being respectful of differing opinions, viewpoints, and experiences
15
+ - Giving and gracefully accepting constructive feedback
16
+ - Accepting responsibility and apologizing to those affected by our mistakes
17
+ - Focusing on what is best for the overall community
18
+
19
+ Examples of unacceptable behavior:
20
+
21
+ - The use of sexualized language or imagery, and sexual attention or advances
22
+ - Trolling, insulting or derogatory comments, and personal or political attacks
23
+ - Public or private harassment
24
+ - Publishing others' private information without explicit permission
25
+ - Other conduct which could reasonably be considered inappropriate in a professional setting
26
+
27
+ ## Enforcement Responsibilities
28
+
29
+ Community leaders are responsible for clarifying and enforcing our standards and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
30
+
31
+ ## Scope
32
+
33
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces.
34
+
35
+ ## Enforcement
36
+
37
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at conduct@eulogik.com. All complaints will be reviewed and investigated promptly and fairly.
38
+
39
+ ## Enforcement Guidelines
40
+
41
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
42
+
43
+ 1. **Correction**: Private, written warning
44
+ 2. **Warning**: Warning with consequences for continued behavior
45
+ 3. **Temporary Ban**: Temporary ban from any community interaction
46
+ 4. **Permanent Ban**: Permanent ban from any community interaction
47
+
48
+ ## Attribution
49
+
50
+ This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 2.1.
CONTRIBUTING.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to LexRAG
2
+
3
+ Thank you for your interest in LexRAG! We welcome contributions from the legal-tech and AI community.
4
+
5
+ ## Code of Conduct
6
+
7
+ All contributors must abide by our [Code of Conduct](CODE_OF_CONDUCT.md).
8
+
9
+ ## Getting Started
10
+
11
+ 1. Fork the repository
12
+ 2. Clone your fork: `git clone https://github.com/eulogik/LexRAG.git`
13
+ 3. Create a virtual environment: `python3 -m venv venv && source venv/bin/activate`
14
+ 4. Install dependencies: `pip install -r requirements.txt`
15
+ 5. Install dev dependencies: `pip install pytest pytest-cov`
16
+ 6. Run tests: `pytest`
17
+
18
+ ## Development Workflow
19
+
20
+ - Create a feature branch: `git checkout -b feat/my-feature`
21
+ - Write tests for your changes
22
+ - Ensure all tests pass: `pytest`
23
+ - Run linting: `ruff check .` (if available)
24
+ - Commit with conventional commits: `feat:`, `fix:`, `docs:`, `refactor:`, etc.
25
+ - Push and open a Pull Request
26
+
27
+ ## Pull Request Guidelines
28
+
29
+ - Link to any relevant issues
30
+ - Include test coverage for new functionality
31
+ - Update documentation (README, inline docs) as needed
32
+ - Ensure the PR passes CI checks
33
+
34
+ ## Project Structure
35
+
36
+ ```
37
+ LexRAG/
38
+ ├── api/ # FastAPI server, RAG engine, memory, utils
39
+ ├── embeddings/ # Vector embedding models (fastembed + Qdrant)
40
+ ├── scrapers/ # Legal document scrapers (UAE, India)
41
+ ├── scripts/ # Ingestion, updates, batch processing
42
+ ├── ui/ # Terminal-style SPA frontend
43
+ ├── tests/ # Test suite
44
+ └── data/ # SQLite DB, raw/processed documents
45
+ ```
46
+
47
+ ## Adding a New Scraper
48
+
49
+ 1. Create `scrapers/<jurisdiction>_scraper.py`
50
+ 2. Implement functions that call `scripts.ingest.ingest_text()`
51
+ 3. Add the scraper to `scripts/daily_update.py`
52
+ 4. Write tests for the scraper
53
+
54
+ ## Adding a New LLM Provider
55
+
56
+ 1. Add a streaming function in `api/rag_engine.py` (e.g., `stream_anthropic()`)
57
+ 2. Register in `stream_provider()` dispatcher
58
+ 3. Add the provider to `MODEL_CATALOG` in `api/main.py`
59
+ 4. Add the provider label in `ui/app.js`
60
+ 5. Document the required environment variable
61
+
62
+ ## Questions?
63
+
64
+ Open an issue at https://github.com/eulogik/LexRAG/issues
65
+ Or reach out to engineering@eulogik.com
LICENSE ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU AFFERO GENERAL PUBLIC LICENSE
2
+ Version 3, 19 November 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
6
+
7
+ Preamble
8
+
9
+ The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
10
+
11
+ The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
12
+
13
+ When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
14
+
15
+ Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
16
+
17
+ A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation.
18
+
19
+ However, in the case of AGPL, the network server software, the combination of the program with a server may make it available to all users of that server. For example, if you run a modified version of an AGPL-licensed program on a server, the users of that server could be considered to be recipients of the modified version. The AGPL is designed to ensure that such users receive the source code of the modified version as well.
20
+
21
+ The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software.
22
+
23
+ The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users.
24
+
25
+ When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
26
+
27
+ Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software.
28
+
29
+ A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation.
30
+
31
+ However, in the case of AGPL, the network server software, the combination of the program with a server may make it available to all users of that server. For example, if you run a modified version of an AGPL-licensed program on a server, the users of that server could be considered to be recipients of the modified version. The AGPL is designed to ensure that such users receive the source code of the modified version as well.
32
+
33
+ The precise terms and conditions for copying, distribution and modification follow.
34
+
35
+ TERMS AND CONDITIONS
36
+
37
+ 0. Definitions.
38
+
39
+ "This License" refers to version 3 of the GNU Affero General Public License.
40
+
41
+ "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
42
+
43
+ "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations.
44
+
45
+ To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work.
46
+
47
+ A "covered work" means either the unmodified Program or a work based on the Program.
48
+
49
+ To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
50
+
51
+ To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
52
+
53
+ An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
54
+
55
+ 1. Source Code.
56
+
57
+ The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work.
58
+
59
+ A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
60
+
61
+ The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
62
+
63
+ The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
64
+
65
+ The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
66
+
67
+ The Corresponding Source for a work in source code form is that same work.
68
+
69
+ 2. Basic Permissions.
70
+
71
+ All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
72
+
73
+ You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
74
+
75
+ Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
76
+
77
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
78
+
79
+ No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
80
+
81
+ When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
82
+
83
+ 4. Conveying Verbatim Copies.
84
+
85
+ You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
86
+
87
+ You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
88
+
89
+ 5. Conveying Modified Source Versions.
90
+
91
+ You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
92
+
93
+ a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
94
+
95
+ b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices".
96
+
97
+ c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
98
+
99
+ d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
100
+
101
+ A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
102
+
103
+ 6. Conveying Non-Source Forms.
104
+
105
+ You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
106
+
107
+ a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
108
+
109
+ b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
110
+
111
+ c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
112
+
113
+ d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
114
+
115
+ e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
116
+
117
+ A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
118
+
119
+ A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
120
+
121
+ "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
122
+
123
+ If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
124
+
125
+ The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
126
+
127
+ Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
128
+
129
+ 7. Additional Terms.
130
+
131
+ "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of the conditions of this License. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
132
+
133
+ When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
134
+
135
+ Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
136
+
137
+ a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
138
+
139
+ b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
140
+
141
+ c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
142
+
143
+ d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
144
+
145
+ e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
146
+
147
+ f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
148
+
149
+ All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
150
+
151
+ If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
152
+
153
+ Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
154
+
155
+ 8. Termination.
156
+
157
+ You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
158
+
159
+ However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
160
+
161
+ Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
162
+
163
+ Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
164
+
165
+ 9. Acceptance Not Required for Having Copies.
166
+
167
+ You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
168
+
169
+ 10. Automatic Licensing of Downstream Recipients.
170
+
171
+ Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
172
+
173
+ An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
174
+
175
+ You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
176
+
177
+ 11. Patents.
178
+
179
+ A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version".
180
+
181
+ A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
182
+
183
+ Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
184
+
185
+ In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
186
+
187
+ If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
188
+
189
+ If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
190
+
191
+ A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
192
+
193
+ Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
194
+
195
+ 12. No Surrender of Others' Freedom.
196
+
197
+ If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
198
+
199
+ 13. Remote Network Interaction; Use with the GNU General Public License.
200
+
201
+ Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph.
202
+
203
+ Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License.
204
+
205
+ 14. Revised Versions of this License.
206
+
207
+ The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
208
+
209
+ Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation.
210
+
211
+ If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
212
+
213
+ Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
214
+
215
+ 15. Disclaimer of Warranty.
216
+
217
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
218
+
219
+ 16. Limitation of Liability.
220
+
221
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
222
+
223
+ 17. Interpretation of Sections 15 and 16.
224
+
225
+ If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
226
+
227
+ END OF TERMS AND CONDITIONS
228
+
229
+ How to Apply These Terms to Your New Programs
230
+
231
+ If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
232
+
233
+ To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found.
234
+
235
+ <one line to give the program's name and a brief idea of what it does.>
236
+ Copyright (C) <year> <name of author>
237
+
238
+ This program is free software: you can redistribute it and/or modify
239
+ it under the terms of the GNU Affero General Public License as published
240
+ by the Free Software Foundation, either version 3 of the License, or
241
+ (at your option) any later version.
242
+
243
+ This program is distributed in the hope that it will be useful,
244
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
245
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
246
+ GNU Affero General Public License for more details.
247
+
248
+ You should have received a copy of the GNU Affero General Public License
249
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
250
+
251
+ Also add information on how to contact you by electronic and paper mail.
252
+
253
+ If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements.
254
+
255
+ You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <https://www.gnu.org/licenses/>.
LICENSES.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LexRAG Licensing
2
+
3
+ ## Open Source License
4
+
5
+ LexRAG is released under the **GNU Affero General Public License v3.0** (AGPL-3.0).
6
+
7
+ The full license text is in the [LICENSE](./LICENSE) file.
8
+
9
+ ## Commercial License
10
+
11
+ For organizations that wish to incorporate LexRAG into proprietary products or closed-source deployments where the AGPL's copyleft requirements are not suitable, **alternative commercial licensing** terms are available.
12
+
13
+ **Contact**: [Evolucent AI](https://evolucentai.com) — hello@evolucentai.com
14
+
15
+ **Built by**: [Evolucent AI](https://evolucentai.com) — Premium Legal Technology Solutions
16
+ **Engineered by**: [Eulogik](https://eulogik.com) — Enterprise AI & Systems Integration
README.md ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: lexrag
3
+ pipeline_tag: text-generation
4
+ tags:
5
+ - legal-rag
6
+ - legal-ai
7
+ - legal-research
8
+ - retrieval-augmented-generation
9
+ - uae-law
10
+ - indian-law
11
+ - gst
12
+ - vat
13
+ - corporate-tax
14
+ - hybrid-search
15
+ - fastembed
16
+ - qdrant
17
+ - legal-tech
18
+ - compliance
19
+ - tax-research
20
+ - case-law
21
+ - evolucentai
22
+ - eulogik
23
+ license: agpl-3.0
24
+ language:
25
+ - en
26
+ widget:
27
+ - text: "What is the GST rate on online gaming contest prizes in India?"
28
+ - text: "UAE VAT on financial services"
29
+ - text: "TDS under Section 194B on winnings"
30
+ - text: "UAE Corporate Tax free zone treatment"
31
+ inference: false
32
+ ---
33
+
34
+ <br/>
35
+ <h1 align="center">⚖️ LexRAG — The Legal Intelligence Terminal</h1>
36
+ <p align="center">
37
+ <strong>Enterprise-Grade Hybrid RAG for UAE & Indian Law, Taxation & Compliance</strong>
38
+ <br/><br/>
39
+ <a href="https://github.com/eulogik/LexRAG/stargazers"><img src="https://img.shields.io/github/stars/eulogik/LexRAG?style=flat-square&logo=github" alt="Stars"/></a>
40
+ <a href="https://github.com/eulogik/LexRAG/blob/main/LICENSE"><img src="https://img.shields.io/github/license/eulogik/LexRAG?style=flat-square" alt="License"/></a>
41
+ <a href="https://pypi.org/project/lexrag/"><img src="https://img.shields.io/pypi/v/lexrag?style=flat-square&logo=pypi" alt="PyPI"/></a>
42
+ <a href="https://huggingface.co/EvolucentAI/lexrag"><img src="https://img.shields.io/badge/%F0%9F%A4%97-Hugging%20Face-ffcc00?style=flat-square" alt="HuggingFace"/></a>
43
+ </p>
44
+
45
+ ---
46
+
47
+ ## What is LexRAG?
48
+
49
+ **LexRAG** is a professional-grade, high-performance Retrieval-Augmented Generation (RAG) platform purpose-built for **UAE and Indian laws, taxation, accounting standards, and corporate compliance**. It combines hybrid dense-sparse retrieval, neural reranking, auto-jurisdiction detection, and multi-provider LLM streaming into a zero-latency terminal interface.
50
+
51
+ > ⚡ **Built by [Evolucent AI](https://evolucentai.com)** — Premium Legal Technology Solutions
52
+ > 🛠️ **Engineered by [Eulogik](https://eulogik.com)** — Enterprise AI & Systems Integration
53
+
54
+ ---
55
+
56
+ ## Key Capabilities
57
+
58
+ | Capability | Technology |
59
+ |------------|------------|
60
+ | **Dense Retrieval** | `BAAI/bge-small-en-v1.5` via fastembed |
61
+ | **Sparse Retrieval** | `prithivida/Splade_PP_en_v1` via fastembed |
62
+ | **Hybrid Fusion** | Reciprocal Rank Fusion (RRF) |
63
+ | **Neural Reranker** | `BAAI/bge-reranker-base` (CrossEncoder) |
64
+ | **Vector Database** | Qdrant (on-disk, no Docker required) |
65
+ | **LLM Providers** | Groq, OpenRouter, Ollama (dynamic model catalog) |
66
+ | **Jurisdiction** | Auto-detect India/UAE/Both with manual override |
67
+ | **Confidence Tiers** | GROUNDED / PARTIAL / SYNTHESIZED |
68
+ | **Streaming** | SSE with heartbeat keep-alive |
69
+ | **Persistence** | SQLite chat history with session management |
70
+
71
+ ---
72
+
73
+ ## Quick Start
74
+
75
+ ```bash
76
+ # Install from PyPI
77
+ pip install lexrag
78
+
79
+ # Or clone from source
80
+ git clone https://github.com/eulogik/LexRAG.git
81
+ cd LexRAG
82
+ pip install -r requirements.txt
83
+
84
+ # Configure
85
+ cp .env.example .env
86
+ # Edit .env with your API keys
87
+
88
+ # Run
89
+ python -m uvicorn api.main:app --host 0.0.0.0 --port 8000
90
+ # Open http://localhost:8000
91
+ ```
92
+
93
+ ---
94
+
95
+ ## Architecture
96
+
97
+ ```mermaid
98
+ flowchart TD
99
+ UI[HTML/CSS/JS SPA] <-->|SSE / API| FastAPI[FastAPI Server]
100
+ FastAPI <-->|History| SQL[(SQLite)]
101
+ Query --> Detect[Auto-Jurisdiction]
102
+ Detect --> Search{Hybrid Search}
103
+ Search -->|Dense| Dense[BGE-small-en-v1.5]
104
+ Search -->|Sparse| Sparse[Splade_PP_en_v1]
105
+ Dense & Sparse -->|RRF| Qdrant[(Qdrant)]
106
+ Qdrant -->|Candidates| Rerank[BGE-Reranker-Base]
107
+ Rerank -->|Top Docs| Context[Build Prompt]
108
+ Context --> LLM{LLM Router}
109
+ LLM -->|Cloud| Groq[Groq]
110
+ LLM -->|Cloud| OpenRouter[OpenRouter]
111
+ LLM -->|Local| Ollama[Ollama]
112
+ ```
113
+
114
+ ---
115
+
116
+ ## Ecosystem
117
+
118
+ | Platform | Link | Description |
119
+ |----------|------|-------------|
120
+ | **GitHub** | [eulogik/LexRAG](https://github.com/eulogik/LexRAG) | Source code & issues |
121
+ | **PyPI** | [lexrag](https://pypi.org/project/lexrag/) | Python package |
122
+ | **HuggingFace** | [EvolucentAI/lexrag](https://huggingface.co/EvolucentAI/lexrag) | Model card & codebase |
123
+ | **HF Space** | [EvolucentAI/lexrag-demo](https://huggingface.co/spaces/EvolucentAI/lexrag-demo) | Interactive Gradio demo |
124
+ | **Eulogik** | [eulogik.com](https://eulogik.com) | Engineering partner |
125
+ | **Evolucent AI** | [evolucentai.com](https://evolucentai.com) | Product & commercial |
126
+
127
+ ---
128
+
129
+ ## License
130
+
131
+ **AGPL v3** — Free for open-source and internal use.
132
+ Commercial licenses available from [Evolucent AI](https://evolucentai.com) for proprietary deployments.
133
+
134
+ ---
135
+
136
+ <div align="center">
137
+ <sub>
138
+ Built by <a href="https://evolucentai.com">Evolucent AI</a> —
139
+ Engineered by <a href="https://eulogik.com">Eulogik</a>
140
+ </sub>
141
+ </div>
SECURITY.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Security Policy
2
+
3
+ ## Supported Versions
4
+
5
+ | Version | Supported |
6
+ | ------- | ------------------ |
7
+ | >= 3.3 | :white_check_mark: |
8
+ | < 3.3 | :x: |
9
+
10
+ ## Reporting a Vulnerability
11
+
12
+ LexRAG is a legal research tool designed for professional use. Security is a top priority.
13
+
14
+ **Please do not report security vulnerabilities through public GitHub issues.**
15
+
16
+ Instead, report them directly to:
17
+
18
+ - **Email**: security@eulogik.com
19
+ - **PGP Key**: Available on request
20
+
21
+ ### What to include
22
+
23
+ - Type of vulnerability
24
+ - Steps to reproduce
25
+ - Affected versions
26
+ - Potential impact
27
+ - Suggested fix (if any)
28
+
29
+ ### What to expect
30
+
31
+ - **Acknowledgment** within 48 hours
32
+ - **Status update** within 5 business days
33
+ - **Fix timeline** communicated within 10 business days
34
+
35
+ ## Best Practices for Deployment
36
+
37
+ 1. **API Keys**: Never commit `.env` to version control. Use environment variables or a secrets manager.
38
+ 2. **Network**: Run the server behind a reverse proxy (nginx, Caddy) with TLS in production.
39
+ 3. **Authentication**: Add API key authentication for production deployments (see `LEXRAG_API_KEY`).
40
+ 4. **Database**: Regularly backup `data/lexrag.db` and `qdrant_storage/`.
41
+ 5. **Updates**: Keep dependencies updated: `pip install --upgrade -r requirements.txt`
42
+
43
+ ## Hallucination & Accuracy Disclaimer
44
+
45
+ LexRAG uses Retrieval-Augmented Generation (RAG) to ground answers in legal documents. However:
46
+ - AI models may still produce inaccurate or incomplete responses
47
+ - Always verify AI-generated legal analysis against primary sources
48
+ - LexRAG is a research assistance tool, not a substitute for qualified legal counsel
49
+
50
+ ## Responsible Disclosure
51
+
52
+ We believe in responsible disclosure. If you discover a vulnerability, please give us a reasonable time to fix it before public disclosure.
api/__init__.py ADDED
File without changes
api/main.py ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+ import asyncio
5
+ import uuid
6
+ from typing import Optional
7
+
8
+ from fastapi import FastAPI, HTTPException, Request
9
+ from fastapi.responses import HTMLResponse, FileResponse, StreamingResponse
10
+ from fastapi.staticfiles import StaticFiles
11
+ from fastapi.middleware.cors import CORSMiddleware
12
+ from pydantic import BaseModel
13
+ from dotenv import load_dotenv
14
+
15
+ load_dotenv()
16
+ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
17
+ if ROOT_DIR not in sys.path:
18
+ sys.path.insert(0, ROOT_DIR)
19
+
20
+ from api.rag_engine import (
21
+ search_and_rerank, build_prompt, SYSTEM_PROMPT, stream_provider,
22
+ LLM_PROVIDER, GROQ_MODEL, OPENROUTER_MODEL
23
+ )
24
+ from api.utils import detect_jurisdiction, auto_context_depth, tier_sources
25
+ from api.memory import (
26
+ save_message, get_history, get_history_full,
27
+ list_sessions, delete_session, update_session_name, get_session_name
28
+ )
29
+ from api.utils import parse_citations
30
+
31
+ app = FastAPI(title="LexRAG", version="3.1")
32
+
33
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
34
+
35
+ UI_DIR = os.path.join(ROOT_DIR, "ui")
36
+ MARKETING_DIR = os.path.join(ROOT_DIR, "marketing")
37
+ SETTINGS_FILE = os.path.join(ROOT_DIR, "settings.json")
38
+
39
+ app.mount("/ui", StaticFiles(directory=UI_DIR), name="ui")
40
+ app.mount("/marketing", StaticFiles(directory=MARKETING_DIR), name="marketing")
41
+
42
+ # ─── Model Catalog ───────────────────────────────────────────────────────────
43
+ MODEL_CATALOG = {
44
+ "groq": [
45
+ {"id": "llama-3.3-70b-versatile", "name": "Llama 3.3 70B"},
46
+ {"id": "llama-3.1-8b-instant", "name": "Llama 3.1 8B"},
47
+ {"id": "gemma2-9b-it", "name": "Gemma 2 9B"},
48
+ ],
49
+ "openrouter": [
50
+ {"id": "meta-llama/llama-3.3-70b-instruct:free", "name": "Llama 3.3 70B (Free)"},
51
+ {"id": "deepseek/deepseek-r1:free", "name": "DeepSeek R1 (Free)"},
52
+ {"id": "google/gemma-2-9b-it:free", "name": "Gemma 2 9B (Free)"},
53
+ {"id": "qwen/qwen-2.5-coder-32b-instruct:free", "name": "Qwen 2.5 Coder 32B (Free)"},
54
+ ],
55
+ "ollama": [
56
+ {"id": "qwen3:14b", "name": "Qwen3 14B (Local)"},
57
+ {"id": "llama3:latest", "name": "Llama 3 (Local)"},
58
+ ]
59
+ }
60
+
61
+ # Default active models if settings don't exist
62
+ DEFAULT_ACTIVE_MODELS = {
63
+ "groq": ["llama-3.3-70b-versatile", "llama-3.1-8b-instant", "gemma2-9b-it"],
64
+ "openrouter": ["meta-llama/llama-3.3-70b-instruct:free", "deepseek/deepseek-r1:free", "google/gemma-2-9b-it:free"],
65
+ "ollama": ["qwen3:14b", "llama3:latest"]
66
+ }
67
+
68
+ DEFAULT_PROVIDER_MODELS = {
69
+ "groq": "llama-3.3-70b-versatile",
70
+ "openrouter": "meta-llama/llama-3.3-70b-instruct:free",
71
+ "ollama": "qwen3:14b"
72
+ }
73
+
74
+ DEFAULT_SETTINGS = {
75
+ "provider": LLM_PROVIDER,
76
+ "model": DEFAULT_PROVIDER_MODELS.get(LLM_PROVIDER, "llama-3.3-70b-versatile"),
77
+ "jurisdiction_override": None,
78
+ "active_models": DEFAULT_ACTIVE_MODELS,
79
+ "custom_models": {} # {"groq": [{"id": "...", "name": "..."}]}
80
+ }
81
+
82
+ def load_settings() -> dict:
83
+ if os.path.exists(SETTINGS_FILE):
84
+ saved = {}
85
+ with open(SETTINGS_FILE) as f:
86
+ try: saved = json.load(f)
87
+ except Exception: pass
88
+ merged = {**DEFAULT_SETTINGS, **saved}
89
+ # Ensure active_models has all providers
90
+ for p in DEFAULT_ACTIVE_MODELS:
91
+ if p not in merged.get("active_models", {}):
92
+ merged.setdefault("active_models", {})[p] = DEFAULT_ACTIVE_MODELS[p]
93
+ return merged
94
+ return DEFAULT_SETTINGS.copy()
95
+
96
+ def save_settings_to_disk(data: dict):
97
+ current = load_settings()
98
+ current.update(data)
99
+ with open(SETTINGS_FILE, "w") as f:
100
+ json.dump(current, f, indent=2)
101
+
102
+ # ─── Pages ───────────────────────────────────────────────────────────────────
103
+ @app.get("/", response_class=HTMLResponse)
104
+ def serve_app():
105
+ with open(os.path.join(UI_DIR, "index.html")) as f:
106
+ return HTMLResponse(content=f.read())
107
+
108
+ # ─── API: Models ─────────────────────────────────────────────────────────────
109
+ @app.get("/api/models")
110
+ def get_models():
111
+ """Returns full catalog plus any custom models from settings."""
112
+ settings = load_settings()
113
+ catalog = {p: list(models) for p, models in MODEL_CATALOG.items()}
114
+ # Merge custom models
115
+ for provider, custom in settings.get("custom_models", {}).items():
116
+ if provider in catalog:
117
+ existing_ids = {m["id"] for m in catalog[provider]}
118
+ for cm in custom:
119
+ if cm["id"] not in existing_ids:
120
+ catalog[provider].append(cm)
121
+ else:
122
+ catalog[provider] = custom
123
+ return catalog
124
+
125
+ # ─── API: Settings ───────────────────────────────────────────────────────────
126
+ @app.get("/api/settings")
127
+ def get_settings_endpoint():
128
+ return load_settings()
129
+
130
+ @app.post("/api/settings")
131
+ async def update_settings_endpoint(request: Request):
132
+ data = await request.json()
133
+ current = load_settings()
134
+ # Deep merge active_models and custom_models
135
+ for deep_key in ("active_models", "custom_models"):
136
+ if deep_key in data and isinstance(data[deep_key], dict):
137
+ current.setdefault(deep_key, {}).update(data[deep_key])
138
+ del data[deep_key]
139
+ current.update(data)
140
+ with open(SETTINGS_FILE, "w") as f:
141
+ json.dump(current, f, indent=2)
142
+ return current
143
+
144
+ # ─── API: Sessions ────────────────────────────────────────────────────────────
145
+ @app.get("/api/sessions")
146
+ def api_list_sessions():
147
+ return list_sessions()
148
+
149
+ @app.get("/api/sessions/{session_id}")
150
+ def api_get_session(session_id: str):
151
+ return {
152
+ "session_id": session_id,
153
+ "name": get_session_name(session_id),
154
+ "messages": get_history_full(session_id)
155
+ }
156
+
157
+ @app.delete("/api/sessions/{session_id}")
158
+ def api_delete_session(session_id: str):
159
+ delete_session(session_id)
160
+ return {"success": True}
161
+
162
+ # ─── API: Ingestion Endpoints (Server-Centric De-confliction) ──────────────────
163
+ class IngestTextRequest(BaseModel):
164
+ text: str
165
+ metadata: dict
166
+
167
+ class IngestPDFRequest(BaseModel):
168
+ filepath: str
169
+ metadata: dict
170
+ thorough: Optional[bool] = True
171
+
172
+ @app.post("/api/ingest")
173
+ async def api_ingest_text(req: IngestTextRequest):
174
+ from scripts.ingest import _local_ingest_text
175
+ try:
176
+ await asyncio.get_event_loop().run_in_executor(
177
+ None, lambda: _local_ingest_text(req.text, req.metadata)
178
+ )
179
+ return {"success": True}
180
+ except Exception as e:
181
+ raise HTTPException(status_code=500, detail=str(e))
182
+
183
+ @app.post("/api/ingest/pdf")
184
+ async def api_ingest_pdf(req: IngestPDFRequest):
185
+ from scripts.ingest import _local_ingest_pdf
186
+ if not os.path.exists(req.filepath):
187
+ raise HTTPException(status_code=404, detail="PDF file not found at specified path")
188
+ try:
189
+ await asyncio.get_event_loop().run_in_executor(
190
+ None, lambda: _local_ingest_pdf(req.filepath, req.metadata, req.thorough)
191
+ )
192
+ return {"success": True}
193
+ except Exception as e:
194
+ raise HTTPException(status_code=500, detail=str(e))
195
+
196
+ # ─── API: Chat (SSE Streaming) ────────────────────────────────────────────────
197
+ class ChatRequest(BaseModel):
198
+ question: str
199
+ session_id: str
200
+ provider: Optional[str] = None
201
+ model: Optional[str] = None
202
+ jurisdiction_override: Optional[str] = None
203
+
204
+ @app.post("/api/chat")
205
+ async def chat_stream(req: ChatRequest):
206
+ settings = load_settings()
207
+ provider = req.provider or settings.get("provider") or LLM_PROVIDER
208
+ model = req.model or settings.get("model")
209
+
210
+ async def generate():
211
+ start_all = asyncio.get_event_loop().time()
212
+ full_answer = ""
213
+ sources_out = []
214
+ jurisdiction = "Both"
215
+ confidence = "GROUNDED"
216
+
217
+ def format_sse(event: str, data: any) -> str:
218
+ return f"event: {event}\ndata: {json.dumps(data)}\n\n"
219
+
220
+ # ── Step 0: Save user message IMMEDIATELY ───────────────────────────
221
+ try:
222
+ session_name = req.question[:60].strip()
223
+ save_message(req.session_id, "user", req.question)
224
+ update_session_name(req.session_id, session_name)
225
+ except Exception as e:
226
+ print(f"Warning: Could not save user message: {e}")
227
+
228
+ try:
229
+ # ── Step 1: Jurisdiction & Pings ────────────────────────────────
230
+ # Send initial ping to confirm stream start
231
+ yield ": ping\n\n"
232
+
233
+ override = req.jurisdiction_override or settings.get("jurisdiction_override")
234
+ if override and override != "Both":
235
+ jurisdiction = override
236
+ else:
237
+ jurisdiction = detect_jurisdiction(req.question)
238
+
239
+ # ── Step 2: Retrieval (with 15s timeout) ───────────────────────
240
+ top_k = auto_context_depth(req.question)
241
+ try:
242
+ t0 = asyncio.get_event_loop().time()
243
+ docs = await asyncio.wait_for(
244
+ asyncio.get_event_loop().run_in_executor(
245
+ None, lambda: search_and_rerank(req.question, jurisdiction, top_k)
246
+ ),
247
+ timeout=15.0
248
+ )
249
+ print(f"Retrieval + Rerank took: {asyncio.get_event_loop().time() - t0:.3f}s")
250
+ except asyncio.TimeoutError:
251
+ docs = []
252
+ print("Warning: Retrieval timed out, using general knowledge.")
253
+
254
+ confidence = tier_sources(docs)
255
+ # Deduplicate sources by (title, source) — same document split into many
256
+ # chunks will produce identical titles; keep the highest-scoring one.
257
+ seen_src: dict = {}
258
+ for d in docs:
259
+ key = (d.get("doc_title", d.get("source", "")), d.get("source", ""))
260
+ score = round(d.get("rerank_score", d.get("score", 0)), 3)
261
+ if key not in seen_src or score > seen_src[key]["score"]:
262
+ seen_src[key] = {
263
+ "title": d.get("doc_title", d.get("source", "Unknown")),
264
+ "source": d.get("source", ""),
265
+ "jurisdiction": d.get("jurisdiction", ""),
266
+ "type": d.get("source_type", ""),
267
+ "url": d.get("url", ""),
268
+ "score": score
269
+ }
270
+ sources_out = list(seen_src.values())
271
+
272
+ # ── Step 3: Emit sources immediately ───────────────────────────
273
+ yield format_sse("sources", {
274
+ "sources": sources_out,
275
+ "confidence": confidence,
276
+ "jurisdiction": jurisdiction
277
+ })
278
+
279
+ # ── Step 4: Build prompt ────────────────────────────────────────
280
+ history = get_history(req.session_id, limit=5)
281
+ prompt = build_prompt(req.question, docs, history, confidence)
282
+ messages = [
283
+ {"role": "system", "content": SYSTEM_PROMPT},
284
+ {"role": "user", "content": prompt}
285
+ ]
286
+
287
+ # ── Step 5: Stream with total 90s timeout ──────────────────────
288
+ async def stream_with_timeout():
289
+ t_gen_start = asyncio.get_event_loop().time()
290
+ first = True
291
+ async for token in stream_provider(messages, provider, model):
292
+ if first:
293
+ print(f"Time to first token: {asyncio.get_event_loop().time() - t_gen_start:.3f}s")
294
+ first = False
295
+ yield token
296
+
297
+ # Periodic ping wrapper to prevent proxy timeouts
298
+ async def stream_with_pings():
299
+ queue = asyncio.Queue()
300
+
301
+ async def producer():
302
+ try:
303
+ async for token in stream_with_timeout():
304
+ await queue.put(("token", token))
305
+ except Exception as e:
306
+ await queue.put(("error", e))
307
+ finally:
308
+ await queue.put(("done", None))
309
+
310
+ producer_task = asyncio.create_task(producer())
311
+ got_first_token = False
312
+
313
+ try:
314
+ async with asyncio.timeout(90):
315
+ while True:
316
+ try:
317
+ msg_type, val = await asyncio.wait_for(queue.get(), timeout=5.0)
318
+ if msg_type == "token":
319
+ got_first_token = True
320
+ yield val
321
+ elif msg_type == "error":
322
+ raise val
323
+ elif msg_type == "done":
324
+ break
325
+ except asyncio.TimeoutError:
326
+ # Yield SSE comment ping directly to bypass format_sse
327
+ yield ": ping\n\n"
328
+ except asyncio.TimeoutError:
329
+ if not got_first_token:
330
+ yield "\n\n*Response timed out. Try a smaller model or check your network.*"
331
+ finally:
332
+ producer_task.cancel()
333
+
334
+ async for token in stream_with_pings():
335
+ if token.startswith(": ping"):
336
+ yield token
337
+ else:
338
+ full_answer += token
339
+ yield format_sse("token", {"content": token})
340
+
341
+ # ── Step 6: Citation links + save answer ───────────────────────
342
+ full_answer = parse_citations(full_answer)
343
+ try:
344
+ save_message(req.session_id, "assistant", full_answer,
345
+ sources=sources_out, provider=provider)
346
+ except Exception as e:
347
+ print(f"Warning: Could not save assistant message: {e}")
348
+
349
+ yield format_sse("done", {
350
+ "session_name": session_name,
351
+ "confidence": confidence,
352
+ "jurisdiction": jurisdiction
353
+ })
354
+
355
+ except Exception as e:
356
+ error_msg = str(e)
357
+ print(f"Chat error: {error_msg}")
358
+
359
+ # Flush error to UI
360
+ yield format_sse("error", {"content": error_msg})
361
+ yield format_sse("done", {"error": True})
362
+
363
+ if full_answer:
364
+ try:
365
+ save_message(req.session_id, "assistant", full_answer,
366
+ sources=sources_out, provider=provider)
367
+ except Exception:
368
+ pass
369
+
370
+ return StreamingResponse(generate(), media_type="text/event-stream")
371
+
372
+ @app.get("/health")
373
+ def health():
374
+ return {"status": "ok", "version": "3.1"}
api/memory.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ import json
3
+ import os
4
+ from datetime import datetime
5
+ from sqlite_utils import Database
6
+
7
+ DB_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "lexrag.db")
8
+
9
+ def setup_db():
10
+ db = Database(DB_PATH)
11
+ if "conversations" not in db.table_names():
12
+ db["conversations"].create({
13
+ "id": int,
14
+ "session_id": str,
15
+ "role": str,
16
+ "content": str,
17
+ "sources": str,
18
+ "timestamp": str,
19
+ "provider": str
20
+ }, pk="id")
21
+ if "sessions" not in db.table_names():
22
+ db["sessions"].create({
23
+ "session_id": str,
24
+ "name": str,
25
+ "created_at": str,
26
+ "updated_at": str
27
+ }, pk="session_id")
28
+
29
+ # Add indexes if not exists to optimize session lookup performance
30
+ try:
31
+ db["conversations"].create_index(["session_id"], if_not_exists=True)
32
+ db["conversations"].create_index(["timestamp"], if_not_exists=True)
33
+ except Exception:
34
+ pass
35
+
36
+ return db
37
+
38
+ def update_session_name(session_id: str, name: str):
39
+ db = setup_db()
40
+ now = datetime.now().isoformat()
41
+ try:
42
+ exists = list(db["sessions"].rows_where("session_id = ?", [session_id]))
43
+ if exists:
44
+ db["sessions"].update(session_id, {"name": name, "updated_at": now})
45
+ else:
46
+ db["sessions"].insert({
47
+ "session_id": session_id,
48
+ "name": name,
49
+ "created_at": now,
50
+ "updated_at": now
51
+ })
52
+ except Exception as e:
53
+ print(f"Warning: could not update session name: {e}")
54
+
55
+ def get_session_name(session_id: str) -> str:
56
+ db = setup_db()
57
+ try:
58
+ rows = list(db["sessions"].rows_where("session_id = ?", [session_id]))
59
+ return rows[0]["name"] if rows else session_id[:8]
60
+ except Exception:
61
+ return session_id[:8]
62
+
63
+ def save_message(session_id: str, role: str, content: str, sources: list = None, provider: str = None):
64
+ db = setup_db()
65
+ db["conversations"].insert({
66
+ "session_id": session_id,
67
+ "role": role,
68
+ "content": content,
69
+ "sources": json.dumps(sources) if sources else "[]",
70
+ "timestamp": datetime.now().isoformat(),
71
+ "provider": provider
72
+ })
73
+
74
+ def get_history(session_id: str, limit: int = 10):
75
+ db = setup_db()
76
+ rows = db["conversations"].rows_where(
77
+ "session_id = ?", [session_id], order_by="timestamp DESC", limit=limit
78
+ )
79
+ history = list(rows)
80
+ history.reverse()
81
+ return [{"role": r["role"], "content": r["content"]} for r in history]
82
+
83
+ def get_history_full(session_id: str, limit: int = 100):
84
+ """Returns full message objects including sources for UI rendering."""
85
+ db = setup_db()
86
+ rows = db["conversations"].rows_where(
87
+ "session_id = ?", [session_id], order_by="timestamp ASC", limit=limit
88
+ )
89
+ result = []
90
+ for r in rows:
91
+ sources = []
92
+ try:
93
+ sources = json.loads(r.get("sources", "[]"))
94
+ except Exception:
95
+ pass
96
+ result.append({
97
+ "role": r["role"],
98
+ "content": r["content"],
99
+ "sources": sources,
100
+ "provider": r.get("provider"),
101
+ "timestamp": r.get("timestamp")
102
+ })
103
+ return result
104
+
105
+ def list_sessions():
106
+ db = setup_db()
107
+ if "conversations" not in db.table_names():
108
+ return []
109
+ rows = list(db.query("""
110
+ SELECT c.session_id,
111
+ COALESCE(s.name, c.session_id) as name,
112
+ MAX(c.timestamp) as last_active,
113
+ MIN(c.timestamp) as created_at,
114
+ COUNT(*) as message_count,
115
+ (SELECT content FROM conversations c2 WHERE c2.session_id = c.session_id AND c2.role = 'user' ORDER BY c2.timestamp ASC LIMIT 1) as preview
116
+ FROM conversations c
117
+ LEFT JOIN sessions s ON s.session_id = c.session_id
118
+ GROUP BY c.session_id
119
+ ORDER BY last_active DESC
120
+ """))
121
+ return rows
122
+
123
+ def delete_session(session_id: str):
124
+ db = setup_db()
125
+ db["conversations"].delete_where("session_id = ?", [session_id])
126
+ try:
127
+ db["sessions"].delete(session_id)
128
+ except Exception:
129
+ pass
api/rag_engine.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import json
4
+ from dotenv import load_dotenv
5
+
6
+ load_dotenv()
7
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8
+
9
+ from embeddings.embedder import search
10
+ from sentence_transformers import CrossEncoder
11
+ from api.utils import detect_jurisdiction, auto_context_depth, tier_sources, strip_think_tags
12
+
13
+ # ─── Reranker ────────────────────────────────────────────────────────────────
14
+ _reranker = None
15
+ def get_reranker():
16
+ global _reranker
17
+ if _reranker is None:
18
+ print("Initializing Reranker (Lazy)...")
19
+ _reranker = CrossEncoder('BAAI/bge-reranker-base')
20
+ return _reranker
21
+
22
+ # ─── Provider Config ──────────────────────────────────────────────────────────
23
+ OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434/api/chat")
24
+ OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "llama3:latest")
25
+
26
+ OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")
27
+ OPENROUTER_MODEL = "meta-llama/llama-3.3-70b-instruct:free"
28
+
29
+ GROQ_API_KEY = os.environ.get("GROQ_API_KEY")
30
+ GROQ_MODEL = "llama-3.3-70b-versatile"
31
+
32
+
33
+ LLM_PROVIDER = os.environ.get("LLM_PROVIDER", "openrouter")
34
+
35
+ # ─── System Prompt ────────────────────────────────────────────────────────────
36
+ SYSTEM_PROMPT = """You are LexRAG, an expert AI counsel for UAE and Indian law, taxation, and accounting.
37
+
38
+ RULES:
39
+ 1. If context documents are provided and relevant, answer ONLY from them. Cite source title and jurisdiction.
40
+ 2. If context is insufficient or the question is off-topic, answer helpfully using your knowledge. Prefix ALL such paragraphs with [INDEPENDENT ANALYSIS].
41
+ 3. Be concise and structured. Use bullet points for lists of rules or rates.
42
+ 4. Always end your response with a one-line tag: JURISDICTION: India | UAE | Both | General
43
+ 5. Never fabricate statute numbers or case names."""
44
+
45
+ # ─── Retrieval + Reranking ────────────────────────────────────────────────────
46
+ def search_and_rerank(question: str, jurisdiction: str = None, top_k: int = 5) -> list:
47
+ filters = {}
48
+ if jurisdiction and jurisdiction != "Both":
49
+ filters["jurisdiction"] = [jurisdiction, "Both"]
50
+ initial = search(question, top_k=20, filters=filters if filters else None)
51
+ if not initial:
52
+ return []
53
+ try:
54
+ pairs = [[question, d["text"]] for d in initial]
55
+ scores = get_reranker().predict(pairs)
56
+ for i, s in enumerate(scores):
57
+ initial[i]["rerank_score"] = float(s)
58
+ ranked = sorted(initial, key=lambda x: x["rerank_score"], reverse=True)
59
+ return ranked[:top_k]
60
+ except Exception as e:
61
+ print(f"Rerank error: {e}")
62
+ return initial[:top_k]
63
+
64
+ # ─── Prompt Builder ───────────────────────────────────────────────────────────
65
+ def build_prompt(query: str, context_docs: list, history: list = None, confidence: str = "GROUNDED") -> str:
66
+ if context_docs:
67
+ ctx = "\n\n---\n\n".join([
68
+ f"[Source: {d['source']} | Jurisdiction: {d['jurisdiction']} | Date: {d.get('date','')}]\n"
69
+ f"Title: {d['doc_title']}\n\n{d['text']}"
70
+ for d in context_docs
71
+ ])
72
+ else:
73
+ ctx = "No relevant documents found."
74
+
75
+ hist_str = ""
76
+ if history:
77
+ hist_str = "CONVERSATION HISTORY:\n" + "\n".join(
78
+ f"{h['role'].upper()}: {h['content']}" for h in history
79
+ ) + "\n\n"
80
+
81
+ fallback = ""
82
+ if confidence == "SYNTHESIZED":
83
+ fallback = "\nNote: No strong document matches found. Provide an independent analysis based on your knowledge and mark paragraphs with [INDEPENDENT ANALYSIS].\n"
84
+
85
+ return f"""{hist_str}CONTEXT DOCUMENTS:
86
+ {ctx}
87
+ {fallback}
88
+ QUESTION: {query}"""
89
+
90
+ # ─── Streaming Generators ────────────────────────────────────────────────────
91
+ import httpx
92
+
93
+ async def stream_groq(messages: list, model: str = None):
94
+ model = model or GROQ_MODEL
95
+ in_think = False
96
+ async with httpx.AsyncClient(timeout=120.0) as client:
97
+ async with client.stream(
98
+ "POST", "https://api.groq.com/openai/v1/chat/completions",
99
+ headers={"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"},
100
+ json={"model": model, "messages": messages, "stream": True}
101
+ ) as resp:
102
+ if resp.status_code != 200:
103
+ err_body = await resp.aread()
104
+ try: err_json = json.loads(err_body)
105
+ except: err_json = {"error": {"message": err_body.decode()}}
106
+ msg = err_json.get("error", {}).get("message", "Unknown Groq error")
107
+ raise Exception(f"Groq API Error ({resp.status_code}): {msg}")
108
+
109
+ async for line in resp.aiter_lines():
110
+ if not line.startswith("data: "): continue
111
+ data = line[6:]
112
+ if data.strip() == "[DONE]": break
113
+ try:
114
+ pdata = json.loads(data)
115
+ if "error" in pdata:
116
+ raise Exception(f"Groq Stream Error: {pdata['error'].get('message', 'Unknown')}")
117
+ token = pdata["choices"][0]["delta"].get("content", "")
118
+ if not token: continue
119
+ clean, in_think = strip_think_tags(token, in_think)
120
+ if clean: yield clean
121
+ except Exception as e:
122
+ if "Stream Error" in str(e) or "API Error" in str(e): raise e
123
+ pass
124
+
125
+ async def stream_openrouter(messages: list, model: str = None):
126
+ model = model or OPENROUTER_MODEL
127
+ in_think = False
128
+ async with httpx.AsyncClient(timeout=120.0) as client:
129
+ async with client.stream(
130
+ "POST", "https://openrouter.ai/api/v1/chat/completions",
131
+ headers={"Authorization": f"Bearer {OPENROUTER_API_KEY}", "Content-Type": "application/json"},
132
+ json={"model": model, "messages": messages, "stream": True}
133
+ ) as resp:
134
+ if resp.status_code != 200:
135
+ err_body = await resp.aread()
136
+ try: err_json = json.loads(err_body)
137
+ except: err_json = {"error": {"message": err_body.decode()}}
138
+ msg = err_json.get("error", {}).get("message", "Unknown OpenRouter error")
139
+ raise Exception(f"OpenRouter API Error ({resp.status_code}): {msg}")
140
+
141
+ async for line in resp.aiter_lines():
142
+ if not line.startswith("data: "): continue
143
+ data = line[6:]
144
+ if data.strip() == "[DONE]": break
145
+ try:
146
+ pdata = json.loads(data)
147
+ if "error" in pdata:
148
+ raise Exception(f"OpenRouter Stream Error: {pdata['error'].get('message', 'Unknown')}")
149
+ token = pdata["choices"][0]["delta"].get("content", "")
150
+ if not token: continue
151
+ clean, in_think = strip_think_tags(token, in_think)
152
+ if clean: yield clean
153
+ except Exception as e:
154
+ if "Stream Error" in str(e) or "API Error" in str(e): raise e
155
+ pass
156
+
157
+ async def stream_ollama(messages: list, model: str = None):
158
+ model = model or OLLAMA_MODEL
159
+ async with httpx.AsyncClient(timeout=180.0) as client:
160
+ async with client.stream(
161
+ "POST", OLLAMA_URL,
162
+ json={"model": model, "messages": messages, "stream": True}
163
+ ) as resp:
164
+ if resp.status_code != 200:
165
+ err_body = await resp.aread()
166
+ raise Exception(f"Ollama API Error ({resp.status_code}): {err_body.decode()}")
167
+ async for line in resp.aiter_lines():
168
+ if not line.strip():
169
+ continue
170
+ try:
171
+ chunk = json.loads(line)
172
+ token = chunk.get("message", {}).get("content", "")
173
+ if token: yield token
174
+ if chunk.get("done"): break
175
+ except Exception:
176
+ pass
177
+
178
+ async def stream_provider(messages: list, provider: str, model: str = None):
179
+ if provider == "groq":
180
+ async for t in stream_groq(messages, model): yield t
181
+ elif provider == "openrouter":
182
+ async for t in stream_openrouter(messages, model): yield t
183
+ elif provider == "ollama":
184
+ async for t in stream_ollama(messages, model): yield t
185
+ else:
186
+ async for t in stream_groq(messages, model): yield t
187
+
188
+ # ─── Legacy sync query (CLI) ──────────────────────────────────────────────────
189
+ def query_rag(question: str, jurisdiction: str = None, source_type: str = None,
190
+ top_k: int = None, provider: str = None, session_id: str = "default") -> dict:
191
+ from api.memory import save_message, get_history
192
+ from api.utils import parse_citations
193
+ provider = provider or LLM_PROVIDER
194
+ top_k = top_k or auto_context_depth(question)
195
+ jurisdiction = jurisdiction or detect_jurisdiction(question)
196
+ docs = search_and_rerank(question, jurisdiction, top_k)
197
+ confidence = tier_sources(docs)
198
+ history = get_history(session_id, limit=5)
199
+ prompt = build_prompt(question, docs, history, confidence)
200
+ messages = [{"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": prompt}]
201
+ try:
202
+ import httpx as _h
203
+ if provider == "groq":
204
+ r = _h.Client(timeout=60).post(
205
+ "https://api.groq.com/openai/v1/chat/completions",
206
+ headers={"Authorization": f"Bearer {GROQ_API_KEY}"},
207
+ json={"model": GROQ_MODEL, "messages": messages}
208
+ ).json()["choices"][0]["message"]["content"]
209
+ elif provider == "openrouter":
210
+ r = _h.Client(timeout=60).post(
211
+ "https://openrouter.ai/api/v1/chat/completions",
212
+ headers={"Authorization": f"Bearer {OPENROUTER_API_KEY}"},
213
+ json={"model": OPENROUTER_MODEL, "messages": messages}
214
+ ).json()["choices"][0]["message"]["content"]
215
+ else:
216
+ r = "Provider not supported in sync mode."
217
+ r = parse_citations(r)
218
+ except Exception as e:
219
+ r = f"Error: {e}"
220
+ save_message(session_id, "user", question)
221
+ save_message(session_id, "assistant", r, sources=docs, provider=provider)
222
+ return {"answer": r, "sources": [{"title": d["doc_title"], "source": d["source"],
223
+ "jurisdiction": d["jurisdiction"], "type": d["source_type"], "url": d["url"],
224
+ "score": round(d.get("rerank_score", 0), 3)} for d in docs],
225
+ "context_used": len(docs), "provider": provider, "session_id": session_id,
226
+ "confidence": confidence, "jurisdiction": jurisdiction}
227
+
228
+ if __name__ == "__main__":
229
+ r = query_rag("What is the GST rate on online gaming contest entry fees in India?")
230
+ print("ANSWER:", r["answer"][:300])
231
+ print("CONFIDENCE:", r["confidence"])
232
+ print("JURISDICTION:", r["jurisdiction"])
api/utils.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import os
3
+ import urllib.parse
4
+
5
+
6
+ # ─── Jurisdiction Detection ───────────────────────────────────────────────────
7
+ INDIA_KEYWORDS = [
8
+ "gst", "cgst", "sgst", "igst", "tds", "tcs", "itc", "sebi", "rbi", "india", "indian",
9
+ "rupee", "inr", "crore", "lakh", "section 194", "companies act", "ipc", "ibc",
10
+ "income tax", "delhi", "mumbai", "bombay", "chennai", "bangalore", "hyderabad",
11
+ "goods and services tax", "finance act", "cbdt", "gstr", "pan", "tan",
12
+ "fema", "rera", "msme", "nri", "oci", "itat", "nclt", "nclat"
13
+ ]
14
+ UAE_KEYWORDS = [
15
+ "vat", "uae vat", "fta", "uae", "dubai", "abu dhabi", "sharjah", "ajman",
16
+ "dirham", "aed", "free zone", "difc", "adgm", "excise tax",
17
+ "federal tax authority", "corporate tax", "uae corporate", "ministry of finance",
18
+ "cabinet decision", "federal decree", "mainland uae", "freezone"
19
+ ]
20
+
21
+ def detect_jurisdiction(query: str) -> str:
22
+ q = query.lower()
23
+ india = sum(1 for kw in INDIA_KEYWORDS if kw in q)
24
+ uae = sum(1 for kw in UAE_KEYWORDS if kw in q)
25
+ if india > 0 and uae == 0: return "India"
26
+ if uae > 0 and india == 0: return "UAE"
27
+ return "Both"
28
+
29
+ # ─── Auto Context Depth ───────────────────────────────────────────────────────
30
+ COMPLEX_TERMS = [
31
+ "section", "act", "regulation", "notification", "circular", "judgment",
32
+ "case", "versus", "liability", "exemption", "penalty", "compliance",
33
+ "provision", "clause", "amendment", "appeal", "tribunal", "writ",
34
+ "holding", "ratio", "precedent", "article", "schedule"
35
+ ]
36
+
37
+ def auto_context_depth(query: str) -> int:
38
+ wc = len(query.split())
39
+ hits = sum(1 for t in COMPLEX_TERMS if t in query.lower())
40
+ if wc < 12 and hits < 2: return 5
41
+ if wc < 30 and hits < 4: return 8
42
+ if wc < 60 or hits < 6: return 12
43
+ return 15
44
+
45
+ # ─── Source Confidence Tiering ────────────────────────────────────────────────
46
+ def tier_sources(docs: list) -> str:
47
+ if not docs: return "SYNTHESIZED"
48
+ max_score = max(d.get("rerank_score", d.get("score", 0)) for d in docs)
49
+ if max_score > 0.4: return "GROUNDED"
50
+ if max_score > 0.12: return "PARTIAL"
51
+ return "SYNTHESIZED"
52
+
53
+ # ─── Think-Tag State Machine ──────────────────────────────────────────────────
54
+ def strip_think_tags(token: str, in_think: bool) -> tuple[str, bool]:
55
+ output = ""
56
+ remaining = token
57
+ while remaining:
58
+ if in_think:
59
+ end_idx = remaining.find("</think>")
60
+ if end_idx == -1:
61
+ remaining = ""
62
+ else:
63
+ in_think = False
64
+ remaining = remaining[end_idx + len("</think>"):]
65
+ else:
66
+ start_idx = remaining.find("<think>")
67
+ if start_idx == -1:
68
+ output += remaining
69
+ remaining = ""
70
+ else:
71
+ output += remaining[:start_idx]
72
+ in_think = True
73
+ remaining = remaining[start_idx + len("<think>"):]
74
+ return output, in_think
75
+
76
+ # ─── Citation patterns for UAE and India ─────────────────────────────────────
77
+ UAE_LAW_PATTERN = r"((?:Federal\s+)?(?:Decree-)?Law\s+No\.\s*(?:\(?\d+\)?)\s+of\s+\d{4})"
78
+ INDIA_LAW_PATTERN = r"((?:Income[\s-]?Tax\s+Act|Companies\s+Act|GST\s+Act|Income[\s-]?Tax\s+Rules?|Indian\s+Penal\s+Code|Insolvency\s+and\s+Bankruptcy\s+Code),?\s+\d{4})"
79
+ INDIA_SECTION_PATTERN = r"(Section\s+\d+[A-Z]?(?:-\s*[A-Z]+)?)"
80
+
81
+ def parse_citations(text: str) -> str:
82
+ """
83
+ Scans text for legal citations and wraps them in professional tagging or markdown links.
84
+ Avoids double wrapping already-linked text.
85
+ """
86
+ # UAE Law linking (Search on UAE Legislation Portal - ignores existing markdown links)
87
+ uae_combined = r"(\[[^\]]+\]\([^\)]+\))|" + UAE_LAW_PATTERN
88
+ def uae_repl(match):
89
+ if match.group(1):
90
+ return match.group(1)
91
+ val = match.group(2)
92
+ encoded = urllib.parse.quote(val)
93
+ return f"[{val}](https://elaws.moj.gov.ae/UAE-Legislations-Search-en.aspx?query={encoded})"
94
+ text = re.sub(uae_combined, uae_repl, text)
95
+
96
+ # India Law linking (Search on Indian Kanoon)
97
+ india_combined = r"(\[[^\]]+\]\([^\)]+\))|" + INDIA_LAW_PATTERN
98
+ def india_repl(match):
99
+ if match.group(1):
100
+ return match.group(1)
101
+ val = match.group(2)
102
+ encoded = urllib.parse.quote(val)
103
+ return f"[{val}](https://indiankanoon.org/search/?formInput={encoded})"
104
+ text = re.sub(india_combined, india_repl, text)
105
+
106
+ # Section linking (Contextual search on Indian Kanoon)
107
+ section_combined = r"(\[[^\]]+\]\([^\)]+\))|" + INDIA_SECTION_PATTERN
108
+ def section_repl(match):
109
+ if match.group(1):
110
+ return match.group(1)
111
+ val = match.group(2)
112
+ encoded = urllib.parse.quote(val)
113
+ return f"[{val}](https://indiankanoon.org/search/?formInput={encoded})"
114
+ text = re.sub(section_combined, section_repl, text)
115
+
116
+ return text
117
+
118
+ def format_score(score: float) -> str:
119
+ """Formats a search score into a user-friendly percentage or indicator."""
120
+ if score > 0.8: return "High"
121
+ if score > 0.5: return "Medium"
122
+ return "Low"
data/statutes/india_gst_contests.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Indian Law: GST on Contests, Games of Skill, and Prize Distribution
2
+
3
+ ## 1. GST on Entry Fees/Participation Charges
4
+ Under Indian GST law, organizing contests where a fee is charged is considered a supply of services.
5
+ - **Online Gaming & Action-Based Contests:** Effective from October 1, 2023, a uniform GST rate of **28%** is applicable on the full face value of the entry fee or deposit paid by players. This applies whether the game is a "game of skill" or a "game of chance."
6
+ - **General Contests:** Other types of contests (quizzes, physical events) where entry fees are charged attract a GST rate of **18%** as a general service supply.
7
+
8
+ ## 2. GST on Prize Distribution
9
+ - **Receipt by Winner:** The winning of a prize in money or kind by a participant does not constitute a "supply" by the winner to the organizer. Therefore, no GST is applicable on the winner upon receiving the prize.
10
+ - **Input Tax Credit (ITC):** Organizers generally cannot claim ITC on the value of prizes distributed if they are goods, as Section 17(5)(h) of the CGST Act restricts ITC on "goods disposed of by way of gift or free samples."
11
+
12
+ ## 3. GST on Sponsored Prizes (Sponsorship Services)
13
+ - **Nature of Supply:** Sponsorship is a taxable supply of service under GST. The organizer provides a promotional service to the sponsor in exchange for the prize money or goods.
14
+ - **Reverse Charge Mechanism (RCM):** Under Notification No. 13/2017-Central Tax (Rate), GST on sponsorship services is payable under **Reverse Charge** if the sponsor (the person providing the money/prizes) is a "body corporate" or "partnership firm" located in the taxable territory. In this case, the sponsor pays the tax, not the organizer.
15
+ - **Exemptions:** Sponsorship of recognized sporting events by National Sports Federations is exempt under Notification 12/2017.
16
+
17
+ ## 4. Income Tax (TDS) Implications on Winnings
18
+ - **Section 194B:** Any person responsible for paying winnings from a lottery, crossword puzzle, card game, or other games of any sort exceeding **INR 10,000** must deduct tax at source (TDS) at the rate of **30%** (plus applicable cess/surcharge).
19
+ - **Non-Monetary Prizes:** If the prize is given in kind (e.g., a car, electronics), the organizer must ensure the tax is paid before releasing the prize. The market value of the prize is considered for TDS calculation.
20
+
21
+ # Summary Table for Organizer
22
+ | Item | GST Rate | Payer | Notes |
23
+ |------|----------|-------|-------|
24
+ | Entry fees (Mining/Gaming) | 28% | Organizer | On total amount collected |
25
+ | Entry fees (Standard) | 18% | Organizer | On entry fee value |
26
+ | Sponsored Prizes | 18% | Sponsor (RCM) | If sponsor is a body corporate |
27
+ | Prize Money | 0% | - | No GST on winner |
28
+ | Winner Winnings | 30% | Organizer (TDS) | Deducted from prize if >10k |
embeddings/embedder.py ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastembed import TextEmbedding, SparseTextEmbedding
2
+ from qdrant_client import QdrantClient
3
+ from qdrant_client.models import Distance, VectorParams, SparseVectorParams, PointStruct, Filter, FieldCondition, MatchValue, MatchAny, Fusion, FusionQuery, Prefetch
4
+ import uuid
5
+ import json
6
+ import os
7
+
8
+ COLLECTION_NAME = "lexrag_docs_v3"
9
+ QDRANT_URL = "http://localhost:6333"
10
+
11
+ # Memory-efficient models for 1GB RAM server
12
+ DENSE_MODEL = "BAAI/bge-small-en-v1.5"
13
+ SPARSE_MODEL = "prithivida/Splade_PP_en_v1"
14
+
15
+ _embedder = None
16
+
17
+ def get_embedder():
18
+ global _embedder
19
+ if _embedder is None:
20
+ _embedder = LexEmbedder()
21
+ return _embedder
22
+
23
+ class LexEmbedder:
24
+ def __init__(self):
25
+ root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+ cache_path = os.path.join(root_dir, "embeddings_cache")
27
+ os.makedirs(cache_path, exist_ok=True)
28
+
29
+ print(f"Initializing LexEmbedder with {DENSE_MODEL} and {SPARSE_MODEL}...")
30
+ self.dense_model = TextEmbedding(model_name=DENSE_MODEL, cache_dir=cache_path)
31
+ self.sparse_model = SparseTextEmbedding(model_name=SPARSE_MODEL, cache_dir=cache_path)
32
+ storage_path = os.path.join(root_dir, "qdrant_storage")
33
+ self.client = QdrantClient(path=storage_path)
34
+
35
+ def ensure_collection(self):
36
+ existing = [c.name for c in self.client.get_collections().collections]
37
+ if COLLECTION_NAME not in existing:
38
+ self.client.create_collection(
39
+ collection_name=COLLECTION_NAME,
40
+ vectors_config={
41
+ "dense": VectorParams(size=384, distance=Distance.COSINE)
42
+ },
43
+ sparse_vectors_config={
44
+ "sparse": SparseVectorParams(index=None)
45
+ }
46
+ )
47
+ print(f"Created Hybrid Collection: {COLLECTION_NAME}")
48
+ else:
49
+ print(f"Hybrid Collection exists: {COLLECTION_NAME}")
50
+
51
+ def embed(self, text: str):
52
+ dense_vec = list(self.dense_model.embed([f"passage: {text}"]))[0].tolist()
53
+ sparse_vec = list(self.sparse_model.embed([text]))[0]
54
+ return dense_vec, sparse_vec
55
+
56
+ def upsert_document(self, text: str, metadata: dict):
57
+ self.ensure_collection()
58
+ doc_id = str(uuid.uuid4())
59
+ dense_vec, sparse_vec = self.embed(text)
60
+
61
+ sparse_vector_data = {
62
+ "indices": sparse_vec.indices.tolist(),
63
+ "values": sparse_vec.values.tolist()
64
+ }
65
+
66
+ point = PointStruct(
67
+ id=doc_id,
68
+ vector={
69
+ "dense": dense_vec,
70
+ "sparse": sparse_vector_data
71
+ },
72
+ payload={**metadata, "text": text}
73
+ )
74
+ self.client.upsert(collection_name=COLLECTION_NAME, points=[point])
75
+ return doc_id
76
+
77
+ def search(self, query: str, top_k: int = 15, filters: dict = None) -> list:
78
+ self.ensure_collection()
79
+ dense_query = list(self.dense_model.embed([f"query: {query}"]))[0].tolist()
80
+ sparse_query_vec = list(self.sparse_model.embed([query]))[0]
81
+
82
+ sparse_query = {
83
+ "indices": sparse_query_vec.indices.tolist(),
84
+ "values": sparse_query_vec.values.tolist()
85
+ }
86
+
87
+ qdrant_filter = None
88
+ if filters:
89
+ conditions = []
90
+ for key, value in filters.items():
91
+ if isinstance(value, list):
92
+ conditions.append(FieldCondition(key=key, match=MatchAny(any=value)))
93
+ else:
94
+ conditions.append(FieldCondition(key=key, match=MatchValue(value=value)))
95
+ qdrant_filter = Filter(must=conditions)
96
+
97
+ # Hybrid Search using Prefetch and Fusion
98
+ results = self.client.query_points(
99
+ collection_name=COLLECTION_NAME,
100
+ prefetch=[
101
+ Prefetch(
102
+ query=dense_query,
103
+ using="dense",
104
+ limit=top_k,
105
+ filter=qdrant_filter
106
+ ),
107
+ Prefetch(
108
+ query=sparse_query,
109
+ using="sparse",
110
+ limit=top_k,
111
+ filter=qdrant_filter
112
+ )
113
+ ],
114
+ query=FusionQuery(fusion=Fusion.RRF),
115
+ limit=top_k,
116
+ query_filter=qdrant_filter,
117
+ with_payload=True
118
+ ).points
119
+
120
+ return [
121
+ {
122
+ "text": r.payload.get("text", ""),
123
+ "score": r.score,
124
+ "source": r.payload.get("source", ""),
125
+ "source_type": r.payload.get("source_type", ""),
126
+ "jurisdiction": r.payload.get("jurisdiction", ""),
127
+ "date": r.payload.get("date", ""),
128
+ "doc_title": r.payload.get("doc_title", ""),
129
+ "url": r.payload.get("url", "")
130
+ }
131
+ for r in results
132
+ ]
133
+
134
+ # Lazy initialization wrappers
135
+ def ensure_collection(): return get_embedder().ensure_collection()
136
+ def upsert_document(text, meta): return get_embedder().upsert_document(text, meta)
137
+ def search(query, top_k=5, filters=None): return get_embedder().search(query, top_k, filters)
marketing/assets/evolution_core.png ADDED

Git LFS Details

  • SHA256: a9ec6fffe5175816172bcea53b76c53e1ddfc43b0164ecebbe578b9d91481bca
  • Pointer size: 131 Bytes
  • Size of remote file: 722 kB
marketing/assets/hero.png ADDED

Git LFS Details

  • SHA256: a9ec6fffe5175816172bcea53b76c53e1ddfc43b0164ecebbe578b9d91481bca
  • Pointer size: 131 Bytes
  • Size of remote file: 722 kB
marketing/index.html ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>LexRAG | The Intelligence Terminal for Sovereign Law</title>
7
+ <link rel="stylesheet" href="style.css">
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10
+ <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@200;400;700&family=JetBrains+Mono&display=swap" rel="stylesheet">
11
+ </head>
12
+ <body>
13
+ <nav>
14
+ <div class="logo">LexRAG</div>
15
+ <div class="nav-links">
16
+ <span class="dev-tag">By Evolucent AI</span>
17
+ <a href="https://eulogik.com" class="nav-btn">Engineered by Eulogik</a>
18
+ <a href="https://evolucentai.com/" class="nav-btn">Inquire →</a>
19
+ </div>
20
+ </nav>
21
+
22
+ <main>
23
+ <!-- Hero Section -->
24
+ <section class="hero">
25
+ <div class="hero-image">
26
+ <img src="assets/hero.png" alt="LexRAG Sovereign Intelligence Core">
27
+ </div>
28
+ <div class="hero-content">
29
+ <div class="badge reveal">SVRN TERMINAL v3.2</div>
30
+ <h1 class="reveal">LexRAG</h1>
31
+ <p class="tagline reveal">The Sovereign Intelligence Terminal.</p>
32
+ <p class="subtitle reveal">Grounding legal precision in a high-performance architecture. Built for professionals in the UAE and India.</p>
33
+ <div class="cta-wrap reveal">
34
+ <a href="https://evolucentai.com/" class="btn-primary">Acquire Terminal Access</a>
35
+ </div>
36
+ </div>
37
+ </section>
38
+
39
+ <!-- The Evolution (V1 + V2) -->
40
+ <section class="evolution reveal">
41
+ <div class="section-label">// NARRATIVE</div>
42
+ <div class="split-row">
43
+ <div class="split-col">
44
+ <h2>The Genesis of Precision.</h2>
45
+ <p>LexRAG began as a high-performance RAG engine (v1)—a foundational core designed to parse and vectorize the complex nuances of Indian and UAE statutes. In v2, this intelligence was encased in a professional terminal interface, engineered for zero-latency analysis and institutional persistence.</p>
46
+ </div>
47
+ <div class="split-col stats-grid">
48
+ <div class="stat-box">
49
+ <span class="stat-num">v1</span>
50
+ <span class="stat-label">Neural Engine</span>
51
+ </div>
52
+ <div class="stat-box">
53
+ <span class="stat-num">v2</span>
54
+ <span class="stat-label">Genius Terminal</span>
55
+ </div>
56
+ </div>
57
+ </div>
58
+ </section>
59
+
60
+ <!-- Specialized Jurisdictions -->
61
+ <section class="jurisdictions reveal">
62
+ <div class="section-label">// SPECIALIZATION</div>
63
+ <div class="jur-row">
64
+ <div class="jur-card">
65
+ <img src="https://flagcdn.com/in.svg" alt="India" width="40">
66
+ <h3>India</h3>
67
+ <ul>
68
+ <li>GST & Indirect Taxation</li>
69
+ <li>Indian Kanoon Case Law</li>
70
+ <li>CBDT Circulars & Rulings</li>
71
+ </ul>
72
+ </div>
73
+ <div class="jur-card">
74
+ <img src="https://flagcdn.com/ae.svg" alt="UAE" width="40">
75
+ <h3>UAE</h3>
76
+ <ul>
77
+ <li>Corporate Tax Framework</li>
78
+ <li>FTA Federal Decrees</li>
79
+ <li>MOJ Statute Library</li>
80
+ </ul>
81
+ </div>
82
+ </div>
83
+ </section>
84
+
85
+ <!-- Use Cases -->
86
+ <section class="use-cases reveal">
87
+ <div class="section-label">// ADOPTION</div>
88
+ <h2>Built for the Strategists.</h2>
89
+ <div class="case-grid">
90
+ <div class="case-card">
91
+ <h4>Legal Counsel</h4>
92
+ <p>Rapid precedent discovery and statute cross-referencing with citation transparency.</p>
93
+ </div>
94
+ <div class="case-card">
95
+ <h4>Chartered Accountants</h4>
96
+ <p>Instant clarity on tax treatment, free zone regulations, and compliance statutes.</p>
97
+ </div>
98
+ <div class="case-card">
99
+ <h4>Tax Consultants</h4>
100
+ <p>Strategic advisory grounded in absolute legal truth, not probabilistic guesses.</p>
101
+ </div>
102
+ </div>
103
+ </section>
104
+
105
+ <!-- Grounded Accuracy Section -->
106
+ <section class="grounded reveal">
107
+ <div class="section-label">// TECHNOLOGY</div>
108
+ <h2>Zero Hallucination. Absolute Grounding.</h2>
109
+ <p>Unlike general-purpose models, LexRAG does not guess. It retrieves, reranks, and synthesizes official law documents using a hybrid neural architecture, ensuring every answer is backed by a primary source.</p>
110
+ <div class="tech-tags">
111
+ <span>Hybrid Retrieval</span>
112
+ <span>Neural Reranking</span>
113
+ <span>Contextual Persistence</span>
114
+ </div>
115
+ </section>
116
+
117
+ <!-- Final CTA -->
118
+ <section class="bottom-cta reveal">
119
+ <div class="glow"></div>
120
+ <h2>Ready for Sovereign Intelligence?</h2>
121
+ <p>LexRAG is available for bespoke deployment. Elevate your legal operations today.</p>
122
+ <a href="https://evolucentai.com/" class="btn-primary">Connect with Evolucent AI</a>
123
+ </section>
124
+ </main>
125
+
126
+ <footer>
127
+ <div class="footer-grid">
128
+ <div class="footer-brand">
129
+ <div class="logo">LexRAG</div>
130
+ <p>Strategic Intelligence Terminal</p>
131
+ <p style="margin-top:0.5rem;font-size:0.7rem;opacity:0.6">Engineered by <a href="https://eulogik.com" style="color:inherit;text-decoration:underline;text-decoration-style:dotted;">Eulogik</a></p>
132
+ </div>
133
+ <div class="footer-meta">
134
+ <span>v3.2.2</span>
135
+ <span>By Evolucent AI</span>
136
+ </div>
137
+ <div class="footer-legal">
138
+ <p>© 2024 Evolucent AI. All Rights Reserved. | Engineered by <a href="https://eulogik.com" style="color:inherit;text-decoration:underline;text-decoration-style:dotted;">Eulogik</a></p>
139
+ </div>
140
+ </div>
141
+ </footer>
142
+
143
+ <script>
144
+ // Simple reveal on scroll
145
+ const observerOptions = {
146
+ threshold: 0.1
147
+ };
148
+
149
+ const observer = new IntersectionObserver((entries) => {
150
+ entries.forEach(entry => {
151
+ if (entry.isIntersecting) {
152
+ entry.target.classList.add('active');
153
+ }
154
+ });
155
+ }, observerOptions);
156
+
157
+ document.querySelectorAll('.reveal').forEach(el => observer.observe(el));
158
+ </script>
159
+ </body>
160
+ </html>
marketing/style.css ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ :root {
2
+ --bg: #000000;
3
+ --fg: #ffffff;
4
+ --muted: #888888;
5
+ --accent: #222222;
6
+ --line: rgba(255,255,255,0.06);
7
+ --card-bg: #050505;
8
+ }
9
+
10
+ * {
11
+ margin: 0;
12
+ padding: 0;
13
+ box-sizing: border-box;
14
+ }
15
+
16
+ body {
17
+ background-color: var(--bg);
18
+ color: var(--fg);
19
+ font-family: 'Outfit', sans-serif;
20
+ line-height: 1.6;
21
+ overflow-x: hidden;
22
+ -webkit-font-smoothing: antialiased;
23
+ }
24
+
25
+ /* Nav */
26
+ nav {
27
+ display: flex;
28
+ justify-content: space-between;
29
+ align-items: center;
30
+ padding: 1.5rem 8%;
31
+ position: fixed;
32
+ width: 100%;
33
+ top: 0;
34
+ z-index: 1000;
35
+ background: rgba(0,0,0,0.8);
36
+ backdrop-filter: blur(20px);
37
+ border-bottom: 1px solid var(--line);
38
+ }
39
+
40
+ .logo {
41
+ font-size: 1.1rem;
42
+ font-weight: 700;
43
+ letter-spacing: -0.04em;
44
+ text-transform: uppercase;
45
+ }
46
+
47
+ .dev-tag {
48
+ font-family: 'JetBrains Mono', monospace;
49
+ font-size: 0.6rem;
50
+ color: var(--muted);
51
+ text-transform: uppercase;
52
+ letter-spacing: 2px;
53
+ margin-right: 2rem;
54
+ }
55
+
56
+ .nav-btn {
57
+ color: var(--fg);
58
+ text-decoration: none;
59
+ font-weight: 400;
60
+ font-size: 0.75rem;
61
+ border: 1px solid var(--line);
62
+ padding: 0.5rem 1.2rem;
63
+ border-radius: 4px;
64
+ transition: all 0.2s;
65
+ font-family: 'JetBrains Mono', monospace;
66
+ }
67
+
68
+ .nav-btn:hover {
69
+ background: var(--fg);
70
+ color: var(--bg);
71
+ }
72
+
73
+ /* Sections */
74
+ section {
75
+ padding: 10rem 8%;
76
+ border-bottom: 1px solid var(--line);
77
+ }
78
+
79
+ .section-label {
80
+ font-family: 'JetBrains Mono', monospace;
81
+ font-size: 0.65rem;
82
+ color: var(--muted);
83
+ margin-bottom: 3rem;
84
+ letter-spacing: 2px;
85
+ }
86
+
87
+ /* Hero Section */
88
+ .hero {
89
+ height: 100vh;
90
+ display: flex;
91
+ flex-direction: column;
92
+ justify-content: center;
93
+ align-items: center;
94
+ position: relative;
95
+ padding: 0 5%;
96
+ border-bottom: none;
97
+ }
98
+
99
+ .hero-image {
100
+ position: absolute;
101
+ width: 100%;
102
+ height: 100%;
103
+ top: 0;
104
+ left: 0;
105
+ display: flex;
106
+ justify-content: center;
107
+ align-items: center;
108
+ z-index: -1;
109
+ opacity: 0.4;
110
+ mask-image: radial-gradient(circle, black 40%, transparent 90%);
111
+ }
112
+
113
+ .hero-image img {
114
+ max-width: 900px;
115
+ width: 90%;
116
+ filter: saturate(0.5) contrast(1.1);
117
+ }
118
+
119
+ .hero-content {
120
+ text-align: center;
121
+ }
122
+
123
+ .badge {
124
+ font-family: 'JetBrains Mono', monospace;
125
+ font-size: 0.6rem;
126
+ color: var(--fg);
127
+ border: 1px solid var(--line);
128
+ padding: 4px 12px;
129
+ border-radius: 4px;
130
+ display: inline-block;
131
+ margin-bottom: 2rem;
132
+ letter-spacing: 3px;
133
+ background: rgba(255,255,255,0.03);
134
+ }
135
+
136
+ h1 {
137
+ font-size: clamp(4rem, 12vw, 12rem);
138
+ font-weight: 700;
139
+ letter-spacing: -0.06em;
140
+ line-height: 0.8;
141
+ margin-bottom: 1.5rem;
142
+ }
143
+
144
+ .tagline {
145
+ font-size: clamp(1.2rem, 3vw, 2.5rem);
146
+ font-weight: 200;
147
+ letter-spacing: -0.02em;
148
+ color: #ffffff;
149
+ margin-bottom: 2rem;
150
+ opacity: 0.8;
151
+ }
152
+
153
+ .subtitle {
154
+ font-size: 0.9rem;
155
+ color: var(--muted);
156
+ max-width: 450px;
157
+ margin: 0 auto 3rem;
158
+ font-family: 'JetBrains Mono', monospace;
159
+ }
160
+
161
+ .btn-primary {
162
+ display: inline-block;
163
+ background: var(--fg);
164
+ color: var(--bg);
165
+ padding: 1rem 3rem;
166
+ border-radius: 4px;
167
+ text-decoration: none;
168
+ font-weight: 700;
169
+ font-size: 0.85rem;
170
+ transition: all 0.3s;
171
+ font-family: 'JetBrains Mono', monospace;
172
+ }
173
+
174
+ .btn-primary:hover {
175
+ transform: translateY(-2px);
176
+ box-shadow: 0 10px 30px rgba(255,255,255,0.1);
177
+ }
178
+
179
+ /* Evolution Section */
180
+ .split-row {
181
+ display: flex;
182
+ justify-content: space-between;
183
+ gap: 4rem;
184
+ }
185
+
186
+ .split-col {
187
+ flex: 1;
188
+ }
189
+
190
+ .split-col h2 {
191
+ font-size: clamp(2rem, 5vw, 4rem);
192
+ letter-spacing: -0.04em;
193
+ line-height: 1.1;
194
+ margin-bottom: 2rem;
195
+ }
196
+
197
+ .split-col p {
198
+ font-size: 1.2rem;
199
+ color: var(--muted);
200
+ font-weight: 200;
201
+ }
202
+
203
+ .stats-grid {
204
+ display: grid;
205
+ grid-template-columns: 1fr 1fr;
206
+ gap: 1.5rem;
207
+ }
208
+
209
+ .stat-box {
210
+ border: 1px solid var(--line);
211
+ padding: 2.5rem;
212
+ display: flex;
213
+ flex-direction: column;
214
+ justify-content: center;
215
+ align-items: center;
216
+ background: var(--card-bg);
217
+ }
218
+
219
+ .stat-num {
220
+ font-size: 2.5rem;
221
+ font-weight: 700;
222
+ font-family: 'JetBrains Mono', monospace;
223
+ color: var(--fg);
224
+ }
225
+
226
+ .stat-label {
227
+ font-size: 0.6rem;
228
+ color: var(--muted);
229
+ text-transform: uppercase;
230
+ letter-spacing: 2px;
231
+ margin-top: 0.5rem;
232
+ }
233
+
234
+ /* Jurisdictions */
235
+ .jur-row {
236
+ display: grid;
237
+ grid-template-columns: 1fr 1fr;
238
+ gap: 2rem;
239
+ }
240
+
241
+ .jur-card {
242
+ background: var(--card-bg);
243
+ border: 1px solid var(--line);
244
+ padding: 3rem;
245
+ }
246
+
247
+ .jur-card h3 {
248
+ font-size: 1.5rem;
249
+ margin: 1.5rem 0;
250
+ }
251
+
252
+ .jur-card ul {
253
+ list-style: none;
254
+ color: var(--muted);
255
+ font-size: 0.9rem;
256
+ font-weight: 200;
257
+ }
258
+
259
+ .jur-card li {
260
+ margin-bottom: 0.8rem;
261
+ display: flex;
262
+ align-items: center;
263
+ }
264
+
265
+ .jur-card li::before {
266
+ content: "—";
267
+ margin-right: 0.8rem;
268
+ opacity: 0.3;
269
+ }
270
+
271
+ /* Use Cases */
272
+ .use-cases h2 {
273
+ font-size: 3rem;
274
+ margin-bottom: 4rem;
275
+ letter-spacing: -0.04em;
276
+ }
277
+
278
+ .case-grid {
279
+ display: grid;
280
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
281
+ gap: 1rem;
282
+ }
283
+
284
+ .case-card {
285
+ border: 1px solid var(--line);
286
+ padding: 2.5rem;
287
+ transition: all 0.3s;
288
+ }
289
+
290
+ .case-card:hover {
291
+ background: var(--fg);
292
+ color: var(--bg);
293
+ }
294
+
295
+ .case-card h4 {
296
+ font-size: 1.2rem;
297
+ margin-bottom: 1rem;
298
+ font-family: 'JetBrains Mono', monospace;
299
+ }
300
+
301
+ .case-card p {
302
+ font-size: 0.9rem;
303
+ opacity: 0.7;
304
+ }
305
+
306
+ /* Grounded Section */
307
+ .grounded {
308
+ text-align: center;
309
+ }
310
+
311
+ .grounded h2 {
312
+ font-size: clamp(2rem, 6vw, 5rem);
313
+ letter-spacing: -0.05em;
314
+ margin-bottom: 2rem;
315
+ }
316
+
317
+ .grounded p {
318
+ max-width: 700px;
319
+ margin: 0 auto 3rem;
320
+ font-size: 1.2rem;
321
+ color: var(--muted);
322
+ font-weight: 200;
323
+ }
324
+
325
+ .tech-tags {
326
+ display: flex;
327
+ justify-content: center;
328
+ gap: 1rem;
329
+ flex-wrap: wrap;
330
+ }
331
+
332
+ .tech-tags span {
333
+ font-family: 'JetBrains Mono', monospace;
334
+ font-size: 0.65rem;
335
+ border: 1px solid var(--line);
336
+ padding: 8px 16px;
337
+ color: var(--muted);
338
+ }
339
+
340
+ /* Bottom CTA */
341
+ .bottom-cta {
342
+ position: relative;
343
+ text-align: center;
344
+ padding: 15rem 10%;
345
+ overflow: hidden;
346
+ }
347
+
348
+ .glow {
349
+ position: absolute;
350
+ width: 600px;
351
+ height: 600px;
352
+ background: radial-gradient(circle, rgba(255,255,255,0.05) 0%, transparent 70%);
353
+ top: 50%;
354
+ left: 50%;
355
+ transform: translate(-50%, -50%);
356
+ z-index: -1;
357
+ }
358
+
359
+ .bottom-cta h2 {
360
+ font-size: 3.5rem;
361
+ margin-bottom: 1.5rem;
362
+ letter-spacing: -0.04em;
363
+ }
364
+
365
+ .bottom-cta p {
366
+ margin-bottom: 3.5rem;
367
+ color: var(--muted);
368
+ font-size: 1.1rem;
369
+ }
370
+
371
+ /* Footer */
372
+ footer {
373
+ padding: 4rem 8%;
374
+ border-top: 1px solid var(--line);
375
+ }
376
+
377
+ .footer-grid {
378
+ display: grid;
379
+ grid-template-columns: 2fr 1fr 1fr;
380
+ gap: 4rem;
381
+ }
382
+
383
+ .footer-brand p {
384
+ font-size: 0.8rem;
385
+ color: var(--muted);
386
+ margin-top: 1rem;
387
+ }
388
+
389
+ .footer-meta {
390
+ display: flex;
391
+ flex-direction: column;
392
+ gap: 0.5rem;
393
+ font-family: 'JetBrains Mono', monospace;
394
+ font-size: 0.7rem;
395
+ color: var(--muted);
396
+ }
397
+
398
+ .footer-legal {
399
+ font-size: 0.7rem;
400
+ color: #444;
401
+ }
402
+
403
+ /* Animations */
404
+ .reveal {
405
+ opacity: 0;
406
+ transform: translateY(30px);
407
+ transition: all 1s cubic-bezier(0.16, 1, 0.3, 1);
408
+ }
409
+
410
+ .reveal.active {
411
+ opacity: 1;
412
+ transform: translateY(0);
413
+ }
414
+
415
+ @media (max-width: 1024px) {
416
+ .split-row { flex-direction: column; }
417
+ .jur-row { grid-template-columns: 1fr; }
418
+ }
419
+
420
+ @media (max-width: 768px) {
421
+ h1 { font-size: 5rem; }
422
+ footer .footer-grid { grid-template-columns: 1fr; text-align: center; }
423
+ .footer-meta { align-items: center; }
424
+ }
pyproject.toml ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lexrag"
7
+ version = "3.3.0"
8
+ description = "Legal Intelligence Terminal — Hybrid RAG for UAE & Indian Law, Tax and Compliance"
9
+ readme = "README.md"
10
+ license = { text = "AGPL-3.0-or-later" }
11
+ requires-python = ">=3.10"
12
+
13
+ authors = [
14
+ { name = "Evolucent AI", email = "hello@evolucentai.com" },
15
+ ]
16
+
17
+ maintainers = [
18
+ { name = "Eulogik", email = "engineering@eulogik.com" },
19
+ ]
20
+
21
+ keywords = [
22
+ "legal-rag", "legal-ai", "legal-research", "retrieval-augmented-generation",
23
+ "uae-law", "indian-law", "gst", "vat", "corporate-tax",
24
+ "fastembed", "qdrant", "hybrid-search", "rag",
25
+ "legal-tech", "compliance", "tax-research", "case-law",
26
+ "artificial-intelligence", "nlp", "legal-intelligence"
27
+ ]
28
+
29
+ classifiers = [
30
+ "Development Status :: 4 - Beta",
31
+ "Intended Audience :: Legal Industry",
32
+ "Intended Audience :: Financial and Insurance Industry",
33
+ "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",
34
+ "Natural Language :: English",
35
+ "Operating System :: OS Independent",
36
+ "Programming Language :: Python :: 3",
37
+ "Programming Language :: Python :: 3.10",
38
+ "Programming Language :: Python :: 3.11",
39
+ "Programming Language :: Python :: 3.12",
40
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
41
+ "Topic :: Office/Business :: Financial :: Accounting",
42
+ "Topic :: Office/Business :: Financial",
43
+ ]
44
+
45
+ dependencies = [
46
+ "fastapi>=0.136.0",
47
+ "uvicorn>=0.34.2",
48
+ "fastembed>=0.8.0",
49
+ "qdrant-client>=1.13.3",
50
+ "sentence-transformers>=5.4.1",
51
+ "httpx>=0.28.1",
52
+ "httpx-sse>=0.4.3",
53
+ "python-dotenv>=1.1.0",
54
+ "sqlite-utils>=0.38",
55
+ "unstructured>=0.16",
56
+ "pydantic>=2.11",
57
+ "PyMuPDF>=1.25",
58
+ "beautifulsoup4>=4.13",
59
+ "lxml>=5.3",
60
+ "schedule>=1.2",
61
+ "sse-starlette>=2.2",
62
+ "aiofiles>=24.1",
63
+ "orjson>=3.10",
64
+ ]
65
+
66
+ [project.urls]
67
+ Homepage = "https://github.com/eulogik/LexRAG"
68
+ Repository = "https://github.com/eulogik/LexRAG"
69
+ Documentation = "https://github.com/eulogik/LexRAG#readme"
70
+ Changelog = "https://github.com/eulogik/LexRAG/releases"
71
+ Issues = "https://github.com/eulogik/LexRAG/issues"
72
+ Organization = "https://eulogik.com"
73
+ Product = "https://evolucentai.com"
74
+ HuggingFace = "https://huggingface.co/evolucentai"
75
+
76
+ [project.scripts]
77
+ lexrag = "api.main:app"
78
+
79
+ [tool.setuptools]
80
+ packages = ["api", "embeddings", "scripts", "scrapers"]
81
+
82
+ [tool.pytest.ini_options]
83
+ testpaths = ["tests"]
84
+ python_files = ["test_*.py"]
85
+ addopts = "-v --tb=short"
86
+
87
+ [tool.coverage.run]
88
+ source = ["api", "embeddings", "scripts"]
89
+ omit = ["*/tests/*", "*/venv/*"]
requirements.txt ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate
2
+ aiofiles
3
+ aiohappyeyeballs
4
+ aiohttp
5
+ aiosignal
6
+ altair
7
+ annotated-doc
8
+ annotated-types
9
+ anyio
10
+ attrs
11
+ beautifulsoup4
12
+ blinker
13
+ blis
14
+ cachetools
15
+ catalogue
16
+ certifi
17
+ cffi
18
+ charset-normalizer
19
+ click
20
+ click-default-group
21
+ cloudpathlib
22
+ confection
23
+ contourpy
24
+ cryptography
25
+ cycler
26
+ cymem
27
+ dataclasses-json
28
+ Deprecated
29
+ emoji
30
+ et_xmlfile
31
+ fastapi>=0.136.0
32
+ fastembed>=0.8.0
33
+ filelock
34
+ filetype
35
+ flatbuffers
36
+ fonttools
37
+ frozenlist
38
+ fsspec
39
+ gitdb
40
+ GitPython
41
+ google-api-core
42
+ google-auth
43
+ google-cloud-vision
44
+ googleapis-common-protos
45
+ grpcio
46
+ grpcio-status
47
+ grpcio-tools
48
+ h11
49
+ h2
50
+ hf-xet
51
+ hpack
52
+ html5lib
53
+ httpcore
54
+ httpx>=0.28.1
55
+ httpx-sse>=0.4.3
56
+ huggingface_hub
57
+ hyperframe
58
+ idna
59
+ installer
60
+ Jinja2
61
+ joblib
62
+ jsonpatch
63
+ jsonpointer
64
+ jsonschema
65
+ jsonschema-specifications
66
+ kiwisolver
67
+ langchain
68
+ langchain-community
69
+ langchain-core
70
+ langchain-ollama
71
+ langchain-text-splitters
72
+ langdetect
73
+ langsmith
74
+ llvmlite
75
+ loguru
76
+ lxml
77
+ lxml_html_clean
78
+ Markdown
79
+ markdown-it-py
80
+ MarkupSafe
81
+ marshmallow
82
+ matplotlib
83
+ mdurl
84
+ ml_dtypes
85
+ mmh3
86
+ more-itertools
87
+ mpmath
88
+ msoffcrypto-tool
89
+ multidict
90
+ murmurhash
91
+ mypy_extensions
92
+ narwhals
93
+ networkx
94
+ numba
95
+ numpy
96
+ olefile
97
+ ollama
98
+ onnx
99
+ onnxruntime
100
+ openai-whisper
101
+ opencv-python
102
+ openpyxl
103
+ orjson
104
+ packaging
105
+ pandas
106
+ pdf2image
107
+ pdfminer.six
108
+ pi_heif
109
+ pikepdf
110
+ pillow
111
+ pluggy
112
+ portalocker
113
+ preshed
114
+ propcache
115
+ proto-plus
116
+ protobuf
117
+ psutil
118
+ py_rust_stemmers
119
+ pyarrow
120
+ pyasn1
121
+ pyasn1_modules
122
+ pycparser
123
+ pydantic
124
+ pydantic-settings
125
+ pydantic_core
126
+ pydeck
127
+ Pygments
128
+ PyMuPDF
129
+ pypandoc_binary
130
+ pyparsing
131
+ pypdf
132
+ pypdfium2
133
+ python-dateutil
134
+ python-docx
135
+ python-dotenv
136
+ python-iso639
137
+ python-magic
138
+ python-multipart
139
+ python-oxmsg
140
+ python-pptx
141
+ pytz
142
+ PyYAML
143
+ qdrant-client>=1.13.3
144
+ RapidFuzz
145
+ referencing
146
+ regex
147
+ requests
148
+ requests-toolbelt
149
+ rich
150
+ rpds-py
151
+ safetensors
152
+ schedule
153
+ scikit-learn
154
+ scipy
155
+ sentence-transformers>=5.4.1
156
+ shellingham
157
+ six
158
+ smart_open
159
+ smmap
160
+ soupsieve
161
+ spacy
162
+ spacy-legacy
163
+ spacy-loggers
164
+ SQLAlchemy
165
+ sqlite-fts4
166
+ sqlite-utils
167
+ srsly
168
+ sse-starlette
169
+ starlette
170
+ sympy
171
+ tabulate
172
+ tenacity
173
+ thinc
174
+ threadpoolctl
175
+ tiktoken
176
+ timm
177
+ tokenizers
178
+ toml
179
+ torch>=2.11.0
180
+ torchvision>=0.26.0
181
+ tornado
182
+ tqdm
183
+ transformers>=5.5.4
184
+ typer
185
+ typing-inspect
186
+ typing-inspection
187
+ typing_extensions
188
+ tzdata
189
+ unstructured
190
+ unstructured-client
191
+ unstructured.pytesseract
192
+ unstructured_inference
193
+ urllib3
194
+ uuid_utils
195
+ uvicorn>=0.34.2
196
+ wasabi
197
+ weasel
198
+ webencodings
199
+ wrapt
200
+ xlrd
201
+ xlsxwriter
202
+ yarl
203
+ zstandard
scrapers/india_scraper.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ import os
4
+ import sys
5
+ import hashlib
6
+ from dotenv import load_dotenv
7
+
8
+ # Load environment variables from .env file
9
+ load_dotenv()
10
+
11
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
12
+ from scripts.ingest import ingest_text
13
+
14
+ SEEN_HASHES_FILE = os.path.join(os.path.dirname(__file__), "seen_hashes_india.txt")
15
+ INDIAN_KANOON_API = "https://api.indiankanoon.org/search/"
16
+ INDIANKANOON_TOKEN = os.environ.get("INDIANKANOON_TOKEN")
17
+
18
+
19
+ def load_seen():
20
+ if not os.path.exists(SEEN_HASHES_FILE):
21
+ return set()
22
+ with open(SEEN_HASHES_FILE) as f:
23
+ return set(line.strip() for line in f)
24
+
25
+ def save_hash(h: str):
26
+ with open(SEEN_HASHES_FILE, "a") as f:
27
+ f.write(h + "\n")
28
+
29
+ def scrape_cbic_gst():
30
+ """Scrapes CBIC GST circulars and notifications"""
31
+ url = "https://cbic-gst.gov.in/gst-goods-services-rates.html"
32
+ seen = load_seen()
33
+ try:
34
+ resp = requests.get(url, timeout=15, headers={"User-Agent": "Mozilla/5.0"})
35
+ soup = BeautifulSoup(resp.text, "lxml")
36
+ items = soup.find_all(["p", "li", "td"])
37
+ count = 0
38
+ for item in items:
39
+ text = item.get_text(strip=True)
40
+ if len(text) < 50:
41
+ continue
42
+ h = hashlib.md5(text.encode()).hexdigest()
43
+ if h in seen:
44
+ continue
45
+ ingest_text(text, {
46
+ "source": "CBIC GST India",
47
+ "source_type": "ruling",
48
+ "jurisdiction": "India",
49
+ "doc_title": text[:100],
50
+ "date": "scraped",
51
+ "url": url
52
+ })
53
+ save_hash(h)
54
+ count += 1
55
+ print(f"CBIC GST India: {count} new items ingested")
56
+ except Exception as e:
57
+ print(f"CBIC scrape error: {e}")
58
+
59
+ def fetch_indian_kanoon_cases(query: str, num_results: int = 10):
60
+ if not INDIANKANOON_TOKEN:
61
+ print("INDIANKANOON_TOKEN not set. Skip. Get free token at https://api.indiankanoon.org/api/")
62
+ return
63
+ seen = load_seen()
64
+ try:
65
+ resp = requests.post(
66
+ INDIAN_KANOON_API,
67
+ data={"formInput": query, "pagenum": 0},
68
+ headers={"Authorization": f"Token {INDIANKANOON_TOKEN}"},
69
+ timeout=15
70
+ )
71
+ data = resp.json()
72
+ docs = data.get("docs", [])
73
+ count = 0
74
+ for doc in docs[:num_results]:
75
+ text = doc.get("headline", "") + " " + doc.get("title", "")
76
+ if len(text) < 30:
77
+ continue
78
+ h = hashlib.md5(text.encode()).hexdigest()
79
+ if h in seen:
80
+ continue
81
+ ingest_text(text, {
82
+ "source": "Indian Kanoon",
83
+ "source_type": "case",
84
+ "jurisdiction": "India",
85
+ "doc_title": doc.get("title", "")[:100],
86
+ "date": doc.get("publishdate", ""),
87
+ "url": f"https://indiankanoon.org/doc/{doc.get('tid', '')}/"
88
+ })
89
+ save_hash(h)
90
+ count += 1
91
+ print(f"Indian Kanoon [{query}]: {count} new cases ingested")
92
+ except Exception as e:
93
+ print(f"Indian Kanoon error: {e}")
94
+
95
+ if __name__ == "__main__":
96
+ scrape_cbic_gst()
97
+ fetch_indian_kanoon_cases("GST input tax credit")
98
+ fetch_indian_kanoon_cases("income tax section 80C deduction")
99
+ fetch_indian_kanoon_cases("VAT tribunal ruling")
scrapers/uae_scraper.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ from bs4 import BeautifulSoup
3
+ import os
4
+ import sys
5
+ import hashlib
6
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
7
+ from scripts.ingest import ingest_text
8
+
9
+ SEEN_HASHES_FILE = os.path.join(os.path.dirname(__file__), "seen_hashes_uae.txt")
10
+
11
+ def load_seen():
12
+ if not os.path.exists(SEEN_HASHES_FILE):
13
+ return set()
14
+ with open(SEEN_HASHES_FILE) as f:
15
+ return set(line.strip() for line in f)
16
+
17
+ def save_hash(h: str):
18
+ with open(SEEN_HASHES_FILE, "a") as f:
19
+ f.write(h + "\n")
20
+
21
+ def scrape_fta_updates():
22
+ """Scrapes UAE FTA latest announcements page"""
23
+ url = "https://www.tax.gov.ae/en/legislation.aspx"
24
+ seen = load_seen()
25
+ try:
26
+ resp = requests.get(url, timeout=15, headers={"User-Agent": "Mozilla/5.0"})
27
+ soup = BeautifulSoup(resp.text, "lxml")
28
+ items = soup.find_all("a", href=True)
29
+ count = 0
30
+ for item in items:
31
+ text = item.get_text(strip=True)
32
+ if len(text) < 30:
33
+ continue
34
+ h = hashlib.md5(text.encode()).hexdigest()
35
+ if h in seen:
36
+ continue
37
+ ingest_text(text, {
38
+ "source": "FTA UAE",
39
+ "source_type": "ruling",
40
+ "jurisdiction": "UAE",
41
+ "doc_title": text[:100],
42
+ "date": "scraped",
43
+ "url": "https://www.tax.gov.ae" + item["href"]
44
+ })
45
+ save_hash(h)
46
+ count += 1
47
+ print(f"FTA UAE: {count} new items ingested")
48
+ except Exception as e:
49
+ print(f"FTA scrape error: {e}")
50
+
51
+ def scrape_moj_uae():
52
+ """Scrapes UAE Ministry of Justice legislation page"""
53
+ url = "https://uaelegislation.gov.ae/en/legislations"
54
+ seen = load_seen()
55
+ try:
56
+ resp = requests.get(url, timeout=15, headers={"User-Agent": "Mozilla/5.0"})
57
+ soup = BeautifulSoup(resp.text, "lxml")
58
+ links = soup.find_all("a", href=True)
59
+ count = 0
60
+ for link in links:
61
+ text = link.get_text(strip=True)
62
+ if len(text) < 20:
63
+ continue
64
+ h = hashlib.md5(text.encode()).hexdigest()
65
+ if h in seen:
66
+ continue
67
+ ingest_text(text, {
68
+ "source": "UAE Legislation Portal",
69
+ "source_type": "statute",
70
+ "jurisdiction": "UAE",
71
+ "doc_title": text[:100],
72
+ "date": "scraped",
73
+ "url": link["href"] if link["href"].startswith("http") else "https://uaelegislation.gov.ae" + link["href"]
74
+ })
75
+ save_hash(h)
76
+ count += 1
77
+ print(f"MOJ UAE: {count} new items ingested")
78
+ except Exception as e:
79
+ print(f"MOJ UAE scrape error: {e}")
80
+
81
+ if __name__ == "__main__":
82
+ scrape_fta_updates()
83
+ scrape_moj_uae()
scripts/bulk_ingest_pdfs.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
4
+ from scripts.ingest import ingest_pdf
5
+
6
+ RAW_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "data", "raw")
7
+
8
+ JURISDICTION_HINTS = {
9
+ "uae": "UAE", "dubai": "UAE", "adgm": "UAE", "difc": "UAE",
10
+ "fta": "UAE", "cbuae": "UAE",
11
+ "india": "India", "cbic": "India", "gst": "India", "incometax": "India",
12
+ "sebi": "India", "rbi": "India"
13
+ }
14
+ SOURCE_TYPE_HINTS = {
15
+ "act": "statute", "law": "statute", "decree": "statute", "regulation": "statute",
16
+ "case": "case", "judgment": "case", "ruling": "ruling", "circular": "ruling",
17
+ "notification": "ruling", "order": "ruling"
18
+ }
19
+
20
+ def guess_meta(filename: str) -> dict:
21
+ name_lower = filename.lower()
22
+ jurisdiction = "Both"
23
+ for hint, j in JURISDICTION_HINTS.items():
24
+ if hint in name_lower:
25
+ jurisdiction = j
26
+ break
27
+ source_type = "statute"
28
+ for hint, t in SOURCE_TYPE_HINTS.items():
29
+ if hint in name_lower:
30
+ source_type = t
31
+ break
32
+ return {
33
+ "source": "Bulk PDF Import",
34
+ "source_type": source_type,
35
+ "jurisdiction": jurisdiction,
36
+ "doc_title": filename.replace("_", " ").replace(".pdf", ""),
37
+ "date": "imported",
38
+ "url": ""
39
+ }
40
+
41
+ if __name__ == "__main__":
42
+ pdfs = [f for f in os.listdir(RAW_DIR) if f.endswith(".pdf")]
43
+ if not pdfs:
44
+ print(f"No PDFs found in {RAW_DIR}. Drop your PDF files there and rerun.")
45
+ for pdf in pdfs:
46
+ meta = guess_meta(pdf)
47
+ print(f"Processing: {pdf} → jurisdiction={meta['jurisdiction']}, type={meta['source_type']}")
48
+ ingest_pdf(os.path.join(RAW_DIR, pdf), meta)
49
+ print(f"Done. {len(pdfs)} PDFs ingested.")
scripts/daily_update.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import schedule
2
+ import time
3
+ import sys
4
+ import os
5
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
6
+ from scrapers.uae_scraper import scrape_fta_updates, scrape_moj_uae
7
+ from scrapers.india_scraper import scrape_cbic_gst, fetch_indian_kanoon_cases
8
+
9
+ def run_all_scrapers():
10
+ print("=== Daily LexRAG Update Started ===")
11
+ scrape_fta_updates()
12
+ scrape_moj_uae()
13
+ scrape_cbic_gst()
14
+ fetch_indian_kanoon_cases("corporate tax UAE 2024")
15
+ fetch_indian_kanoon_cases("GST input credit")
16
+ fetch_indian_kanoon_cases("income tax penalty")
17
+ fetch_indian_kanoon_cases("VAT exemption")
18
+ print("=== Daily Update Complete ===")
19
+
20
+ run_all_scrapers()
21
+
22
+ schedule.every().day.at("02:00").do(run_all_scrapers)
23
+
24
+ print("Scheduler running. Will update daily at 2 AM. Press Ctrl+C to stop.")
25
+ while True:
26
+ schedule.run_pending()
27
+ time.sleep(60)
scripts/ingest.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from unstructured.partition.pdf import partition_pdf
4
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
5
+ from embeddings.embedder import upsert_document
6
+ import httpx
7
+
8
+ def is_api_running() -> bool:
9
+ try:
10
+ r = httpx.get("http://127.0.0.1:8000/health", timeout=1.0)
11
+ return r.status_code == 200
12
+ except Exception:
13
+ return False
14
+
15
+ def _local_ingest_pdf(filepath: str, metadata: dict, thorough: bool = True):
16
+ print(f"Starting advanced partitioning for {filepath}...")
17
+
18
+ # Partitioning logic
19
+ elements = partition_pdf(
20
+ filename=filepath,
21
+ strategy="hi_res" if thorough else "fast",
22
+ )
23
+
24
+ chunks = []
25
+ current_chunk = ""
26
+ for el in elements:
27
+ if hasattr(el, 'text'):
28
+ if len(current_chunk) + len(el.text) > 2000: # Max chunk size
29
+ chunks.append(current_chunk)
30
+ current_chunk = el.text
31
+ else:
32
+ current_chunk += "\n" + el.text
33
+ if current_chunk:
34
+ chunks.append(current_chunk)
35
+
36
+ print(f"Ingesting {filepath}: {len(chunks)} high-fidelity chunks")
37
+ for i, chunk in enumerate(chunks):
38
+ chunk_meta = {**metadata, "chunk_index": i, "total_chunks": len(chunks), "method": "unstructured"}
39
+ upsert_document(chunk, chunk_meta)
40
+ print(f"Done: {filepath}")
41
+
42
+ def ingest_pdf(filepath: str, metadata: dict, thorough: bool = True):
43
+ """
44
+ Advanced ingestion using unstructured.io for high-fidelity partitioning.
45
+ Routes to API if server is active to prevent lock conflict and double models in memory.
46
+ """
47
+ if is_api_running():
48
+ print(f"API server is active. Routing PDF ingestion for {filepath} through endpoint...")
49
+ try:
50
+ r = httpx.post("http://127.0.0.1:8000/api/ingest/pdf", json={
51
+ "filepath": os.path.abspath(filepath),
52
+ "metadata": metadata,
53
+ "thorough": thorough
54
+ }, timeout=180.0)
55
+ r.raise_for_status()
56
+ print(f"API successfully ingested {filepath}")
57
+ return
58
+ except Exception as e:
59
+ print(f"API Ingestion failed, falling back to local database write: {e}")
60
+
61
+ _local_ingest_pdf(filepath, metadata, thorough)
62
+
63
+ def _local_ingest_text(text: str, metadata: dict):
64
+ # Basic chunking for plain text
65
+ words = text.split()
66
+ chunks = []
67
+ chunk_size = 500
68
+ overlap = 50
69
+ i = 0
70
+ while i < len(words):
71
+ chunk = " ".join(words[i:i+chunk_size])
72
+ chunks.append(chunk)
73
+ i += chunk_size - overlap
74
+
75
+ for i, chunk in enumerate(chunks):
76
+ if len(chunk.strip()) > 100:
77
+ chunk_meta = {**metadata, "chunk_index": i, "total_chunks": len(chunks)}
78
+ upsert_document(chunk, chunk_meta)
79
+
80
+ def ingest_text(text: str, metadata: dict):
81
+ if is_api_running():
82
+ try:
83
+ r = httpx.post("http://127.0.0.1:8000/api/ingest", json={
84
+ "text": text,
85
+ "metadata": metadata
86
+ }, timeout=300.0)
87
+ r.raise_for_status()
88
+ return
89
+ except Exception as e:
90
+ print(f"API Ingestion failed, falling back to local database write: {e}")
91
+
92
+ _local_ingest_text(text, metadata)
93
+
94
+ if __name__ == "__main__":
95
+ # Test ingestion with a sample text
96
+ sample = """
97
+ The UAE Federal Tax Authority (FTA) administers Value Added Tax (VAT)
98
+ at a standard rate of 5% on most goods and services. Corporate Tax was
99
+ introduced in June 2023 at 9% on taxable income exceeding AED 375,000.
100
+ """
101
+ ingest_text(sample, {
102
+ "source": "sample_v2",
103
+ "source_type": "statute",
104
+ "jurisdiction": "UAE",
105
+ "doc_title": "Tax Overview UAE 2024",
106
+ "date": "2024-01-01",
107
+ "url": ""
108
+ })
109
+ print("Sample V2 ingestion complete.")
scripts/ingest_all.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from glob import glob
4
+
5
+ # Add root directory to path to ensure proper imports
6
+ ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
7
+ if ROOT_DIR not in sys.path:
8
+ sys.path.insert(0, ROOT_DIR)
9
+
10
+ from scripts.ingest import ingest_text, ingest_pdf
11
+
12
+ DATA_DIR = os.path.join(ROOT_DIR, "data")
13
+
14
+ def main():
15
+ # Ingest Text Files
16
+ txt_files = glob(os.path.join(DATA_DIR, "**", "*.txt"), recursive=True)
17
+ for f in txt_files:
18
+ print(f"Ingesting text file: {f}")
19
+ with open(f, "r") as r:
20
+ content = r.read()
21
+ # Extract metadata from filename or use defaults
22
+ title = os.path.basename(f).replace(".txt", "").replace("_", " ").title()
23
+ jurisdiction = "India" if "india" in f.lower() else ("UAE" if "uae" in f.lower() else "Both")
24
+ ingest_text(content, {
25
+ "source": os.path.basename(f),
26
+ "source_type": "statute",
27
+ "jurisdiction": jurisdiction,
28
+ "doc_title": title,
29
+ "date": "2024-04-20",
30
+ "url": ""
31
+ })
32
+
33
+ # Ingest PDF Files (if any)
34
+ pdf_files = glob(os.path.join(DATA_DIR, "**", "*.pdf"), recursive=True)
35
+ for f in pdf_files:
36
+ print(f"Ingesting PDF file: {f}")
37
+ title = os.path.basename(f).replace(".pdf", "").replace("_", " ").title()
38
+ jurisdiction = "India" if "india" in f.lower() else ("UAE" if "uae" in f.lower() else "Both")
39
+ ingest_pdf(f, {
40
+ "source": os.path.basename(f),
41
+ "source_type": "statute",
42
+ "jurisdiction": jurisdiction,
43
+ "doc_title": title,
44
+ "date": "2024-04-20",
45
+ "url": ""
46
+ })
47
+
48
+ if __name__ == "__main__":
49
+ main()
settings.json ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "provider": "groq",
3
+ "model": "llama-3.1-8b-instant",
4
+ "jurisdiction_override": null,
5
+ "active_models": {
6
+ "openrouter": [
7
+ "meta-llama/llama-3.3-70b-instruct:free",
8
+ "openrouter/free"
9
+ ],
10
+ "groq": [
11
+ "llama-3.3-70b-versatile",
12
+ "llama-3.1-8b-instant",
13
+ "openai/gpt-oss-20b",
14
+ "openai/gpt-oss-120b"
15
+ ],
16
+ "ollama": []
17
+ },
18
+ "custom_models": {
19
+ "openrouter": [
20
+ {
21
+ "id": "openrouter/free",
22
+ "name": "openrouter:free"
23
+ }
24
+ ],
25
+ "groq": [
26
+ {
27
+ "id": "openai/gpt-oss-20b",
28
+ "name": "GPT-OSS 20B"
29
+ },
30
+ {
31
+ "id": "openai/gpt-oss-120b",
32
+ "name": "GPT-OSS 120B"
33
+ }
34
+ ]
35
+ }
36
+ }
setup.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LexRAG — Legal Intelligence Terminal
3
+ =====================================
4
+ Hybrid RAG (Retrieval-Augmented Generation) system for UAE & Indian law,
5
+ taxation, accounting standards, and corporate compliance.
6
+
7
+ Built by Evolucent AI (https://evolucentai.com)
8
+ Engineered by Eulogik (https://eulogik.com)
9
+ """
10
+ from setuptools import setup, find_packages
11
+
12
+ setup(
13
+ packages=find_packages(),
14
+ include_package_data=True,
15
+ )
tests/__init__.py ADDED
File without changes
tests/test_confidence_tier.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for source confidence tiering."""
2
+
3
+ import sys
4
+ import os
5
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
6
+
7
+ from api.utils import tier_sources
8
+
9
+
10
+ def test_empty_docs_returns_synthesized():
11
+ assert tier_sources([]) == "SYNTHESIZED"
12
+
13
+
14
+ def test_high_score_returns_grounded():
15
+ docs = [{"rerank_score": 0.5}, {"rerank_score": 0.3}]
16
+ assert tier_sources(docs) == "GROUNDED"
17
+
18
+
19
+ def test_medium_score_returns_partial():
20
+ docs = [{"rerank_score": 0.2}, {"rerank_score": 0.15}]
21
+ assert tier_sources(docs) == "PARTIAL"
22
+
23
+
24
+ def test_low_score_returns_synthesized():
25
+ docs = [{"rerank_score": 0.05}]
26
+ assert tier_sources(docs) == "SYNTHESIZED"
27
+
28
+
29
+ def test_fallback_to_score():
30
+ docs = [{"score": 0.5}]
31
+ assert tier_sources(docs) == "GROUNDED"
32
+
33
+
34
+ def test_mixed_scores():
35
+ # max is 0.4 which is NOT > 0.4, so PARTIAL
36
+ docs = [{"rerank_score": 0.1}, {"score": 0.4}]
37
+ assert tier_sources(docs) == "PARTIAL"
tests/test_context_depth.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for auto-context-depth calculation."""
2
+
3
+ import sys
4
+ import os
5
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
6
+
7
+ from api.utils import auto_context_depth
8
+
9
+
10
+ def test_short_simple_query():
11
+ assert auto_context_depth("What is VAT?") == 5
12
+
13
+
14
+ def test_medium_complexity():
15
+ depth = auto_context_depth("What is the GST rate on restaurants under section 7 of CGST Act?")
16
+ assert depth >= 5
17
+
18
+
19
+ def test_complex_legal_query():
20
+ depth = auto_context_depth(
21
+ "Under section 194 of the Income Tax Act, what is the TDS rate for "
22
+ "payments to contractors and how does the recent amendment in the "
23
+ "Finance Act 2023 affect the exemption limit for professional fees?"
24
+ )
25
+ assert depth >= 8
26
+
27
+
28
+ def test_very_long_query():
29
+ long_query = " ".join(["section"] * 20 + ["liability"] * 20 + ["exemption"] * 20)
30
+ assert auto_context_depth(long_query) >= 10
tests/test_embedder.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for embedder module (mocked, no model loading)."""
2
+
3
+ import sys
4
+ import os
5
+ import unittest.mock as mock
6
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
7
+
8
+ from embeddings.embedder import LexEmbedder
9
+
10
+
11
+ def test_collection_name():
12
+ from embeddings.embedder import COLLECTION_NAME
13
+ assert COLLECTION_NAME == "lexrag_docs_v3"
14
+
15
+
16
+ def test_model_names():
17
+ from embeddings.embedder import DENSE_MODEL, SPARSE_MODEL
18
+ assert "bge-small" in DENSE_MODEL
19
+ assert "Splade" in SPARSE_MODEL
20
+
21
+
22
+ def test_get_embedder_caching():
23
+ """Test that get_embedder returns the same instance."""
24
+ from embeddings.embedder import get_embedder
25
+ e1 = get_embedder()
26
+ e2 = get_embedder()
27
+ assert e1 is e2
tests/test_jurisdiction.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for jurisdiction auto-detection."""
2
+
3
+ import sys
4
+ import os
5
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
6
+
7
+ from api.utils import detect_jurisdiction
8
+
9
+
10
+ def test_detect_india():
11
+ assert detect_jurisdiction("What is the GST rate on restaurants?") == "India"
12
+
13
+
14
+ def test_detect_uae():
15
+ assert detect_jurisdiction("What is the VAT rate in Dubai?") == "UAE"
16
+
17
+
18
+ def test_detect_both():
19
+ assert detect_jurisdiction("Compare GST and VAT rates") == "Both"
20
+
21
+
22
+ def test_detect_ambiguous():
23
+ assert detect_jurisdiction("Hello world") == "Both"
24
+
25
+
26
+ def test_india_keyword_tds():
27
+ assert detect_jurisdiction("TDS under section 194J") == "India"
28
+
29
+
30
+ def test_uae_keyword_corporate_tax():
31
+ assert detect_jurisdiction("UAE corporate tax 9% threshold") == "UAE"
32
+
33
+
34
+ def test_india_specific():
35
+ assert detect_jurisdiction("Income Tax Act 1961 section 80C deduction") == "India"
36
+
37
+
38
+ def test_uae_specific():
39
+ assert detect_jurisdiction("Cabinet Decision on VAT refund") == "UAE"
tests/test_think_tags.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for think-tag state machine."""
2
+
3
+ import sys
4
+ import os
5
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
6
+
7
+ from api.utils import strip_think_tags
8
+
9
+
10
+ def test_no_think_tag():
11
+ text = "This is a normal response."
12
+ out, state = strip_think_tags(text, False)
13
+ assert out == text
14
+ assert state is False
15
+
16
+
17
+ def test_simple_think_block():
18
+ text = "Hello <think>internal reasoning</think> world"
19
+ out, state = strip_think_tags(text, False)
20
+ assert out == "Hello world"
21
+ assert state is False
22
+
23
+
24
+ def test_unclosed_think():
25
+ text = "Hello <think>still thinking"
26
+ out, state = strip_think_tags(text, False)
27
+ assert out == "Hello "
28
+ assert state is True
29
+
30
+
31
+ def test_close_in_second_chunk():
32
+ out1, state = strip_think_tags("Hello <think>thinking", False)
33
+ assert out1 == "Hello "
34
+ assert state is True
35
+ out2, state = strip_think_tags(" still thinking</think> world", state)
36
+ assert out2 == " world"
37
+ assert state is False
38
+
39
+
40
+ def test_multiple_think_blocks():
41
+ text = "A<think>hidden</think>B<think>hidden2</think>C"
42
+ out, state = strip_think_tags(text, False)
43
+ assert out == "ABC"
44
+ assert state is False
45
+
46
+
47
+ def test_empty_content():
48
+ out, state = strip_think_tags("", False)
49
+ assert out == ""
50
+ assert state is False
tests/test_utils.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for utility functions."""
2
+
3
+ import sys
4
+ import os
5
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
6
+
7
+ from api.utils import parse_citations, format_score
8
+
9
+
10
+ def test_parse_citations_uae_law():
11
+ result = parse_citations("Under Federal Decree-Law No. 8 of 2017")
12
+ assert "[" in result
13
+ assert "elaws.moj.gov.ae" in result
14
+
15
+
16
+ def test_parse_citations_india_law():
17
+ # "Income Tax Act" needs space between Income and Tax matched
18
+ result = parse_citations("Under the Income-Tax Act, 1961")
19
+ assert "[" in result
20
+ assert "indiankanoon.org" in result
21
+
22
+
23
+ def test_parse_citations_section():
24
+ result = parse_citations("Section 194 of the Act")
25
+ assert "[" in result
26
+
27
+
28
+ def test_no_double_wrapping():
29
+ result = parse_citations("Already [linked](https://example.com) text")
30
+ # Should not double-wrap
31
+
32
+ import re
33
+ # Count the number of markdown links
34
+ links = re.findall(r'\[([^\]]+)\]\(([^\)]+)\)', result)
35
+ # Should have at most 1 link
36
+ assert len(links) >= 1
37
+
38
+
39
+ def test_format_score_high():
40
+ assert format_score(0.9) == "High"
41
+
42
+
43
+ def test_format_score_medium():
44
+ assert format_score(0.6) == "Medium"
45
+
46
+
47
+ def test_format_score_low():
48
+ assert format_score(0.3) == "Low"
49
+
50
+
51
+ def test_format_score_boundary_high():
52
+ # > 0.8 for High, so 0.8 is Medium
53
+ assert format_score(0.8) == "Medium"
54
+
55
+
56
+ def test_format_score_boundary_medium():
57
+ # > 0.5 for Medium, so 0.5 is Low
58
+ assert format_score(0.5) == "Low"
ui/__init__.py ADDED
File without changes
ui/app.js ADDED
@@ -0,0 +1,924 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ // ══ State ════════════════════════════════════════════════════════════════════
4
+ let currentSessionId = genId();
5
+ let currentProvider = 'groq';
6
+ let currentModel = 'llama-3.3-70b-versatile';
7
+ let currentModelLabel = 'Groq · Llama 3.3';
8
+ let jurisdictionOverride = null;
9
+ let isStreaming = false;
10
+ let allModels = {}; // full catalog from /api/models
11
+ let settings = {}; // from /api/settings
12
+
13
+ // ══ Bootstrap ════════════════════════════════════════════════════════════════
14
+ document.addEventListener('DOMContentLoaded', async () => {
15
+ try {
16
+ const [modelsData, settingsData] = await Promise.all([
17
+ api('/api/models'),
18
+ api('/api/settings')
19
+ ]);
20
+ allModels = modelsData;
21
+ settings = settingsData;
22
+
23
+ currentProvider = settings.provider || 'groq';
24
+ currentModel = settings.model || firstModel(currentProvider);
25
+ jurisdictionOverride = settings.jurisdiction_override || null;
26
+
27
+ syncModelLabel();
28
+ renderModelDropdown();
29
+ await refreshSessions();
30
+ } catch (e) {
31
+ console.error('Init failed:', e);
32
+ }
33
+ });
34
+
35
+ // ══ Helpers ══════════════════════════════════════════════════════════════════
36
+ async function api(url, opts = {}) {
37
+ const resp = await fetch(url, opts);
38
+ if (!resp.ok) throw new Error(`${resp.status} ${resp.statusText}`);
39
+ return resp.json();
40
+ }
41
+
42
+ function genId() {
43
+ return 'sess_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
44
+ }
45
+
46
+ function firstModel(provider) {
47
+ const active = (settings.active_models || {})[provider] || [];
48
+ if (active.length) return active[0];
49
+ return (allModels[provider] || [])[0]?.id || null;
50
+ }
51
+
52
+ function providerLabel(p) {
53
+ return { groq: 'Groq', openrouter: 'OpenRouter', ollama: 'Ollama' }[p] || p;
54
+ }
55
+
56
+ function shortModelName(id, name) {
57
+ if (name) return name.split(' ').slice(0, 3).join(' ');
58
+ return id.split('/').pop().split(':')[0];
59
+ }
60
+
61
+ function getActiveModels() {
62
+ const active = settings.active_models || {};
63
+ const result = {};
64
+ for (const [p, catalog] of Object.entries(allModels)) {
65
+ const allowed = new Set(active[p] || catalog.map(m => m.id));
66
+ result[p] = catalog.filter(m => allowed.has(m.id));
67
+ }
68
+ return result;
69
+ }
70
+
71
+ function syncModelLabel() {
72
+ const catalog = (allModels[currentProvider] || []);
73
+ const m = catalog.find(m => m.id === currentModel);
74
+ currentModelLabel =
75
+ providerLabel(currentProvider) + ' · ' + shortModelName(currentModel, m?.name);
76
+ const el = document.getElementById('model-label');
77
+ if (el) el.textContent = currentModelLabel;
78
+ }
79
+
80
+ // ══ Model Dropdown ═══════════════════════════════════════════════════════════
81
+ function renderModelDropdown() {
82
+ const dd = document.getElementById('model-dropdown');
83
+ if (!dd) return;
84
+ dd.innerHTML = '';
85
+
86
+ const activeModels = getActiveModels();
87
+ let hasAny = false;
88
+
89
+ for (const [prov, models] of Object.entries(activeModels)) {
90
+ if (!models.length) continue;
91
+ hasAny = true;
92
+
93
+ const lbl = document.createElement('div');
94
+ lbl.className = 'model-group-label';
95
+ lbl.textContent = providerLabel(prov);
96
+ dd.appendChild(lbl);
97
+
98
+ models.forEach(m => {
99
+ const btn = document.createElement('button');
100
+ btn.className = 'model-option' + (prov === currentProvider && m.id === currentModel ? ' selected' : '');
101
+ btn.textContent = m.name;
102
+ btn.onclick = e => { e.stopPropagation(); selectModel(prov, m.id, m.name); };
103
+ dd.appendChild(btn);
104
+ });
105
+
106
+ const sep = document.createElement('hr');
107
+ sep.className = 'model-separator';
108
+ dd.appendChild(sep);
109
+ }
110
+
111
+ if (!hasAny) {
112
+ dd.innerHTML = '<div class="model-group-label" style="padding:0.75rem">No active models. Enable some in Settings → Models.</div>';
113
+ }
114
+ }
115
+
116
+ function selectModel(provider, modelId, modelName) {
117
+ currentProvider = provider;
118
+ currentModel = modelId;
119
+ currentModelLabel = providerLabel(provider) + ' · ' + shortModelName(modelId, modelName);
120
+ document.getElementById('model-label').textContent = currentModelLabel;
121
+ renderModelDropdown();
122
+ document.getElementById('model-dropdown').classList.add('hidden');
123
+ }
124
+
125
+ function toggleModelDropdown(e) {
126
+ e.stopPropagation();
127
+ document.getElementById('model-dropdown').classList.toggle('hidden');
128
+ }
129
+
130
+ document.addEventListener('click', () => {
131
+ document.getElementById('model-dropdown')?.classList.add('hidden');
132
+ });
133
+
134
+ // ══ Sessions ═════════════════════════════════════════════════════════════════
135
+ async function refreshSessions() {
136
+ try {
137
+ const sessions = await api('/api/sessions');
138
+ renderSessions(sessions);
139
+ } catch (e) { /* silent */ }
140
+ }
141
+
142
+ function renderSessions(sessions) {
143
+ const el = document.getElementById('session-list');
144
+ if (!el) return;
145
+ el.innerHTML = '';
146
+
147
+ if (!sessions || !sessions.length) {
148
+ el.innerHTML = '<div style="padding:.5rem .5rem;font-size:.75rem;color:var(--fg-muted)">No conversations yet</div>';
149
+ return;
150
+ }
151
+
152
+ sessions.forEach(s => {
153
+ const item = document.createElement('div');
154
+ item.className = 'session-item' + (s.session_id === currentSessionId ? ' active' : '');
155
+ item.dataset.id = s.session_id;
156
+
157
+ const name = document.createElement('span');
158
+ name.className = 'session-name';
159
+ name.textContent = s.name || s.preview || s.session_id.slice(0, 10);
160
+ name.title = name.textContent;
161
+
162
+ const del = document.createElement('button');
163
+ del.className = 'session-del';
164
+ del.textContent = '×';
165
+ del.title = 'Delete';
166
+ del.onclick = async ex => {
167
+ ex.stopPropagation();
168
+ await fetch(`/api/sessions/${s.session_id}`, { method: 'DELETE' });
169
+ await refreshSessions();
170
+ if (s.session_id === currentSessionId) newChat();
171
+ };
172
+
173
+ item.onclick = () => loadSession(s.session_id);
174
+ item.appendChild(name);
175
+ item.appendChild(del);
176
+ el.appendChild(item);
177
+ });
178
+ }
179
+
180
+ async function loadSession(id) {
181
+ currentSessionId = id;
182
+ document.querySelectorAll('.session-item').forEach(el =>
183
+ el.classList.toggle('active', el.dataset.id === id));
184
+ clearMessages();
185
+ hideEmpty();
186
+
187
+ try {
188
+ const data = await api(`/api/sessions/${id}`);
189
+ const msgs = data.messages || [];
190
+ let lastUserQuestion = '';
191
+ msgs.forEach(msg => {
192
+ if (msg.role === 'user') {
193
+ appendUserBubble(msg.content);
194
+ lastUserQuestion = msg.content;
195
+ } else {
196
+ const wrap = appendAIBubble();
197
+ const contentEl = wrap.querySelector('.msg-ai-content');
198
+ // Remove cursor before setting text
199
+ contentEl.querySelector('.cursor')?.remove();
200
+
201
+ // Parse JURISDICTION tag if present in history message
202
+ let content = msg.content || '';
203
+ let msgJur = 'Both';
204
+ const jurMatch = content.match(/JURISDICTION:\s*(India|UAE|Both|General)/i);
205
+ if (jurMatch) {
206
+ msgJur = jurMatch[1];
207
+ content = content.replace(/JURISDICTION:\s*(India|UAE|Both|General)/i, '').trim();
208
+ }
209
+
210
+ if (typeof marked !== 'undefined') {
211
+ contentEl.innerHTML = marked.parse(content);
212
+ } else {
213
+ contentEl.textContent = content;
214
+ }
215
+
216
+ const outer = wrap.querySelector('.msg-ai');
217
+ if (outer) outer.dataset.question = lastUserQuestion;
218
+ const sources = Array.isArray(msg.sources) ? msg.sources : [];
219
+ const confidence = sources.length ? 'GROUNDED' : 'SYNTHESIZED';
220
+ renderMetaBar(outer, { sources, confidence, jurisdiction: msgJur });
221
+ }
222
+ });
223
+ scrollBottom();
224
+ } catch (e) {
225
+ console.error('Load session error:', e);
226
+ }
227
+ }
228
+
229
+ function newChat() {
230
+ currentSessionId = genId();
231
+ clearMessages();
232
+ showEmpty();
233
+ document.querySelectorAll('.session-item').forEach(el => el.classList.remove('active'));
234
+ }
235
+
236
+ // ══ Messaging ════════════════════════════════════════════════════════════════
237
+ function handleKey(e) {
238
+ if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); }
239
+ }
240
+
241
+ function useSuggestion(btn) {
242
+ document.getElementById('query-input').value = btn.textContent;
243
+ sendMessage();
244
+ }
245
+
246
+ async function sendMessage() {
247
+ if (isStreaming) return;
248
+
249
+ const input = document.getElementById('query-input');
250
+ const question = input.value.trim();
251
+ if (!question) return;
252
+
253
+ input.value = '';
254
+ autoResize(input);
255
+ hideEmpty();
256
+ isStreaming = true;
257
+ setDisabled(true);
258
+
259
+ // Append user bubble
260
+ appendUserBubble(question);
261
+
262
+ // Append AI bubble with thinking indicator
263
+ const aiWrap = appendAIBubble();
264
+ const outerEl = aiWrap.querySelector('.msg-ai');
265
+ if (outerEl) outerEl.dataset.question = question;
266
+ const contentEl = aiWrap.querySelector('.msg-ai-content');
267
+ const thinkEl = appendThinking(contentEl);
268
+ let thinkGone = false;
269
+
270
+ const removeThink = () => {
271
+ if (!thinkGone) { thinkEl?.remove(); thinkGone = true; }
272
+ };
273
+
274
+ const updateStatus = (text) => {
275
+ const s = contentEl.querySelector('.status-text');
276
+ if (s) s.textContent = text;
277
+ };
278
+
279
+ // absolute safety watchdog (100s)
280
+ const watchdog = setTimeout(() => {
281
+ if (isStreaming) {
282
+ removeThink();
283
+ if (!fullAnswer) {
284
+ contentEl.querySelector('.cursor')?.remove();
285
+ contentEl.textContent = '⚠ Interaction timed out (100s). This could be a connection issue or high server load.';
286
+ }
287
+ finishStreaming();
288
+ }
289
+ }, 100000);
290
+
291
+ let meta = null;
292
+ let fullAnswer = '';
293
+ let sessionName = question.slice(0, 60);
294
+
295
+ try {
296
+ const resp = await fetch('/api/chat', {
297
+ method: 'POST',
298
+ headers: { 'Content-Type': 'application/json' },
299
+ body: JSON.stringify({
300
+ question,
301
+ session_id: currentSessionId,
302
+ provider: currentProvider,
303
+ model: currentModel,
304
+ jurisdiction_override: jurisdictionOverride
305
+ })
306
+ });
307
+
308
+ if (!resp.ok) {
309
+ clearTimeout(watchdog);
310
+ removeThink();
311
+ const err = await resp.text();
312
+ contentEl.querySelector('.cursor')?.remove();
313
+ contentEl.textContent = '⚠ Server error: ' + resp.status + ' - ' + err;
314
+ return finishStreaming();
315
+ }
316
+
317
+ const reader = resp.body.getReader();
318
+ const decoder = new TextDecoder();
319
+ let buf = '';
320
+
321
+ while (true) {
322
+ const { done, value } = await reader.read();
323
+ if (done) break;
324
+ buf += decoder.decode(value, { stream: true });
325
+
326
+ // SSE lines are separated by \n or \r\n
327
+ let lines = buf.split(/\r?\n/);
328
+ buf = lines.pop(); // Keep partial line
329
+
330
+ let evType = null;
331
+ for (const line of lines) {
332
+ const trimmed = line.trim();
333
+ if (!trimmed || trimmed.startsWith(':')) continue; // Ignore empty lines and pings
334
+
335
+ if (trimmed.startsWith('event:')) {
336
+ evType = trimmed.slice(6).trim();
337
+ } else if (trimmed.startsWith('data:')) {
338
+ const dataStr = trimmed.slice(5).trim();
339
+ let data;
340
+ try { data = JSON.parse(dataStr); } catch(e) { continue; }
341
+
342
+ switch (evType) {
343
+ case 'sources':
344
+ meta = data;
345
+ updateStatus('Synthesizing expert legal response...');
346
+ break;
347
+
348
+ case 'token':
349
+ removeThink();
350
+ if (data.content) {
351
+ appendToken(contentEl, data.content);
352
+ fullAnswer += data.content;
353
+ scrollBottom();
354
+ }
355
+ break;
356
+
357
+ case 'done':
358
+ removeThink();
359
+ sessionName = data.session_name || sessionName;
360
+ if (meta) Object.assign(meta, { session_name: sessionName });
361
+ break;
362
+
363
+ case 'error':
364
+ removeThink();
365
+ if (!fullAnswer) {
366
+ contentEl.querySelector('.cursor')?.remove();
367
+ contentEl.textContent = '⚠ ' + (data.content || 'Unknown error');
368
+ }
369
+ break;
370
+ }
371
+ evType = null; // reset for next data block
372
+ }
373
+ }
374
+ }
375
+ } catch (e) {
376
+ removeThink();
377
+ if (!fullAnswer) {
378
+ contentEl.querySelector('.cursor')?.remove();
379
+ contentEl.textContent = '⚠ Network error: ' + e.message;
380
+ }
381
+ }
382
+
383
+ // Finalize bubble
384
+ clearTimeout(watchdog);
385
+ contentEl.querySelector('.cursor')?.remove();
386
+ finalizeAI(aiWrap, meta);
387
+
388
+ await refreshSessions();
389
+ finishStreaming();
390
+ input.focus();
391
+ }
392
+
393
+ function finishStreaming() {
394
+ isStreaming = false;
395
+ setDisabled(false);
396
+ }
397
+
398
+ // ══ DOM Helpers ══════════════════════════════════════════════════════════════
399
+ function appendUserBubble(text) {
400
+ const wrap = document.createElement('div');
401
+ wrap.className = 'message-wrap';
402
+
403
+ const outer = document.createElement('div');
404
+ outer.className = 'msg-user';
405
+
406
+ const bub = document.createElement('div');
407
+ bub.className = 'msg-user-bubble';
408
+ bub.textContent = text;
409
+ outer.appendChild(bub);
410
+
411
+ const actions = document.createElement('div');
412
+ actions.className = 'msg-user-actions';
413
+ const editBtn = document.createElement('button');
414
+ editBtn.className = 'icon-action-btn';
415
+ editBtn.title = 'Edit';
416
+ editBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`;
417
+ editBtn.onclick = () => {
418
+ const input = document.getElementById('query-input');
419
+ input.value = text;
420
+ input.focus();
421
+ autoResize(input);
422
+ };
423
+ actions.appendChild(editBtn);
424
+ outer.appendChild(actions);
425
+
426
+ wrap.appendChild(outer);
427
+ document.getElementById('messages').appendChild(wrap);
428
+ scrollBottom();
429
+ return wrap;
430
+ }
431
+
432
+ function appendAIBubble() {
433
+ const wrap = document.createElement('div');
434
+ wrap.className = 'message-wrap';
435
+ const outer = document.createElement('div');
436
+ outer.className = 'msg-ai';
437
+ const content = document.createElement('div');
438
+ content.className = 'msg-ai-content';
439
+ const cursor = document.createElement('span');
440
+ cursor.className = 'cursor';
441
+ content.appendChild(cursor);
442
+ outer.appendChild(content);
443
+ wrap.appendChild(outer);
444
+ document.getElementById('messages').appendChild(wrap);
445
+ return wrap;
446
+ }
447
+
448
+ function appendThinking(parent) {
449
+ const el = document.createElement('div');
450
+ el.className = 'thinking';
451
+ el.innerHTML = `
452
+ <div class="dots-row">
453
+ <div class="thinking-dot"></div>
454
+ <div class="thinking-dot"></div>
455
+ <div class="thinking-dot"></div>
456
+ </div>
457
+ <div class="status-text">Searching legal archives...</div>
458
+ `;
459
+ parent.prepend(el);
460
+ return el;
461
+ }
462
+
463
+ function appendToken(contentEl, token) {
464
+ const cursor = contentEl.querySelector('.cursor');
465
+ const node = document.createTextNode(token);
466
+ cursor ? contentEl.insertBefore(node, cursor) : contentEl.appendChild(node);
467
+ }
468
+
469
+ function finalizeAI(wrap, meta) {
470
+ const contentEl = wrap.querySelector('.msg-ai-content');
471
+ let content = contentEl ? contentEl.textContent : '';
472
+ let msgJur = meta?.jurisdiction || 'Both';
473
+
474
+ // Parse JURISDICTION tag if present in final text
475
+ const jurMatch = content.match(/JURISDICTION:\s*(India|UAE|Both|General)/i);
476
+ if (jurMatch) {
477
+ msgJur = jurMatch[1];
478
+ content = content.replace(/JURISDICTION:\s*(India|UAE|Both|General)/i, '').trim();
479
+ }
480
+
481
+ if (contentEl) {
482
+ if (typeof marked !== 'undefined') {
483
+ contentEl.innerHTML = marked.parse(content);
484
+ } else {
485
+ contentEl.textContent = content;
486
+ }
487
+ }
488
+
489
+ if (!meta) return;
490
+ const outer = wrap.querySelector('.msg-ai');
491
+ if (outer) {
492
+ meta.jurisdiction = msgJur;
493
+ renderMetaBar(outer, meta);
494
+ }
495
+ }
496
+
497
+ function renderMetaBar(outer, meta) {
498
+ const confidence = meta.confidence || 'GROUNDED';
499
+ const jurisdiction = meta.jurisdiction || 'Both';
500
+ const sources = meta.sources || [];
501
+ const isGeneral = (confidence === 'GENERAL' || confidence === 'SYNTHESIZED');
502
+
503
+ const bar = document.createElement('div');
504
+ bar.className = 'msg-meta';
505
+
506
+ // Confidence badge
507
+ const confMap = {
508
+ GROUNDED: ['badge-grounded', '✓ Verified Sources'],
509
+ PARTIAL: ['badge-partial', '✦ Assisted Research'],
510
+ SYNTHESIZED: ['badge-general', '🗎 Independent Analysis'],
511
+ GENERAL: ['badge-general', '🗎 Independent Analysis']
512
+ };
513
+ const [cls, lbl] = confMap[confidence] || confMap.PARTIAL;
514
+ const confBadge = document.createElement('span');
515
+ confBadge.className = `badge ${cls}`;
516
+ confBadge.textContent = lbl;
517
+ bar.appendChild(confBadge);
518
+
519
+ // Jurisdiction badge
520
+ const jurIcon = { India: '🇮🇳', UAE: '🇦🇪', Both: '🌐', General: '🌐' }[jurisdiction] || '🌐';
521
+ const jurBadge = document.createElement('span');
522
+ jurBadge.className = 'badge-jur';
523
+ jurBadge.textContent = `${jurIcon} ${jurisdiction}`;
524
+ bar.appendChild(jurBadge);
525
+
526
+ // Action buttons group (Copy + Retry) — icon-only ghost
527
+ const actionGroup = document.createElement('div');
528
+ actionGroup.className = 'msg-ai-actions';
529
+
530
+ const copyBtn = document.createElement('button');
531
+ copyBtn.className = 'icon-action-btn';
532
+ copyBtn.title = 'Copy';
533
+ copyBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`;
534
+ copyBtn.onclick = () => {
535
+ const textEl = outer.querySelector('.msg-ai-content');
536
+ const textToCopy = textEl ? textEl.innerText : '';
537
+ navigator.clipboard.writeText(textToCopy).then(() => {
538
+ copyBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`;
539
+ copyBtn.style.color = 'var(--green)';
540
+ setTimeout(() => {
541
+ copyBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>`;
542
+ copyBtn.style.color = '';
543
+ }, 2000);
544
+ });
545
+ };
546
+ actionGroup.appendChild(copyBtn);
547
+
548
+ const retryBtn = document.createElement('button');
549
+ retryBtn.className = 'icon-action-btn';
550
+ retryBtn.title = 'Retry';
551
+ retryBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="1 4 1 10 7 10"/><path d="M3.51 15a9 9 0 1 0 .49-4.96"/></svg>`;
552
+ retryBtn.onclick = () => {
553
+ const question = outer.dataset.question || '';
554
+ if (question) {
555
+ document.getElementById('query-input').value = question;
556
+ sendMessage();
557
+ }
558
+ };
559
+ actionGroup.appendChild(retryBtn);
560
+
561
+ bar.appendChild(actionGroup);
562
+
563
+ outer.appendChild(bar);
564
+
565
+ // Disclaimer (Synthesized only)
566
+ if (isGeneral) {
567
+ const btn = document.createElement('button');
568
+ btn.className = 'disclaimer-btn';
569
+ btn.title = 'Disclaimer';
570
+ btn.textContent = 'ⓘ';
571
+ bar.appendChild(btn);
572
+
573
+ const box = document.createElement('div');
574
+ box.className = 'disclaimer-box';
575
+ box.textContent = 'This response is synthesized from the AI model\'s general knowledge, rather than being retrieved from LexRAG\'s verified document base. It may not reflect the most current statutory provisions. Always consult a qualified legal professional before acting.';
576
+ btn.onclick = () => box.classList.toggle('visible');
577
+ outer.appendChild(box);
578
+ }
579
+
580
+ // Sources toggle
581
+ if (sources.length) {
582
+ const toggle = document.createElement('button');
583
+ toggle.className = 'sources-toggle';
584
+ toggle.textContent = `${sources.length} source${sources.length > 1 ? 's' : ''} ↓`;
585
+ bar.appendChild(toggle);
586
+
587
+ const panel = document.createElement('div');
588
+ panel.className = 'sources-panel';
589
+ sources.forEach(s => {
590
+ const item = document.createElement('div');
591
+ item.className = 'source-item';
592
+ item.innerHTML = `
593
+ <span>${s.title || s.source || 'Source'}</span>
594
+ <span class="badge-jur" style="font-size:.55rem">${s.jurisdiction || ''}</span>
595
+ <span class="source-score">${s.score != null ? s.score.toFixed(2) : ''}</span>
596
+ ${s.url ? `<a href="${s.url}" target="_blank" class="source-link" onclick="event.stopPropagation()">↗</a>` : ''}
597
+ `;
598
+ panel.appendChild(item);
599
+ });
600
+
601
+ toggle.onclick = () => {
602
+ const open = panel.classList.toggle('visible');
603
+ toggle.textContent = `${sources.length} source${sources.length > 1 ? 's' : ''} ${open ? '↑' : '↓'}`;
604
+ };
605
+ outer.appendChild(panel);
606
+ }
607
+ }
608
+
609
+ // ══ Settings ═════════════════════════════════════════════════════════════════
610
+ function openSettings() {
611
+ document.getElementById('settings-overlay').classList.remove('hidden');
612
+ const panel = document.getElementById('settings-panel');
613
+ panel.classList.remove('hidden');
614
+ requestAnimationFrame(() => panel.classList.add('visible'));
615
+ populateSettings();
616
+ }
617
+
618
+ function closeSettings() {
619
+ const panel = document.getElementById('settings-panel');
620
+ panel.classList.remove('visible');
621
+ setTimeout(() => {
622
+ panel.classList.add('hidden');
623
+ document.getElementById('settings-overlay').classList.add('hidden');
624
+ }, 300);
625
+ }
626
+
627
+ function switchSettingsTab(tab, btn) {
628
+ document.querySelectorAll('.stab-content').forEach(el => el.classList.add('hidden'));
629
+ document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
630
+ document.getElementById(`stab-${tab}`).classList.remove('hidden');
631
+ btn.classList.add('active');
632
+ }
633
+
634
+ // ── General Tab ───────────────────────────────────────────────────────────
635
+ function populateSettings() {
636
+ // Provider pills
637
+ const pills = document.getElementById('s-provider-pills');
638
+ if (pills) {
639
+ pills.innerHTML = '';
640
+ ['groq', 'openrouter', 'ollama'].forEach(p => {
641
+ const btn = document.createElement('button');
642
+ btn.className = 'pill-btn' + (p === (settings.provider || currentProvider) ? ' active' : '');
643
+ btn.textContent = providerLabel(p);
644
+ btn.onclick = () => {
645
+ document.querySelectorAll('#s-provider-pills .pill-btn').forEach(b => b.classList.remove('active'));
646
+ btn.classList.add('active');
647
+ populateSettingsModelSelect(p);
648
+ };
649
+ pills.appendChild(btn);
650
+ });
651
+ }
652
+ populateSettingsModelSelect(settings.provider || currentProvider);
653
+
654
+ // Jurisdiction
655
+ document.querySelectorAll('#s-jur-pills button[data-jur]').forEach(btn => {
656
+ const v = btn.dataset.jur === 'null' ? null : btn.dataset.jur;
657
+ btn.classList.toggle('active', v === jurisdictionOverride);
658
+ });
659
+
660
+ // Models tab
661
+ populateModelsTab();
662
+
663
+ // Custom tab
664
+ populateCustomTab();
665
+ }
666
+
667
+ function populateSettingsModelSelect(provider) {
668
+ const sel = document.getElementById('s-model-select');
669
+ if (!sel) return;
670
+ sel.innerHTML = '';
671
+ (allModels[provider] || []).forEach(m => {
672
+ const opt = document.createElement('option');
673
+ opt.value = m.id;
674
+ opt.textContent = m.name;
675
+ opt.selected = m.id === (settings.model || currentModel);
676
+ sel.appendChild(opt);
677
+ });
678
+ }
679
+
680
+ function setJurSetting(btn) {
681
+ document.querySelectorAll('#s-jur-pills button[data-jur]').forEach(b => b.classList.remove('active'));
682
+ btn.classList.add('active');
683
+ jurisdictionOverride = btn.dataset.jur === 'null' ? null : btn.dataset.jur;
684
+ }
685
+
686
+ // ── Models Tab ────────────────────────────────────────────────────────────
687
+ function populateModelsTab() {
688
+ const list = document.getElementById('s-models-list');
689
+ if (!list) return;
690
+ list.innerHTML = '';
691
+
692
+ const activeModels = settings.active_models || {};
693
+
694
+ for (const [prov, models] of Object.entries(allModels)) {
695
+ if (!models.length) continue;
696
+ const group = document.createElement('div');
697
+ group.className = 'model-provider-group';
698
+
699
+ const title = document.createElement('div');
700
+ title.className = 'model-provider-title';
701
+ title.textContent = providerLabel(prov);
702
+ group.appendChild(title);
703
+
704
+ const activeSet = new Set(activeModels[prov] || models.map(m => m.id));
705
+
706
+ models.forEach(m => {
707
+ const row = document.createElement('div');
708
+ row.className = 'model-toggle-row';
709
+
710
+ const nameEl = document.createElement('span');
711
+ nameEl.className = 'model-toggle-name';
712
+ nameEl.textContent = m.name;
713
+
714
+ const idEl = document.createElement('span');
715
+ idEl.className = 'model-toggle-id';
716
+ idEl.textContent = m.id.split('/').pop().split(':')[0];
717
+
718
+ const sw = document.createElement('label');
719
+ sw.className = 'toggle-switch';
720
+ sw.title = activeSet.has(m.id) ? 'Active — click to deactivate' : 'Inactive — click to activate';
721
+
722
+ const inp = document.createElement('input');
723
+ inp.type = 'checkbox';
724
+ inp.checked = activeSet.has(m.id);
725
+ inp.dataset.provider = prov;
726
+ inp.dataset.modelId = m.id;
727
+
728
+ const slider = document.createElement('span');
729
+ slider.className = 'toggle-slider';
730
+
731
+ sw.appendChild(inp);
732
+ sw.appendChild(slider);
733
+
734
+ const delBtn = document.createElement('button');
735
+ delBtn.className = 'model-del-btn';
736
+ delBtn.textContent = '×';
737
+ delBtn.title = 'Remove model';
738
+ delBtn.onclick = () => removeModelFromCatalog(prov, m.id);
739
+
740
+ row.appendChild(nameEl);
741
+ row.appendChild(idEl);
742
+ row.appendChild(sw);
743
+ row.appendChild(delBtn);
744
+ group.appendChild(row);
745
+ });
746
+
747
+ list.appendChild(group);
748
+ }
749
+ }
750
+
751
+ function removeModelFromCatalog(provider, modelId) {
752
+ // Remove from allModels
753
+ if (allModels[provider]) {
754
+ allModels[provider] = allModels[provider].filter(m => m.id !== modelId);
755
+ }
756
+ // Remove from custom_models if present
757
+ const custom = settings.custom_models || {};
758
+ if (custom[provider]) {
759
+ custom[provider] = custom[provider].filter(m => m.id !== modelId);
760
+ }
761
+ // Remove from active_models
762
+ const active = settings.active_models || {};
763
+ if (active[provider]) {
764
+ active[provider] = active[provider].filter(id => id !== modelId);
765
+ }
766
+ settings.custom_models = custom;
767
+ settings.active_models = active;
768
+
769
+ // If removed model was the currently selected one, switch to first available
770
+ if (currentModel === modelId) {
771
+ const remaining = allModels[currentProvider] || [];
772
+ currentModel = remaining[0]?.id || '';
773
+ syncModelLabel();
774
+ renderModelDropdown();
775
+ }
776
+
777
+ saveSettings(true);
778
+ populateSettings();
779
+ }
780
+
781
+ // ── Custom Tab ────────────────────────────────────────────────────────────
782
+ function populateCustomTab() {
783
+ const list = document.getElementById('s-custom-list');
784
+ if (!list) return;
785
+ list.innerHTML = '';
786
+
787
+ const custom = settings.custom_models || {};
788
+ let any = false;
789
+ for (const [prov, models] of Object.entries(custom)) {
790
+ models.forEach(m => {
791
+ any = true;
792
+ const item = document.createElement('div');
793
+ item.className = 'custom-model-item';
794
+ item.innerHTML = `<span>${m.name} <span style="color:var(--fg-muted);font-size:.75rem">(${providerLabel(prov)})</span></span>`;
795
+ const del = document.createElement('button');
796
+ del.className = 'custom-del-btn';
797
+ del.textContent = '×';
798
+ del.onclick = () => removeCustomModel(prov, m.id);
799
+ item.appendChild(del);
800
+ list.appendChild(item);
801
+ });
802
+ }
803
+ if (!any) {
804
+ list.innerHTML = '<div style="padding:1rem 1.5rem;font-size:.8rem;color:var(--fg-muted)">No custom models added yet.</div>';
805
+ }
806
+ }
807
+
808
+ async function addCustomModel() {
809
+ const provider = document.getElementById('c-provider').value;
810
+ const id = document.getElementById('c-model-id').value.trim();
811
+ const name = document.getElementById('c-model-name').value.trim();
812
+ if (!id || !name) { alert('Please enter both Model ID and display name.'); return; }
813
+
814
+ const custom = settings.custom_models || {};
815
+ if (!custom[provider]) custom[provider] = [];
816
+
817
+ // Prevent duplicates
818
+ if (custom[provider].find(m => m.id === id)) { alert('Model already added.'); return; }
819
+ custom[provider].push({ id, name });
820
+
821
+ // Also add to allModels catalog client-side
822
+ if (!allModels[provider]) allModels[provider] = [];
823
+ if (!allModels[provider].find(m => m.id === id)) allModels[provider].push({ id, name });
824
+
825
+ // Activate by default
826
+ const active = settings.active_models || {};
827
+ if (!active[provider]) active[provider] = [];
828
+ if (!active[provider].includes(id)) active[provider].push(id);
829
+
830
+ settings.custom_models = custom;
831
+ settings.active_models = active;
832
+
833
+ document.getElementById('c-model-id').value = '';
834
+ document.getElementById('c-model-name').value = '';
835
+
836
+ // Auto-save and refresh everything
837
+ await saveSettings(true); // pass true to skip closing the panel
838
+ populateSettings(); // Refresh all tabs
839
+ }
840
+
841
+ async function removeCustomModel(provider, modelId) {
842
+ const custom = settings.custom_models || {};
843
+ if (custom[provider]) {
844
+ custom[provider] = custom[provider].filter(m => m.id !== modelId);
845
+ }
846
+ const active = settings.active_models || {};
847
+ if (active[provider]) {
848
+ active[provider] = active[provider].filter(id => id !== modelId);
849
+ }
850
+ if (allModels[provider]) {
851
+ allModels[provider] = allModels[provider].filter(m => m.id !== modelId);
852
+ }
853
+ settings.custom_models = custom;
854
+ settings.active_models = active;
855
+ if (allModels[provider]) {
856
+ allModels[provider] = allModels[provider].filter(m => m.id !== modelId);
857
+ }
858
+
859
+ await saveSettings(true);
860
+ populateSettings();
861
+ }
862
+
863
+ async function saveSettings(skipClose = false) {
864
+ // Read active provider from pills
865
+ const activePill = document.querySelector('#s-provider-pills .pill-btn.active');
866
+ const provLabels = ['groq', 'openrouter', 'ollama'];
867
+ let selProvider = settings.provider || currentProvider;
868
+ if (activePill) {
869
+ const idx = [...document.querySelectorAll('#s-provider-pills .pill-btn')].indexOf(activePill);
870
+ if (idx >= 0) selProvider = provLabels[idx];
871
+ }
872
+
873
+ const selModel = document.getElementById('s-model-select')?.value || currentModel;
874
+
875
+ // Collect active models from toggles
876
+ const activeModels = {};
877
+ document.querySelectorAll('.toggle-switch input[type="checkbox"]').forEach(inp => {
878
+ const prov = inp.dataset.provider;
879
+ const id = inp.dataset.modelId;
880
+ if (!activeModels[prov]) activeModels[prov] = [];
881
+ if (inp.checked) activeModels[prov].push(id);
882
+ });
883
+
884
+ const toSave = {
885
+ provider: selProvider,
886
+ model: selModel,
887
+ jurisdiction_override: jurisdictionOverride,
888
+ active_models: activeModels,
889
+ custom_models: settings.custom_models || {}
890
+ };
891
+
892
+ try {
893
+ const updated = await api('/api/settings', {
894
+ method: 'POST',
895
+ headers: { 'Content-Type': 'application/json' },
896
+ body: JSON.stringify(toSave)
897
+ });
898
+ settings = updated;
899
+ currentProvider = selProvider;
900
+ currentModel = selModel;
901
+ syncModelLabel();
902
+ renderModelDropdown();
903
+ if (!skipClose) closeSettings();
904
+ } catch (e) {
905
+ alert('Failed to save settings: ' + e.message);
906
+ }
907
+ }
908
+
909
+ // ══ Utils ═════════════════════════════════════════════════════════════════════
910
+ function clearMessages() { document.getElementById('messages').innerHTML = ''; }
911
+ function showEmpty() { document.getElementById('empty-state').classList.remove('hidden'); }
912
+ function hideEmpty() { document.getElementById('empty-state').classList.add('hidden'); }
913
+ function scrollBottom() {
914
+ const el = document.getElementById('messages');
915
+ el.scrollTop = el.scrollHeight;
916
+ }
917
+ function setDisabled(v) {
918
+ document.getElementById('send-btn').disabled = v;
919
+ document.getElementById('query-input').disabled = v;
920
+ }
921
+ function autoResize(el) {
922
+ el.style.height = 'auto';
923
+ el.style.height = Math.min(el.scrollHeight, 180) + 'px';
924
+ }
ui/index.html ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>LexRAG — Legal Intelligence Terminal | UAE & India Law AI</title>
7
+ <meta name="description" content="LexRAG is a professional legal research AI for UAE and Indian law, taxation, and compliance. Hybrid RAG with multi-provider LLM streaming.">
8
+ <meta name="keywords" content="legal AI, RAG, UAE law, Indian law, GST, VAT, legal research, compliance, tax AI, retrieval augmented generation">
9
+ <meta property="og:title" content="LexRAG — Legal Intelligence Terminal">
10
+ <meta property="og:description" content="Enterprise hybrid RAG for UAE & Indian law, taxation and compliance.">
11
+ <meta property="og:url" content="https://github.com/eulogik/LexRAG">
12
+ <meta name="author" content="Evolucent AI / Eulogik">
13
+ <link rel="stylesheet" href="/ui/style.css?v=4">
14
+ <link rel="preconnect" href="https://fonts.googleapis.com">
15
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
16
+ <link href="https://fonts.googleapis.com/css2?family=Outfit:wght@300;400;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
17
+ </head>
18
+ <body>
19
+
20
+ <!-- ── SETTINGS PANEL ─────────────────────────────────────────────────────── -->
21
+ <div id="settings-overlay" class="overlay hidden" onclick="closeSettings()"></div>
22
+ <aside id="settings-panel" class="settings-panel hidden">
23
+ <div class="settings-header">
24
+ <span>Settings</span>
25
+ <button class="icon-btn" onclick="closeSettings()">✕</button>
26
+ </div>
27
+
28
+ <!-- Tabs -->
29
+ <div class="settings-tabs">
30
+ <button class="tab-btn active" onclick="switchSettingsTab('general', this)">General</button>
31
+ <button class="tab-btn" onclick="switchSettingsTab('models', this)">Models</button>
32
+ <button class="tab-btn" onclick="switchSettingsTab('custom', this)">Custom</button>
33
+ </div>
34
+
35
+ <!-- General Tab -->
36
+ <div id="stab-general" class="stab-content">
37
+ <div class="settings-section">
38
+ <label class="settings-label">Default Provider</label>
39
+ <div id="s-provider-pills" class="pill-group"></div>
40
+ </div>
41
+ <div class="settings-section">
42
+ <label class="settings-label">Default Model</label>
43
+ <select id="s-model-select" class="select-input"></select>
44
+ </div>
45
+ <div class="settings-section">
46
+ <label class="settings-label">Jurisdiction Lock</label>
47
+ <p class="settings-hint">When set to "Auto", the system detects India/UAE/Both from your query.</p>
48
+ <div class="pill-group" id="s-jur-pills">
49
+ <button class="pill-btn active" data-jur="null" onclick="setJurSetting(this)">Auto-detect</button>
50
+ <button class="pill-btn" data-jur="India" onclick="setJurSetting(this)">🇮🇳 India only</button>
51
+ <button class="pill-btn" data-jur="UAE" onclick="setJurSetting(this)">🇦🇪 UAE only</button>
52
+ <button class="pill-btn" data-jur="Both" onclick="setJurSetting(this)">🌐 Always Both</button>
53
+ </div>
54
+ </div>
55
+ </div>
56
+
57
+ <!-- Models Tab -->
58
+ <div id="stab-models" class="stab-content hidden">
59
+ <div class="settings-section">
60
+ <p class="settings-hint">Toggle which models appear in the chat model selector. At least one must remain active per provider.</p>
61
+ </div>
62
+ <div id="s-models-list"></div>
63
+ </div>
64
+
65
+ <!-- Custom Tab -->
66
+ <div id="stab-custom" class="stab-content hidden">
67
+ <div class="settings-section">
68
+ <label class="settings-label">Add Custom Model</label>
69
+ <p class="settings-hint">Add a model ID from Groq or OpenRouter to your active catalog.</p>
70
+ <div class="form-row">
71
+ <select id="c-provider" class="select-input" style="flex:1">
72
+ <option value="groq">Groq</option>
73
+ <option value="openrouter">OpenRouter</option>
74
+ </select>
75
+ </div>
76
+ <input id="c-model-id" class="text-input" placeholder="Model ID (e.g. llama3-8b-8192)" style="margin-top:.5rem">
77
+ <input id="c-model-name" class="text-input" placeholder="Display name (e.g. Llama 3 8B)" style="margin-top:.5rem">
78
+ <button class="btn-add" onclick="addCustomModel()">Add Model</button>
79
+ </div>
80
+
81
+ <div class="settings-section">
82
+ <label class="settings-label">Custom Models</label>
83
+ <div id="s-custom-list"></div>
84
+ </div>
85
+ </div>
86
+
87
+ <div class="settings-footer">
88
+ <button class="btn-save" onclick="saveSettings()">Save Changes</button>
89
+ </div>
90
+ </aside>
91
+
92
+ <!-- ── MAIN LAYOUT ────────────────────────────────────────────────────────── -->
93
+ <div class="layout">
94
+
95
+ <!-- Sidebar -->
96
+ <nav class="sidebar">
97
+ <div class="sidebar-top">
98
+ <div class="logo">
99
+ <span class="logo-name">LexRAG</span>
100
+ <span class="logo-sub">By <a href="https://evolucentai.com" target="_blank" style="color:inherit;text-decoration:underline;text-decoration-style:dotted;">Evolucent AI</a></span>
101
+ </div>
102
+ <button class="new-chat-btn" onclick="newChat()"><span>+</span> New Chat</button>
103
+ </div>
104
+
105
+ <div class="sidebar-sessions">
106
+ <div class="section-label">Recent</div>
107
+ <div id="session-list"></div>
108
+ </div>
109
+
110
+ <div class="sidebar-bottom">
111
+ <button class="settings-trigger" onclick="openSettings()">
112
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
113
+ <circle cx="12" cy="12" r="3"/>
114
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>
115
+ </svg>
116
+ Settings
117
+ </button>
118
+ </div>
119
+ </nav>
120
+
121
+ <!-- Chat Area -->
122
+ <main class="chat-area">
123
+ <div id="messages" class="messages"></div>
124
+
125
+ <!-- Empty State -->
126
+ <div id="empty-state" class="empty-state">
127
+ <div class="empty-logo">⚖</div>
128
+ <h2>LexRAG</h2>
129
+ <p>Legal intelligence for UAE and Indian law, taxation, and compliance.</p>
130
+ <div class="suggestion-chips">
131
+ <button class="chip" onclick="useSuggestion(this)">GST on online gaming contest prizes</button>
132
+ <button class="chip" onclick="useSuggestion(this)">UAE VAT on financial services</button>
133
+ <button class="chip" onclick="useSuggestion(this)">TDS under Section 194B on winnings</button>
134
+ <button class="chip" onclick="useSuggestion(this)">UAE Corporate Tax free zone treatment</button>
135
+ </div>
136
+ </div>
137
+
138
+ <!-- Input Row -->
139
+ <div class="input-row">
140
+ <div class="input-shell">
141
+ <textarea
142
+ id="query-input"
143
+ class="query-input"
144
+ placeholder="Ask about law, tax, or regulations..."
145
+ rows="1"
146
+ onkeydown="handleKey(event)"
147
+ oninput="autoResize(this)"
148
+ ></textarea>
149
+ <div class="input-controls">
150
+ <div class="model-selector" id="model-selector" onclick="toggleModelDropdown(event)">
151
+ <span id="model-label">Groq · Llama 3.3</span>
152
+ <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
153
+ <div id="model-dropdown" class="model-dropdown hidden"></div>
154
+ </div>
155
+ <button id="send-btn" class="send-btn" onclick="sendMessage()">
156
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
157
+ </button>
158
+ </div>
159
+ </div>
160
+ </div>
161
+ </main>
162
+ </div>
163
+
164
+ <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
165
+ <script src="/ui/app.js?v=3"></script>
166
+ </body>
167
+ </html>
ui/style.css ADDED
@@ -0,0 +1,912 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ── Reset & Tokens ──────────────────────────────────────────────────────── */
2
+ *, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
3
+ button {
4
+ appearance: none;
5
+ -webkit-appearance: none;
6
+ background: transparent;
7
+ border: none;
8
+ cursor: pointer;
9
+ font-family: inherit;
10
+ color: inherit;
11
+ }
12
+
13
+ :root {
14
+ --bg: #000000;
15
+ --bg-2: #050505;
16
+ --bg-3: #0A0A0A;
17
+ --border: #141414;
18
+ --border-soft: #1e1e1e;
19
+ --fg: #ffffff;
20
+ --fg-2: #c0c0c0;
21
+ --fg-muted: #666666;
22
+ --accent: #ffffff;
23
+ --amber: #d97706;
24
+ --green: #22c55e;
25
+ --sidebar-w: 240px;
26
+ --input-h: 60px;
27
+ --radius: 16px;
28
+ --transition: 0.18s cubic-bezier(0.4,0,0.2,1);
29
+ }
30
+
31
+ html, body { height: 100%; overflow: hidden; }
32
+ body {
33
+ background: var(--bg);
34
+ color: var(--fg);
35
+ font-family: 'Outfit', sans-serif;
36
+ font-size: 15px;
37
+ line-height: 1.6;
38
+ -webkit-font-smoothing: antialiased;
39
+ }
40
+
41
+ /* ── Layout ──────────────────────────────────────────────────────────────── */
42
+ .layout {
43
+ display: flex;
44
+ height: 100vh;
45
+ overflow: hidden;
46
+ }
47
+
48
+ /* ── Sidebar ─────────────────────────────────────────────────────────────── */
49
+ .sidebar {
50
+ width: var(--sidebar-w);
51
+ flex-shrink: 0;
52
+ background: var(--bg);
53
+ border-right: 1px solid var(--border);
54
+ display: flex;
55
+ flex-direction: column;
56
+ height: 100%;
57
+ overflow: hidden;
58
+ }
59
+
60
+ .sidebar-top {
61
+ padding: 1.5rem 1rem 1rem;
62
+ border-bottom: 1px solid var(--border);
63
+ }
64
+
65
+ .logo { margin-bottom: 1rem; }
66
+ .logo-name {
67
+ display: block;
68
+ font-size: 1.2rem;
69
+ font-weight: 700;
70
+ letter-spacing: -0.04em;
71
+ }
72
+ .logo-sub {
73
+ display: block;
74
+ font-family: 'JetBrains Mono', monospace;
75
+ font-size: 0.55rem;
76
+ color: var(--fg-muted);
77
+ text-transform: uppercase;
78
+ letter-spacing: 2px;
79
+ margin-top: 2px;
80
+ }
81
+
82
+ .new-chat-btn {
83
+ width: 100%;
84
+ padding: 0.6rem 1rem;
85
+ background: transparent;
86
+ color: var(--fg);
87
+ border: 1px solid var(--border-soft);
88
+ border-radius: 50px;
89
+ font-family: 'Outfit', sans-serif;
90
+ font-size: 0.82rem;
91
+ font-weight: 600;
92
+ cursor: pointer;
93
+ text-align: left;
94
+ display: flex;
95
+ align-items: center;
96
+ gap: 0.5rem;
97
+ transition: all var(--transition);
98
+ }
99
+ .new-chat-btn:hover {
100
+ background: var(--fg);
101
+ color: var(--bg);
102
+ border-color: var(--fg);
103
+ }
104
+ .new-chat-btn span { font-size: 1rem; }
105
+
106
+ .sidebar-sessions {
107
+ flex: 1;
108
+ overflow-y: auto;
109
+ padding: 1rem 0.5rem;
110
+ scrollbar-width: thin;
111
+ scrollbar-color: var(--border) transparent;
112
+ }
113
+ .sidebar-sessions::-webkit-scrollbar { width: 3px; }
114
+ .sidebar-sessions::-webkit-scrollbar-thumb { background: var(--border); }
115
+
116
+ .section-label {
117
+ font-family: 'JetBrains Mono', monospace;
118
+ font-size: 0.55rem;
119
+ color: var(--fg-muted);
120
+ text-transform: uppercase;
121
+ letter-spacing: 2px;
122
+ padding: 0 0.5rem 0.5rem;
123
+ }
124
+
125
+ .session-item {
126
+ display: flex;
127
+ align-items: center;
128
+ gap: 0.3rem;
129
+ padding: 0.55rem 0.6rem;
130
+ border-radius: 10px;
131
+ cursor: pointer;
132
+ transition: background var(--transition);
133
+ group: true;
134
+ }
135
+ .session-item:hover { background: var(--bg-3); }
136
+ .session-item.active { background: var(--bg-3); }
137
+
138
+ .session-name {
139
+ flex: 1;
140
+ font-size: 0.8rem;
141
+ color: var(--fg-2);
142
+ white-space: nowrap;
143
+ overflow: hidden;
144
+ text-overflow: ellipsis;
145
+ max-width: 160px;
146
+ }
147
+ .session-item.active .session-name { color: var(--fg); }
148
+
149
+ .session-del {
150
+ opacity: 0;
151
+ background: none;
152
+ border: none;
153
+ color: var(--fg-muted);
154
+ cursor: pointer;
155
+ font-size: 0.8rem;
156
+ padding: 2px 5px;
157
+ border-radius: 4px;
158
+ transition: opacity var(--transition), color var(--transition);
159
+ }
160
+ .session-item:hover .session-del { opacity: 1; }
161
+ .session-del:hover { color: var(--fg); }
162
+
163
+ .sidebar-bottom {
164
+ padding: 0.75rem 1rem;
165
+ border-top: 1px solid var(--border);
166
+ }
167
+
168
+ .settings-trigger {
169
+ display: flex;
170
+ align-items: center;
171
+ gap: 0.5rem;
172
+ background: none;
173
+ border: none;
174
+ color: var(--fg-muted);
175
+ font-family: 'Outfit', sans-serif;
176
+ font-size: 0.82rem;
177
+ cursor: pointer;
178
+ padding: 0.4rem 0;
179
+ transition: color var(--transition);
180
+ }
181
+ .settings-trigger:hover { color: var(--fg); }
182
+
183
+ /* ── Chat Area ───────────────────────────────────────────────────────────── */
184
+ .chat-area {
185
+ flex: 1;
186
+ display: flex;
187
+ flex-direction: column;
188
+ height: 100%;
189
+ overflow: hidden;
190
+ position: relative;
191
+ }
192
+
193
+ .messages {
194
+ flex: 1;
195
+ overflow-y: auto;
196
+ padding: 2rem 0;
197
+ scroll-behavior: smooth;
198
+ scrollbar-width: thin;
199
+ scrollbar-color: var(--border) transparent;
200
+ }
201
+ .messages::-webkit-scrollbar { width: 4px; }
202
+ .messages::-webkit-scrollbar-thumb { background: var(--border); }
203
+
204
+ /* ── Empty State ─────────────────────────────────────────────────────────── */
205
+ .empty-state {
206
+ position: absolute;
207
+ top: 50%;
208
+ left: 50%;
209
+ transform: translate(-50%, -60%);
210
+ text-align: center;
211
+ pointer-events: none;
212
+ }
213
+ .empty-state.hidden { display: none; }
214
+ .empty-logo {
215
+ font-size: 2.5rem;
216
+ margin-bottom: 1rem;
217
+ filter: grayscale(1) opacity(0.5);
218
+ }
219
+ .empty-state h2 {
220
+ font-size: 1.8rem;
221
+ font-weight: 700;
222
+ letter-spacing: -0.04em;
223
+ margin-bottom: 0.5rem;
224
+ }
225
+ .empty-state p {
226
+ font-size: 0.9rem;
227
+ color: var(--fg-muted);
228
+ max-width: 380px;
229
+ margin: 0 auto 2rem;
230
+ }
231
+ .suggestion-chips {
232
+ display: flex;
233
+ flex-wrap: wrap;
234
+ gap: 0.5rem;
235
+ justify-content: center;
236
+ pointer-events: all;
237
+ }
238
+ .chip {
239
+ background: transparent;
240
+ border: 1px solid var(--border-soft);
241
+ color: var(--fg-2);
242
+ padding: 0.5rem 1rem;
243
+ border-radius: 50px;
244
+ font-family: 'Outfit', sans-serif;
245
+ font-size: 0.78rem;
246
+ cursor: pointer;
247
+ transition: all var(--transition);
248
+ }
249
+ .chip:hover { background: var(--fg); color: var(--bg); border-color: var(--fg); }
250
+
251
+ /* ── Message Bubbles ──────────────────────────────────────────────────────── */
252
+ .message-wrap {
253
+ max-width: 760px;
254
+ margin: 0 auto;
255
+ padding: 0 2rem;
256
+ width: 100%;
257
+ }
258
+
259
+ .msg-user {
260
+ margin: 1.5rem 0;
261
+ display: flex;
262
+ flex-direction: column;
263
+ align-items: flex-end;
264
+ gap: 0.35rem;
265
+ }
266
+ .msg-user-bubble {
267
+ background: var(--bg-3);
268
+ border: 1px solid var(--border-soft);
269
+ padding: 0.9rem 1.3rem;
270
+ border-radius: 20px 20px 5px 20px;
271
+ max-width: 75%;
272
+ font-size: 0.98rem;
273
+ line-height: 1.55;
274
+ color: var(--fg);
275
+ word-wrap: break-word;
276
+ }
277
+
278
+ .msg-ai {
279
+ margin: 1.5rem 0;
280
+ }
281
+ .msg-ai-content {
282
+ font-size: 0.98rem;
283
+ line-height: 1.75;
284
+ color: var(--fg-2);
285
+ padding: 0.25rem 0;
286
+ white-space: pre-wrap;
287
+ word-wrap: break-word;
288
+ }
289
+ .msg-ai-content p { margin-bottom: 0.6em; }
290
+ .msg-ai-content h3, .msg-ai-content h4 { color: var(--fg); margin: 1em 0 0.3em; }
291
+ .msg-ai-content strong { color: var(--fg); }
292
+ .msg-ai-content a { color: var(--fg-2); text-underline-offset: 3px; }
293
+
294
+ /* Streaming cursor */
295
+ .cursor {
296
+ display: inline-block;
297
+ width: 2px;
298
+ height: 1em;
299
+ background: var(--fg-muted);
300
+ margin-left: 2px;
301
+ animation: blink 0.8s step-end infinite;
302
+ vertical-align: text-bottom;
303
+ }
304
+ @keyframes blink { 50% { opacity: 0; } }
305
+
306
+ /* ── Message Meta Bar ────────────────────────────────────────────────────── */
307
+ .msg-meta {
308
+ display: flex;
309
+ align-items: center;
310
+ gap: 0.5rem;
311
+ margin-top: 0.9rem;
312
+ flex-wrap: nowrap;
313
+ overflow: visible;
314
+ }
315
+
316
+ .badge {
317
+ font-family: 'JetBrains Mono', monospace;
318
+ font-size: 0.6rem;
319
+ letter-spacing: 1px;
320
+ text-transform: uppercase;
321
+ padding: 3px 9px;
322
+ border-radius: 50px;
323
+ border: 1px solid;
324
+ }
325
+ .badge-grounded { border-color: rgba(34,197,94,0.3); color: #22c55e; }
326
+ .badge-partial { border-color: var(--border-soft); color: var(--fg-muted); }
327
+ .badge-general { border-color: rgba(217,119,6,0.35); color: var(--amber); }
328
+
329
+ .badge-jur {
330
+ font-family: 'JetBrains Mono', monospace;
331
+ font-size: 0.6rem;
332
+ letter-spacing: 1px;
333
+ text-transform: uppercase;
334
+ padding: 3px 9px;
335
+ border-radius: 50px;
336
+ border: 1px solid var(--border-soft);
337
+ color: var(--fg-muted);
338
+ }
339
+
340
+ .disclaimer-btn {
341
+ background: none;
342
+ border: none;
343
+ color: var(--amber);
344
+ cursor: pointer;
345
+ font-size: 0.75rem;
346
+ padding: 0 4px;
347
+ line-height: 1;
348
+ transition: opacity var(--transition);
349
+ }
350
+ .disclaimer-btn:hover { opacity: 0.7; }
351
+
352
+ .disclaimer-box {
353
+ margin-top: 0.75rem;
354
+ padding: 0.75rem 1rem;
355
+ background: rgba(217,119,6,0.05);
356
+ border: 1px solid rgba(217,119,6,0.2);
357
+ border-radius: 10px;
358
+ font-size: 0.82rem;
359
+ color: var(--amber);
360
+ line-height: 1.5;
361
+ display: none;
362
+ }
363
+ .disclaimer-box.visible { display: block; }
364
+
365
+ /* Sources toggle */
366
+ .sources-toggle {
367
+ background: none;
368
+ border: none;
369
+ color: var(--fg-muted);
370
+ font-family: 'JetBrains Mono', monospace;
371
+ font-size: 0.6rem;
372
+ letter-spacing: 1px;
373
+ text-transform: uppercase;
374
+ cursor: pointer;
375
+ padding: 3px 9px;
376
+ border-radius: 50px;
377
+ border: 1px solid var(--border);
378
+ transition: all var(--transition);
379
+ margin-left: auto;
380
+ }
381
+ .sources-toggle:hover { color: var(--fg); border-color: var(--border-soft); }
382
+
383
+ .sources-panel {
384
+ margin-top: 0.75rem;
385
+ display: none;
386
+ flex-direction: column;
387
+ gap: 0.4rem;
388
+ }
389
+ .sources-panel.visible { display: flex; }
390
+
391
+ .source-item {
392
+ display: flex;
393
+ align-items: center;
394
+ gap: 0.5rem;
395
+ padding: 0.5rem 0.75rem;
396
+ background: var(--bg-2);
397
+ border: 1px solid var(--border);
398
+ border-radius: 8px;
399
+ font-size: 0.78rem;
400
+ color: var(--fg-2);
401
+ }
402
+ .source-score {
403
+ font-family: 'JetBrains Mono', monospace;
404
+ font-size: 0.6rem;
405
+ color: var(--fg-muted);
406
+ margin-left: auto;
407
+ }
408
+ .source-link {
409
+ color: var(--fg-muted);
410
+ text-decoration: none;
411
+ font-size: 0.7rem;
412
+ }
413
+ .source-link:hover { color: var(--fg); }
414
+
415
+ /* ── Input Row ───────────────────────────────────────────────────────────── */
416
+ .input-row {
417
+ padding: 1rem 2rem 1.5rem;
418
+ border-top: 1px solid var(--border);
419
+ max-width: 800px;
420
+ width: 100%;
421
+ margin: 0 auto;
422
+ }
423
+
424
+ .input-shell {
425
+ display: flex;
426
+ align-items: flex-end;
427
+ gap: 0;
428
+ background: var(--bg-2);
429
+ border: 1px solid var(--border-soft);
430
+ border-radius: 20px;
431
+ padding: 0.75rem 0.75rem 0.75rem 1.25rem;
432
+ transition: border-color var(--transition);
433
+ }
434
+ .input-shell:focus-within { border-color: rgba(255,255,255,0.15); }
435
+
436
+ .query-input {
437
+ flex: 1;
438
+ background: none;
439
+ border: none;
440
+ outline: none;
441
+ color: var(--fg);
442
+ font-family: 'Outfit', sans-serif;
443
+ font-size: 0.95rem;
444
+ resize: none;
445
+ max-height: 180px;
446
+ line-height: 1.5;
447
+ padding: 0;
448
+ padding-top: 3px;
449
+ }
450
+ .query-input::placeholder { color: var(--fg-muted); }
451
+ .query-input:disabled { opacity: 0.5; }
452
+
453
+ .input-controls {
454
+ display: flex;
455
+ align-items: center;
456
+ gap: 0.4rem;
457
+ flex-shrink: 0;
458
+ padding-left: 0.6rem;
459
+ }
460
+
461
+ /* Model Selector */
462
+ .model-selector {
463
+ display: flex;
464
+ align-items: center;
465
+ gap: 0.3rem;
466
+ background: var(--bg-3);
467
+ border: 1px solid var(--border-soft);
468
+ border-radius: 50px;
469
+ padding: 0.35rem 0.75rem;
470
+ font-size: 0.72rem;
471
+ font-weight: 600;
472
+ color: var(--fg-2);
473
+ cursor: pointer;
474
+ position: relative;
475
+ user-select: none;
476
+ white-space: nowrap;
477
+ transition: all var(--transition);
478
+ }
479
+ .model-selector:hover { border-color: rgba(255,255,255,0.15); color: var(--fg); }
480
+
481
+ .model-dropdown {
482
+ position: absolute;
483
+ bottom: calc(100% + 8px);
484
+ right: 0;
485
+ background: var(--bg-2);
486
+ border: 1px solid var(--border-soft);
487
+ border-radius: 14px;
488
+ padding: 0.5rem;
489
+ min-width: 220px;
490
+ z-index: 100;
491
+ box-shadow: 0 8px 32px rgba(0,0,0,0.6);
492
+ }
493
+ .model-dropdown.hidden { display: none; }
494
+
495
+ .model-group-label {
496
+ font-family: 'JetBrains Mono', monospace;
497
+ font-size: 0.55rem;
498
+ color: var(--fg-muted);
499
+ text-transform: uppercase;
500
+ letter-spacing: 2px;
501
+ padding: 0.4rem 0.6rem 0.25rem;
502
+ }
503
+ .model-option {
504
+ display: block;
505
+ width: 100%;
506
+ background: none;
507
+ border: none;
508
+ color: var(--fg-2);
509
+ font-family: 'Outfit', sans-serif;
510
+ font-size: 0.82rem;
511
+ text-align: left;
512
+ padding: 0.45rem 0.6rem;
513
+ border-radius: 8px;
514
+ cursor: pointer;
515
+ transition: all var(--transition);
516
+ }
517
+ .model-option:hover { background: var(--bg-3); color: var(--fg); }
518
+ .model-option.selected { color: var(--fg); background: var(--bg-3); }
519
+ .model-separator { border: none; border-top: 1px solid var(--border); margin: 0.4rem 0; }
520
+
521
+ .send-btn {
522
+ width: 38px;
523
+ height: 38px;
524
+ background: var(--fg);
525
+ color: var(--bg);
526
+ border: none;
527
+ border-radius: 50%;
528
+ cursor: pointer;
529
+ display: flex;
530
+ align-items: center;
531
+ justify-content: center;
532
+ flex-shrink: 0;
533
+ transition: all var(--transition);
534
+ }
535
+ .send-btn:hover { transform: scale(1.06); }
536
+ .send-btn:disabled { opacity: 0.4; cursor: not-allowed; transform: none; }
537
+
538
+ /* ── Settings Panel ──────────────────────────────────────────────────────── */
539
+ .overlay {
540
+ position: fixed; inset: 0;
541
+ background: rgba(0,0,0,0.5);
542
+ backdrop-filter: blur(4px);
543
+ z-index: 50;
544
+ }
545
+ .overlay.hidden { display: none; }
546
+
547
+ .settings-panel {
548
+ position: fixed;
549
+ right: 0; top: 0; bottom: 0;
550
+ width: 340px;
551
+ background: var(--bg-2);
552
+ border-left: 1px solid var(--border-soft);
553
+ z-index: 51;
554
+ display: flex;
555
+ flex-direction: column;
556
+ transform: translateX(100%);
557
+ transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1);
558
+ }
559
+ .settings-panel.visible { transform: translateX(0); }
560
+ .settings-panel.hidden { display: none; }
561
+
562
+ .settings-header {
563
+ display: flex;
564
+ align-items: center;
565
+ justify-content: space-between;
566
+ padding: 1.5rem;
567
+ border-bottom: 1px solid var(--border);
568
+ }
569
+ .mono-tag {
570
+ font-family: 'JetBrains Mono', monospace;
571
+ font-size: 0.65rem;
572
+ text-transform: uppercase;
573
+ letter-spacing: 2px;
574
+ color: var(--fg-muted);
575
+ }
576
+
577
+ .icon-btn {
578
+ background: none;
579
+ border: none;
580
+ color: var(--fg-muted);
581
+ cursor: pointer;
582
+ font-size: 1rem;
583
+ padding: 4px;
584
+ transition: color var(--transition);
585
+ }
586
+ .icon-btn:hover { color: var(--fg); }
587
+
588
+ .settings-section {
589
+ padding: 1.5rem;
590
+ border-bottom: 1px solid var(--border);
591
+ }
592
+ .settings-label {
593
+ display: block;
594
+ font-family: 'JetBrains Mono', monospace;
595
+ font-size: 0.6rem;
596
+ text-transform: uppercase;
597
+ letter-spacing: 1.5px;
598
+ color: var(--fg-muted);
599
+ margin-bottom: 0.75rem;
600
+ }
601
+
602
+ .pill-group {
603
+ display: flex;
604
+ flex-wrap: wrap;
605
+ gap: 0.4rem;
606
+ }
607
+ .pill-btn {
608
+ background: transparent;
609
+ border: 1px solid var(--border-soft);
610
+ color: var(--fg-2);
611
+ padding: 0.4rem 0.9rem;
612
+ border-radius: 50px;
613
+ font-family: 'Outfit', sans-serif;
614
+ font-size: 0.78rem;
615
+ cursor: pointer;
616
+ transition: all var(--transition);
617
+ }
618
+ .pill-btn.active, .pill-btn:hover { background: var(--fg); color: var(--bg); border-color: var(--fg); }
619
+
620
+ .select-input {
621
+ width: 100%;
622
+ background: var(--bg-3);
623
+ border: 1px solid var(--border-soft);
624
+ color: var(--fg);
625
+ padding: 0.6rem 1rem;
626
+ border-radius: 10px;
627
+ font-family: 'Outfit', sans-serif;
628
+ font-size: 0.85rem;
629
+ outline: none;
630
+ cursor: pointer;
631
+ }
632
+
633
+ .settings-footer {
634
+ padding: 1.5rem;
635
+ margin-top: auto;
636
+ }
637
+ .btn-save {
638
+ width: 100%;
639
+ background: var(--fg);
640
+ color: var(--bg);
641
+ border: none;
642
+ padding: 0.85rem;
643
+ border-radius: 50px;
644
+ font-family: 'Outfit', sans-serif;
645
+ font-size: 0.9rem;
646
+ font-weight: 700;
647
+ cursor: pointer;
648
+ transition: all var(--transition);
649
+ }
650
+ .btn-save:hover { opacity: 0.9; transform: scale(1.01); }
651
+
652
+ /* ── Utility ─────────────────────────────────────────────────────────────── */
653
+ .hidden { display: none !important; }
654
+
655
+ /* Thinking Indicator */
656
+ .thinking {
657
+ display: flex;
658
+ flex-direction: column;
659
+ gap: 0.5rem;
660
+ padding: 0.25rem 0.5rem;
661
+ }
662
+ .dots-row {
663
+ display: flex;
664
+ gap: 6px;
665
+ }
666
+ .thinking-dot {
667
+ width: 5px;
668
+ height: 5px;
669
+ background: var(--fg);
670
+ border-radius: 50%;
671
+ animation: blink 1.4s infinite both;
672
+ opacity: 0.3;
673
+ }
674
+ .status-text {
675
+ font-family: 'JetBrains Mono', monospace;
676
+ font-size: 0.72rem;
677
+ color: var(--fg-muted);
678
+ letter-spacing: 0.5px;
679
+ }
680
+ @keyframes blink {
681
+ 0% { opacity: 0.2; transform: scale(0.9); }
682
+ 20% { opacity: 1; transform: scale(1.1); }
683
+ 100% { opacity: 0.2; transform: scale(0.9); }
684
+ }
685
+ .thinking-dot:nth-child(2) { animation-delay: 0.2s; }
686
+ .thinking-dot:nth-child(3) { animation-delay: 0.4s; }
687
+ @keyframes bounce {
688
+ 0%,80%,100% { transform: translateY(0); opacity: 0.4; }
689
+ 40% { transform: translateY(-6px); opacity: 1; }
690
+ }
691
+
692
+ /* Responsive */
693
+ @media (max-width: 640px) {
694
+ .sidebar { display: none; }
695
+ .message-wrap { padding: 0 1rem; }
696
+ .input-row { padding: 0.75rem 1rem 1.25rem; }
697
+ }
698
+
699
+ /* ── Settings Tabs ───────────────────────────────────────────────────────── */
700
+ .settings-header {
701
+ font-weight: 600;
702
+ font-size: 0.95rem;
703
+ }
704
+
705
+ .settings-tabs {
706
+ display: flex;
707
+ border-bottom: 1px solid var(--border);
708
+ padding: 0 1rem;
709
+ }
710
+ .tab-btn {
711
+ background: none;
712
+ border: none;
713
+ color: var(--fg-muted);
714
+ font-family: 'Outfit', sans-serif;
715
+ font-size: 0.82rem;
716
+ padding: 0.75rem 0.75rem;
717
+ cursor: pointer;
718
+ border-bottom: 2px solid transparent;
719
+ margin-bottom: -1px;
720
+ transition: all var(--transition);
721
+ }
722
+ .tab-btn:hover { color: var(--fg); }
723
+ .tab-btn.active { color: var(--fg); border-bottom-color: var(--fg); }
724
+
725
+ .stab-content {
726
+ flex: 1;
727
+ overflow-y: auto;
728
+ scrollbar-width: thin;
729
+ scrollbar-color: var(--border) transparent;
730
+ }
731
+
732
+ /* ── Settings hints & form ───────────────────────────────────────────────── */
733
+ .settings-hint {
734
+ font-size: 0.78rem;
735
+ color: var(--fg-muted);
736
+ margin-bottom: 0.75rem;
737
+ line-height: 1.5;
738
+ }
739
+
740
+ .text-input {
741
+ width: 100%;
742
+ background: var(--bg-3);
743
+ border: 1px solid var(--border-soft);
744
+ color: var(--fg);
745
+ padding: 0.55rem 0.9rem;
746
+ border-radius: 10px;
747
+ font-family: 'Outfit', sans-serif;
748
+ font-size: 0.85rem;
749
+ outline: none;
750
+ }
751
+ .text-input:focus { border-color: rgba(255,255,255,0.2); }
752
+ .text-input::placeholder { color: var(--fg-muted); }
753
+
754
+ .form-row {
755
+ display: flex;
756
+ gap: 0.5rem;
757
+ }
758
+
759
+ .btn-add {
760
+ width: 100%;
761
+ margin-top: 0.75rem;
762
+ background: transparent;
763
+ color: var(--fg);
764
+ border: 1px solid var(--border-soft);
765
+ border-radius: 50px;
766
+ padding: 0.55rem;
767
+ font-family: 'Outfit', sans-serif;
768
+ font-size: 0.82rem;
769
+ cursor: pointer;
770
+ transition: all var(--transition);
771
+ }
772
+ .btn-add:hover { background: var(--fg); color: var(--bg); }
773
+
774
+ /* ── Model Toggle Rows ───────────────────────────────────────────────────── */
775
+ .model-provider-group {
776
+ padding: 1rem 1.5rem 0;
777
+ }
778
+ .model-provider-title {
779
+ font-family: 'JetBrains Mono', monospace;
780
+ font-size: 0.6rem;
781
+ color: var(--fg-muted);
782
+ text-transform: uppercase;
783
+ letter-spacing: 2px;
784
+ margin-bottom: 0.5rem;
785
+ }
786
+ .model-toggle-row {
787
+ display: flex;
788
+ align-items: center;
789
+ justify-content: space-between;
790
+ padding: 0.55rem 0;
791
+ border-bottom: 1px solid var(--border);
792
+ }
793
+ .model-toggle-row:last-child { border-bottom: none; }
794
+ .model-toggle-name {
795
+ font-size: 0.82rem;
796
+ color: var(--fg-2);
797
+ flex: 1;
798
+ }
799
+ .model-toggle-id {
800
+ font-family: 'JetBrains Mono', monospace;
801
+ font-size: 0.6rem;
802
+ color: var(--fg-muted);
803
+ margin-right: 0.75rem;
804
+ }
805
+ .model-del-btn {
806
+ opacity: 0.25;
807
+ color: var(--fg-muted);
808
+ font-size: 1rem;
809
+ line-height: 1;
810
+ padding: 2px 6px;
811
+ border-radius: 5px;
812
+ margin-left: 0.5rem;
813
+ transition: all var(--transition);
814
+ flex-shrink: 0;
815
+ }
816
+ .model-toggle-row:hover .model-del-btn { opacity: 1; }
817
+ .model-del-btn:hover { color: #f87171; background: rgba(248,113,113,0.08); }
818
+
819
+ /* Toggle Switch */
820
+ .toggle-switch {
821
+ position: relative;
822
+ width: 34px;
823
+ height: 18px;
824
+ flex-shrink: 0;
825
+ }
826
+ .toggle-switch input { opacity: 0; width: 0; height: 0; }
827
+ .toggle-slider {
828
+ position: absolute;
829
+ inset: 0;
830
+ background: var(--border-soft);
831
+ border-radius: 18px;
832
+ cursor: pointer;
833
+ transition: background var(--transition);
834
+ }
835
+ .toggle-slider::before {
836
+ content: '';
837
+ position: absolute;
838
+ width: 12px; height: 12px;
839
+ left: 3px; top: 3px;
840
+ background: var(--fg-muted);
841
+ border-radius: 50%;
842
+ transition: all var(--transition);
843
+ }
844
+ .toggle-switch input:checked + .toggle-slider { background: rgba(255,255,255,0.15); }
845
+ .toggle-switch input:checked + .toggle-slider::before {
846
+ background: var(--fg);
847
+ transform: translateX(16px);
848
+ }
849
+
850
+ /* Custom model list */
851
+ .custom-model-item {
852
+ display: flex;
853
+ align-items: center;
854
+ justify-content: space-between;
855
+ padding: 0.5rem 1.5rem;
856
+ border-bottom: 1px solid var(--border);
857
+ font-size: 0.82rem;
858
+ color: var(--fg-2);
859
+ }
860
+ .custom-del-btn {
861
+ background: none;
862
+ border: none;
863
+ color: var(--fg-muted);
864
+ cursor: pointer;
865
+ padding: 2px 6px;
866
+ border-radius: 4px;
867
+ transition: color var(--transition);
868
+ }
869
+ .custom-del-btn:hover { color: var(--fg); }
870
+
871
+ /* Icon Ghost Action Buttons (Copy, Retry, Edit) */
872
+ .icon-action-btn {
873
+ display: inline-flex;
874
+ align-items: center;
875
+ justify-content: center;
876
+ width: 28px;
877
+ height: 28px;
878
+ border-radius: 7px;
879
+ color: var(--fg-muted);
880
+ transition: color var(--transition), background var(--transition);
881
+ flex-shrink: 0;
882
+ }
883
+ .icon-action-btn:hover {
884
+ color: var(--fg);
885
+ background: rgba(255,255,255,0.06);
886
+ }
887
+ .icon-action-btn svg { display: block; }
888
+
889
+ /* AI action buttons row — appears on hover of the AI message */
890
+ .msg-ai-actions {
891
+ display: flex;
892
+ align-items: center;
893
+ gap: 0.1rem;
894
+ opacity: 0;
895
+ transition: opacity var(--transition);
896
+ margin-left: auto;
897
+ }
898
+ .msg-ai:hover .msg-ai-actions,
899
+ .msg-meta:hover .msg-ai-actions {
900
+ opacity: 1;
901
+ }
902
+
903
+ /* User bubble action buttons row — appears on hover */
904
+ .msg-user-actions {
905
+ display: flex;
906
+ gap: 0.1rem;
907
+ opacity: 0;
908
+ transition: opacity var(--transition);
909
+ }
910
+ .msg-user:hover .msg-user-actions {
911
+ opacity: 1;
912
+ }