atad-tokyo commited on
Commit
08bfbca
·
verified ·
1 Parent(s): 81ab390

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. LightRAG/.dockerignore +63 -0
  2. LightRAG/.gitattributes +2 -0
  3. LightRAG/.github/ISSUE_TEMPLATE/bug_report.yml +61 -0
  4. LightRAG/.github/ISSUE_TEMPLATE/config.yml +1 -0
  5. LightRAG/.github/ISSUE_TEMPLATE/feature_request.yml +26 -0
  6. LightRAG/.github/ISSUE_TEMPLATE/question.yml +26 -0
  7. LightRAG/.github/dependabot.yml +11 -0
  8. LightRAG/.github/pull_request_template.md +32 -0
  9. LightRAG/.github/workflows/docker-build-manual.yml +73 -0
  10. LightRAG/.github/workflows/docker-publish.yml +62 -0
  11. LightRAG/.github/workflows/linting.yaml +30 -0
  12. LightRAG/.github/workflows/pypi-publish.yml +69 -0
  13. LightRAG/.github/workflows/stale.yaml +27 -0
  14. LightRAG/.gitignore +75 -0
  15. LightRAG/.pre-commit-config.yaml +28 -0
  16. LightRAG/Dockerfile +63 -0
  17. LightRAG/LICENSE +21 -0
  18. LightRAG/MANIFEST.in +3 -0
  19. LightRAG/README-zh.md +1738 -0
  20. LightRAG/README.md +1889 -0
  21. LightRAG/SECURITY.md +18 -0
  22. LightRAG/config.ini.example +37 -0
  23. LightRAG/docker-compose.yml +24 -0
  24. LightRAG/docs/Algorithm.md +4 -0
  25. LightRAG/docs/DockerDeployment.md +175 -0
  26. LightRAG/docs/LightRAG_concurrent_explain.md +114 -0
  27. LightRAG/env.example +357 -0
  28. LightRAG/env.ollama-binding-options.example +195 -0
  29. LightRAG/k8s-deploy/README-zh.md +191 -0
  30. LightRAG/k8s-deploy/README.md +191 -0
  31. LightRAG/k8s-deploy/databases/00-config.sh +21 -0
  32. LightRAG/k8s-deploy/databases/01-prepare.sh +33 -0
  33. LightRAG/k8s-deploy/databases/02-install-database.sh +62 -0
  34. LightRAG/k8s-deploy/databases/03-uninstall-database.sh +20 -0
  35. LightRAG/k8s-deploy/databases/04-cleanup.sh +26 -0
  36. LightRAG/k8s-deploy/databases/install-kubeblocks.sh +52 -0
  37. LightRAG/k8s-deploy/databases/postgresql/values.yaml +33 -0
  38. LightRAG/k8s-deploy/install_lightrag.sh +95 -0
  39. LightRAG/k8s-deploy/install_lightrag_dev.sh +81 -0
  40. LightRAG/k8s-deploy/uninstall_lightrag.sh +4 -0
  41. LightRAG/k8s-deploy/uninstall_lightrag_dev.sh +4 -0
  42. LightRAG/lightrag-api +4 -0
  43. LightRAG/lightrag.service.example +17 -0
  44. LightRAG/paging.md +251 -0
  45. LightRAG/pyproject.toml +105 -0
  46. LightRAG/setup.py +6 -0
  47. LightRAG/stgong.txt +3 -0
  48. gpt_bu2/qa_per_neg_batch/不二_neg.jsonl +0 -0
  49. gpt_bu2/qa_per_neg_batch/加罗_neg.jsonl +0 -0
  50. gpt_bu2/qa_per_role_gpt4o_cot/加罗.json +0 -0
LightRAG/.dockerignore ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python-related files and directories
2
+ __pycache__
3
+ .cache
4
+
5
+ # Virtual environment directories
6
+ *.venv
7
+
8
+ # Env
9
+ env/
10
+ *.env*
11
+ .env_example
12
+
13
+ # Distribution / build files
14
+ site
15
+ dist/
16
+ build/
17
+ .eggs/
18
+ *.egg-info/
19
+ *.tgz
20
+ *.tar.gz
21
+
22
+ # Exclude siles and folders
23
+ *.yml
24
+ .dockerignore
25
+ Dockerfile
26
+ Makefile
27
+
28
+ # Exclude other projects
29
+ /tests
30
+ /scripts
31
+
32
+ # Python version manager file
33
+ .python-version
34
+
35
+ # Reports
36
+ *.coverage/
37
+ *.log
38
+ log/
39
+ *.logfire
40
+
41
+ # Cache
42
+ .cache/
43
+ .mypy_cache
44
+ .pytest_cache
45
+ .ruff_cache
46
+ .gradio
47
+ .logfire
48
+ temp/
49
+
50
+ # MacOS-related files
51
+ .DS_Store
52
+
53
+ # VS Code settings (local configuration files)
54
+ .vscode
55
+
56
+ # file
57
+ TODO.md
58
+
59
+ # Exclude Git-related files
60
+ .git
61
+ .github
62
+ .gitignore
63
+ .pre-commit-config.yaml
LightRAG/.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ lightrag/api/webui/** binary
2
+ lightrag/api/webui/** linguist-generated
LightRAG/.github/ISSUE_TEMPLATE/bug_report.yml ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Bug Report
2
+ description: File a bug report
3
+ title: "[Bug]:"
4
+ labels: ["bug", "triage"]
5
+
6
+ body:
7
+ - type: checkboxes
8
+ id: existingcheck
9
+ attributes:
10
+ label: Do you need to file an issue?
11
+ description: Please help us manage our time by avoiding duplicates and common bugs with the steps below.
12
+ options:
13
+ - label: I have searched the existing issues and this bug is not already filed.
14
+ - label: I believe this is a legitimate bug, not just a question or feature request.
15
+ - type: textarea
16
+ id: description
17
+ attributes:
18
+ label: Describe the bug
19
+ description: A clear and concise description of what the bug is.
20
+ placeholder: What went wrong?
21
+ - type: textarea
22
+ id: reproduce
23
+ attributes:
24
+ label: Steps to reproduce
25
+ description: Steps to reproduce the behavior.
26
+ placeholder: How can we replicate the issue?
27
+ - type: textarea
28
+ id: expected_behavior
29
+ attributes:
30
+ label: Expected Behavior
31
+ description: A clear and concise description of what you expected to happen.
32
+ placeholder: What should have happened?
33
+ - type: textarea
34
+ id: configused
35
+ attributes:
36
+ label: LightRAG Config Used
37
+ description: The LightRAG configuration used for the run.
38
+ placeholder: The settings content or LightRAG configuration
39
+ value: |
40
+ # Paste your config here
41
+ - type: textarea
42
+ id: screenshotslogs
43
+ attributes:
44
+ label: Logs and screenshots
45
+ description: If applicable, add screenshots and logs to help explain your problem.
46
+ placeholder: Add logs and screenshots here
47
+ - type: textarea
48
+ id: additional_information
49
+ attributes:
50
+ label: Additional Information
51
+ description: |
52
+ - LightRAG Version: e.g., v0.1.1
53
+ - Operating System: e.g., Windows 10, Ubuntu 20.04
54
+ - Python Version: e.g., 3.8
55
+ - Related Issues: e.g., #1
56
+ - Any other relevant information.
57
+ value: |
58
+ - LightRAG Version:
59
+ - Operating System:
60
+ - Python Version:
61
+ - Related Issues:
LightRAG/.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1 @@
 
 
1
+ blank_issues_enabled: false
LightRAG/.github/ISSUE_TEMPLATE/feature_request.yml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Feature Request
2
+ description: File a feature request
3
+ labels: ["enhancement"]
4
+ title: "[Feature Request]:"
5
+
6
+ body:
7
+ - type: checkboxes
8
+ id: existingcheck
9
+ attributes:
10
+ label: Do you need to file a feature request?
11
+ description: Please help us manage our time by avoiding duplicates and common feature request with the steps below.
12
+ options:
13
+ - label: I have searched the existing feature request and this feature request is not already filed.
14
+ - label: I believe this is a legitimate feature request, not just a question or bug.
15
+ - type: textarea
16
+ id: feature_request_description
17
+ attributes:
18
+ label: Feature Request Description
19
+ description: A clear and concise description of the feature request you would like.
20
+ placeholder: What this feature request add more or improve?
21
+ - type: textarea
22
+ id: additional_context
23
+ attributes:
24
+ label: Additional Context
25
+ description: Add any other context or screenshots about the feature request here.
26
+ placeholder: Any additional information
LightRAG/.github/ISSUE_TEMPLATE/question.yml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Question
2
+ description: Ask a general question
3
+ labels: ["question"]
4
+ title: "[Question]:"
5
+
6
+ body:
7
+ - type: checkboxes
8
+ id: existingcheck
9
+ attributes:
10
+ label: Do you need to ask a question?
11
+ description: Please help us manage our time by avoiding duplicates and common questions with the steps below.
12
+ options:
13
+ - label: I have searched the existing question and discussions and this question is not already answered.
14
+ - label: I believe this is a legitimate question, not just a bug or feature request.
15
+ - type: textarea
16
+ id: question
17
+ attributes:
18
+ label: Your Question
19
+ description: A clear and concise description of your question.
20
+ placeholder: What is your question?
21
+ - type: textarea
22
+ id: context
23
+ attributes:
24
+ label: Additional Context
25
+ description: Provide any additional context or details that might help us understand your question better.
26
+ placeholder: Add any relevant information here
LightRAG/.github/dependabot.yml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # To get started with Dependabot version updates, you'll need to specify which
2
+ # package ecosystems to update and where the package manifests are located.
3
+ # Please see the documentation for all configuration options:
4
+ # https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
5
+
6
+ version: 2
7
+ updates:
8
+ - package-ecosystem: "pip" # See documentation for possible values
9
+ directory: "/" # Location of package manifests
10
+ schedule:
11
+ interval: "weekly"
LightRAG/.github/pull_request_template.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!--
2
+ Thanks for contributing to LightRAG!
3
+
4
+ Please ensure your pull request is ready for review before submitting.
5
+
6
+ About this template
7
+
8
+ This template helps contributors provide a clear and concise description of their changes. Feel free to adjust it as needed.
9
+ -->
10
+
11
+ ## Description
12
+
13
+ [Briefly describe the changes made in this pull request.]
14
+
15
+ ## Related Issues
16
+
17
+ [Reference any related issues or tasks addressed by this pull request.]
18
+
19
+ ## Changes Made
20
+
21
+ [List the specific changes made in this pull request.]
22
+
23
+ ## Checklist
24
+
25
+ - [ ] Changes tested locally
26
+ - [ ] Code reviewed
27
+ - [ ] Documentation updated (if necessary)
28
+ - [ ] Unit tests added (if applicable)
29
+
30
+ ## Additional Notes
31
+
32
+ [Add any additional notes or context for the reviewer(s).]
LightRAG/.github/workflows/docker-build-manual.yml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build Test Docker Image manually
2
+
3
+ on:
4
+ workflow_dispatch:
5
+
6
+ permissions:
7
+ contents: read
8
+ packages: write
9
+
10
+ jobs:
11
+ build-and-push:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - name: Checkout code
15
+ uses: actions/checkout@v4
16
+ with:
17
+ fetch-depth: 0 # Fetch all history for tags
18
+
19
+ - name: Get latest tag
20
+ id: get_tag
21
+ run: |
22
+ # Get the latest tag, fallback to commit SHA if no tags exist
23
+ LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
24
+ if [ -z "$LATEST_TAG" ]; then
25
+ LATEST_TAG="sha-$(git rev-parse --short HEAD)"
26
+ echo "No tags found, using commit SHA: $LATEST_TAG"
27
+ else
28
+ echo "Latest tag found: $LATEST_TAG"
29
+ fi
30
+ echo "tag=$LATEST_TAG" >> $GITHUB_OUTPUT
31
+ echo "image_tag=$LATEST_TAG" >> $GITHUB_OUTPUT
32
+
33
+ - name: Update version in __init__.py
34
+ run: |
35
+ sed -i "s/__version__ = \".*\"/__version__ = \"${{ steps.get_tag.outputs.tag }}\"/" lightrag/__init__.py
36
+ echo "Updated __init__.py with version ${{ steps.get_tag.outputs.tag }}"
37
+ cat lightrag/__init__.py | grep __version__
38
+
39
+ - name: Set up Docker Buildx
40
+ uses: docker/setup-buildx-action@v3
41
+
42
+ - name: Login to GitHub Container Registry
43
+ uses: docker/login-action@v3
44
+ with:
45
+ registry: ghcr.io
46
+ username: ${{ github.actor }}
47
+ password: ${{ secrets.GITHUB_TOKEN }}
48
+
49
+ - name: Extract metadata for Docker
50
+ id: meta
51
+ uses: docker/metadata-action@v5
52
+ with:
53
+ images: ghcr.io/${{ github.repository }}
54
+ tags: |
55
+ type=raw,value=${{ steps.get_tag.outputs.tag }}
56
+
57
+ - name: Build and push Docker image
58
+ uses: docker/build-push-action@v5
59
+ with:
60
+ context: .
61
+ platforms: linux/amd64,linux/arm64
62
+ push: true
63
+ tags: ${{ steps.meta.outputs.tags }}
64
+ labels: ${{ steps.meta.outputs.labels }}
65
+ cache-from: type=gha
66
+ cache-to: type=gha,mode=max
67
+
68
+ - name: Output image details
69
+ run: |
70
+ echo "Docker image built and pushed successfully!"
71
+ echo "Image tags:"
72
+ echo " - ghcr.io/${{ github.repository }}:${{ steps.get_tag.outputs.tag }}"
73
+ echo "Latest Git tag used: ${{ steps.get_tag.outputs.tag }}"
LightRAG/.github/workflows/docker-publish.yml ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Build Latest Docker Image on Release
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+ packages: write
11
+
12
+ jobs:
13
+ build-and-push:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - name: Checkout code
17
+ uses: actions/checkout@v4
18
+ with:
19
+ fetch-depth: 0 # Fetch all history for tags
20
+
21
+ - name: Set up Docker Buildx
22
+ uses: docker/setup-buildx-action@v3
23
+
24
+ - name: Login to GitHub Container Registry
25
+ uses: docker/login-action@v3
26
+ with:
27
+ registry: ghcr.io
28
+ username: ${{ github.actor }}
29
+ password: ${{ secrets.GITHUB_TOKEN }}
30
+
31
+ - name: Get latest tag
32
+ id: get_tag
33
+ run: |
34
+ TAG=$(git describe --tags --abbrev=0)
35
+ echo "Found tag: $TAG"
36
+ echo "tag=$TAG" >> $GITHUB_OUTPUT
37
+
38
+ - name: Update version in __init__.py
39
+ run: |
40
+ sed -i "s/__version__ = \".*\"/__version__ = \"${{ steps.get_tag.outputs.tag }}\"/" lightrag/__init__.py
41
+ echo "Updated __init__.py with version ${{ steps.get_tag.outputs.tag }}"
42
+ cat lightrag/__init__.py | grep __version__
43
+
44
+ - name: Extract metadata for Docker
45
+ id: meta
46
+ uses: docker/metadata-action@v5
47
+ with:
48
+ images: ghcr.io/${{ github.repository }}
49
+ tags: |
50
+ type=raw,value=${{ steps.get_tag.outputs.tag }}
51
+ type=raw,value=latest
52
+
53
+ - name: Build and push Docker image
54
+ uses: docker/build-push-action@v5
55
+ with:
56
+ context: .
57
+ platforms: linux/amd64,linux/arm64
58
+ push: true
59
+ tags: ${{ steps.meta.outputs.tags }}
60
+ labels: ${{ steps.meta.outputs.labels }}
61
+ cache-from: type=gha
62
+ cache-to: type=gha,mode=max
LightRAG/.github/workflows/linting.yaml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Linting and Formatting
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ pull_request:
8
+ branches:
9
+ - main
10
+
11
+ jobs:
12
+ lint-and-format:
13
+ runs-on: ubuntu-latest
14
+
15
+ steps:
16
+ - name: Checkout code
17
+ uses: actions/checkout@v2
18
+
19
+ - name: Set up Python
20
+ uses: actions/setup-python@v2
21
+ with:
22
+ python-version: '3.x'
23
+
24
+ - name: Install dependencies
25
+ run: |
26
+ python -m pip install --upgrade pip
27
+ pip install pre-commit
28
+
29
+ - name: Run pre-commit
30
+ run: pre-commit run --all-files --show-diff-on-failure
LightRAG/.github/workflows/pypi-publish.yml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Upload LightRAG-hku Package
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ release-build:
13
+ runs-on: ubuntu-latest
14
+
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ with:
18
+ fetch-depth: 0 # Fetch all history for tags
19
+
20
+ - uses: actions/setup-python@v5
21
+ with:
22
+ python-version: "3.x"
23
+
24
+ - name: Get version from tag
25
+ id: get_version
26
+ run: |
27
+ TAG=$(git describe --tags --abbrev=0)
28
+ echo "Found tag: $TAG"
29
+ echo "Extracted version: $TAG"
30
+ echo "version=$TAG" >> $GITHUB_OUTPUT
31
+
32
+ - name: Update version in __init__.py
33
+ run: |
34
+ sed -i "s/__version__ = \".*\"/__version__ = \"${{ steps.get_version.outputs.version }}\"/" lightrag/__init__.py
35
+ echo "Updated __init__.py with version ${{ steps.get_version.outputs.version }}"
36
+ cat lightrag/__init__.py | grep __version__
37
+
38
+ - name: Build release distributions
39
+ run: |
40
+ python -m pip install build
41
+ python -m build
42
+
43
+ - name: Upload distributions
44
+ uses: actions/upload-artifact@v4
45
+ with:
46
+ name: release-dists
47
+ path: dist/
48
+
49
+ pypi-publish:
50
+ runs-on: ubuntu-latest
51
+ needs:
52
+ - release-build
53
+ permissions:
54
+ id-token: write
55
+
56
+ environment:
57
+ name: pypi
58
+
59
+ steps:
60
+ - name: Retrieve release distributions
61
+ uses: actions/download-artifact@v4
62
+ with:
63
+ name: release-dists
64
+ path: dist/
65
+
66
+ - name: Publish release distributions to PyPI
67
+ uses: pypa/gh-action-pypi-publish@release/v1
68
+ with:
69
+ packages-dir: dist/
LightRAG/.github/workflows/stale.yaml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # .github/workflows/stale.yml
2
+ name: Mark stale issues and pull requests
3
+
4
+ on:
5
+ schedule:
6
+ - cron: '30 22 * * *' # run at 22:30+08 every day
7
+
8
+ permissions:
9
+ issues: write
10
+ pull-requests: write
11
+
12
+ jobs:
13
+ stale:
14
+ runs-on: ubuntu-latest
15
+ steps:
16
+ - uses: actions/stale@v9
17
+ with:
18
+ days-before-stale: 90 # 90 days
19
+ days-before-close: 7 # 7 days after marked as stale
20
+ stale-issue-message: 'This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.'
21
+ close-issue-message: 'This issue has been automatically closed because it has not had recent activity. Please open a new issue if you still have this problem.'
22
+ stale-pr-message: 'This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs.'
23
+ close-pr-message: 'This pull request has been automatically closed because it has not had recent activity.'
24
+ # If there are specific labels, exempt them from being marked as stale, for example:
25
+ exempt-issue-labels: 'enhancement,tracked'
26
+ # exempt-pr-labels: 'bug,enhancement,help wanted'
27
+ repo-token: ${{ secrets.GITHUB_TOKEN }} # token provided by GitHub
LightRAG/.gitignore ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python-related files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ .eggs/
6
+ *.tgz
7
+ *.tar.gz
8
+ *.ini
9
+
10
+ # Virtual Environment
11
+ .venv/
12
+ env/
13
+ venv/
14
+ *.env*
15
+ .env_example
16
+
17
+ # Build / Distribution
18
+ dist/
19
+ build/
20
+ site/
21
+
22
+ # Logs / Reports
23
+ *.log
24
+ *.log.*
25
+ *.logfire
26
+ *.coverage/
27
+ log/
28
+
29
+ # Caches
30
+ .cache/
31
+ .mypy_cache/
32
+ .pytest_cache/
33
+ .ruff_cache/
34
+ .gradio/
35
+ .history/
36
+ temp/
37
+
38
+ # IDE / Editor Files
39
+ .idea/
40
+ .vscode/
41
+ .vscode/settings.json
42
+
43
+ # Framework-specific files
44
+ local_neo4jWorkDir/
45
+ neo4jWorkDir/
46
+
47
+ # Data & Storage
48
+ inputs/
49
+ rag_storage/
50
+ examples/input/
51
+ examples/output/
52
+ output*/
53
+ data/
54
+
55
+ # Miscellaneous
56
+ .DS_Store
57
+ TODO.md
58
+ ignore_this.txt
59
+ *.ignore.*
60
+
61
+ # Project-specific files
62
+ dickens*/
63
+ book.txt
64
+ LightRAG.pdf
65
+ download_models_hf.py
66
+ lightrag-dev/
67
+ gui/
68
+
69
+ # unit-test files
70
+ test_*
71
+
72
+ # Cline files
73
+ memory-bank
74
+ memory-bank/
75
+ .clinerules
LightRAG/.pre-commit-config.yaml ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/pre-commit/pre-commit-hooks
3
+ rev: v5.0.0
4
+ hooks:
5
+ - id: trailing-whitespace
6
+ exclude: ^lightrag/api/webui/
7
+ - id: end-of-file-fixer
8
+ exclude: ^lightrag/api/webui/
9
+ - id: requirements-txt-fixer
10
+ exclude: ^lightrag/api/webui/
11
+
12
+
13
+ - repo: https://github.com/astral-sh/ruff-pre-commit
14
+ rev: v0.6.4
15
+ hooks:
16
+ - id: ruff-format
17
+ exclude: ^lightrag/api/webui/
18
+ - id: ruff
19
+ args: [--fix, --ignore=E402]
20
+ exclude: ^lightrag/api/webui/
21
+
22
+
23
+ - repo: https://github.com/mgedmin/check-manifest
24
+ rev: "0.49"
25
+ hooks:
26
+ - id: check-manifest
27
+ stages: [manual]
28
+ exclude: ^lightrag/api/webui/
LightRAG/Dockerfile ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Build stage
2
+ FROM python:3.12-slim AS builder
3
+
4
+ WORKDIR /app
5
+
6
+ # Upgrade pip、setuptools and wheel to the latest version
7
+ RUN pip install --upgrade pip setuptools wheel
8
+
9
+ # Install Rust and required build dependencies
10
+ RUN apt-get update && apt-get install -y \
11
+ curl \
12
+ build-essential \
13
+ pkg-config \
14
+ && rm -rf /var/lib/apt/lists/* \
15
+ && curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \
16
+ && . $HOME/.cargo/env
17
+
18
+ # Copy pyproject.toml and source code for dependency installation
19
+ COPY pyproject.toml .
20
+ COPY setup.py .
21
+ COPY lightrag/ ./lightrag/
22
+
23
+ # Install dependencies
24
+ ENV PATH="/root/.cargo/bin:${PATH}"
25
+ RUN pip install --user --no-cache-dir --use-pep517 .
26
+ RUN pip install --user --no-cache-dir --use-pep517 .[api]
27
+
28
+ # Install depndencies for default storage
29
+ RUN pip install --user --no-cache-dir nano-vectordb networkx
30
+ # Install depndencies for default LLM
31
+ RUN pip install --user --no-cache-dir openai ollama tiktoken
32
+ # Install depndencies for default document loader
33
+ RUN pip install --user --no-cache-dir pypdf2 python-docx python-pptx openpyxl
34
+
35
+ # Final stage
36
+ FROM python:3.12-slim
37
+
38
+ WORKDIR /app
39
+
40
+ # Upgrade pip and setuptools
41
+ RUN pip install --upgrade pip setuptools wheel
42
+
43
+ # Copy only necessary files from builder
44
+ COPY --from=builder /root/.local /root/.local
45
+ COPY ./lightrag ./lightrag
46
+ COPY setup.py .
47
+
48
+ RUN pip install --use-pep517 ".[api]"
49
+ # Make sure scripts in .local are usable
50
+ ENV PATH=/root/.local/bin:$PATH
51
+
52
+ # Create necessary directories
53
+ RUN mkdir -p /app/data/rag_storage /app/data/inputs
54
+
55
+ # Docker data directories
56
+ ENV WORKING_DIR=/app/data/rag_storage
57
+ ENV INPUT_DIR=/app/data/inputs
58
+
59
+ # Expose the default port
60
+ EXPOSE 9621
61
+
62
+ # Set entrypoint
63
+ ENTRYPOINT ["python", "-m", "lightrag.api.lightrag_server"]
LightRAG/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 LightRAG Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
LightRAG/MANIFEST.in ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ include requirements.txt
2
+ include lightrag/api/requirements.txt
3
+ recursive-include lightrag/api/webui *
LightRAG/README-zh.md ADDED
@@ -0,0 +1,1738 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <div style="margin: 20px 0;">
4
+ <img src="./assets/logo.png" width="120" height="120" alt="LightRAG Logo" style="border-radius: 20px; box-shadow: 0 8px 32px rgba(0, 217, 255, 0.3);">
5
+ </div>
6
+
7
+ # 🚀 LightRAG: Simple and Fast Retrieval-Augmented Generation
8
+
9
+ <div align="center">
10
+ <a href="https://trendshift.io/repositories/13043" target="_blank"><img src="https://trendshift.io/api/badge/repositories/13043" alt="HKUDS%2FLightRAG | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
11
+ </div>
12
+
13
+ <div align="center">
14
+ <div style="width: 100%; height: 2px; margin: 20px 0; background: linear-gradient(90deg, transparent, #00d9ff, transparent);"></div>
15
+ </div>
16
+
17
+ <div align="center">
18
+ <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; padding: 25px; text-align: center;">
19
+ <p>
20
+ <a href='https://github.com/HKUDS/LightRAG'><img src='https://img.shields.io/badge/🔥项目-主页-00d9ff?style=for-the-badge&logo=github&logoColor=white&labelColor=1a1a2e'></a>
21
+ <a href='https://arxiv.org/abs/2410.05779'><img src='https://img.shields.io/badge/📄arXiv-2410.05779-ff6b6b?style=for-the-badge&logo=arxiv&logoColor=white&labelColor=1a1a2e'></a>
22
+ <a href="https://github.com/HKUDS/LightRAG/stargazers"><img src='https://img.shields.io/github/stars/HKUDS/LightRAG?color=00d9ff&style=for-the-badge&logo=star&logoColor=white&labelColor=1a1a2e' /></a>
23
+ </p>
24
+ <p>
25
+ <img src="https://img.shields.io/badge/🐍Python-3.10-4ecdc4?style=for-the-badge&logo=python&logoColor=white&labelColor=1a1a2e">
26
+ <a href="https://pypi.org/project/lightrag-hku/"><img src="https://img.shields.io/pypi/v/lightrag-hku.svg?style=for-the-badge&logo=pypi&logoColor=white&labelColor=1a1a2e&color=ff6b6b"></a>
27
+ </p>
28
+ <p>
29
+ <a href="https://discord.gg/yF2MmDJyGJ"><img src="https://img.shields.io/badge/💬Discord-社区-7289da?style=for-the-badge&logo=discord&logoColor=white&labelColor=1a1a2e"></a>
30
+ <a href="https://github.com/HKUDS/LightRAG/issues/285"><img src="https://img.shields.io/badge/💬微信群-交流-07c160?style=for-the-badge&logo=wechat&logoColor=white&labelColor=1a1a2e"></a>
31
+ </p>
32
+ <p>
33
+ <a href="README-zh.md"><img src="https://img.shields.io/badge/🇨🇳中文版-1a1a2e?style=for-the-badge"></a>
34
+ <a href="README.md"><img src="https://img.shields.io/badge/🇺🇸English-1a1a2e?style=for-the-badge"></a>
35
+ </p>
36
+ <p>
37
+ <a href="https://pepy.tech/projects/lightrag-hku"><img src="https://static.pepy.tech/personalized-badge/lightrag-hku?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads"></a>
38
+ </p>
39
+ </div>
40
+ </div>
41
+
42
+ </div>
43
+
44
+ <div align="center" style="margin: 30px 0;">
45
+ <img src="https://user-images.githubusercontent.com/74038190/212284100-561aa473-3905-4a80-b561-0d28506553ee.gif" width="800">
46
+ </div>
47
+
48
+ <div align="center" style="margin: 30px 0;">
49
+ <img src="./README.assets/b2aaf634151b4706892693ffb43d9093.png" width="800" alt="LightRAG Diagram">
50
+ </div>
51
+
52
+ ---
53
+
54
+ ## 🎉 新闻
55
+
56
+ - [X] [2025.06.16]🎯📢我们的团队发布了[RAG-Anything](https://github.com/HKUDS/RAG-Anything),一个用于无缝处理文本、图像、表格和方程式的全功能多模态 RAG 系统。
57
+ - [X] [2025.06.05]🎯📢LightRAG现已集成[RAG-Anything](https://github.com/HKUDS/RAG-Anything),支持全面的多模态文档解析与RAG能力(PDF、图片、Office文档、表格、公式等)。详见下方[多模态处理模块](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#多模态文档处理rag-anything集成)。
58
+ - [X] [2025.03.18]🎯📢LightRAG现已支持引文功能。
59
+ - [X] [2025.02.05]🎯📢我们团队发布了[VideoRAG](https://github.com/HKUDS/VideoRAG),用于理解超长上下文视频。
60
+ - [X] [2025.01.13]🎯📢我们团队发布了[MiniRAG](https://github.com/HKUDS/MiniRAG),使用小型模型简化RAG。
61
+ - [X] [2025.01.06]🎯📢现在您可以[使用PostgreSQL进行存储](#using-postgresql-for-storage)。
62
+ - [X] [2024.12.31]🎯📢LightRAG现在支持[通过文档ID删除](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#delete)。
63
+ - [X] [2024.11.25]🎯📢LightRAG现在支持无缝集成[自定义知识图谱](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#insert-custom-kg),使用户能够用自己的领域专业知识增强系统。
64
+ - [X] [2024.11.19]🎯📢LightRAG的综合指南现已在[LearnOpenCV](https://learnopencv.com/lightrag)上发布。非常感谢博客作者。
65
+ - [X] [2024.11.11]🎯📢LightRAG现在支持[通过实体名称删除实体](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#delete)。
66
+ - [X] [2024.11.09]🎯📢推出[LightRAG Gui](https://lightrag-gui.streamlit.app),允许您插入、查询、可视化和下载LightRAG知识。
67
+ - [X] [2024.11.04]🎯📢现在您可以[使用Neo4J进行存储](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#using-neo4j-for-storage)。
68
+ - [X] [2024.10.29]🎯📢LightRAG现在通过`textract`支持多种文件类型,包括PDF、DOC、PPT和CSV。
69
+ - [X] [2024.10.20]🎯📢我们为LightRAG添加了一个新功能:图形可视化。
70
+ - [X] [2024.10.18]🎯📢我们添加了[LightRAG介绍视频](https://youtu.be/oageL-1I0GE)的链接。感谢作者!
71
+ - [X] [2024.10.17]🎯📢我们创建了一个[Discord频道](https://discord.gg/yF2MmDJyGJ)!欢迎加入分享和讨论!🎉🎉
72
+ - [X] [2024.10.16]🎯📢LightRAG现在支持[Ollama模型](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
73
+ - [X] [2024.10.15]🎯📢LightRAG现在支持[Hugging Face模型](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
74
+
75
+ <details>
76
+ <summary style="font-size: 1.4em; font-weight: bold; cursor: pointer; display: list-item;">
77
+ 算法流程图
78
+ </summary>
79
+
80
+ ![LightRAG索引流程图](https://learnopencv.com/wp-content/uploads/2024/11/LightRAG-VectorDB-Json-KV-Store-Indexing-Flowchart-scaled.jpg)
81
+ *图1:LightRAG索引流程图 - 图片来源:[Source](https://learnopencv.com/lightrag/)*
82
+ ![LightRAG检索和查询流程图](https://learnopencv.com/wp-content/uploads/2024/11/LightRAG-Querying-Flowchart-Dual-Level-Retrieval-Generation-Knowledge-Graphs-scaled.jpg)
83
+ *图2:LightRAG检索和查询流程图 - 图片来源:[Source](https://learnopencv.com/lightrag/)*
84
+
85
+ </details>
86
+
87
+ ## 安装
88
+
89
+ ### 安装LightRAG服务器
90
+
91
+ LightRAG服务器旨在提供Web UI和API支持。Web UI便于文档索引、知识图谱探索和简单的RAG查询界面。LightRAG服务器还提供兼容Ollama的接口,旨在将LightRAG模拟为Ollama聊天模型。这使得AI聊天机器人(如Open WebUI)可以轻松访问LightRAG。
92
+
93
+ * 从PyPI安装
94
+
95
+ ```bash
96
+ pip install "lightrag-hku[api]"
97
+ cp env.example .env
98
+ lightrag-server
99
+ ```
100
+
101
+ * 从源代码安装
102
+
103
+ ```bash
104
+ git clone https://github.com/HKUDS/LightRAG.git
105
+ cd LightRAG
106
+ # 如有必要,创建Python虚拟环境
107
+ # 以可编辑模式安装并支持API
108
+ pip install -e ".[api]"
109
+ cp env.example .env
110
+ lightrag-server
111
+ ```
112
+
113
+ * 使用 Docker Compose 启动 LightRAG 服务器
114
+
115
+ ```
116
+ git clone https://github.com/HKUDS/LightRAG.git
117
+ cd LightRAG
118
+ cp env.example .env
119
+ # modify LLM and Embedding settings in .env
120
+ docker compose up
121
+ ```
122
+
123
+ > 在此获取LightRAG docker镜像历史版本: [LightRAG Docker Images]( https://github.com/HKUDS/LightRAG/pkgs/container/lightrag)
124
+
125
+ ### 安装LightRAG Core
126
+
127
+ * 从源代码安装(推荐)
128
+
129
+ ```bash
130
+ cd LightRAG
131
+ pip install -e .
132
+ ```
133
+
134
+ * 从PyPI安装
135
+
136
+ ```bash
137
+ pip install lightrag-hku
138
+ ```
139
+
140
+ ## 快速开始
141
+
142
+ ### LightRAG的LLM及配套技术栈要求
143
+
144
+ LightRAG对大型语言模型(LLM)的能力要求远高于传统RAG,因为它需要LLM执行文档中的实体关系抽取任务。配置合适的Embedding和Reranker模型对提高查询表现也至关重要。
145
+
146
+ - **LLM选型**:
147
+ - 推荐选用参数量至少为32B的LLM。
148
+ - 上下文长度至少为32KB,推荐达到64KB。
149
+ - 在文档索引阶段不建议选择推理模型。
150
+ - 在查询阶段建议选择比索引阶段能力更强的模型,以达到更高的查询效果。
151
+ - **Embedding模型**:
152
+ - 高性能的Embedding模型对RAG至关重要。
153
+ - 推荐使用主流的多语言Embedding模型,例如:BAAI/bge-m3 和 text-embedding-3-large。
154
+ - **重要提示**:在文档索引前必须确定使用的Embedding模型,且在文档查询阶段必须沿用与索引阶段相同的模型。有些存储(例如PostgreSQL)在首次建立数表的时候需要确定向量维度,因此更换Embedding模型后需要删除向量相关库表,以便让LightRAG重建新的库表。
155
+ - **Reranker模型配置**:
156
+ - 配置Reranker模型能够显著提升LightRAG的检索效果。
157
+ - 启用Reranker模型后,推荐将“mix模式”设为默认查询模式。
158
+ - 推荐选用主流的Reranker模型,例如:BAAI/bge-reranker-v2-m3 或 Jina 等服务商提供的模型。
159
+
160
+ ### 使用LightRAG服务器
161
+
162
+ **有关LightRAG服务器的更多信息,请参阅[LightRAG服务器](./lightrag/api/README.md)。**
163
+
164
+ ### 使用LightRAG Core
165
+
166
+ LightRAG核心功能的示例代码请参见`examples`目录。您还可参照[视频](https://www.youtube.com/watch?v=g21royNJ4fw)视频完成环境配置。若已持有OpenAI API密钥,可以通过以下命令运行演示代码:
167
+
168
+ ```bash
169
+ ### you should run the demo code with project folder
170
+ cd LightRAG
171
+ ### provide your API-KEY for OpenAI
172
+ export OPENAI_API_KEY="sk-...your_opeai_key..."
173
+ ### download the demo document of "A Christmas Carol" by Charles Dickens
174
+ curl https://raw.githubusercontent.com/gusye1234/nano-graphrag/main/tests/mock_data.txt > ./book.txt
175
+ ### run the demo code
176
+ python examples/lightrag_openai_demo.py
177
+ ```
178
+
179
+ 如需流式响应示例的实现代码,请参阅 `examples/lightrag_openai_compatible_demo.py`。运行前,请确保根据需求修改示例代码中的LLM及嵌入模型配置。
180
+
181
+ **注意1**:在运行demo程序的时候需要注意,不同的测试程序可能使用的是不同的embedding模型,更换不同的embeding模型的时候需要把清空数据目录(`./dickens`),否则层序执行会出错。如果你想保留LLM缓存,可以在清除数据目录时保留`kv_store_llm_response_cache.json`文件。
182
+
183
+ **注意2**:官方支持的示例代码仅为 `lightrag_openai_demo.py` 和 `lightrag_openai_compatible_demo.py` 两个文件。其他示例文件均为社区贡献内容,尚未经过完整测试与优化。
184
+
185
+ ## 使用LightRAG Core进行编程
186
+
187
+ > ⚠️ **如果您希望将LightRAG集成到您的项目中,建议您使用LightRAG Server提供的REST API**。LightRAG Core通常用于嵌入式应用,或供希望进行研究与评估的学者使用。
188
+
189
+ ### 一个简单程序
190
+
191
+ 以下Python代码片段演示了如何初始化LightRAG、插入文本并进行查询:
192
+
193
+ ```python
194
+ import os
195
+ import asyncio
196
+ from lightrag import LightRAG, QueryParam
197
+ from lightrag.llm.openai import gpt_4o_mini_complete, gpt_4o_complete, openai_embed
198
+ from lightrag.kg.shared_storage import initialize_pipeline_status
199
+ from lightrag.utils import setup_logger
200
+
201
+ setup_logger("lightrag", level="INFO")
202
+
203
+ WORKING_DIR = "./rag_storage"
204
+ if not os.path.exists(WORKING_DIR):
205
+ os.mkdir(WORKING_DIR)
206
+
207
+ async def initialize_rag():
208
+ rag = LightRAG(
209
+ working_dir=WORKING_DIR,
210
+ embedding_func=openai_embed,
211
+ llm_model_func=gpt_4o_mini_complete,
212
+ )
213
+ await rag.initialize_storages()
214
+ await initialize_pipeline_status()
215
+ return rag
216
+
217
+ async def main():
218
+ try:
219
+ # 初始化RAG实例
220
+ rag = await initialize_rag()
221
+ # 插入文本
222
+ await rag.insert("Your text")
223
+
224
+ # 执行混合检索
225
+ mode = "hybrid"
226
+ print(
227
+ await rag.query(
228
+ "这个故事的主要主题是什么?",
229
+ param=QueryParam(mode=mode)
230
+ )
231
+ )
232
+
233
+ except Exception as e:
234
+ print(f"发生错误: {e}")
235
+ finally:
236
+ if rag:
237
+ await rag.finalize_storages()
238
+
239
+ if __name__ == "__main__":
240
+ asyncio.run(main())
241
+ ```
242
+
243
+ 重要说明:
244
+ - 运行脚本前请先导出你的OPENAI_API_KEY环境变量。
245
+ - 该程序使用LightRAG的默认存储设置,所有数据将持久化在WORKING_DIR/rag_storage目录下。
246
+ - 该示例仅展示了初始化LightRAG对象的最简单方式:注入embedding和LLM函数,并在创建LightRAG对象后初始化存储和管道状态。
247
+
248
+ ### LightRAG初始化参数
249
+
250
+ 以下是完整的LightRAG对象初始化参数清单:
251
+
252
+ <details>
253
+ <summary> 参数 </summary>
254
+
255
+ | **参数** | **类型** | **说明** | **默认值** |
256
+ |--------------|----------|-----------------|-------------|
257
+ | **working_dir** | `str` | 存储缓存的目录 | `lightrag_cache+timestamp` |
258
+ | **kv_storage** | `str` | Storage type for documents and text chunks. Supported types: `JsonKVStorage`,`PGKVStorage`,`RedisKVStorage`,`MongoKVStorage` | `JsonKVStorage` |
259
+ | **vector_storage** | `str` | Storage type for embedding vectors. Supported types: `NanoVectorDBStorage`,`PGVectorStorage`,`MilvusVectorDBStorage`,`ChromaVectorDBStorage`,`FaissVectorDBStorage`,`MongoVectorDBStorage`,`QdrantVectorDBStorage` | `NanoVectorDBStorage` |
260
+ | **graph_storage** | `str` | Storage type for graph edges and nodes. Supported types: `NetworkXStorage`,`Neo4JStorage`,`PGGraphStorage`,`AGEStorage` | `NetworkXStorage` |
261
+ | **doc_status_storage** | `str` | Storage type for documents process status. Supported types: `JsonDocStatusStorage`,`PGDocStatusStorage`,`MongoDocStatusStorage` | `JsonDocStatusStorage` |
262
+ | **chunk_token_size** | `int` | 拆分文档时每个块的最大令牌大小 | `1200` |
263
+ | **chunk_overlap_token_size** | `int` | 拆分文档时两个块之间的重叠令牌大小 | `100` |
264
+ | **tokenizer** | `Tokenizer` | 用于将文本转换为 tokens(数字)以及使用遵循 TokenizerInterface 协议的 .encode() 和 .decode() 函数将 tokens 转换回文本的函数。 如果您不指定,它将使用默认的 Tiktoken tokenizer。 | `TiktokenTokenizer` |
265
+ | **tiktoken_model_name** | `str` | 如果您使用的是默认的 Tiktoken tokenizer,那么这是要使用的特定 Tiktoken 模型的名称。如果您提供自己的 tokenizer,则忽略此设置。 | `gpt-4o-mini` |
266
+ | **entity_extract_max_gleaning** | `int` | 实体提取过程中的循环次数,附加历史消息 | `1` |
267
+ | **node_embedding_algorithm** | `str` | 节点嵌入算法(当前未使用) | `node2vec` |
268
+ | **node2vec_params** | `dict` | 节点嵌入的参数 | `{"dimensions": 1536,"num_walks": 10,"walk_length": 40,"window_size": 2,"iterations": 3,"random_seed": 3,}` |
269
+ | **embedding_func** | `EmbeddingFunc` | 从文本生成嵌入向量的函数 | `openai_embed` |
270
+ | **embedding_batch_num** | `int` | 嵌入过程的最大批量大小(每批发送多个文本) | `32` |
271
+ | **embedding_func_max_async** | `int` | 最大并发异步嵌入进程数 | `16` |
272
+ | **llm_model_func** | `callable` | LLM生成的函数 | `gpt_4o_mini_complete` |
273
+ | **llm_model_name** | `str` | 用于生成的LLM模型名称 | `meta-llama/Llama-3.2-1B-Instruct` |
274
+ | **summary_context_size** | `int` | 合并实体关系摘要时送给LLM的最大令牌数 | `10000`(由环境变量 SUMMARY_MAX_CONTEXT 设置) |
275
+ | **summary_max_tokens** | `int` | 合并实体关系描述的最大令牌数长度 | `500`(由环境变量 SUMMARY_MAX_TOKENS 设置) |
276
+ | **llm_model_max_async** | `int` | 最大并发异步LLM进程数 | `4`(默认值由环境变量MAX_ASYNC更改) |
277
+ | **llm_model_kwargs** | `dict` | LLM生成的附加参数 | |
278
+ | **vector_db_storage_cls_kwargs** | `dict` | 向量数据库的附加参数,如设置节点和关系检索的阈值 | cosine_better_than_threshold: 0.2(默认值由环境变量COSINE_THRESHOLD更改) |
279
+ | **enable_llm_cache** | `bool` | 如果为`TRUE`,将LLM结果存储在缓存中;重复的提示返回缓存的响应 | `TRUE` |
280
+ | **enable_llm_cache_for_entity_extract** | `bool` | 如果为`TRUE`,将实体提取的LLM结果存储在缓存中;适合初学者调试应用程序 | `TRUE` |
281
+ | **addon_params** | `dict` | 附加参数,例如`{"language": "Simplified Chinese", "entity_types": ["organization", "person", "location", "event"]}`:设置示例限制、输出语言和文档处理的批量大小 | language: English` |
282
+ | **embedding_cache_config** | `dict` | 问答缓存的配置。包含三个参数:`enabled`:布尔值,启用/禁用缓存查找功能。启用时,系统将在生成新答案之前检查缓存的响应。`similarity_threshold`:浮点值(0-1),相似度阈值。当新问题与缓存问题的相似度超过此阈值时,将直接返回缓存的答案而不调用LLM。`use_llm_check`:布尔值,启用/禁用LLM相似度验证。启用时,在返回缓存答案之前,将使用LLM作为二次检查来验证问题之间的相似度。 | 默认:`{"enabled": False, "similarity_threshold": 0.95, "use_llm_check": False}` |
283
+
284
+ </details>
285
+
286
+ ### 查询参数
287
+
288
+ 使用QueryParam控制你的查询行为:
289
+
290
+ ```python
291
+ class QueryParam:
292
+ """Configuration parameters for query execution in LightRAG."""
293
+
294
+ mode: Literal["local", "global", "hybrid", "naive", "mix", "bypass"] = "global"
295
+ """Specifies the retrieval mode:
296
+ - "local": Focuses on context-dependent information.
297
+ - "global": Utilizes global knowledge.
298
+ - "hybrid": Combines local and global retrieval methods.
299
+ - "naive": Performs a basic search without advanced techniques.
300
+ - "mix": Integrates knowledge graph and vector retrieval.
301
+ """
302
+
303
+ only_need_context: bool = False
304
+ """If True, only returns the retrieved context without generating a response."""
305
+
306
+ only_need_prompt: bool = False
307
+ """If True, only returns the generated prompt without producing a response."""
308
+
309
+ response_type: str = "Multiple Paragraphs"
310
+ """Defines the response format. Examples: 'Multiple Paragraphs', 'Single Paragraph', 'Bullet Points'."""
311
+
312
+ stream: bool = False
313
+ """If True, enables streaming output for real-time responses."""
314
+
315
+ top_k: int = int(os.getenv("TOP_K", "60"))
316
+ """Number of top items to retrieve. Represents entities in 'local' mode and relationships in 'global' mode."""
317
+
318
+ chunk_top_k: int = int(os.getenv("CHUNK_TOP_K", "20"))
319
+ """Number of text chunks to retrieve initially from vector search and keep after reranking.
320
+ If None, defaults to top_k value.
321
+ """
322
+
323
+ max_entity_tokens: int = int(os.getenv("MAX_ENTITY_TOKENS", "6000"))
324
+ """Maximum number of tokens allocated for entity context in unified token control system."""
325
+
326
+ max_relation_tokens: int = int(os.getenv("MAX_RELATION_TOKENS", "8000"))
327
+ """Maximum number of tokens allocated for relationship context in unified token control system."""
328
+
329
+ max_total_tokens: int = int(os.getenv("MAX_TOTAL_TOKENS", "30000"))
330
+ """Maximum total tokens budget for the entire query context (entities + relations + chunks + system prompt)."""
331
+
332
+ hl_keywords: list[str] = field(default_factory=list)
333
+ """List of high-level keywords to prioritize in retrieval."""
334
+
335
+ ll_keywords: list[str] = field(default_factory=list)
336
+ """List of low-level keywords to refine retrieval focus."""
337
+
338
+ conversation_history: list[dict[str, str]] = field(default_factory=list)
339
+ """Stores past conversation history to maintain context.
340
+ Format: [{"role": "user/assistant", "content": "message"}].
341
+ """
342
+
343
+ # Deprated: history message have negtive effect on query performance
344
+ history_turns: int = 0
345
+ """Number of complete conversation turns (user-assistant pairs) to consider in the response context."""
346
+
347
+ ids: list[str] | None = None
348
+ """List of ids to filter the results."""
349
+
350
+ model_func: Callable[..., object] | None = None
351
+ """Optional override for the LLM model function to use for this specific query.
352
+ If provided, this will be used instead of the global model function.
353
+ This allows using different models for different query modes.
354
+ """
355
+
356
+ user_prompt: str | None = None
357
+ """User-provided prompt for the query.
358
+ If proivded, this will be use instead of the default vaulue from prompt template.
359
+ """
360
+
361
+ enable_rerank: bool = True
362
+ """Enable reranking for retrieved text chunks. If True but no rerank model is configured, a warning will be issued.
363
+ Default is True to enable reranking when rerank model is available.
364
+ """
365
+ ```
366
+
367
+ > top_k的默认值可以通过环境变量TOP_K更改。
368
+
369
+ ### LLM and Embedding注入
370
+
371
+ LightRAG 需要利用LLM和Embeding模型来完成文档索引和知识库查询工作。在初始化LightRAG的时候需要把阶段,需要把LLM和Embedding的操作函数注入到对象中:
372
+
373
+ <details>
374
+ <summary> <b>使用类OpenAI的API</b> </summary>
375
+
376
+ * LightRAG还支持类OpenAI的聊天/嵌入API:
377
+
378
+ ```python
379
+ async def llm_model_func(
380
+ prompt, system_prompt=None, history_messages=[], keyword_extraction=False, **kwargs
381
+ ) -> str:
382
+ return await openai_complete_if_cache(
383
+ "solar-mini",
384
+ prompt,
385
+ system_prompt=system_prompt,
386
+ history_messages=history_messages,
387
+ api_key=os.getenv("UPSTAGE_API_KEY"),
388
+ base_url="https://api.upstage.ai/v1/solar",
389
+ **kwargs
390
+ )
391
+
392
+ async def embedding_func(texts: list[str]) -> np.ndarray:
393
+ return await openai_embed(
394
+ texts,
395
+ model="solar-embedding-1-large-query",
396
+ api_key=os.getenv("UPSTAGE_API_KEY"),
397
+ base_url="https://api.upstage.ai/v1/solar"
398
+ )
399
+
400
+ async def initialize_rag():
401
+ rag = LightRAG(
402
+ working_dir=WORKING_DIR,
403
+ llm_model_func=llm_model_func,
404
+ embedding_func=EmbeddingFunc(
405
+ embedding_dim=4096,
406
+ func=embedding_func
407
+ )
408
+ )
409
+
410
+ await rag.initialize_storages()
411
+ await initialize_pipeline_status()
412
+
413
+ return rag
414
+ ```
415
+
416
+ </details>
417
+
418
+ <details>
419
+ <summary> <b>使用Hugging Face模型</b> </summary>
420
+
421
+ * 如果您想使用Hugging Face模型,只需要按如下方式设置LightRAG:
422
+
423
+ 参见`lightrag_hf_demo.py`
424
+
425
+ ```python
426
+ # 使用Hugging Face模型初始化LightRAG
427
+ rag = LightRAG(
428
+ working_dir=WORKING_DIR,
429
+ llm_model_func=hf_model_complete, # 使用Hugging Face模型进行文本生成
430
+ llm_model_name='meta-llama/Llama-3.1-8B-Instruct', # Hugging Face的模型名称
431
+ # 使用Hugging Face嵌入函数
432
+ embedding_func=EmbeddingFunc(
433
+ embedding_dim=384,
434
+ func=lambda texts: hf_embed(
435
+ texts,
436
+ tokenizer=AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2"),
437
+ embed_model=AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
438
+ )
439
+ ),
440
+ )
441
+ ```
442
+
443
+ </details>
444
+
445
+ <details>
446
+ <summary> <b>使用Ollama模型</b> </summary>
447
+ 如果您想使用Ollama模型,您需要拉取计划使用的模型和嵌入模型,例如`nomic-embed-text`。
448
+
449
+ 然后您只需要按如下方式设置LightRAG:
450
+
451
+ ```python
452
+ # 使用Ollama模型初始化LightRAG
453
+ rag = LightRAG(
454
+ working_dir=WORKING_DIR,
455
+ llm_model_func=ollama_model_complete, # 使用Ollama模型进行文本生成
456
+ llm_model_name='your_model_name', # 您的模型名称
457
+ # 使用Ollama嵌入函数
458
+ embedding_func=EmbeddingFunc(
459
+ embedding_dim=768,
460
+ func=lambda texts: ollama_embed(
461
+ texts,
462
+ embed_model="nomic-embed-text"
463
+ )
464
+ ),
465
+ )
466
+ ```
467
+
468
+ * **增加上下文大小**
469
+
470
+ 为了使LightRAG正常工作,上下文应至少为32k令牌。默认情况下,Ollama模型的上下文大小为8k。您可以通过以下两种方式之一实现这一点:
471
+
472
+ * **在Modelfile中增加`num_ctx`参数**
473
+
474
+ 1. 拉取模型:
475
+
476
+ ```bash
477
+ ollama pull qwen2
478
+ ```
479
+
480
+ 2. 显示模型文件:
481
+
482
+ ```bash
483
+ ollama show --modelfile qwen2 > Modelfile
484
+ ```
485
+
486
+ 3. 编辑Modelfile,添加以下行:
487
+
488
+ ```bash
489
+ PARAMETER num_ctx 32768
490
+ ```
491
+
492
+ 4. 创建修改后的模型:
493
+
494
+ ```bash
495
+ ollama create -f Modelfile qwen2m
496
+ ```
497
+
498
+ * **通过Ollama API设置`num_ctx`**
499
+
500
+ 您可以使用`llm_model_kwargs`参数配置ollama:
501
+
502
+ ```python
503
+ rag = LightRAG(
504
+ working_dir=WORKING_DIR,
505
+ llm_model_func=ollama_model_complete, # 使用Ollama模型进行文本生成
506
+ llm_model_name='your_model_name', # 您的模型名称
507
+ llm_model_kwargs={"options": {"num_ctx": 32768}},
508
+ # 使用Ollama嵌入函数
509
+ embedding_func=EmbeddingFunc(
510
+ embedding_dim=768,
511
+ func=lambda texts: ollama_embed(
512
+ texts,
513
+ embed_model="nomic-embed-text"
514
+ )
515
+ ),
516
+ )
517
+ ```
518
+
519
+ * **低RAM GPU**
520
+
521
+ 为了在低RAM GPU上运行此实验,您应该选择小型模型并调整上下文窗口(增加上下文会增加内存消耗)。例如,在6Gb RAM的改装挖矿GPU上运行这个ollama示例需要将上下文大小设置为26k,同时使用`gemma2:2b`。它能够在`book.txt`中找到197个实体和19个关系。
522
+
523
+ </details>
524
+ <details>
525
+ <summary> <b>LlamaIndex</b> </summary>
526
+
527
+ LightRAG支持与LlamaIndex集成 (`llm/llama_index_impl.py`):
528
+
529
+ - 通过LlamaIndex与OpenAI和其他提供商集成
530
+ - 详细设置和示例请参见[LlamaIndex文档](lightrag/llm/Readme.md)
531
+
532
+ **使用示例:**
533
+
534
+ ```python
535
+ # 使用LlamaIndex直接访问OpenAI
536
+ import asyncio
537
+ from lightrag import LightRAG
538
+ from lightrag.llm.llama_index_impl import llama_index_complete_if_cache, llama_index_embed
539
+ from llama_index.embeddings.openai import OpenAIEmbedding
540
+ from llama_index.llms.openai import OpenAI
541
+ from lightrag.kg.shared_storage import initialize_pipeline_status
542
+ from lightrag.utils import setup_logger
543
+
544
+ # 为LightRAG设置日志处理程序
545
+ setup_logger("lightrag", level="INFO")
546
+
547
+ async def initialize_rag():
548
+ rag = LightRAG(
549
+ working_dir="your/path",
550
+ llm_model_func=llama_index_complete_if_cache, # LlamaIndex兼容的完成函数
551
+ embedding_func=EmbeddingFunc( # LlamaIndex兼容的嵌入函数
552
+ embedding_dim=1536,
553
+ func=lambda texts: llama_index_embed(texts, embed_model=embed_model)
554
+ ),
555
+ )
556
+
557
+ await rag.initialize_storages()
558
+ await initialize_pipeline_status()
559
+
560
+ return rag
561
+
562
+ def main():
563
+ # 初始化RAG实例
564
+ rag = asyncio.run(initialize_rag())
565
+
566
+ with open("./book.txt", "r", encoding="utf-8") as f:
567
+ rag.insert(f.read())
568
+
569
+ # 执行朴素搜索
570
+ print(
571
+ rag.query("这个故事的主要主题是什么?", param=QueryParam(mode="naive"))
572
+ )
573
+
574
+ # 执行本地搜索
575
+ print(
576
+ rag.query("这个故事的主要主题是什么?", param=QueryParam(mode="local"))
577
+ )
578
+
579
+ # 执行全局搜索
580
+ print(
581
+ rag.query("这个故事的主要主题是什么?", param=QueryParam(mode="global"))
582
+ )
583
+
584
+ # 执行混合搜索
585
+ print(
586
+ rag.query("这个故事的主要主题是什么?", param=QueryParam(mode="hybrid"))
587
+ )
588
+
589
+ if __name__ == "__main__":
590
+ main()
591
+ ```
592
+
593
+ **详细文档和示例,请参见:**
594
+
595
+ - [LlamaIndex文档](lightrag/llm/Readme.md)
596
+ - [直接OpenAI示例](examples/lightrag_llamaindex_direct_demo.py)
597
+ - [LiteLLM代理示例](examples/lightrag_llamaindex_litellm_demo.py)
598
+
599
+ </details>
600
+
601
+ ### Rerank函数注入
602
+
603
+ 为了提高检索质量,可以根据更有效的相关性评分模型对文档进行重排序。`rerank.py`文件提供了三个Reranker提供商的驱动函数:
604
+
605
+ * **Cohere / vLLM**: `cohere_rerank`
606
+ * **Jina AI**: `jina_rerank`
607
+ * **Aliyun阿里云**: `ali_rerank`
608
+
609
+ 您可以将这些函数之一注入到LightRAG对象的`rerank_model_func`属性中。这将使LightRAG的查询功能能够使用注入的函数对检索到的文本块进行重新排序。有关详细用法,请参阅`examples/rerank_example.py`文件。
610
+
611
+ ### 用户提示词 vs. 查询内容
612
+
613
+ 当使用LightRAG查询内容的时候,不要把内容查询和与查询结果无关的输出加工写在一起。因为把两者混在一起会严重影响查询的效果。Query Param中的`user_prompt`就是为解决这一问题而设计的。`user_prompt`中的内容不参与RAG中的查询过程,它仅会在获得查询结果之后,与查询结果一起送给LLM,指导LLM如何处理查询结果。以下是使用方法:
614
+
615
+ ```python
616
+ # Create query parameters
617
+ query_param = QueryParam(
618
+ mode = "hybrid", # Other modes:local, global, hybrid, mix, naive
619
+ user_prompt = "如需画图使用mermaid格式,节点名称用英文或拼音,显示名称用中文",
620
+ )
621
+
622
+ # Query and process
623
+ response_default = rag.query(
624
+ "请画出 Scrooge 的人物关系图谱",
625
+ param=query_param
626
+ )
627
+ print(response_default)
628
+ ```
629
+
630
+ ### 插入
631
+
632
+ <details>
633
+ <summary> <b> 基本插入 </b></summary>
634
+
635
+ ```python
636
+ # 基本插入
637
+ rag.insert("文本")
638
+ ```
639
+
640
+ </details>
641
+
642
+ <details>
643
+ <summary> <b> 批量插入 </b></summary>
644
+
645
+ ```python
646
+ # 基本批量插入:一次插入多个文本
647
+ rag.insert(["文本1", "文本2",...])
648
+
649
+ # 带有自定义批量大小配置的批量插入
650
+ rag = LightRAG(
651
+ ...
652
+ working_dir=WORKING_DIR,
653
+ max_parallel_insert = 4
654
+ )
655
+
656
+ rag.insert(["文本1", "文本2", "文本3", ...]) # 文档将以4个为一批进行处理
657
+ ```
658
+
659
+ 参数 `max_parallel_insert` 用于控制文档索引流水线中并行处理的文档数量。若未指定,默认值为 **2**。建议将该参数设置为 **10 以下**,因为性能瓶颈通常出现在大语言模型(LLM)的处理环节。
660
+
661
+ </details>
662
+
663
+ <details>
664
+ <summary> <b> 带ID插入 </b></summary>
665
+
666
+ 如果您想为文档提供自己的ID,文档数量和ID数量必须相同。
667
+
668
+ ```python
669
+ # 插入单个文本,并为其提供ID
670
+ rag.insert("文本1", ids=["文本1的ID"])
671
+
672
+ # 插入多个文本,并为它们提供ID
673
+ rag.insert(["文本1", "文本2",...], ids=["文本1的ID", "文本2的ID"])
674
+ ```
675
+
676
+ </details>
677
+
678
+ <details>
679
+ <summary><b>使用流水线插入</b></summary>
680
+
681
+ `apipeline_enqueue_documents`和`apipeline_process_enqueue_documents`函数允许您对文档进行增量插入到图中。
682
+
683
+ 这对于需要在后台处理文档的场景很有用,同时仍允许主线程继续执行。
684
+
685
+ 并使用例程处理新文档。
686
+
687
+ ```python
688
+ rag = LightRAG(..)
689
+
690
+ await rag.apipeline_enqueue_documents(input)
691
+ # 您的循环例程
692
+ await rag.apipeline_process_enqueue_documents(input)
693
+ ```
694
+
695
+ </details>
696
+
697
+ <details>
698
+ <summary><b>插入多文件类型支持</b></summary>
699
+
700
+ `textract`支持读取TXT、DOCX、PPTX、CSV和PDF等文件类型。
701
+
702
+ ```python
703
+ import textract
704
+
705
+ file_path = 'TEXT.pdf'
706
+ text_content = textract.process(file_path)
707
+
708
+ rag.insert(text_content.decode('utf-8'))
709
+ ```
710
+
711
+ </details>
712
+
713
+ <details>
714
+ <summary><b>引文功能</b></summary>
715
+
716
+ 通过提供文件路径,系统确保可以将来源追溯到其原始文档。
717
+
718
+ ```python
719
+ # 定义文档及其文件路径
720
+ documents = ["文档内容1", "文档内容2"]
721
+ file_paths = ["path/to/doc1.txt", "path/to/doc2.txt"]
722
+
723
+ # 插入带有文件路径的文档
724
+ rag.insert(documents, file_paths=file_paths)
725
+ ```
726
+
727
+ </details>
728
+
729
+ ### 存储
730
+
731
+ LightRAG 使用 4 种类型的存储用于不同目的:
732
+
733
+ * KV_STORAGE:llm 响应缓存、文本块、文档信息
734
+ * VECTOR_STORAGE:实体向量、关系向量、块向量
735
+ * GRAPH_STORAGE:实体关系图
736
+ * DOC_STATUS_STORAGE:文档索引状态
737
+
738
+ 每种存储类型都有几种实现:
739
+
740
+ * KV_STORAGE 支持的实现名称
741
+
742
+ ```
743
+ JsonKVStorage JsonFile(默认)
744
+ PGKVStorage Postgres
745
+ RedisKVStorage Redis
746
+ MongoKVStorage MogonDB
747
+ ```
748
+
749
+ * GRAPH_STORAGE 支持的实现名称
750
+
751
+ ```
752
+ NetworkXStorage NetworkX(默认)
753
+ Neo4JStorage Neo4J
754
+ PGGraphStorage PostgreSQL with AGE plugin
755
+ ```
756
+
757
+ > 在测试中Neo4j图形数据库相比PostgreSQL AGE有更好的性能表现。
758
+
759
+ * VECTOR_STORAGE 支持的实现名称
760
+
761
+ ```
762
+ NanoVectorDBStorage NanoVector(默认)
763
+ PGVectorStorage Postgres
764
+ MilvusVectorDBStorge Milvus
765
+ FaissVectorDBStorage Faiss
766
+ QdrantVectorDBStorage Qdrant
767
+ MongoVectorDBStorage MongoDB
768
+ ```
769
+
770
+ * DOC_STATUS_STORAGE 支持的实现名称
771
+
772
+ ```
773
+ JsonDocStatusStorage JsonFile(默认)
774
+ PGDocStatusStorage Postgres
775
+ MongoDocStatusStorage MongoDB
776
+ ```
777
+
778
+ 每一种存储类型的链接配置范例可以在 `env.example` 文件中找到。链接字符串中的数据库实例是需要你预先在数据库服务器上创建好的,LightRAG 仅负责在数据库实例中创建数据表,不负责创建数据库实例。如果使用 Redis 作为存储,记得给 Redis 配置自动持久化数据规则,否则 Redis 服务重启后数据会丢失。如果使用PostgreSQL数据库,推荐使用16.6版本或以上。
779
+
780
+ <details>
781
+ <summary> <b>使用Neo4J存储</b> </summary>
782
+
783
+ * 对于生产级场景,您很可能想要利用企业级解决方案
784
+ * 进行KG存储。推荐在Docker中运行Neo4J以进行无缝本地测试。
785
+ * 参见:https://hub.docker.com/_/neo4j
786
+
787
+ ```python
788
+ export NEO4J_URI="neo4j://localhost:7687"
789
+ export NEO4J_USERNAME="neo4j"
790
+ export NEO4J_PASSWORD="password"
791
+
792
+ # 为LightRAG设置日志记录器
793
+ setup_logger("lightrag", level="INFO")
794
+
795
+ # 当您启动项目时,请确保通过指定kg="Neo4JStorage"来覆盖默认的KG:NetworkX。
796
+
797
+ # 注意:默认设置使用NetworkX
798
+ # 使用Neo4J实现初始化LightRAG。
799
+ async def initialize_rag():
800
+ rag = LightRAG(
801
+ working_dir=WORKING_DIR,
802
+ llm_model_func=gpt_4o_mini_complete, # 使用gpt_4o_mini_complete LLM模型
803
+ graph_storage="Neo4JStorage", #<-----------覆盖KG默认值
804
+ )
805
+
806
+ # 初始化数据库连接
807
+ await rag.initialize_storages()
808
+ # 初始化文档处理的管道状态
809
+ await initialize_pipeline_status()
810
+
811
+ return rag
812
+ ```
813
+
814
+ 参见test_neo4j.py获取工作示例。
815
+
816
+ </details>
817
+
818
+ <details>
819
+ <summary> <b>使用Faiss存储</b> </summary>
820
+ 在使用Faiss向量数据库之前必须手工安装`faiss-cpu`或`faiss-gpu`。
821
+
822
+ - 安装所需依赖:
823
+
824
+ ```
825
+ pip install faiss-cpu
826
+ ```
827
+
828
+ 如果您有GPU支持,也可以安装`faiss-gpu`。
829
+
830
+ - 这里我们使用`sentence-transformers`,但您也可以使用维度为`3072`的`OpenAIEmbedding`模型。
831
+
832
+ ```python
833
+ async def embedding_func(texts: list[str]) -> np.ndarray:
834
+ model = SentenceTransformer('all-MiniLM-L6-v2')
835
+ embeddings = model.encode(texts, convert_to_numpy=True)
836
+ return embeddings
837
+
838
+ # 使用LLM模型函数和嵌入函数初始化LightRAG
839
+ rag = LightRAG(
840
+ working_dir=WORKING_DIR,
841
+ llm_model_func=llm_model_func,
842
+ embedding_func=EmbeddingFunc(
843
+ embedding_dim=384,
844
+ func=embedding_func,
845
+ ),
846
+ vector_storage="FaissVectorDBStorage",
847
+ vector_db_storage_cls_kwargs={
848
+ "cosine_better_than_threshold": 0.3 # 您期望的阈值
849
+ }
850
+ )
851
+ ```
852
+
853
+ </details>
854
+
855
+ <details>
856
+ <summary> <b>使用PostgreSQL存储</b> </summary>
857
+
858
+ 对于生产级场景,您很可能想要利用企业级解决方案。PostgreSQL可以为您提供一站式储解解决方案,作为KV存储、向量数据库(pgvector)和图数据库(apache AGE)。支持 PostgreSQL 版本为16.6或以上。
859
+
860
+ * 如果您是初学者并想避免麻烦,推荐使用docker,请从这个镜像开始(请务必阅读概述):https://hub.docker.com/r/shangor/postgres-for-rag
861
+ * Apache AGE的性能不如Neo4j。最求高性能的图数据库请使用Noe4j。
862
+
863
+ </details>
864
+
865
+ <details>
866
+ <summary> <b>使用MogonDB存储</b> </summary>
867
+
868
+ MongoDB为LightRAG提供了一站式的存储解决方案。MongoDB提供原生的KV存储和向量存储。LightRAG使用MogoDB的集合实现了一个简易的图存储。MongoDB 官方的向量检索功能(`$vectorSearch`)目前必须依赖其官方的云服务 MongoDB Atlas。无法在自托管的 MongoDB Community/Enterprise 版本上使用此功能。
869
+
870
+ </details>
871
+
872
+ <details>
873
+ <summary> <b>使用Redis存储</b> </summary>
874
+
875
+ LightRAG支持使用Reidis作为KV存储。使用Redis存储的时候需要注意进行持久化配置和内存使用量配置。以下是推荐的redis配置
876
+
877
+ ```
878
+ save 900 1
879
+ save 300 10
880
+ save 60 1000
881
+ stop-writes-on-bgsave-error yes
882
+ maxmemory 4gb
883
+ maxmemory-policy noeviction
884
+ maxclients 500
885
+ ```
886
+
887
+ </details>
888
+
889
+ ### LightRAG实例间的数据隔离
890
+
891
+ 通过 workspace 参数可以不同实现不同LightRAG实例之间的存储数据隔离。LightRAG在初始化后workspace就已经确定,之后修改workspace是无效的。下面是不同类型的存储实现工作空间的方式:
892
+
893
+ - **对于本地基于文件的数据库,数据隔离通过工作空间子目录实现:** JsonKVStorage, JsonDocStatusStorage, NetworkXStorage, NanoVectorDBStorage, FaissVectorDBStorage。
894
+ - **对于将数据存储在集合(collection)中的数据库,通过在集合名称前添加工作空间前缀来实现:** RedisKVStorage, RedisDocStatusStorage, MilvusVectorDBStorage, QdrantVectorDBStorage, MongoKVStorage, MongoDocStatusStorage, MongoVectorDBStorage, MongoGraphStorage, PGGraphStorage。
895
+ - **对于关系型数据库,数据隔离通过向表中添加 `workspace` 字段进行数据的逻辑隔离:** PGKVStorage, PGVectorStorage, PGDocStatusStorage。
896
+
897
+ * **对于Neo4j图数据库,通过label来实现数据的逻辑隔离**:Neo4JStorage
898
+
899
+ 为了保持对遗留数据的兼容,在未配置工作空间时PostgreSQL非图存储的工作空间为`default`,PostgreSQL AGE图存储的工作空间为空,Neo4j图存储的默认工作空间为`base`。对于所有的外部存储,系统都提供了专用的工作空间环境变量,用于覆盖公共的 `WORKSPACE`环境变量配置。这些适用于指定存储类型的工作空间环境变量为:`REDIS_WORKSPACE`, `MILVUS_WORKSPACE`, `QDRANT_WORKSPACE`, `MONGODB_WORKSPACE`, `POSTGRES_WORKSPACE`, `NEO4J_WORKSPACE`。
900
+
901
+ ## 编辑实体和关系
902
+
903
+ LightRAG现在支持全面的知识图谱管理功能,允许您在知识图谱中创建、编辑和删除实体和关系。
904
+
905
+ <details>
906
+ <summary> <b>创建实体和关系</b> </summary>
907
+
908
+ ```python
909
+ # 创建新实体
910
+ entity = rag.create_entity("Google", {
911
+ "description": "Google是一家专注于互联网相关服务和产品的跨国科技公司。",
912
+ "entity_type": "company"
913
+ })
914
+
915
+ # 创建另一个实体
916
+ product = rag.create_entity("Gmail", {
917
+ "description": "Gmail是由Google开发的电子邮件服务。",
918
+ "entity_type": "product"
919
+ })
920
+
921
+ # 创建实体之间的关系
922
+ relation = rag.create_relation("Google", "Gmail", {
923
+ "description": "Google开发和运营Gmail。",
924
+ "keywords": "开发 运营 服务",
925
+ "weight": 2.0
926
+ })
927
+ ```
928
+
929
+ </details>
930
+
931
+ <details>
932
+ <summary> <b>编辑实体和关系</b> </summary>
933
+
934
+ ```python
935
+ # 编辑现有实体
936
+ updated_entity = rag.edit_entity("Google", {
937
+ "description": "Google是Alphabet Inc.的子公司,成立于1998年。",
938
+ "entity_type": "tech_company"
939
+ })
940
+
941
+ # 重命名实体(所有关系都会正确迁移)
942
+ renamed_entity = rag.edit_entity("Gmail", {
943
+ "entity_name": "Google Mail",
944
+ "description": "Google Mail(前身为Gmail)是一项电子邮件服务。"
945
+ })
946
+
947
+ # 编辑实体之间的关系
948
+ updated_relation = rag.edit_relation("Google", "Google Mail", {
949
+ "description": "Google创建并维护Google Mail服务。",
950
+ "keywords": "创建 维护 电子邮件服务",
951
+ "weight": 3.0
952
+ })
953
+ ```
954
+
955
+ 所有操作都有同步和异步版本。异步版本带有前缀"a"(例如,`acreate_entity`,`aedit_relation`)。
956
+
957
+ </details>
958
+
959
+ <details>
960
+ <summary> <b>插入自定义知识</b> </summary>
961
+
962
+ ```python
963
+ custom_kg = {
964
+ "chunks": [
965
+ {
966
+ "content": "Alice和Bob正在合作进行量子计算研究。",
967
+ "source_id": "doc-1"
968
+ }
969
+ ],
970
+ "entities": [
971
+ {
972
+ "entity_name": "Alice",
973
+ "entity_type": "person",
974
+ "description": "Alice是一位专门研究量子物理的研究员。",
975
+ "source_id": "doc-1"
976
+ },
977
+ {
978
+ "entity_name": "Bob",
979
+ "entity_type": "person",
980
+ "description": "Bob是一位数学家。",
981
+ "source_id": "doc-1"
982
+ },
983
+ {
984
+ "entity_name": "量子计算",
985
+ "entity_type": "technology",
986
+ "description": "量子计算利用量子力学现象进行计算。",
987
+ "source_id": "doc-1"
988
+ }
989
+ ],
990
+ "relationships": [
991
+ {
992
+ "src_id": "Alice",
993
+ "tgt_id": "Bob",
994
+ "description": "Alice和Bob是研究伙伴。",
995
+ "keywords": "合作 研究",
996
+ "weight": 1.0,
997
+ "source_id": "doc-1"
998
+ },
999
+ {
1000
+ "src_id": "Alice",
1001
+ "tgt_id": "量子计算",
1002
+ "description": "Alice进行量子计算研究。",
1003
+ "keywords": "研究 专业",
1004
+ "weight": 1.0,
1005
+ "source_id": "doc-1"
1006
+ },
1007
+ {
1008
+ "src_id": "Bob",
1009
+ "tgt_id": "量子计算",
1010
+ "description": "Bob研究量子计算。",
1011
+ "keywords": "研究 应用",
1012
+ "weight": 1.0,
1013
+ "source_id": "doc-1"
1014
+ }
1015
+ ]
1016
+ }
1017
+
1018
+ rag.insert_custom_kg(custom_kg)
1019
+ ```
1020
+
1021
+ </details>
1022
+
1023
+ <details>
1024
+ <summary> <b>其它实体与关系操作</b> </summary>
1025
+
1026
+ - **create_entity**:创建具有指定属性的新实体
1027
+ - **edit_entity**:更新现有实体的属性或重命名它
1028
+
1029
+ - **create_relation**:在现有实体之间创建新关系
1030
+ - **edit_relation**:更新现有关系的属性
1031
+
1032
+ 这些操作在图数据库和向量数据库组件之间保持数据一致性,确保您的知识图谱保持连贯。
1033
+
1034
+ </details>
1035
+
1036
+ ## 删除功能
1037
+
1038
+ LightRAG提供了全面的删除功能,允许您删除文档、实体和关系。
1039
+
1040
+ <details>
1041
+ <summary> <b>删除实体</b> </summary>
1042
+
1043
+ 您可以通过实体名称删除实体及其所有关联关系:
1044
+
1045
+ ```python
1046
+ # 删除实体及其所有关系(同步版本)
1047
+ rag.delete_by_entity("Google")
1048
+
1049
+ # 异步版本
1050
+ await rag.adelete_by_entity("Google")
1051
+ ```
1052
+
1053
+ 删除实体时会:
1054
+ - 从知识图谱中移除该实体节点
1055
+ - 删除该实体的所有关联关系
1056
+ - 从向量数据库中移除相关的嵌入向量
1057
+ - 保持知识图谱的完整性
1058
+
1059
+ </details>
1060
+
1061
+ <details>
1062
+ <summary> <b>删除关系</b> </summary>
1063
+
1064
+ 您可以删除两个特定实体之间的关系:
1065
+
1066
+ ```python
1067
+ # 删除两个实体之间的关系(同步版本)
1068
+ rag.delete_by_relation("Google", "Gmail")
1069
+
1070
+ # 异步版本
1071
+ await rag.adelete_by_relation("Google", "Gmail")
1072
+ ```
1073
+
1074
+ 删除关系时会:
1075
+ - 移除指定的关系边
1076
+ - 从向量数据库中删除关系的嵌入向量
1077
+ - 保留两个实体节点及其他关系
1078
+
1079
+ </details>
1080
+
1081
+ <details>
1082
+ <summary> <b>通过文档ID删除</b> </summary>
1083
+
1084
+ 您可以通过文档ID删除整个文档及其相关的所有知识:
1085
+
1086
+ ```python
1087
+ # 通过文档ID删除(异步版本)
1088
+ await rag.adelete_by_doc_id("doc-12345")
1089
+ ```
1090
+
1091
+ 通过文档ID删除时的优化处理:
1092
+ - **智能清理**:自动识别并删除仅属于该文档的实体和关系
1093
+ - **保留共享知识**:如果实体或关系在其他文档中也存在,则会保留并重新构建描述
1094
+ - **缓存优化**:清理相关的LLM缓存以减少存储开销
1095
+ - **增量重建**:从剩余文档重新构建受影响的实体和关系描述
1096
+
1097
+ 删除过程包括:
1098
+ 1. 删除文档相关的所有文本块
1099
+ 2. 识别仅属于该文档的实体和关系并删除
1100
+ 3. 重新构建在其他文档中仍存在的实体和关系
1101
+ 4. 更新所有相关的向量索引
1102
+ 5. 清理文档状态记录
1103
+
1104
+ 注意:通过文档ID删除是一个异步操作,因为它涉及复杂的知识图谱重构过程。
1105
+
1106
+ </details>
1107
+
1108
+ <details>
1109
+ <summary> <b>删除注意事项</b> </summary>
1110
+
1111
+ **重要提醒:**
1112
+
1113
+ 1. **不可逆操作**:所有删除操作都是不可逆的,请谨慎使用
1114
+ 2. **性能考虑**:删除大量数据时可能需要一些时间,特别是通过文档ID删除
1115
+ 3. **数据一致性**:删除操作会自动维护知识图谱和向量数据库之间的一致性
1116
+ 4. **备份建议**:在执行重要删除操作前建议备份数据
1117
+
1118
+ **批量删除建议:**
1119
+ - 对于批量删除操作,建议使用异步方法以获得更好的性能
1120
+ - 大规模删除时,考虑分批进行以避免系统负载过高
1121
+
1122
+ </details>
1123
+
1124
+ ## 实体合并
1125
+
1126
+ <details>
1127
+ <summary> <b>合并实体及其关系</b> </summary>
1128
+
1129
+ LightRAG现在支持将多个实体合并为单个实体,自动处理所有关系:
1130
+
1131
+ ```python
1132
+ # 基本实体合并
1133
+ rag.merge_entities(
1134
+ source_entities=["人工智能", "AI", "机器智能"],
1135
+ target_entity="AI技术"
1136
+ )
1137
+ ```
1138
+
1139
+ 使用自定义合并策略:
1140
+
1141
+ ```python
1142
+ # 为不同字段定义自定义合并策略
1143
+ rag.merge_entities(
1144
+ source_entities=["约翰·史密斯", "史密斯博士", "J·史密斯"],
1145
+ target_entity="约翰·史密斯",
1146
+ merge_strategy={
1147
+ "description": "concatenate", # 组合所有描述
1148
+ "entity_type": "keep_first", # 保留第一个实体的类型
1149
+ "source_id": "join_unique" # 组合所有唯一的源ID
1150
+ }
1151
+ )
1152
+ ```
1153
+
1154
+ 使用自定义目标实体数据:
1155
+
1156
+ ```python
1157
+ # 为合并后的实体指定确切值
1158
+ rag.merge_entities(
1159
+ source_entities=["纽约", "NYC", "大苹果"],
1160
+ target_entity="纽约市",
1161
+ target_entity_data={
1162
+ "entity_type": "LOCATION",
1163
+ "description": "纽约市是美国人口最多的城市。",
1164
+ }
1165
+ )
1166
+ ```
1167
+
1168
+ 结合两种方法的高级用法:
1169
+
1170
+ ```python
1171
+ # 使用策略和自定义数据合并公司实体
1172
+ rag.merge_entities(
1173
+ source_entities=["微软公司", "Microsoft Corporation", "MSFT"],
1174
+ target_entity="微软",
1175
+ merge_strategy={
1176
+ "description": "concatenate", # 组合所有描述
1177
+ "source_id": "join_unique" # 组合源ID
1178
+ },
1179
+ target_entity_data={
1180
+ "entity_type": "ORGANIZATION",
1181
+ }
1182
+ )
1183
+ ```
1184
+
1185
+ 合并实体时:
1186
+
1187
+ * 所有来自源实体的关系都会重定向到目标实体
1188
+ * 重复的关系会被智能合并
1189
+ * 防止自我关系(循环)
1190
+ * 合并后删除源实体
1191
+ * 保留关系权重和属性
1192
+
1193
+ </details>
1194
+
1195
+ ## 多模态文档处理(RAG-Anything集成)
1196
+
1197
+ LightRAG 现已与 [RAG-Anything](https://github.com/HKUDS/RAG-Anything) 实现无缝集成,这是一个专为 LightRAG 构建的**全能多模态文档处理RAG系统**。RAG-Anything 提供先进的解析和检索增强生成(RAG)能力,让您能够无缝处理多模态文档,并从各种文档格式中提取结构化内容——包括文本、图片、表格和公式——以集成到您的RAG流程中。
1198
+
1199
+ **主要特性:**
1200
+ - **端到端多模态流程**:从文档摄取解析到智能多模态问答的完整工作流程
1201
+ - **通用文档支持**:无缝处理PDF、Office文档(DOC/DOCX/PPT/PPTX/XLS/XLSX)、图片和各种文件格式
1202
+ - **专业内容分析**:针对图片、表格、数学公式和异构内容类型的专用处理器
1203
+ - **多模态知识图谱**:自动实体提取和跨模态关系发现以增强理解
1204
+ - **混合智能检索**:覆盖文本和多模态内容的高级搜索能力,具备上下文理解
1205
+
1206
+ **快速开始:**
1207
+ 1. 安装RAG-Anything:
1208
+ ```bash
1209
+ pip install raganything
1210
+ ```
1211
+ 2. 处理多模态文档:
1212
+ <details>
1213
+ <summary> <b> RAGAnything 使用示例 </b></summary>
1214
+
1215
+ ```python
1216
+ import asyncio
1217
+ from raganything import RAGAnything
1218
+ from lightrag import LightRAG
1219
+ from lightrag.llm.openai import openai_complete_if_cache, openai_embed
1220
+ from lightrag.utils import EmbeddingFunc
1221
+ import os
1222
+
1223
+ async def load_existing_lightrag():
1224
+ # 首先,创建或加载现有的 LightRAG 实例
1225
+ lightrag_working_dir = "./existing_lightrag_storage"
1226
+
1227
+ # 检查是否存在之前的 LightRAG 实例
1228
+ if os.path.exists(lightrag_working_dir) and os.listdir(lightrag_working_dir):
1229
+ print("✅ Found existing LightRAG instance, loading...")
1230
+ else:
1231
+ print("❌ No existing LightRAG instance found, will create new one")
1232
+
1233
+ # 使用您的配置创建/加载 LightRAG 实例
1234
+ lightrag_instance = LightRAG(
1235
+ working_dir=lightrag_working_dir,
1236
+ llm_model_func=lambda prompt, system_prompt=None, history_messages=[], **kwargs: openai_complete_if_cache(
1237
+ "gpt-4o-mini",
1238
+ prompt,
1239
+ system_prompt=system_prompt,
1240
+ history_messages=history_messages,
1241
+ api_key="your-api-key",
1242
+ **kwargs,
1243
+ ),
1244
+ embedding_func=EmbeddingFunc(
1245
+ embedding_dim=3072,
1246
+ func=lambda texts: openai_embed(
1247
+ texts,
1248
+ model="text-embedding-3-large",
1249
+ api_key=api_key,
1250
+ base_url=base_url,
1251
+ ),
1252
+ )
1253
+ )
1254
+
1255
+ # 初始化存储(如果有现有数据,这将加载现有数据)
1256
+ await lightrag_instance.initialize_storages()
1257
+
1258
+ # 现在使用现有的 LightRAG 实例初始化 RAGAnything
1259
+ rag = RAGAnything(
1260
+ lightrag=lightrag_instance, # 传递现有的 LightRAG 实例
1261
+ # 仅需要视觉模型用于多模态处理
1262
+ vision_model_func=lambda prompt, system_prompt=None, history_messages=[], image_data=None, **kwargs: openai_complete_if_cache(
1263
+ "gpt-4o",
1264
+ "",
1265
+ system_prompt=None,
1266
+ history_messages=[],
1267
+ messages=[
1268
+ {"role": "system", "content": system_prompt} if system_prompt else None,
1269
+ {"role": "user", "content": [
1270
+ {"type": "text", "text": prompt},
1271
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_data}"}}
1272
+ ]} if image_data else {"role": "user", "content": prompt}
1273
+ ],
1274
+ api_key="your-api-key",
1275
+ **kwargs,
1276
+ ) if image_data else openai_complete_if_cache(
1277
+ "gpt-4o-mini",
1278
+ prompt,
1279
+ system_prompt=system_prompt,
1280
+ history_messages=history_messages,
1281
+ api_key="your-api-key",
1282
+ **kwargs,
1283
+ )
1284
+ # 注意:working_dir、llm_model_func��embedding_func 等都从 lightrag_instance 继承
1285
+ )
1286
+
1287
+ # 查询现有的知识库
1288
+ result = await rag.query_with_multimodal(
1289
+ "What data has been processed in this LightRAG instance?",
1290
+ mode="hybrid"
1291
+ )
1292
+ print("Query result:", result)
1293
+
1294
+ # 向现有的 LightRAG 实例添加新的多模态文档
1295
+ await rag.process_document_complete(
1296
+ file_path="path/to/new/multimodal_document.pdf",
1297
+ output_dir="./output"
1298
+ )
1299
+
1300
+ if __name__ == "__main__":
1301
+ asyncio.run(load_existing_lightrag())
1302
+ ```
1303
+
1304
+ </details>
1305
+
1306
+ 如需详细文档和高级用法,请参阅 [RAG-Anything 仓库](https://github.com/HKUDS/RAG-Anything)。
1307
+
1308
+ ## Token统计功能
1309
+
1310
+ <details>
1311
+ <summary> <b>概述和使用</b> </summary>
1312
+
1313
+ LightRAG提供了TokenTracker工具来跟踪和管理大模型的token消耗。这个功能对于控制API成本和优化性能特别有用。
1314
+
1315
+ ### 使用方法
1316
+
1317
+ ```python
1318
+ from lightrag.utils import TokenTracker
1319
+
1320
+ # 创建TokenTracker实例
1321
+ token_tracker = TokenTracker()
1322
+
1323
+ # 方法1:使用上下文管理器(推荐)
1324
+ # 适用于需要自动跟踪token使用的场景
1325
+ with token_tracker:
1326
+ result1 = await llm_model_func("你的问题1")
1327
+ result2 = await llm_model_func("你的问题2")
1328
+
1329
+ # 方法2:手动添加token使用记录
1330
+ # 适用于需要更精细控制token统计的场景
1331
+ token_tracker.reset()
1332
+
1333
+ rag.insert()
1334
+
1335
+ rag.query("你的问题1", param=QueryParam(mode="naive"))
1336
+ rag.query("你的问题2", param=QueryParam(mode="mix"))
1337
+
1338
+ # 显示总token使用量(包含插入和查询操作)
1339
+ print("Token usage:", token_tracker.get_usage())
1340
+ ```
1341
+
1342
+ ### 使用建议
1343
+ - 在长会话或批量操作中使用上下文管理器,可以自动跟踪所有token消耗
1344
+ - 对于需要分段统计的场景,使用手动模式并适时调用reset()
1345
+ - 定期检查token使用情况,有助于及时发现异常消耗
1346
+ - 在开发测试阶段积极使用此功能,以便优化生产环境的成本
1347
+
1348
+ ### 实际应用示例
1349
+ 您可以参考以下示例来实现token统计:
1350
+ - `examples/lightrag_gemini_track_token_demo.py`:使用Google Gemini模型的token统计示例
1351
+ - `examples/lightrag_siliconcloud_track_token_demo.py`:使用SiliconCloud模型的token统计示例
1352
+
1353
+ 这些示例展示了如何在不同模型和场景下有效地使用TokenTracker功能。
1354
+
1355
+ </details>
1356
+
1357
+ ## 数据导出功能
1358
+
1359
+ ### 概述
1360
+
1361
+ LightRAG允许您以各种格式导出知识图谱数据,用于分析、共享和备份目的。系统支持导出实体、关系和关系数据。
1362
+
1363
+ ### 导出功能
1364
+
1365
+ #### 基本用法
1366
+
1367
+ ```python
1368
+ # 基本CSV导出(默认格式)
1369
+ rag.export_data("knowledge_graph.csv")
1370
+
1371
+ # 指定任意格式
1372
+ rag.export_data("output.xlsx", file_format="excel")
1373
+ ```
1374
+
1375
+ #### 支持的不同文件格式
1376
+
1377
+ ```python
1378
+ # 以CSV格式导出数据
1379
+ rag.export_data("graph_data.csv", file_format="csv")
1380
+
1381
+ # 导出数据到Excel表格
1382
+ rag.export_data("graph_data.xlsx", file_format="excel")
1383
+
1384
+ # 以markdown格式导出数据
1385
+ rag.export_data("graph_data.md", file_format="md")
1386
+
1387
+ # 导出数据为文本
1388
+ rag.export_data("graph_data.txt", file_format="txt")
1389
+ ```
1390
+
1391
+ #### 附加选项
1392
+
1393
+ 在导出中包含向量嵌入(可选):
1394
+
1395
+ ```python
1396
+ rag.export_data("complete_data.csv", include_vector_data=True)
1397
+ ```
1398
+
1399
+ ### 导出数据包括
1400
+
1401
+ 所有导出包括:
1402
+
1403
+ * 实体信息(名称、ID、元数据)
1404
+ * 关系数据(实体之间的连接)
1405
+ * 来自向量数据库的关系信息
1406
+
1407
+ ## 缓存
1408
+
1409
+ <details>
1410
+ <summary> <b>清除缓存</b> </summary>
1411
+
1412
+ 您可以使用不同模式清除LLM响应缓存:
1413
+
1414
+ ```python
1415
+ # 清除所有缓存
1416
+ await rag.aclear_cache()
1417
+
1418
+ # 清除本地模式缓存
1419
+ await rag.aclear_cache(modes=["local"])
1420
+
1421
+ # 清除提取缓存
1422
+ await rag.aclear_cache(modes=["default"])
1423
+
1424
+ # 清除多个模式
1425
+ await rag.aclear_cache(modes=["local", "global", "hybrid"])
1426
+
1427
+ # 同步版本
1428
+ rag.clear_cache(modes=["local"])
1429
+ ```
1430
+
1431
+ 有效的模式包括:
1432
+
1433
+ - `"default"`:提取缓存
1434
+ - `"naive"`:朴素搜索缓存
1435
+ - `"local"`:本地搜索缓存
1436
+ - `"global"`:全局搜索缓存
1437
+ - `"hybrid"`:混合搜索缓存
1438
+ - `"mix"`:混合搜索缓存
1439
+
1440
+ </details>
1441
+
1442
+ ## LightRAG API
1443
+
1444
+ LightRAG服务器旨在提供Web UI和API支持。**有关LightRAG服务器的更多信息,请参阅[LightRAG服务器](./lightrag/api/README.md)。**
1445
+
1446
+ ## 知识图谱可视化
1447
+
1448
+ LightRAG服务器提供全面的知识图谱可视化功能。它支持各种重力布局、节点查询、子图过滤等。**有关LightRAG服务器的更多信息,请参阅[LightRAG服务器](./lightrag/api/README.md)。**
1449
+
1450
+ ![iShot_2025-03-23_12.40.08](./README.assets/iShot_2025-03-23_12.40.08.png)
1451
+
1452
+ ## 评估
1453
+
1454
+ ### 数据集
1455
+
1456
+ LightRAG使用的数据集可以从[TommyChien/UltraDomain](https://huggingface.co/datasets/TommyChien/UltraDomain)下载。
1457
+
1458
+ ### 生成查询
1459
+
1460
+ LightRAG使用以下提示生成高级查询,相应的代码在`example/generate_query.py`中。
1461
+
1462
+ <details>
1463
+ <summary> 提示 </summary>
1464
+
1465
+ ```python
1466
+ 给定以下数据集描述:
1467
+
1468
+ {description}
1469
+
1470
+ 请识别5个可能会使用此数据集的潜在用户。对于每个用户,列出他们会使用此数据集执行的5个任务。然后,对于每个(用户,任务)组合,生成5个需要对整个数据集有高级理解的问题。
1471
+
1472
+ 按以下结构输出结果:
1473
+ - 用户1:[用户描述]
1474
+ - 任务1:[任务描述]
1475
+ - 问题1:
1476
+ - 问题2:
1477
+ - 问题3:
1478
+ - 问题4:
1479
+ - 问题5:
1480
+ - 任务2:[任务描述]
1481
+ ...
1482
+ - 任务5:[任务描述]
1483
+ - 用户2:[用户描述]
1484
+ ...
1485
+ - 用户5:[用户描述]
1486
+ ...
1487
+ ```
1488
+
1489
+ </details>
1490
+
1491
+ ### 批量评估
1492
+
1493
+ 为了评估两个RAG系统在高级查询上的性能,LightRAG使用以下提示,具体代码可在`example/batch_eval.py`中找到。
1494
+
1495
+ <details>
1496
+ <summary> 提示 </summary>
1497
+
1498
+ ```python
1499
+ ---角色---
1500
+ 您是一位专家,负责根据三个标准评估同一问题的两个答案:**全面性**、**多样性**和**赋能性**。
1501
+ ---目标---
1502
+ 您将根据三个标准评估同一问题的两个答案:**全面性**、**多样性**和**赋能性**。
1503
+
1504
+ - **全面性**:答案提供了多少细节来涵盖问题的所有方面和细节?
1505
+ - **多样性**:答案在提供关于问题的不同视角和见解方面有多丰富多样?
1506
+ - **赋能性**:答案在多大程度上帮助读者理解并对主题做出明智判断?
1507
+
1508
+ 对于每个标准,选择更好的答案(答案1或答案2)并解释原因。然后,根据这三个类别选择总体赢家。
1509
+
1510
+ 这是问题:
1511
+ {query}
1512
+
1513
+ 这是两个答案:
1514
+
1515
+ **答案1:**
1516
+ {answer1}
1517
+
1518
+ **答案2:**
1519
+ {answer2}
1520
+
1521
+ 使用上述三个标准评估两个答案,并为每个标准提供详细解释。
1522
+
1523
+ 以下列JSON格式输出您的评估:
1524
+
1525
+ {{
1526
+ "全面性": {{
1527
+ "获胜者": "[答案1或答案2]",
1528
+ "解释": "[在此提供解释]"
1529
+ }},
1530
+ "赋能性": {{
1531
+ "获胜者": "[答案1或答案2]",
1532
+ "解释": "[在此提供解释]"
1533
+ }},
1534
+ "总体获胜者": {{
1535
+ "获胜者": "[答案1或答案2]",
1536
+ "解释": "[根据三个标准总结为什么这个答案是总体获胜者]"
1537
+ }}
1538
+ }}
1539
+ ```
1540
+
1541
+ </details>
1542
+
1543
+ ### 总体性能表
1544
+
1545
+ | |**农业**| |**计算机科学**| |**法律**| |**混合**| |
1546
+ |----------------------|---------------|------------|------|------------|---------|------------|-------|------------|
1547
+ | |NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|
1548
+ |**全面性**|32.4%|**67.6%**|38.4%|**61.6%**|16.4%|**83.6%**|38.8%|**61.2%**|
1549
+ |**多样性**|23.6%|**76.4%**|38.0%|**62.0%**|13.6%|**86.4%**|32.4%|**67.6%**|
1550
+ |**赋能性**|32.4%|**67.6%**|38.8%|**61.2%**|16.4%|**83.6%**|42.8%|**57.2%**|
1551
+ |**总体**|32.4%|**67.6%**|38.8%|**61.2%**|15.2%|**84.8%**|40.0%|**60.0%**|
1552
+ | |RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|
1553
+ |**全面性**|31.6%|**68.4%**|38.8%|**61.2%**|15.2%|**84.8%**|39.2%|**60.8%**|
1554
+ |**多样性**|29.2%|**70.8%**|39.2%|**60.8%**|11.6%|**88.4%**|30.8%|**69.2%**|
1555
+ |**赋能性**|31.6%|**68.4%**|36.4%|**63.6%**|15.2%|**84.8%**|42.4%|**57.6%**|
1556
+ |**总体**|32.4%|**67.6%**|38.0%|**62.0%**|14.4%|**85.6%**|40.0%|**60.0%**|
1557
+ | |HyDE|**LightRAG**|HyDE|**LightRAG**|HyDE|**LightRAG**|HyDE|**LightRAG**|
1558
+ |**全面性**|26.0%|**74.0%**|41.6%|**58.4%**|26.8%|**73.2%**|40.4%|**59.6%**|
1559
+ |**多样性**|24.0%|**76.0%**|38.8%|**61.2%**|20.0%|**80.0%**|32.4%|**67.6%**|
1560
+ |**赋能性**|25.2%|**74.8%**|40.8%|**59.2%**|26.0%|**74.0%**|46.0%|**54.0%**|
1561
+ |**总体**|24.8%|**75.2%**|41.6%|**58.4%**|26.4%|**73.6%**|42.4%|**57.6%**|
1562
+ | |GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|
1563
+ |**全面性**|45.6%|**54.4%**|48.4%|**51.6%**|48.4%|**51.6%**|**50.4%**|49.6%|
1564
+ |**多样性**|22.8%|**77.2%**|40.8%|**59.2%**|26.4%|**73.6%**|36.0%|**64.0%**|
1565
+ |**赋能性**|41.2%|**58.8%**|45.2%|**54.8%**|43.6%|**56.4%**|**50.8%**|49.2%|
1566
+ |**总体**|45.2%|**54.8%**|48.0%|**52.0%**|47.2%|**52.8%**|**50.4%**|49.6%|
1567
+
1568
+ ## 复现
1569
+
1570
+ 所有代码都可以在`./reproduce`目录中找到。
1571
+
1572
+ ### 步骤0 提取唯一上下文
1573
+
1574
+ 首先,我们需要提取数据集中的唯一上下文。
1575
+
1576
+ <details>
1577
+ <summary> 代码 </summary>
1578
+
1579
+ ```python
1580
+ def extract_unique_contexts(input_directory, output_directory):
1581
+
1582
+ os.makedirs(output_directory, exist_ok=True)
1583
+
1584
+ jsonl_files = glob.glob(os.path.join(input_directory, '*.jsonl'))
1585
+ print(f"找到{len(jsonl_files)}个JSONL文件。")
1586
+
1587
+ for file_path in jsonl_files:
1588
+ filename = os.path.basename(file_path)
1589
+ name, ext = os.path.splitext(filename)
1590
+ output_filename = f"{name}_unique_contexts.json"
1591
+ output_path = os.path.join(output_directory, output_filename)
1592
+
1593
+ unique_contexts_dict = {}
1594
+
1595
+ print(f"处理��件:{filename}")
1596
+
1597
+ try:
1598
+ with open(file_path, 'r', encoding='utf-8') as infile:
1599
+ for line_number, line in enumerate(infile, start=1):
1600
+ line = line.strip()
1601
+ if not line:
1602
+ continue
1603
+ try:
1604
+ json_obj = json.loads(line)
1605
+ context = json_obj.get('context')
1606
+ if context and context not in unique_contexts_dict:
1607
+ unique_contexts_dict[context] = None
1608
+ except json.JSONDecodeError as e:
1609
+ print(f"文件{filename}第{line_number}行JSON解码错误:{e}")
1610
+ except FileNotFoundError:
1611
+ print(f"未找到文件:{filename}")
1612
+ continue
1613
+ except Exception as e:
1614
+ print(f"处理文件{filename}时发生错误:{e}")
1615
+ continue
1616
+
1617
+ unique_contexts_list = list(unique_contexts_dict.keys())
1618
+ print(f"文件{filename}中有{len(unique_contexts_list)}个唯一的`context`条目。")
1619
+
1620
+ try:
1621
+ with open(output_path, 'w', encoding='utf-8') as outfile:
1622
+ json.dump(unique_contexts_list, outfile, ensure_ascii=False, indent=4)
1623
+ print(f"唯一的`context`条目已保存到:{output_filename}")
1624
+ except Exception as e:
1625
+ print(f"保存到文件{output_filename}时发生错误:{e}")
1626
+
1627
+ print("所有文件已处理完成。")
1628
+
1629
+ ```
1630
+
1631
+ </details>
1632
+
1633
+ ### 步骤1 插入上下文
1634
+
1635
+ 对于提取的上下文,我们将它们插入到LightRAG系统中。
1636
+
1637
+ <details>
1638
+ <summary> 代码 </summary>
1639
+
1640
+ ```python
1641
+ def insert_text(rag, file_path):
1642
+ with open(file_path, mode='r') as f:
1643
+ unique_contexts = json.load(f)
1644
+
1645
+ retries = 0
1646
+ max_retries = 3
1647
+ while retries < max_retries:
1648
+ try:
1649
+ rag.insert(unique_contexts)
1650
+ break
1651
+ except Exception as e:
1652
+ retries += 1
1653
+ print(f"插入失败,重试({retries}/{max_retries}),错误:{e}")
1654
+ time.sleep(10)
1655
+ if retries == max_retries:
1656
+ print("超过最大重试次数后插入失败")
1657
+ ```
1658
+
1659
+ </details>
1660
+
1661
+ ### 步骤2 生成查询
1662
+
1663
+ 我们从数据集中每个上下文的前半部分和后半部分提取令牌,然后将它们组合为数据集描述以生成查询。
1664
+
1665
+ <details>
1666
+ <summary> 代码 </summary>
1667
+
1668
+ ```python
1669
+ tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
1670
+
1671
+ def get_summary(context, tot_tokens=2000):
1672
+ tokens = tokenizer.tokenize(context)
1673
+ half_tokens = tot_tokens // 2
1674
+
1675
+ start_tokens = tokens[1000:1000 + half_tokens]
1676
+ end_tokens = tokens[-(1000 + half_tokens):1000]
1677
+
1678
+ summary_tokens = start_tokens + end_tokens
1679
+ summary = tokenizer.convert_tokens_to_string(summary_tokens)
1680
+
1681
+ return summary
1682
+ ```
1683
+
1684
+ </details>
1685
+
1686
+ ### 步骤3 查询
1687
+
1688
+ 对于步骤2中生成的查询,我们将提取它们并查询LightRAG。
1689
+
1690
+ <details>
1691
+ <summary> 代码 </summary>
1692
+
1693
+ ```python
1694
+ def extract_queries(file_path):
1695
+ with open(file_path, 'r') as f:
1696
+ data = f.read()
1697
+
1698
+ data = data.replace('**', '')
1699
+
1700
+ queries = re.findall(r'- Question \d+: (.+)', data)
1701
+
1702
+ return queries
1703
+ ```
1704
+
1705
+ </details>
1706
+
1707
+ ## Star历史
1708
+
1709
+ <a href="https://star-history.com/#HKUDS/LightRAG&Date">
1710
+ <picture>
1711
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/LightRAG&type=Date&theme=dark" />
1712
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/LightRAG&type=Date" />
1713
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/LightRAG&type=Date" />
1714
+ </picture>
1715
+ </a>
1716
+
1717
+ ## 贡献
1718
+
1719
+ 感谢所有贡献者!
1720
+
1721
+ <a href="https://github.com/HKUDS/LightRAG/graphs/contributors">
1722
+ <img src="https://contrib.rocks/image?repo=HKUDS/LightRAG" />
1723
+ </a>
1724
+
1725
+ ## 🌟引用
1726
+
1727
+ ```python
1728
+ @article{guo2024lightrag,
1729
+ title={LightRAG: Simple and Fast Retrieval-Augmented Generation},
1730
+ author={Zirui Guo and Lianghao Xia and Yanhua Yu and Tu Ao and Chao Huang},
1731
+ year={2024},
1732
+ eprint={2410.05779},
1733
+ archivePrefix={arXiv},
1734
+ primaryClass={cs.IR}
1735
+ }
1736
+ ```
1737
+
1738
+ **感谢您对我们工作的关注!**
LightRAG/README.md ADDED
@@ -0,0 +1,1889 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <div style="margin: 20px 0;">
4
+ <img src="./assets/logo.png" width="120" height="120" alt="LightRAG Logo" style="border-radius: 20px; box-shadow: 0 8px 32px rgba(0, 217, 255, 0.3);">
5
+ </div>
6
+
7
+ # 🚀 LightRAG: Simple and Fast Retrieval-Augmented Generation
8
+
9
+ <div align="center">
10
+ <a href="https://trendshift.io/repositories/13043" target="_blank"><img src="https://trendshift.io/api/badge/repositories/13043" alt="HKUDS%2FLightRAG | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
11
+ </div>
12
+
13
+ <div align="center">
14
+ <div style="width: 100%; height: 2px; margin: 20px 0; background: linear-gradient(90deg, transparent, #00d9ff, transparent);"></div>
15
+ </div>
16
+
17
+ <div align="center">
18
+ <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; padding: 25px; text-align: center;">
19
+ <p>
20
+ <a href='https://github.com/HKUDS/LightRAG'><img src='https://img.shields.io/badge/🔥Project-Page-00d9ff?style=for-the-badge&logo=github&logoColor=white&labelColor=1a1a2e'></a>
21
+ <a href='https://arxiv.org/abs/2410.05779'><img src='https://img.shields.io/badge/📄arXiv-2410.05779-ff6b6b?style=for-the-badge&logo=arxiv&logoColor=white&labelColor=1a1a2e'></a>
22
+ <a href="https://github.com/HKUDS/LightRAG/stargazers"><img src='https://img.shields.io/github/stars/HKUDS/LightRAG?color=00d9ff&style=for-the-badge&logo=star&logoColor=white&labelColor=1a1a2e' /></a>
23
+ </p>
24
+ <p>
25
+ <img src="https://img.shields.io/badge/🐍Python-3.10-4ecdc4?style=for-the-badge&logo=python&logoColor=white&labelColor=1a1a2e">
26
+ <a href="https://pypi.org/project/lightrag-hku/"><img src="https://img.shields.io/pypi/v/lightrag-hku.svg?style=for-the-badge&logo=pypi&logoColor=white&labelColor=1a1a2e&color=ff6b6b"></a>
27
+ </p>
28
+ <p>
29
+ <a href="https://discord.gg/yF2MmDJyGJ"><img src="https://img.shields.io/badge/💬Discord-Community-7289da?style=for-the-badge&logo=discord&logoColor=white&labelColor=1a1a2e"></a>
30
+ <a href="https://github.com/HKUDS/LightRAG/issues/285"><img src="https://img.shields.io/badge/💬WeChat-Group-07c160?style=for-the-badge&logo=wechat&logoColor=white&labelColor=1a1a2e"></a>
31
+ </p>
32
+ <p>
33
+ <a href="README-zh.md"><img src="https://img.shields.io/badge/🇨🇳中文版-1a1a2e?style=for-the-badge"></a>
34
+ <a href="README.md"><img src="https://img.shields.io/badge/🇺🇸English-1a1a2e?style=for-the-badge"></a>
35
+ </p>
36
+ <p>
37
+ <a href="https://pepy.tech/projects/lightrag-hku"><img src="https://static.pepy.tech/personalized-badge/lightrag-hku?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads"></a>
38
+ </p>
39
+ </div>
40
+ </div>
41
+
42
+ </div>
43
+
44
+ <div align="center" style="margin: 30px 0;">
45
+ <img src="https://user-images.githubusercontent.com/74038190/212284100-561aa473-3905-4a80-b561-0d28506553ee.gif" width="800">
46
+ </div>
47
+
48
+ <div align="center" style="margin: 30px 0;">
49
+ <img src="./README.assets/b2aaf634151b4706892693ffb43d9093.png" width="800" alt="LightRAG Diagram">
50
+ </div>
51
+
52
+ ---
53
+ ## 🎉 News
54
+ - [X] [2025.06.16]🎯📢Our team has released [RAG-Anything](https://github.com/HKUDS/RAG-Anything) an All-in-One Multimodal RAG System for seamless text, image, table, and equation processing.
55
+ - [X] [2025.06.05]🎯📢LightRAG now supports comprehensive multimodal data handling through [RAG-Anything](https://github.com/HKUDS/RAG-Anything) integration, enabling seamless document parsing and RAG capabilities across diverse formats including PDFs, images, Office documents, tables, and formulas. Please refer to the new [multimodal section](https://github.com/HKUDS/LightRAG/?tab=readme-ov-file#multimodal-document-processing-rag-anything-integration) for details.
56
+ - [X] [2025.03.18]🎯📢LightRAG now supports citation functionality, enabling proper source attribution.
57
+ - [X] [2025.02.05]🎯📢Our team has released [VideoRAG](https://github.com/HKUDS/VideoRAG) understanding extremely long-context videos.
58
+ - [X] [2025.01.13]🎯📢Our team has released [MiniRAG](https://github.com/HKUDS/MiniRAG) making RAG simpler with small models.
59
+ - [X] [2025.01.06]🎯📢You can now [use PostgreSQL for Storage](#using-postgresql-for-storage).
60
+ - [X] [2024.12.31]🎯📢LightRAG now supports [deletion by document ID](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#delete).
61
+ - [X] [2024.11.25]🎯📢LightRAG now supports seamless integration of [custom knowledge graphs](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#insert-custom-kg), empowering users to enhance the system with their own domain expertise.
62
+ - [X] [2024.11.19]🎯📢A comprehensive guide to LightRAG is now available on [LearnOpenCV](https://learnopencv.com/lightrag). Many thanks to the blog author.
63
+ - [X] [2024.11.11]🎯📢LightRAG now supports [deleting entities by their names](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#delete).
64
+ - [X] [2024.11.09]🎯📢Introducing the [LightRAG Gui](https://lightrag-gui.streamlit.app), which allows you to insert, query, visualize, and download LightRAG knowledge.
65
+ - [X] [2024.11.04]🎯📢You can now [use Neo4J for Storage](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#using-neo4j-for-storage).
66
+ - [X] [2024.10.29]🎯📢LightRAG now supports multiple file types, including PDF, DOC, PPT, and CSV via `textract`.
67
+ - [X] [2024.10.20]🎯📢We've added a new feature to LightRAG: Graph Visualization.
68
+ - [X] [2024.10.18]🎯📢We've added a link to a [LightRAG Introduction Video](https://youtu.be/oageL-1I0GE). Thanks to the author!
69
+ - [X] [2024.10.17]🎯📢We have created a [Discord channel](https://discord.gg/yF2MmDJyGJ)! Welcome to join for sharing and discussions! 🎉🎉
70
+ - [X] [2024.10.16]🎯📢LightRAG now supports [Ollama models](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
71
+ - [X] [2024.10.15]🎯📢LightRAG now supports [Hugging Face models](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
72
+
73
+ <details>
74
+ <summary style="font-size: 1.4em; font-weight: bold; cursor: pointer; display: list-item;">
75
+ Algorithm Flowchart
76
+ </summary>
77
+
78
+ ![LightRAG Indexing Flowchart](https://learnopencv.com/wp-content/uploads/2024/11/LightRAG-VectorDB-Json-KV-Store-Indexing-Flowchart-scaled.jpg)
79
+ *Figure 1: LightRAG Indexing Flowchart - Img Caption : [Source](https://learnopencv.com/lightrag/)*
80
+ ![LightRAG Retrieval and Querying Flowchart](https://learnopencv.com/wp-content/uploads/2024/11/LightRAG-Querying-Flowchart-Dual-Level-Retrieval-Generation-Knowledge-Graphs-scaled.jpg)
81
+ *Figure 2: LightRAG Retrieval and Querying Flowchart - Img Caption : [Source](https://learnopencv.com/lightrag/)*
82
+
83
+ </details>
84
+
85
+ ## Installation
86
+
87
+ ### Install LightRAG Server
88
+
89
+ The LightRAG Server is designed to provide Web UI and API support. The Web UI facilitates document indexing, knowledge graph exploration, and a simple RAG query interface. LightRAG Server also provide an Ollama compatible interfaces, aiming to emulate LightRAG as an Ollama chat model. This allows AI chat bot, such as Open WebUI, to access LightRAG easily.
90
+
91
+ * Install from PyPI
92
+
93
+ ```bash
94
+ pip install "lightrag-hku[api]"
95
+ cp env.example .env
96
+ lightrag-server
97
+ ```
98
+
99
+ * Installation from Source
100
+
101
+ ```bash
102
+ git clone https://github.com/HKUDS/LightRAG.git
103
+ cd LightRAG
104
+ # create a Python virtual enviroment if neccesary
105
+ # Install in editable mode with API support
106
+ pip install -e ".[api]"
107
+ cp env.example .env
108
+ lightrag-server
109
+ ```
110
+
111
+ * Launching the LightRAG Server with Docker Compose
112
+
113
+ ```
114
+ git clone https://github.com/HKUDS/LightRAG.git
115
+ cd LightRAG
116
+ cp env.example .env
117
+ # modify LLM and Embedding settings in .env
118
+ docker compose up
119
+ ```
120
+
121
+ > Historical versions of LightRAG docker images can be found here: [LightRAG Docker Images]( https://github.com/HKUDS/LightRAG/pkgs/container/lightrag)
122
+
123
+ ### Install LightRAG Core
124
+
125
+ * Install from source (Recommend)
126
+
127
+ ```bash
128
+ cd LightRAG
129
+ pip install -e .
130
+ ```
131
+
132
+ * Install from PyPI
133
+
134
+ ```bash
135
+ pip install lightrag-hku
136
+ ```
137
+
138
+ ## Quick Start
139
+
140
+ ### LLM and Technology Stack Requirements for LightRAG
141
+
142
+ LightRAG's demands on the capabilities of Large Language Models (LLMs) are significantly higher than those of traditional RAG, as it requires the LLM to perform entity-relationship extraction tasks from documents. Configuring appropriate Embedding and Reranker models is also crucial for improving query performance.
143
+
144
+ - **LLM Selection**:
145
+ - It is recommended to use an LLM with at least 32 billion parameters.
146
+ - The context length should be at least 32KB, with 64KB being recommended.
147
+ - It is not recommended to choose reasoning models during the document indexing stage.
148
+ - During the query stage, it is recommended to choose models with stronger capabilities than those used in the indexing stage to achieve better query results.
149
+ - **Embedding Model**:
150
+ - A high-performance Embedding model is essential for RAG.
151
+ - We recommend using mainstream multilingual Embedding models, such as: `BAAI/bge-m3` and `text-embedding-3-large`.
152
+ - **Important Note**: The Embedding model must be determined before document indexing, and the same model must be used during the document query phase. For certain storage solutions (e.g., PostgreSQL), the vector dimension must be defined upon initial table creation. Therefore, when changing embedding models, it is necessary to delete the existing vector-related tables and allow LightRAG to recreate them with the new dimensions.
153
+ - **Reranker Model Configuration**:
154
+ - Configuring a Reranker model can significantly enhance LightRAG's retrieval performance.
155
+ - When a Reranker model is enabled, it is recommended to set the "mix mode" as the default query mode.
156
+ - We recommend using mainstream Reranker models, such as: `BAAI/bge-reranker-v2-m3` or models provided by services like Jina.
157
+
158
+ ### Quick Start for LightRAG Server
159
+
160
+ * For more information about LightRAG Server, please refer to [LightRAG Server](./lightrag/api/README.md).
161
+
162
+ ### Quick Start for LightRAG core
163
+
164
+ To get started with LightRAG core, refer to the sample codes available in the `examples` folder. Additionally, a [video demo](https://www.youtube.com/watch?v=g21royNJ4fw) demonstration is provided to guide you through the local setup process. If you already possess an OpenAI API key, you can run the demo right away:
165
+
166
+ ```bash
167
+ ### you should run the demo code with project folder
168
+ cd LightRAG
169
+ ### provide your API-KEY for OpenAI
170
+ export OPENAI_API_KEY="sk-...your_opeai_key..."
171
+ ### download the demo document of "A Christmas Carol" by Charles Dickens
172
+ curl https://raw.githubusercontent.com/gusye1234/nano-graphrag/main/tests/mock_data.txt > ./book.txt
173
+ ### run the demo code
174
+ python examples/lightrag_openai_demo.py
175
+ ```
176
+
177
+ For a streaming response implementation example, please see `examples/lightrag_openai_compatible_demo.py`. Prior to execution, ensure you modify the sample code's LLM and embedding configurations accordingly.
178
+
179
+ **Note 1**: When running the demo program, please be aware that different test scripts may use different embedding models. If you switch to a different embedding model, you must clear the data directory (`./dickens`); otherwise, the program may encounter errors. If you wish to retain the LLM cache, you can preserve the `kv_store_llm_response_cache.json` file while clearing the data directory.
180
+
181
+ **Note 2**: Only `lightrag_openai_demo.py` and `lightrag_openai_compatible_demo.py` are officially supported sample codes. Other sample files are community contributions that haven't undergone full testing and optimization.
182
+
183
+ ## Programing with LightRAG Core
184
+
185
+ > ⚠️ **If you would like to integrate LightRAG into your project, we recommend utilizing the REST API provided by the LightRAG Server**. LightRAG Core is typically intended for embedded applications or for researchers who wish to conduct studies and evaluations.
186
+
187
+ ### ⚠️ Important: Initialization Requirements
188
+
189
+ **LightRAG requires explicit initialization before use.** You must call both `await rag.initialize_storages()` and `await initialize_pipeline_status()` after creating a LightRAG instance, otherwise you will encounter errors like:
190
+
191
+ - `AttributeError: __aenter__` - if storages are not initialized
192
+ - `KeyError: 'history_messages'` - if pipeline status is not initialized
193
+
194
+ ### A Simple Program
195
+
196
+ Use the below Python snippet to initialize LightRAG, insert text to it, and perform queries:
197
+
198
+ ```python
199
+ import os
200
+ import asyncio
201
+ from lightrag import LightRAG, QueryParam
202
+ from lightrag.llm.openai import gpt_4o_mini_complete, gpt_4o_complete, openai_embed
203
+ from lightrag.kg.shared_storage import initialize_pipeline_status
204
+ from lightrag.utils import setup_logger
205
+
206
+ setup_logger("lightrag", level="INFO")
207
+
208
+ WORKING_DIR = "./rag_storage"
209
+ if not os.path.exists(WORKING_DIR):
210
+ os.mkdir(WORKING_DIR)
211
+
212
+ async def initialize_rag():
213
+ rag = LightRAG(
214
+ working_dir=WORKING_DIR,
215
+ embedding_func=openai_embed,
216
+ llm_model_func=gpt_4o_mini_complete,
217
+ )
218
+ # IMPORTANT: Both initialization calls are required!
219
+ await rag.initialize_storages() # Initialize storage backends
220
+ await initialize_pipeline_status() # Initialize processing pipeline
221
+ return rag
222
+
223
+ async def main():
224
+ try:
225
+ # Initialize RAG instance
226
+ rag = await initialize_rag()
227
+ await rag.ainsert("Your text")
228
+
229
+ # Perform hybrid search
230
+ mode = "hybrid"
231
+ print(
232
+ await rag.aquery(
233
+ "What are the top themes in this story?",
234
+ param=QueryParam(mode=mode)
235
+ )
236
+ )
237
+
238
+ except Exception as e:
239
+ print(f"An error occurred: {e}")
240
+ finally:
241
+ if rag:
242
+ await rag.finalize_storages()
243
+
244
+ if __name__ == "__main__":
245
+ asyncio.run(main())
246
+ ```
247
+
248
+ Important notes for the above snippet:
249
+
250
+ - Export your OPENAI_API_KEY environment variable before running the script.
251
+ - This program uses the default storage settings for LightRAG, so all data will be persisted to WORKING_DIR/rag_storage.
252
+ - This program demonstrates only the simplest way to initialize a LightRAG object: Injecting the embedding and LLM functions, and initializing storage and pipeline status after creating the LightRAG object.
253
+
254
+ ### LightRAG init parameters
255
+
256
+ A full list of LightRAG init parameters:
257
+
258
+ <details>
259
+ <summary> Parameters </summary>
260
+
261
+ | **Parameter** | **Type** | **Explanation** | **Default** |
262
+ |--------------|----------|-----------------|-------------|
263
+ | **working_dir** | `str` | Directory where the cache will be stored | `lightrag_cache+timestamp` |
264
+ | **workspace** | str | Workspace name for data isolation between different LightRAG Instances | |
265
+ | **kv_storage** | `str` | Storage type for documents and text chunks. Supported types: `JsonKVStorage`,`PGKVStorage`,`RedisKVStorage`,`MongoKVStorage` | `JsonKVStorage` |
266
+ | **vector_storage** | `str` | Storage type for embedding vectors. Supported types: `NanoVectorDBStorage`,`PGVectorStorage`,`MilvusVectorDBStorage`,`ChromaVectorDBStorage`,`FaissVectorDBStorage`,`MongoVectorDBStorage`,`QdrantVectorDBStorage` | `NanoVectorDBStorage` |
267
+ | **graph_storage** | `str` | Storage type for graph edges and nodes. Supported types: `NetworkXStorage`,`Neo4JStorage`,`PGGraphStorage`,`AGEStorage` | `NetworkXStorage` |
268
+ | **doc_status_storage** | `str` | Storage type for documents process status. Supported types: `JsonDocStatusStorage`,`PGDocStatusStorage`,`MongoDocStatusStorage` | `JsonDocStatusStorage` |
269
+ | **chunk_token_size** | `int` | Maximum token size per chunk when splitting documents | `1200` |
270
+ | **chunk_overlap_token_size** | `int` | Overlap token size between two chunks when splitting documents | `100` |
271
+ | **tokenizer** | `Tokenizer` | The function used to convert text into tokens (numbers) and back using .encode() and .decode() functions following `TokenizerInterface` protocol. If you don't specify one, it will use the default Tiktoken tokenizer. | `TiktokenTokenizer` |
272
+ | **tiktoken_model_name** | `str` | If you're using the default Tiktoken tokenizer, this is the name of the specific Tiktoken model to use. This setting is ignored if you provide your own tokenizer. | `gpt-4o-mini` |
273
+ | **entity_extract_max_gleaning** | `int` | Number of loops in the entity extraction process, appending history messages | `1` |
274
+ | **node_embedding_algorithm** | `str` | Algorithm for node embedding (currently not used) | `node2vec` |
275
+ | **node2vec_params** | `dict` | Parameters for node embedding | `{"dimensions": 1536,"num_walks": 10,"walk_length": 40,"window_size": 2,"iterations": 3,"random_seed": 3,}` |
276
+ | **embedding_func** | `EmbeddingFunc` | Function to generate embedding vectors from text | `openai_embed` |
277
+ | **embedding_batch_num** | `int` | Maximum batch size for embedding processes (multiple texts sent per batch) | `32` |
278
+ | **embedding_func_max_async** | `int` | Maximum number of concurrent asynchronous embedding processes | `16` |
279
+ | **llm_model_func** | `callable` | Function for LLM generation | `gpt_4o_mini_complete` |
280
+ | **llm_model_name** | `str` | LLM model name for generation | `meta-llama/Llama-3.2-1B-Instruct` |
281
+ | **summary_context_size** | `int` | Maximum tokens send to LLM to generate summaries for entity relation merging | `10000`(configured by env var SUMMARY_CONTEXT_SIZE) |
282
+ | **summary_max_tokens** | `int` | Maximum token size for entity/relation description | `500`(configured by env var SUMMARY_MAX_TOKENS) |
283
+ | **llm_model_max_async** | `int` | Maximum number of concurrent asynchronous LLM processes | `4`(default value changed by env var MAX_ASYNC) |
284
+ | **llm_model_kwargs** | `dict` | Additional parameters for LLM generation | |
285
+ | **vector_db_storage_cls_kwargs** | `dict` | Additional parameters for vector database, like setting the threshold for nodes and relations retrieval | cosine_better_than_threshold: 0.2(default value changed by env var COSINE_THRESHOLD) |
286
+ | **enable_llm_cache** | `bool` | If `TRUE`, stores LLM results in cache; repeated prompts return cached responses | `TRUE` |
287
+ | **enable_llm_cache_for_entity_extract** | `bool` | If `TRUE`, stores LLM results in cache for entity extraction; Good for beginners to debug your application | `TRUE` |
288
+ | **addon_params** | `dict` | Additional parameters, e.g., `{"language": "Simplified Chinese", "entity_types": ["organization", "person", "location", "event"]}`: sets example limit, entiy/relation extraction output language | language: English` |
289
+ | **embedding_cache_config** | `dict` | Configuration for question-answer caching. Contains three parameters: `enabled`: Boolean value to enable/disable cache lookup functionality. When enabled, the system will check cached responses before generating new answers. `similarity_threshold`: Float value (0-1), similarity threshold. When a new question's similarity with a cached question exceeds this threshold, the cached answer will be returned directly without calling the LLM. `use_llm_check`: Boolean value to enable/disable LLM similarity verification. When enabled, LLM will be used as a secondary check to verify the similarity between questions before returning cached answers. | Default: `{"enabled": False, "similarity_threshold": 0.95, "use_llm_check": False}` |
290
+
291
+ </details>
292
+
293
+ ### Query Param
294
+
295
+ Use QueryParam to control the behavior your query:
296
+
297
+ ```python
298
+ class QueryParam:
299
+ """Configuration parameters for query execution in LightRAG."""
300
+
301
+ mode: Literal["local", "global", "hybrid", "naive", "mix", "bypass"] = "global"
302
+ """Specifies the retrieval mode:
303
+ - "local": Focuses on context-dependent information.
304
+ - "global": Utilizes global knowledge.
305
+ - "hybrid": Combines local and global retrieval methods.
306
+ - "naive": Performs a basic search without advanced techniques.
307
+ - "mix": Integrates knowledge graph and vector retrieval.
308
+ """
309
+
310
+ only_need_context: bool = False
311
+ """If True, only returns the retrieved context without generating a response."""
312
+
313
+ only_need_prompt: bool = False
314
+ """If True, only returns the generated prompt without producing a response."""
315
+
316
+ response_type: str = "Multiple Paragraphs"
317
+ """Defines the response format. Examples: 'Multiple Paragraphs', 'Single Paragraph', 'Bullet Points'."""
318
+
319
+ stream: bool = False
320
+ """If True, enables streaming output for real-time responses."""
321
+
322
+ top_k: int = int(os.getenv("TOP_K", "60"))
323
+ """Number of top items to retrieve. Represents entities in 'local' mode and relationships in 'global' mode."""
324
+
325
+ chunk_top_k: int = int(os.getenv("CHUNK_TOP_K", "20"))
326
+ """Number of text chunks to retrieve initially from vector search and keep after reranking.
327
+ If None, defaults to top_k value.
328
+ """
329
+
330
+ max_entity_tokens: int = int(os.getenv("MAX_ENTITY_TOKENS", "6000"))
331
+ """Maximum number of tokens allocated for entity context in unified token control system."""
332
+
333
+ max_relation_tokens: int = int(os.getenv("MAX_RELATION_TOKENS", "8000"))
334
+ """Maximum number of tokens allocated for relationship context in unified token control system."""
335
+
336
+ max_total_tokens: int = int(os.getenv("MAX_TOTAL_TOKENS", "30000"))
337
+ """Maximum total tokens budget for the entire query context (entities + relations + chunks + system prompt)."""
338
+
339
+ conversation_history: list[dict[str, str]] = field(default_factory=list)
340
+ """Stores past conversation history to maintain context.
341
+ Format: [{"role": "user/assistant", "content": "message"}].
342
+ """
343
+
344
+ # Deprated: history message have negtive effect on query performance
345
+ history_turns: int = 0
346
+ """Number of complete conversation turns (user-assistant pairs) to consider in the response context."""
347
+
348
+ ids: list[str] | None = None
349
+ """List of ids to filter the results."""
350
+
351
+ model_func: Callable[..., object] | None = None
352
+ """Optional override for the LLM model function to use for this specific query.
353
+ If provided, this will be used instead of the global model function.
354
+ This allows using different models for different query modes.
355
+ """
356
+
357
+ user_prompt: str | None = None
358
+ """User-provided prompt for the query.
359
+ If proivded, this will be use instead of the default vaulue from prompt template.
360
+ """
361
+
362
+ enable_rerank: bool = True
363
+ """Enable reranking for retrieved text chunks. If True but no rerank model is configured, a warning will be issued.
364
+ Default is True to enable reranking when rerank model is available.
365
+ """
366
+ ```
367
+
368
+ > default value of Top_k can be change by environment variables TOP_K.
369
+
370
+ ### LLM and Embedding Injection
371
+
372
+ LightRAG requires the utilization of LLM and Embedding models to accomplish document indexing and querying tasks. During the initialization phase, it is necessary to inject the invocation methods of the relevant models into LightRAG:
373
+
374
+ <details>
375
+ <summary> <b>Using Open AI-like APIs</b> </summary>
376
+
377
+ * LightRAG also supports Open AI-like chat/embeddings APIs:
378
+
379
+ ```python
380
+ async def llm_model_func(
381
+ prompt, system_prompt=None, history_messages=[], keyword_extraction=False, **kwargs
382
+ ) -> str:
383
+ return await openai_complete_if_cache(
384
+ "solar-mini",
385
+ prompt,
386
+ system_prompt=system_prompt,
387
+ history_messages=history_messages,
388
+ api_key=os.getenv("UPSTAGE_API_KEY"),
389
+ base_url="https://api.upstage.ai/v1/solar",
390
+ **kwargs
391
+ )
392
+
393
+ async def embedding_func(texts: list[str]) -> np.ndarray:
394
+ return await openai_embed(
395
+ texts,
396
+ model="solar-embedding-1-large-query",
397
+ api_key=os.getenv("UPSTAGE_API_KEY"),
398
+ base_url="https://api.upstage.ai/v1/solar"
399
+ )
400
+
401
+ async def initialize_rag():
402
+ rag = LightRAG(
403
+ working_dir=WORKING_DIR,
404
+ llm_model_func=llm_model_func,
405
+ embedding_func=EmbeddingFunc(
406
+ embedding_dim=4096,
407
+ func=embedding_func
408
+ )
409
+ )
410
+
411
+ await rag.initialize_storages()
412
+ await initialize_pipeline_status()
413
+
414
+ return rag
415
+ ```
416
+
417
+ </details>
418
+
419
+ <details>
420
+ <summary> <b>Using Hugging Face Models</b> </summary>
421
+
422
+ * If you want to use Hugging Face models, you only need to set LightRAG as follows:
423
+
424
+ See `lightrag_hf_demo.py`
425
+
426
+ ```python
427
+ # Initialize LightRAG with Hugging Face model
428
+ rag = LightRAG(
429
+ working_dir=WORKING_DIR,
430
+ llm_model_func=hf_model_complete, # Use Hugging Face model for text generation
431
+ llm_model_name='meta-llama/Llama-3.1-8B-Instruct', # Model name from Hugging Face
432
+ # Use Hugging Face embedding function
433
+ embedding_func=EmbeddingFunc(
434
+ embedding_dim=384,
435
+ func=lambda texts: hf_embed(
436
+ texts,
437
+ tokenizer=AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2"),
438
+ embed_model=AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
439
+ )
440
+ ),
441
+ )
442
+ ```
443
+
444
+ </details>
445
+
446
+ <details>
447
+ <summary> <b>Using Ollama Models</b> </summary>
448
+ **Overview**
449
+
450
+ If you want to use Ollama models, you need to pull model you plan to use and embedding model, for example `nomic-embed-text`.
451
+
452
+ Then you only need to set LightRAG as follows:
453
+
454
+ ```python
455
+ # Initialize LightRAG with Ollama model
456
+ rag = LightRAG(
457
+ working_dir=WORKING_DIR,
458
+ llm_model_func=ollama_model_complete, # Use Ollama model for text generation
459
+ llm_model_name='your_model_name', # Your model name
460
+ # Use Ollama embedding function
461
+ embedding_func=EmbeddingFunc(
462
+ embedding_dim=768,
463
+ func=lambda texts: ollama_embed(
464
+ texts,
465
+ embed_model="nomic-embed-text"
466
+ )
467
+ ),
468
+ )
469
+ ```
470
+
471
+ * **Increasing context size**
472
+
473
+ In order for LightRAG to work context should be at least 32k tokens. By default Ollama models have context size of 8k. You can achieve this using one of two ways:
474
+
475
+ * **Increasing the `num_ctx` parameter in Modelfile**
476
+
477
+ 1. Pull the model:
478
+
479
+ ```bash
480
+ ollama pull qwen2
481
+ ```
482
+
483
+ 2. Display the model file:
484
+
485
+ ```bash
486
+ ollama show --modelfile qwen2 > Modelfile
487
+ ```
488
+
489
+ 3. Edit the Modelfile by adding the following line:
490
+
491
+ ```bash
492
+ PARAMETER num_ctx 32768
493
+ ```
494
+
495
+ 4. Create the modified model:
496
+
497
+ ```bash
498
+ ollama create -f Modelfile qwen2m
499
+ ```
500
+
501
+ * **Setup `num_ctx` via Ollama API**
502
+
503
+ Tiy can use `llm_model_kwargs` param to configure ollama:
504
+
505
+ ```python
506
+ rag = LightRAG(
507
+ working_dir=WORKING_DIR,
508
+ llm_model_func=ollama_model_complete, # Use Ollama model for text generation
509
+ llm_model_name='your_model_name', # Your model name
510
+ llm_model_kwargs={"options": {"num_ctx": 32768}},
511
+ # Use Ollama embedding function
512
+ embedding_func=EmbeddingFunc(
513
+ embedding_dim=768,
514
+ func=lambda texts: ollama_embed(
515
+ texts,
516
+ embed_model="nomic-embed-text"
517
+ )
518
+ ),
519
+ )
520
+ ```
521
+
522
+ * **Low RAM GPUs**
523
+
524
+ In order to run this experiment on low RAM GPU you should select small model and tune context window (increasing context increase memory consumption). For example, running this ollama example on repurposed mining GPU with 6Gb of RAM required to set context size to 26k while using `gemma2:2b`. It was able to find 197 entities and 19 relations on `book.txt`.
525
+
526
+ </details>
527
+ <details>
528
+ <summary> <b>LlamaIndex</b> </summary>
529
+
530
+ LightRAG supports integration with LlamaIndex (`llm/llama_index_impl.py`):
531
+
532
+ - Integrates with OpenAI and other providers through LlamaIndex
533
+ - See [LlamaIndex Documentation](lightrag/llm/Readme.md) for detailed setup and examples
534
+
535
+ **Example Usage**
536
+
537
+ ```python
538
+ # Using LlamaIndex with direct OpenAI access
539
+ import asyncio
540
+ from lightrag import LightRAG
541
+ from lightrag.llm.llama_index_impl import llama_index_complete_if_cache, llama_index_embed
542
+ from llama_index.embeddings.openai import OpenAIEmbedding
543
+ from llama_index.llms.openai import OpenAI
544
+ from lightrag.kg.shared_storage import initialize_pipeline_status
545
+ from lightrag.utils import setup_logger
546
+
547
+ # Setup log handler for LightRAG
548
+ setup_logger("lightrag", level="INFO")
549
+
550
+ async def initialize_rag():
551
+ rag = LightRAG(
552
+ working_dir="your/path",
553
+ llm_model_func=llama_index_complete_if_cache, # LlamaIndex-compatible completion function
554
+ embedding_func=EmbeddingFunc( # LlamaIndex-compatible embedding function
555
+ embedding_dim=1536,
556
+ func=lambda texts: llama_index_embed(texts, embed_model=embed_model)
557
+ ),
558
+ )
559
+
560
+ await rag.initialize_storages()
561
+ await initialize_pipeline_status()
562
+
563
+ return rag
564
+
565
+ def main():
566
+ # Initialize RAG instance
567
+ rag = asyncio.run(initialize_rag())
568
+
569
+ with open("./book.txt", "r", encoding="utf-8") as f:
570
+ rag.insert(f.read())
571
+
572
+ # Perform naive search
573
+ print(
574
+ rag.query("What are the top themes in this story?", param=QueryParam(mode="naive"))
575
+ )
576
+
577
+ # Perform local search
578
+ print(
579
+ rag.query("What are the top themes in this story?", param=QueryParam(mode="local"))
580
+ )
581
+
582
+ # Perform global search
583
+ print(
584
+ rag.query("What are the top themes in this story?", param=QueryParam(mode="global"))
585
+ )
586
+
587
+ # Perform hybrid search
588
+ print(
589
+ rag.query("What are the top themes in this story?", param=QueryParam(mode="hybrid"))
590
+ )
591
+
592
+ if __name__ == "__main__":
593
+ main()
594
+ ```
595
+
596
+ **For detailed documentation and examples, see:**
597
+
598
+ - [LlamaIndex Documentation](lightrag/llm/Readme.md)
599
+ - [Direct OpenAI Example](examples/lightrag_llamaindex_direct_demo.py)
600
+ - [LiteLLM Proxy Example](examples/lightrag_llamaindex_litellm_demo.py)
601
+
602
+ </details>
603
+
604
+ ### Rerank Function Injection
605
+
606
+ To enhance retrieval quality, documents can be re-ranked based on a more effective relevance scoring model. The `rerank.py` file provides three Reranker provider driver functions:
607
+
608
+ * **Cohere / vLLM**: `cohere_rerank`
609
+ * **Jina AI**: `jina_rerank`
610
+ * **Aliyun**: `ali_rerank`
611
+
612
+ You can inject one of these functions into the `rerank_model_func` attribute of the LightRAG object. This will enable LightRAG's query function to re-order retrieved text blocks using the injected function. For detailed usage, please refer to the `examples/rerank_example.py` file.
613
+
614
+ ### User Prompt vs. Query
615
+
616
+ When using LightRAG for content queries, avoid combining the search process with unrelated output processing, as this significantly impacts query effectiveness. The `user_prompt` parameter in Query Param is specifically designed to address this issue — it does not participate in the RAG retrieval phase, but rather guides the LLM on how to process the retrieved results after the query is completed. Here's how to use it:
617
+
618
+ ```python
619
+ # Create query parameters
620
+ query_param = QueryParam(
621
+ mode = "hybrid", # Other modes:local, global, hybrid, mix, naive
622
+ user_prompt = "For diagrams, use mermaid format with English/Pinyin node names and Chinese display labels",
623
+ )
624
+
625
+ # Query and process
626
+ response_default = rag.query(
627
+ "Please draw a character relationship diagram for Scrooge",
628
+ param=query_param
629
+ )
630
+ print(response_default)
631
+ ```
632
+
633
+ ### Insert
634
+
635
+ <details>
636
+ <summary> <b> Basic Insert </b></summary>
637
+
638
+ ```python
639
+ # Basic Insert
640
+ rag.insert("Text")
641
+ ```
642
+
643
+ </details>
644
+
645
+ <details>
646
+ <summary> <b> Batch Insert </b></summary>
647
+
648
+ ```python
649
+ # Basic Batch Insert: Insert multiple texts at once
650
+ rag.insert(["TEXT1", "TEXT2",...])
651
+
652
+ # Batch Insert with custom batch size configuration
653
+ rag = LightRAG(
654
+ ...
655
+ working_dir=WORKING_DIR,
656
+ max_parallel_insert = 4
657
+ )
658
+
659
+ rag.insert(["TEXT1", "TEXT2", "TEXT3", ...]) # Documents will be processed in batches of 4
660
+ ```
661
+
662
+ The `max_parallel_insert` parameter determines the number of documents processed concurrently in the document indexing pipeline. If unspecified, the default value is **2**. We recommend keeping this setting **below 10**, as the performance bottleneck typically lies with the LLM (Large Language Model) processing.The `max_parallel_insert` parameter determines the number of documents processed concurrently in the document indexing pipeline. If unspecified, the default value is **2**. We recommend keeping this setting **below 10**, as the performance bottleneck typically lies with the LLM (Large Language Model) processing.
663
+
664
+ </details>
665
+
666
+ <details>
667
+ <summary> <b> Insert with ID </b></summary>
668
+
669
+ If you want to provide your own IDs for your documents, number of documents and number of IDs must be the same.
670
+
671
+ ```python
672
+ # Insert single text, and provide ID for it
673
+ rag.insert("TEXT1", ids=["ID_FOR_TEXT1"])
674
+
675
+ # Insert multiple texts, and provide IDs for them
676
+ rag.insert(["TEXT1", "TEXT2",...], ids=["ID_FOR_TEXT1", "ID_FOR_TEXT2"])
677
+ ```
678
+
679
+ </details>
680
+
681
+ <details>
682
+ <summary><b>Insert using Pipeline</b></summary>
683
+
684
+ The `apipeline_enqueue_documents` and `apipeline_process_enqueue_documents` functions allow you to perform incremental insertion of documents into the graph.
685
+
686
+ This is useful for scenarios where you want to process documents in the background while still allowing the main thread to continue executing.
687
+
688
+ And using a routine to process new documents.
689
+
690
+ ```python
691
+ rag = LightRAG(..)
692
+
693
+ await rag.apipeline_enqueue_documents(input)
694
+ # Your routine in loop
695
+ await rag.apipeline_process_enqueue_documents(input)
696
+ ```
697
+
698
+ </details>
699
+
700
+ <details>
701
+ <summary><b>Insert Multi-file Type Support</b></summary>
702
+
703
+ The `textract` supports reading file types such as TXT, DOCX, PPTX, CSV, and PDF.
704
+
705
+ ```python
706
+ import textract
707
+
708
+ file_path = 'TEXT.pdf'
709
+ text_content = textract.process(file_path)
710
+
711
+ rag.insert(text_content.decode('utf-8'))
712
+ ```
713
+
714
+ </details>
715
+
716
+ <details>
717
+ <summary><b>Citation Functionality</b></summary>
718
+
719
+ By providing file paths, the system ensures that sources can be traced back to their original documents.
720
+
721
+ ```python
722
+ # Define documents and their file paths
723
+ documents = ["Document content 1", "Document content 2"]
724
+ file_paths = ["path/to/doc1.txt", "path/to/doc2.txt"]
725
+
726
+ # Insert documents with file paths
727
+ rag.insert(documents, file_paths=file_paths)
728
+ ```
729
+
730
+ </details>
731
+
732
+ ### Storage
733
+
734
+ LightRAG uses 4 types of storage for different purposes:
735
+
736
+ * KV_STORAGE: llm response cache, text chunks, document information
737
+ * VECTOR_STORAGE: entities vectors, relation vectors, chunks vectors
738
+ * GRAPH_STORAGE: entity relation graph
739
+ * DOC_STATUS_STORAGE: document indexing status
740
+
741
+ Each storage type has several implementations:
742
+
743
+ * KV_STORAGE supported implementations:
744
+
745
+ ```
746
+ JsonKVStorage JsonFile (default)
747
+ PGKVStorage Postgres
748
+ RedisKVStorage Redis
749
+ MongoKVStorage MongoDB
750
+ ```
751
+
752
+ * GRAPH_STORAGE supported implementations:
753
+
754
+ ```
755
+ NetworkXStorage NetworkX (default)
756
+ Neo4JStorage Neo4J
757
+ PGGraphStorage PostgreSQL with AGE plugin
758
+ MemgraphStorage. Memgraph
759
+ ```
760
+
761
+ > Testing has shown that Neo4J delivers superior performance in production environments compared to PostgreSQL with AGE plugin.
762
+
763
+ * VECTOR_STORAGE supported implementations:
764
+
765
+ ```
766
+ NanoVectorDBStorage NanoVector (default)
767
+ PGVectorStorage Postgres
768
+ MilvusVectorDBStorage Milvus
769
+ FaissVectorDBStorage Faiss
770
+ QdrantVectorDBStorage Qdrant
771
+ MongoVectorDBStorage MongoDB
772
+ ```
773
+
774
+ * DOC_STATUS_STORAGE: supported implementations:
775
+
776
+ ```
777
+ JsonDocStatusStorage JsonFile (default)
778
+ PGDocStatusStorage Postgres
779
+ MongoDocStatusStorage MongoDB
780
+ ```
781
+
782
+ Example connection configurations for each storage type can be found in the `env.example` file. The database instance in the connection string needs to be created by you on the database server beforehand. LightRAG is only responsible for creating tables within the database instance, not for creating the database instance itself. If using Redis as storage, remember to configure automatic data persistence rules for Redis, otherwise data will be lost after the Redis service restarts. If using PostgreSQL, it is recommended to use version 16.6 or above.
783
+
784
+ <details>
785
+ <summary> <b>Using Neo4J Storage</b> </summary>
786
+
787
+ * For production level scenarios you will most likely want to leverage an enterprise solution
788
+ * for KG storage. Running Neo4J in Docker is recommended for seamless local testing.
789
+ * See: https://hub.docker.com/_/neo4j
790
+
791
+ ```python
792
+ export NEO4J_URI="neo4j://localhost:7687"
793
+ export NEO4J_USERNAME="neo4j"
794
+ export NEO4J_PASSWORD="password"
795
+
796
+ # Setup logger for LightRAG
797
+ setup_logger("lightrag", level="INFO")
798
+
799
+ # When you launch the project be sure to override the default KG: NetworkX
800
+ # by specifying kg="Neo4JStorage".
801
+
802
+ # Note: Default settings use NetworkX
803
+ # Initialize LightRAG with Neo4J implementation.
804
+ async def initialize_rag():
805
+ rag = LightRAG(
806
+ working_dir=WORKING_DIR,
807
+ llm_model_func=gpt_4o_mini_complete, # Use gpt_4o_mini_complete LLM model
808
+ graph_storage="Neo4JStorage", #<-----------override KG default
809
+ )
810
+
811
+ # Initialize database connections
812
+ await rag.initialize_storages()
813
+ # Initialize pipeline status for document processing
814
+ await initialize_pipeline_status()
815
+
816
+ return rag
817
+ ```
818
+
819
+ see test_neo4j.py for a working example.
820
+
821
+ </details>
822
+
823
+ <details>
824
+ <summary> <b>Using PostgreSQL Storage</b> </summary>
825
+
826
+ For production level scenarios you will most likely want to leverage an enterprise solution. PostgreSQL can provide a one-stop solution for you as KV store, VectorDB (pgvector) and GraphDB (apache AGE). PostgreSQL version 16.6 or higher is supported.
827
+
828
+ * PostgreSQL is lightweight,the whole binary distribution including all necessary plugins can be zipped to 40MB: Ref to [Windows Release](https://github.com/ShanGor/apache-age-windows/releases/tag/PG17%2Fv1.5.0-rc0) as it is easy to install for Linux/Mac.
829
+ * If you prefer docker, please start with this image if you are a beginner to avoid hiccups (DO read the overview): https://hub.docker.com/r/shangor/postgres-for-rag
830
+ * How to start? Ref to: [examples/lightrag_zhipu_postgres_demo.py](https://github.com/HKUDS/LightRAG/blob/main/examples/lightrag_zhipu_postgres_demo.py)
831
+ * For high-performance graph database requirements, Neo4j is recommended as Apache AGE's performance is not as competitive.
832
+
833
+ </details>
834
+
835
+ <details>
836
+ <summary> <b>Using Faiss Storage</b> </summary>
837
+ Before using Faiss vector database, you must manually install `faiss-cpu` or `faiss-gpu`.
838
+
839
+ - Install the required dependencies:
840
+
841
+ ```
842
+ pip install faiss-cpu
843
+ ```
844
+
845
+ You can also install `faiss-gpu` if you have GPU support.
846
+
847
+ - Here we are using `sentence-transformers` but you can also use `OpenAIEmbedding` model with `3072` dimensions.
848
+
849
+ ```python
850
+ async def embedding_func(texts: list[str]) -> np.ndarray:
851
+ model = SentenceTransformer('all-MiniLM-L6-v2')
852
+ embeddings = model.encode(texts, convert_to_numpy=True)
853
+ return embeddings
854
+
855
+ # Initialize LightRAG with the LLM model function and embedding function
856
+ rag = LightRAG(
857
+ working_dir=WORKING_DIR,
858
+ llm_model_func=llm_model_func,
859
+ embedding_func=EmbeddingFunc(
860
+ embedding_dim=384,
861
+ func=embedding_func,
862
+ ),
863
+ vector_storage="FaissVectorDBStorage",
864
+ vector_db_storage_cls_kwargs={
865
+ "cosine_better_than_threshold": 0.3 # Your desired threshold
866
+ }
867
+ )
868
+ ```
869
+
870
+ </details>
871
+
872
+ <details>
873
+ <summary> <b>Using Memgraph for Storage</b> </summary>
874
+
875
+ * Memgraph is a high-performance, in-memory graph database compatible with the Neo4j Bolt protocol.
876
+ * You can run Memgraph locally using Docker for easy testing:
877
+ * See: https://memgraph.com/download
878
+
879
+ ```python
880
+ export MEMGRAPH_URI="bolt://localhost:7687"
881
+
882
+ # Setup logger for LightRAG
883
+ setup_logger("lightrag", level="INFO")
884
+
885
+ # When you launch the project, override the default KG: NetworkX
886
+ # by specifying kg="MemgraphStorage".
887
+
888
+ # Note: Default settings use NetworkX
889
+ # Initialize LightRAG with Memgraph implementation.
890
+ async def initialize_rag():
891
+ rag = LightRAG(
892
+ working_dir=WORKING_DIR,
893
+ llm_model_func=gpt_4o_mini_complete, # Use gpt_4o_mini_complete LLM model
894
+ graph_storage="MemgraphStorage", #<-----------override KG default
895
+ )
896
+
897
+ # Initialize database connections
898
+ await rag.initialize_storages()
899
+ # Initialize pipeline status for document processing
900
+ await initialize_pipeline_status()
901
+
902
+ return rag
903
+ ```
904
+
905
+ </details>
906
+
907
+ <details>
908
+ <summary> <b>Using MongoDB Storage</b> </summary>
909
+
910
+ MongoDB provides a one-stop storage solution for LightRAG. MongoDB offers native KV storage and vector storage. LightRAG uses MongoDB collections to implement a simple graph storage. MongoDB's official vector search functionality (`$vectorSearch`) currently requires their official cloud service MongoDB Atlas. This functionality cannot be used on self-hosted MongoDB Community/Enterprise versions.
911
+
912
+ </details>
913
+
914
+ <details>
915
+ <summary> <b>Using Redis Storage</b> </summary>
916
+
917
+ LightRAG supports using Redis as KV storage. When using Redis storage, attention should be paid to persistence configuration and memory usage configuration. The following is the recommended Redis configuration:
918
+
919
+ ```
920
+ save 900 1
921
+ save 300 10
922
+ save 60 1000
923
+ stop-writes-on-bgsave-error yes
924
+ maxmemory 4gb
925
+ maxmemory-policy noeviction
926
+ maxclients 500
927
+ ```
928
+
929
+ </details>
930
+
931
+ ### Data Isolation Between LightRAG Instances
932
+
933
+ The `workspace` parameter ensures data isolation between different LightRAG instances. Once initialized, the `workspace` is immutable and cannot be changed.Here is how workspaces are implemented for different types of storage:
934
+
935
+ - **For local file-based databases, data isolation is achieved through workspace subdirectories:** `JsonKVStorage`, `JsonDocStatusStorage`, `NetworkXStorage`, `NanoVectorDBStorage`, `FaissVectorDBStorage`.
936
+ - **For databases that store data in collections, it's done by adding a workspace prefix to the collection name:** `RedisKVStorage`, `RedisDocStatusStorage`, `MilvusVectorDBStorage`, `QdrantVectorDBStorage`, `MongoKVStorage`, `MongoDocStatusStorage`, `MongoVectorDBStorage`, `MongoGraphStorage`, `PGGraphStorage`.
937
+ - **For relational databases, data isolation is achieved by adding a `workspace` field to the tables for logical data separation:** `PGKVStorage`, `PGVectorStorage`, `PGDocStatusStorage`.
938
+ - **For the Neo4j graph database, logical data isolation is achieved through labels:** `Neo4JStorage`
939
+
940
+ To maintain compatibility with legacy data, the default workspace for PostgreSQL non-graph storage is `default` and, for PostgreSQL AGE graph storage is null, for Neo4j graph storage is `base` when no workspace is configured. For all external storages, the system provides dedicated workspace environment variables to override the common `WORKSPACE` environment variable configuration. These storage-specific workspace environment variables are: `REDIS_WORKSPACE`, `MILVUS_WORKSPACE`, `QDRANT_WORKSPACE`, `MONGODB_WORKSPACE`, `POSTGRES_WORKSPACE`, `NEO4J_WORKSPACE`.
941
+
942
+ ## Edit Entities and Relations
943
+
944
+ LightRAG now supports comprehensive knowledge graph management capabilities, allowing you to create, edit, and delete entities and relationships within your knowledge graph.
945
+
946
+ <details>
947
+ <summary> <b> Create Entities and Relations </b></summary>
948
+
949
+ ```python
950
+ # Create new entity
951
+ entity = rag.create_entity("Google", {
952
+ "description": "Google is a multinational technology company specializing in internet-related services and products.",
953
+ "entity_type": "company"
954
+ })
955
+
956
+ # Create another entity
957
+ product = rag.create_entity("Gmail", {
958
+ "description": "Gmail is an email service developed by Google.",
959
+ "entity_type": "product"
960
+ })
961
+
962
+ # Create relation between entities
963
+ relation = rag.create_relation("Google", "Gmail", {
964
+ "description": "Google develops and operates Gmail.",
965
+ "keywords": "develops operates service",
966
+ "weight": 2.0
967
+ })
968
+ ```
969
+
970
+ </details>
971
+
972
+ <details>
973
+ <summary> <b> Edit Entities and Relations </b></summary>
974
+
975
+ ```python
976
+ # Edit an existing entity
977
+ updated_entity = rag.edit_entity("Google", {
978
+ "description": "Google is a subsidiary of Alphabet Inc., founded in 1998.",
979
+ "entity_type": "tech_company"
980
+ })
981
+
982
+ # Rename an entity (with all its relationships properly migrated)
983
+ renamed_entity = rag.edit_entity("Gmail", {
984
+ "entity_name": "Google Mail",
985
+ "description": "Google Mail (formerly Gmail) is an email service."
986
+ })
987
+
988
+ # Edit a relation between entities
989
+ updated_relation = rag.edit_relation("Google", "Google Mail", {
990
+ "description": "Google created and maintains Google Mail service.",
991
+ "keywords": "creates maintains email service",
992
+ "weight": 3.0
993
+ })
994
+ ```
995
+
996
+ All operations are available in both synchronous and asynchronous versions. The asynchronous versions have the prefix "a" (e.g., `acreate_entity`, `aedit_relation`).
997
+
998
+ </details>
999
+
1000
+ <details>
1001
+ <summary> <b> Insert Custom KG </b></summary>
1002
+
1003
+ ```python
1004
+ custom_kg = {
1005
+ "chunks": [
1006
+ {
1007
+ "content": "Alice and Bob are collaborating on quantum computing research.",
1008
+ "source_id": "doc-1",
1009
+ "file_path": "test_file",
1010
+ }
1011
+ ],
1012
+ "entities": [
1013
+ {
1014
+ "entity_name": "Alice",
1015
+ "entity_type": "person",
1016
+ "description": "Alice is a researcher specializing in quantum physics.",
1017
+ "source_id": "doc-1",
1018
+ "file_path": "test_file"
1019
+ },
1020
+ {
1021
+ "entity_name": "Bob",
1022
+ "entity_type": "person",
1023
+ "description": "Bob is a mathematician.",
1024
+ "source_id": "doc-1",
1025
+ "file_path": "test_file"
1026
+ },
1027
+ {
1028
+ "entity_name": "Quantum Computing",
1029
+ "entity_type": "technology",
1030
+ "description": "Quantum computing utilizes quantum mechanical phenomena for computation.",
1031
+ "source_id": "doc-1",
1032
+ "file_path": "test_file"
1033
+ }
1034
+ ],
1035
+ "relationships": [
1036
+ {
1037
+ "src_id": "Alice",
1038
+ "tgt_id": "Bob",
1039
+ "description": "Alice and Bob are research partners.",
1040
+ "keywords": "collaboration research",
1041
+ "weight": 1.0,
1042
+ "source_id": "doc-1",
1043
+ "file_path": "test_file"
1044
+ },
1045
+ {
1046
+ "src_id": "Alice",
1047
+ "tgt_id": "Quantum Computing",
1048
+ "description": "Alice conducts research on quantum computing.",
1049
+ "keywords": "research expertise",
1050
+ "weight": 1.0,
1051
+ "source_id": "doc-1",
1052
+ "file_path": "test_file"
1053
+ },
1054
+ {
1055
+ "src_id": "Bob",
1056
+ "tgt_id": "Quantum Computing",
1057
+ "description": "Bob researches quantum computing.",
1058
+ "keywords": "research application",
1059
+ "weight": 1.0,
1060
+ "source_id": "doc-1",
1061
+ "file_path": "test_file"
1062
+ }
1063
+ ]
1064
+ }
1065
+
1066
+ rag.insert_custom_kg(custom_kg)
1067
+ ```
1068
+
1069
+ </details>
1070
+
1071
+ <details>
1072
+ <summary> <b>Other Entity and Relation Operations</b></summary>
1073
+
1074
+ - **create_entity**: Creates a new entity with specified attributes
1075
+ - **edit_entity**: Updates an existing entity's attributes or renames it
1076
+
1077
+
1078
+ - **create_relation**: Creates a new relation between existing entities
1079
+ - **edit_relation**: Updates an existing relation's attributes
1080
+
1081
+ These operations maintain data consistency across both the graph database and vector database components, ensuring your knowledge graph remains coherent.
1082
+
1083
+ </details>
1084
+
1085
+ ## Delete Functions
1086
+
1087
+ LightRAG provides comprehensive deletion capabilities, allowing you to delete documents, entities, and relationships.
1088
+
1089
+ <details>
1090
+ <summary> <b>Delete Entities</b> </summary>
1091
+
1092
+ You can delete entities by their name along with all associated relationships:
1093
+
1094
+ ```python
1095
+ # Delete entity and all its relationships (synchronous version)
1096
+ rag.delete_by_entity("Google")
1097
+
1098
+ # Asynchronous version
1099
+ await rag.adelete_by_entity("Google")
1100
+ ```
1101
+
1102
+ When deleting an entity:
1103
+ - Removes the entity node from the knowledge graph
1104
+ - Deletes all associated relationships
1105
+ - Removes related embedding vectors from the vector database
1106
+ - Maintains knowledge graph integrity
1107
+
1108
+ </details>
1109
+
1110
+ <details>
1111
+ <summary> <b>Delete Relations</b> </summary>
1112
+
1113
+ You can delete relationships between two specific entities:
1114
+
1115
+ ```python
1116
+ # Delete relationship between two entities (synchronous version)
1117
+ rag.delete_by_relation("Google", "Gmail")
1118
+
1119
+ # Asynchronous version
1120
+ await rag.adelete_by_relation("Google", "Gmail")
1121
+ ```
1122
+
1123
+ When deleting a relationship:
1124
+ - Removes the specified relationship edge
1125
+ - Deletes the relationship's embedding vector from the vector database
1126
+ - Preserves both entity nodes and their other relationships
1127
+
1128
+ </details>
1129
+
1130
+ <details>
1131
+ <summary> <b>Delete by Document ID</b> </summary>
1132
+
1133
+ You can delete an entire document and all its related knowledge through document ID:
1134
+
1135
+ ```python
1136
+ # Delete by document ID (asynchronous version)
1137
+ await rag.adelete_by_doc_id("doc-12345")
1138
+ ```
1139
+
1140
+ Optimized processing when deleting by document ID:
1141
+ - **Smart Cleanup**: Automatically identifies and removes entities and relationships that belong only to this document
1142
+ - **Preserve Shared Knowledge**: If entities or relationships exist in other documents, they are preserved and their descriptions are rebuilt
1143
+ - **Cache Optimization**: Clears related LLM cache to reduce storage overhead
1144
+ - **Incremental Rebuilding**: Reconstructs affected entity and relationship descriptions from remaining documents
1145
+
1146
+ The deletion process includes:
1147
+ 1. Delete all text chunks related to the document
1148
+ 2. Identify and delete entities and relationships that belong only to this document
1149
+ 3. Rebuild entities and relationships that still exist in other documents
1150
+ 4. Update all related vector indexes
1151
+ 5. Clean up document status records
1152
+
1153
+ Note: Deletion by document ID is an asynchronous operation as it involves complex knowledge graph reconstruction processes.
1154
+
1155
+ </details>
1156
+
1157
+ **Important Reminders:**
1158
+
1159
+ 1. **Irreversible Operations**: All deletion operations are irreversible, please use with caution
1160
+ 2. **Performance Considerations**: Deleting large amounts of data may take some time, especially deletion by document ID
1161
+ 3. **Data Consistency**: Deletion operations automatically maintain consistency between the knowledge graph and vector database
1162
+ 4. **Backup Recommendations**: Consider backing up data before performing important deletion operations
1163
+
1164
+ **Batch Deletion Recommendations:**
1165
+ - For batch deletion operations, consider using asynchronous methods for better performance
1166
+ - For large-scale deletions, consider processing in batches to avoid excessive system load
1167
+
1168
+ ## Entity Merging
1169
+
1170
+ <details>
1171
+ <summary> <b>Merge Entities and Their Relationships</b> </summary>
1172
+
1173
+ LightRAG now supports merging multiple entities into a single entity, automatically handling all relationships:
1174
+
1175
+ ```python
1176
+ # Basic entity merging
1177
+ rag.merge_entities(
1178
+ source_entities=["Artificial Intelligence", "AI", "Machine Intelligence"],
1179
+ target_entity="AI Technology"
1180
+ )
1181
+ ```
1182
+
1183
+ With custom merge strategy:
1184
+
1185
+ ```python
1186
+ # Define custom merge strategy for different fields
1187
+ rag.merge_entities(
1188
+ source_entities=["John Smith", "Dr. Smith", "J. Smith"],
1189
+ target_entity="John Smith",
1190
+ merge_strategy={
1191
+ "description": "concatenate", # Combine all descriptions
1192
+ "entity_type": "keep_first", # Keep the entity type from the first entity
1193
+ "source_id": "join_unique" # Combine all unique source IDs
1194
+ }
1195
+ )
1196
+ ```
1197
+
1198
+ With custom target entity data:
1199
+
1200
+ ```python
1201
+ # Specify exact values for the merged entity
1202
+ rag.merge_entities(
1203
+ source_entities=["New York", "NYC", "Big Apple"],
1204
+ target_entity="New York City",
1205
+ target_entity_data={
1206
+ "entity_type": "LOCATION",
1207
+ "description": "New York City is the most populous city in the United States.",
1208
+ }
1209
+ )
1210
+ ```
1211
+
1212
+ Advanced usage combining both approaches:
1213
+
1214
+ ```python
1215
+ # Merge company entities with both strategy and custom data
1216
+ rag.merge_entities(
1217
+ source_entities=["Microsoft Corp", "Microsoft Corporation", "MSFT"],
1218
+ target_entity="Microsoft",
1219
+ merge_strategy={
1220
+ "description": "concatenate", # Combine all descriptions
1221
+ "source_id": "join_unique" # Combine source IDs
1222
+ },
1223
+ target_entity_data={
1224
+ "entity_type": "ORGANIZATION",
1225
+ }
1226
+ )
1227
+ ```
1228
+
1229
+ When merging entities:
1230
+
1231
+ * All relationships from source entities are redirected to the target entity
1232
+ * Duplicate relationships are intelligently merged
1233
+ * Self-relationships (loops) are prevented
1234
+ * Source entities are removed after merging
1235
+ * Relationship weights and attributes are preserved
1236
+
1237
+ </details>
1238
+
1239
+ ## Multimodal Document Processing (RAG-Anything Integration)
1240
+
1241
+ LightRAG now seamlessly integrates with [RAG-Anything](https://github.com/HKUDS/RAG-Anything), a comprehensive **All-in-One Multimodal Document Processing RAG system** built specifically for LightRAG. RAG-Anything enables advanced parsing and retrieval-augmented generation (RAG) capabilities, allowing you to handle multimodal documents seamlessly and extract structured content—including text, images, tables, and formulas—from various document formats for integration into your RAG pipeline.
1242
+
1243
+ **Key Features:**
1244
+ - **End-to-End Multimodal Pipeline**: Complete workflow from document ingestion and parsing to intelligent multimodal query answering
1245
+ - **Universal Document Support**: Seamless processing of PDFs, Office documents (DOC/DOCX/PPT/PPTX/XLS/XLSX), images, and diverse file formats
1246
+ - **Specialized Content Analysis**: Dedicated processors for images, tables, mathematical equations, and heterogeneous content types
1247
+ - **Multimodal Knowledge Graph**: Automatic entity extraction and cross-modal relationship discovery for enhanced understanding
1248
+ - **Hybrid Intelligent Retrieval**: Advanced search capabilities spanning textual and multimodal content with contextual understanding
1249
+
1250
+ **Quick Start:**
1251
+ 1. Install RAG-Anything:
1252
+ ```bash
1253
+ pip install raganything
1254
+ ```
1255
+ 2. Process multimodal documents:
1256
+ <details>
1257
+ <summary> <b> RAGAnything Usage Example </b></summary>
1258
+
1259
+ ```python
1260
+ import asyncio
1261
+ from raganything import RAGAnything
1262
+ from lightrag import LightRAG
1263
+ from lightrag.llm.openai import openai_complete_if_cache, openai_embed
1264
+ from lightrag.utils import EmbeddingFunc
1265
+ import os
1266
+
1267
+ async def load_existing_lightrag():
1268
+ # First, create or load an existing LightRAG instance
1269
+ lightrag_working_dir = "./existing_lightrag_storage"
1270
+
1271
+ # Check if previous LightRAG instance exists
1272
+ if os.path.exists(lightrag_working_dir) and os.listdir(lightrag_working_dir):
1273
+ print("✅ Found existing LightRAG instance, loading...")
1274
+ else:
1275
+ print("❌ No existing LightRAG instance found, will create new one")
1276
+
1277
+ # Create/Load LightRAG instance with your configurations
1278
+ lightrag_instance = LightRAG(
1279
+ working_dir=lightrag_working_dir,
1280
+ llm_model_func=lambda prompt, system_prompt=None, history_messages=[], **kwargs: openai_complete_if_cache(
1281
+ "gpt-4o-mini",
1282
+ prompt,
1283
+ system_prompt=system_prompt,
1284
+ history_messages=history_messages,
1285
+ api_key="your-api-key",
1286
+ **kwargs,
1287
+ ),
1288
+ embedding_func=EmbeddingFunc(
1289
+ embedding_dim=3072,
1290
+ func=lambda texts: openai_embed(
1291
+ texts,
1292
+ model="text-embedding-3-large",
1293
+ api_key=api_key,
1294
+ base_url=base_url,
1295
+ ),
1296
+ )
1297
+ )
1298
+
1299
+ # Initialize storage (this will load existing data if available)
1300
+ await lightrag_instance.initialize_storages()
1301
+
1302
+ # Now initialize RAGAnything with the existing LightRAG instance
1303
+ rag = RAGAnything(
1304
+ lightrag=lightrag_instance, # Pass the existing LightRAG instance
1305
+ # Only need vision model for multimodal processing
1306
+ vision_model_func=lambda prompt, system_prompt=None, history_messages=[], image_data=None, **kwargs: openai_complete_if_cache(
1307
+ "gpt-4o",
1308
+ "",
1309
+ system_prompt=None,
1310
+ history_messages=[],
1311
+ messages=[
1312
+ {"role": "system", "content": system_prompt} if system_prompt else None,
1313
+ {"role": "user", "content": [
1314
+ {"type": "text", "text": prompt},
1315
+ {"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{image_data}"}}
1316
+ ]} if image_data else {"role": "user", "content": prompt}
1317
+ ],
1318
+ api_key="your-api-key",
1319
+ **kwargs,
1320
+ ) if image_data else openai_complete_if_cache(
1321
+ "gpt-4o-mini",
1322
+ prompt,
1323
+ system_prompt=system_prompt,
1324
+ history_messages=history_messages,
1325
+ api_key="your-api-key",
1326
+ **kwargs,
1327
+ )
1328
+ # Note: working_dir, llm_model_func, embedding_func, etc. are inherited from lightrag_instance
1329
+ )
1330
+
1331
+ # Query the existing knowledge base
1332
+ result = await rag.query_with_multimodal(
1333
+ "What data has been processed in this LightRAG instance?",
1334
+ mode="hybrid"
1335
+ )
1336
+ print("Query result:", result)
1337
+
1338
+ # Add new multimodal documents to the existing LightRAG instance
1339
+ await rag.process_document_complete(
1340
+ file_path="path/to/new/multimodal_document.pdf",
1341
+ output_dir="./output"
1342
+ )
1343
+
1344
+ if __name__ == "__main__":
1345
+ asyncio.run(load_existing_lightrag())
1346
+ ```
1347
+ </details>
1348
+
1349
+ For detailed documentation and advanced usage, please refer to the [RAG-Anything repository](https://github.com/HKUDS/RAG-Anything).
1350
+
1351
+ ## Token Usage Tracking
1352
+
1353
+ <details>
1354
+ <summary> <b>Overview and Usage</b> </summary>
1355
+
1356
+ LightRAG provides a TokenTracker tool to monitor and manage token consumption by large language models. This feature is particularly useful for controlling API costs and optimizing performance.
1357
+
1358
+ ### Usage
1359
+
1360
+ ```python
1361
+ from lightrag.utils import TokenTracker
1362
+
1363
+ # Create TokenTracker instance
1364
+ token_tracker = TokenTracker()
1365
+
1366
+ # Method 1: Using context manager (Recommended)
1367
+ # Suitable for scenarios requiring automatic token usage tracking
1368
+ with token_tracker:
1369
+ result1 = await llm_model_func("your question 1")
1370
+ result2 = await llm_model_func("your question 2")
1371
+
1372
+ # Method 2: Manually adding token usage records
1373
+ # Suitable for scenarios requiring more granular control over token statistics
1374
+ token_tracker.reset()
1375
+
1376
+ rag.insert()
1377
+
1378
+ rag.query("your question 1", param=QueryParam(mode="naive"))
1379
+ rag.query("your question 2", param=QueryParam(mode="mix"))
1380
+
1381
+ # Display total token usage (including insert and query operations)
1382
+ print("Token usage:", token_tracker.get_usage())
1383
+ ```
1384
+
1385
+ ### Usage Tips
1386
+ - Use context managers for long sessions or batch operations to automatically track all token consumption
1387
+ - For scenarios requiring segmented statistics, use manual mode and call reset() when appropriate
1388
+ - Regular checking of token usage helps detect abnormal consumption early
1389
+ - Actively use this feature during development and testing to optimize production costs
1390
+
1391
+ ### Practical Examples
1392
+ You can refer to these examples for implementing token tracking:
1393
+ - `examples/lightrag_gemini_track_token_demo.py`: Token tracking example using Google Gemini model
1394
+ - `examples/lightrag_siliconcloud_track_token_demo.py`: Token tracking example using SiliconCloud model
1395
+
1396
+ These examples demonstrate how to effectively use the TokenTracker feature with different models and scenarios.
1397
+
1398
+ </details>
1399
+
1400
+ ## Data Export Functions
1401
+
1402
+ ### Overview
1403
+
1404
+ LightRAG allows you to export your knowledge graph data in various formats for analysis, sharing, and backup purposes. The system supports exporting entities, relations, and relationship data.
1405
+
1406
+ ### Export Functions
1407
+
1408
+ <details>
1409
+ <summary> <b> Basic Usage </b></summary>
1410
+
1411
+ ```python
1412
+ # Basic CSV export (default format)
1413
+ rag.export_data("knowledge_graph.csv")
1414
+
1415
+ # Specify any format
1416
+ rag.export_data("output.xlsx", file_format="excel")
1417
+ ```
1418
+
1419
+ </details>
1420
+
1421
+ <details>
1422
+ <summary> <b> Different File Formats supported </b></summary>
1423
+
1424
+ ```python
1425
+ #Export data in CSV format
1426
+ rag.export_data("graph_data.csv", file_format="csv")
1427
+
1428
+ # Export data in Excel sheet
1429
+ rag.export_data("graph_data.xlsx", file_format="excel")
1430
+
1431
+ # Export data in markdown format
1432
+ rag.export_data("graph_data.md", file_format="md")
1433
+
1434
+ # Export data in Text
1435
+ rag.export_data("graph_data.txt", file_format="txt")
1436
+ ```
1437
+ </details>
1438
+
1439
+ <details>
1440
+ <summary> <b> Additional Options </b></summary>
1441
+
1442
+ Include vector embeddings in the export (optional):
1443
+
1444
+ ```python
1445
+ rag.export_data("complete_data.csv", include_vector_data=True)
1446
+ ```
1447
+ </details>
1448
+
1449
+ ### Data Included in Export
1450
+
1451
+ All exports include:
1452
+
1453
+ * Entity information (names, IDs, metadata)
1454
+ * Relation data (connections between entities)
1455
+ * Relationship information from vector database
1456
+
1457
+ ## Cache
1458
+
1459
+ <details>
1460
+ <summary> <b>Clear Cache</b> </summary>
1461
+
1462
+ You can clear the LLM response cache with different modes:
1463
+
1464
+ ```python
1465
+ # Clear all cache
1466
+ await rag.aclear_cache()
1467
+
1468
+ # Clear local mode cache
1469
+ await rag.aclear_cache(modes=["local"])
1470
+
1471
+ # Clear extraction cache
1472
+ await rag.aclear_cache(modes=["default"])
1473
+
1474
+ # Clear multiple modes
1475
+ await rag.aclear_cache(modes=["local", "global", "hybrid"])
1476
+
1477
+ # Synchronous version
1478
+ rag.clear_cache(modes=["local"])
1479
+ ```
1480
+
1481
+ Valid modes are:
1482
+
1483
+ - `"default"`: Extraction cache
1484
+ - `"naive"`: Naive search cache
1485
+ - `"local"`: Local search cache
1486
+ - `"global"`: Global search cache
1487
+ - `"hybrid"`: Hybrid search cache
1488
+ - `"mix"`: Mix search cache
1489
+
1490
+ </details>
1491
+
1492
+ ## Troubleshooting
1493
+
1494
+ ### Common Initialization Errors
1495
+
1496
+ If you encounter these errors when using LightRAG:
1497
+
1498
+ 1. **`AttributeError: __aenter__`**
1499
+ - **Cause**: Storage backends not initialized
1500
+ - **Solution**: Call `await rag.initialize_storages()` after creating the LightRAG instance
1501
+
1502
+ 2. **`KeyError: 'history_messages'`**
1503
+ - **Cause**: Pipeline status not initialized
1504
+ - **Solution**: Call `await initialize_pipeline_status()` after initializing storages
1505
+
1506
+ 3. **Both errors in sequence**
1507
+ - **Cause**: Neither initialization method was called
1508
+ - **Solution**: Always follow this pattern:
1509
+ ```python
1510
+ rag = LightRAG(...)
1511
+ await rag.initialize_storages()
1512
+ await initialize_pipeline_status()
1513
+ ```
1514
+
1515
+ ### Model Switching Issues
1516
+
1517
+ When switching between different embedding models, you must clear the data directory to avoid errors. The only file you may want to preserve is `kv_store_llm_response_cache.json` if you wish to retain the LLM cache.
1518
+
1519
+ ## LightRAG API
1520
+
1521
+ The LightRAG Server is designed to provide Web UI and API support. **For more information about LightRAG Server, please refer to [LightRAG Server](./lightrag/api/README.md).**
1522
+
1523
+ ## Graph Visualization
1524
+
1525
+ The LightRAG Server offers a comprehensive knowledge graph visualization feature. It supports various gravity layouts, node queries, subgraph filtering, and more. **For more information about LightRAG Server, please refer to [LightRAG Server](./lightrag/api/README.md).**
1526
+
1527
+ ![iShot_2025-03-23_12.40.08](./README.assets/iShot_2025-03-23_12.40.08.png)
1528
+
1529
+ ## Evaluation
1530
+
1531
+ ### Dataset
1532
+
1533
+ The dataset used in LightRAG can be downloaded from [TommyChien/UltraDomain](https://huggingface.co/datasets/TommyChien/UltraDomain).
1534
+
1535
+ ### Generate Query
1536
+
1537
+ LightRAG uses the following prompt to generate high-level queries, with the corresponding code in `example/generate_query.py`.
1538
+
1539
+ <details>
1540
+ <summary> Prompt </summary>
1541
+
1542
+ ```python
1543
+ Given the following description of a dataset:
1544
+
1545
+ {description}
1546
+
1547
+ Please identify 5 potential users who would engage with this dataset. For each user, list 5 tasks they would perform with this dataset. Then, for each (user, task) combination, generate 5 questions that require a high-level understanding of the entire dataset.
1548
+
1549
+ Output the results in the following structure:
1550
+ - User 1: [user description]
1551
+ - Task 1: [task description]
1552
+ - Question 1:
1553
+ - Question 2:
1554
+ - Question 3:
1555
+ - Question 4:
1556
+ - Question 5:
1557
+ - Task 2: [task description]
1558
+ ...
1559
+ - Task 5: [task description]
1560
+ - User 2: [user description]
1561
+ ...
1562
+ - User 5: [user description]
1563
+ ...
1564
+ ```
1565
+
1566
+ </details>
1567
+
1568
+ ### Batch Eval
1569
+
1570
+ To evaluate the performance of two RAG systems on high-level queries, LightRAG uses the following prompt, with the specific code available in `reproduce/batch_eval.py`.
1571
+
1572
+ <details>
1573
+ <summary> Prompt </summary>
1574
+
1575
+ ```python
1576
+ ---Role---
1577
+ You are an expert tasked with evaluating two answers to the same question based on three criteria: **Comprehensiveness**, **Diversity**, and **Empowerment**.
1578
+ ---Goal---
1579
+ You will evaluate two answers to the same question based on three criteria: **Comprehensiveness**, **Diversity**, and **Empowerment**.
1580
+
1581
+ - **Comprehensiveness**: How much detail does the answer provide to cover all aspects and details of the question?
1582
+ - **Diversity**: How varied and rich is the answer in providing different perspectives and insights on the question?
1583
+ - **Empowerment**: How well does the answer help the reader understand and make informed judgments about the topic?
1584
+
1585
+ For each criterion, choose the better answer (either Answer 1 or Answer 2) and explain why. Then, select an overall winner based on these three categories.
1586
+
1587
+ Here is the question:
1588
+ {query}
1589
+
1590
+ Here are the two answers:
1591
+
1592
+ **Answer 1:**
1593
+ {answer1}
1594
+
1595
+ **Answer 2:**
1596
+ {answer2}
1597
+
1598
+ Evaluate both answers using the three criteria listed above and provide detailed explanations for each criterion.
1599
+
1600
+ Output your evaluation in the following JSON format:
1601
+
1602
+ {{
1603
+ "Comprehensiveness": {{
1604
+ "Winner": "[Answer 1 or Answer 2]",
1605
+ "Explanation": "[Provide explanation here]"
1606
+ }},
1607
+ "Empowerment": {{
1608
+ "Winner": "[Answer 1 or Answer 2]",
1609
+ "Explanation": "[Provide explanation here]"
1610
+ }},
1611
+ "Overall Winner": {{
1612
+ "Winner": "[Answer 1 or Answer 2]",
1613
+ "Explanation": "[Summarize why this answer is the overall winner based on the three criteria]"
1614
+ }}
1615
+ }}
1616
+ ```
1617
+
1618
+ </details>
1619
+
1620
+ ### Overall Performance Table
1621
+
1622
+ | |**Agriculture**| |**CS**| |**Legal**| |**Mix**| |
1623
+ |----------------------|---------------|------------|------|------------|---------|------------|-------|------------|
1624
+ | |NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|
1625
+ |**Comprehensiveness**|32.4%|**67.6%**|38.4%|**61.6%**|16.4%|**83.6%**|38.8%|**61.2%**|
1626
+ |**Diversity**|23.6%|**76.4%**|38.0%|**62.0%**|13.6%|**86.4%**|32.4%|**67.6%**|
1627
+ |**Empowerment**|32.4%|**67.6%**|38.8%|**61.2%**|16.4%|**83.6%**|42.8%|**57.2%**|
1628
+ |**Overall**|32.4%|**67.6%**|38.8%|**61.2%**|15.2%|**84.8%**|40.0%|**60.0%**|
1629
+ | |RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|
1630
+ |**Comprehensiveness**|31.6%|**68.4%**|38.8%|**61.2%**|15.2%|**84.8%**|39.2%|**60.8%**|
1631
+ |**Diversity**|29.2%|**70.8%**|39.2%|**60.8%**|11.6%|**88.4%**|30.8%|**69.2%**|
1632
+ |**Empowerment**|31.6%|**68.4%**|36.4%|**63.6%**|15.2%|**84.8%**|42.4%|**57.6%**|
1633
+ |**Overall**|32.4%|**67.6%**|38.0%|**62.0%**|14.4%|**85.6%**|40.0%|**60.0%**|
1634
+ | |HyDE|**LightRAG**|HyDE|**LightRAG**|HyDE|**LightRAG**|HyDE|**LightRAG**|
1635
+ |**Comprehensiveness**|26.0%|**74.0%**|41.6%|**58.4%**|26.8%|**73.2%**|40.4%|**59.6%**|
1636
+ |**Diversity**|24.0%|**76.0%**|38.8%|**61.2%**|20.0%|**80.0%**|32.4%|**67.6%**|
1637
+ |**Empowerment**|25.2%|**74.8%**|40.8%|**59.2%**|26.0%|**74.0%**|46.0%|**54.0%**|
1638
+ |**Overall**|24.8%|**75.2%**|41.6%|**58.4%**|26.4%|**73.6%**|42.4%|**57.6%**|
1639
+ | |GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|
1640
+ |**Comprehensiveness**|45.6%|**54.4%**|48.4%|**51.6%**|48.4%|**51.6%**|**50.4%**|49.6%|
1641
+ |**Diversity**|22.8%|**77.2%**|40.8%|**59.2%**|26.4%|**73.6%**|36.0%|**64.0%**|
1642
+ |**Empowerment**|41.2%|**58.8%**|45.2%|**54.8%**|43.6%|**56.4%**|**50.8%**|49.2%|
1643
+ |**Overall**|45.2%|**54.8%**|48.0%|**52.0%**|47.2%|**52.8%**|**50.4%**|49.6%|
1644
+
1645
+ ## Reproduce
1646
+
1647
+ All the code can be found in the `./reproduce` directory.
1648
+
1649
+ ### Step-0 Extract Unique Contexts
1650
+
1651
+ First, we need to extract unique contexts in the datasets.
1652
+
1653
+ <details>
1654
+ <summary> Code </summary>
1655
+
1656
+ ```python
1657
+ def extract_unique_contexts(input_directory, output_directory):
1658
+
1659
+ os.makedirs(output_directory, exist_ok=True)
1660
+
1661
+ jsonl_files = glob.glob(os.path.join(input_directory, '*.jsonl'))
1662
+ print(f"Found {len(jsonl_files)} JSONL files.")
1663
+
1664
+ for file_path in jsonl_files:
1665
+ filename = os.path.basename(file_path)
1666
+ name, ext = os.path.splitext(filename)
1667
+ output_filename = f"{name}_unique_contexts.json"
1668
+ output_path = os.path.join(output_directory, output_filename)
1669
+
1670
+ unique_contexts_dict = {}
1671
+
1672
+ print(f"Processing file: {filename}")
1673
+
1674
+ try:
1675
+ with open(file_path, 'r', encoding='utf-8') as infile:
1676
+ for line_number, line in enumerate(infile, start=1):
1677
+ line = line.strip()
1678
+ if not line:
1679
+ continue
1680
+ try:
1681
+ json_obj = json.loads(line)
1682
+ context = json_obj.get('context')
1683
+ if context and context not in unique_contexts_dict:
1684
+ unique_contexts_dict[context] = None
1685
+ except json.JSONDecodeError as e:
1686
+ print(f"JSON decoding error in file {filename} at line {line_number}: {e}")
1687
+ except FileNotFoundError:
1688
+ print(f"File not found: {filename}")
1689
+ continue
1690
+ except Exception as e:
1691
+ print(f"An error occurred while processing file {filename}: {e}")
1692
+ continue
1693
+
1694
+ unique_contexts_list = list(unique_contexts_dict.keys())
1695
+ print(f"There are {len(unique_contexts_list)} unique `context` entries in the file {filename}.")
1696
+
1697
+ try:
1698
+ with open(output_path, 'w', encoding='utf-8') as outfile:
1699
+ json.dump(unique_contexts_list, outfile, ensure_ascii=False, indent=4)
1700
+ print(f"Unique `context` entries have been saved to: {output_filename}")
1701
+ except Exception as e:
1702
+ print(f"An error occurred while saving to the file {output_filename}: {e}")
1703
+
1704
+ print("All files have been processed.")
1705
+
1706
+ ```
1707
+
1708
+ </details>
1709
+
1710
+ ### Step-1 Insert Contexts
1711
+
1712
+ For the extracted contexts, we insert them into the LightRAG system.
1713
+
1714
+ <details>
1715
+ <summary> Code </summary>
1716
+
1717
+ ```python
1718
+ def insert_text(rag, file_path):
1719
+ with open(file_path, mode='r') as f:
1720
+ unique_contexts = json.load(f)
1721
+
1722
+ retries = 0
1723
+ max_retries = 3
1724
+ while retries < max_retries:
1725
+ try:
1726
+ rag.insert(unique_contexts)
1727
+ break
1728
+ except Exception as e:
1729
+ retries += 1
1730
+ print(f"Insertion failed, retrying ({retries}/{max_retries}), error: {e}")
1731
+ time.sleep(10)
1732
+ if retries == max_retries:
1733
+ print("Insertion failed after exceeding the maximum number of retries")
1734
+ ```
1735
+
1736
+ </details>
1737
+
1738
+ ### Step-2 Generate Queries
1739
+
1740
+ We extract tokens from the first and the second half of each context in the dataset, then combine them as dataset descriptions to generate queries.
1741
+
1742
+ <details>
1743
+ <summary> Code </summary>
1744
+
1745
+ ```python
1746
+ tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
1747
+
1748
+ def get_summary(context, tot_tokens=2000):
1749
+ tokens = tokenizer.tokenize(context)
1750
+ half_tokens = tot_tokens // 2
1751
+
1752
+ start_tokens = tokens[1000:1000 + half_tokens]
1753
+ end_tokens = tokens[-(1000 + half_tokens):1000]
1754
+
1755
+ summary_tokens = start_tokens + end_tokens
1756
+ summary = tokenizer.convert_tokens_to_string(summary_tokens)
1757
+
1758
+ return summary
1759
+ ```
1760
+
1761
+ </details>
1762
+
1763
+ ### Step-3 Query
1764
+
1765
+ For the queries generated in Step-2, we will extract them and query LightRAG.
1766
+
1767
+ <details>
1768
+ <summary> Code </summary>
1769
+
1770
+ ```python
1771
+ def extract_queries(file_path):
1772
+ with open(file_path, 'r') as f:
1773
+ data = f.read()
1774
+
1775
+ data = data.replace('**', '')
1776
+
1777
+ queries = re.findall(r'- Question \d+: (.+)', data)
1778
+
1779
+ return queries
1780
+ ```
1781
+
1782
+ </details>
1783
+
1784
+ ## 🔗 Related Projects
1785
+
1786
+ *Ecosystem & Extensions*
1787
+
1788
+ <div align="center">
1789
+ <table>
1790
+ <tr>
1791
+ <td align="center">
1792
+ <a href="https://github.com/HKUDS/RAG-Anything">
1793
+ <div style="width: 100px; height: 100px; background: linear-gradient(135deg, rgba(0, 217, 255, 0.1) 0%, rgba(0, 217, 255, 0.05) 100%); border-radius: 15px; border: 1px solid rgba(0, 217, 255, 0.2); display: flex; align-items: center; justify-content: center; margin-bottom: 10px;">
1794
+ <span style="font-size: 32px;">📸</span>
1795
+ </div>
1796
+ <b>RAG-Anything</b><br>
1797
+ <sub>Multimodal RAG</sub>
1798
+ </a>
1799
+ </td>
1800
+ <td align="center">
1801
+ <a href="https://github.com/HKUDS/VideoRAG">
1802
+ <div style="width: 100px; height: 100px; background: linear-gradient(135deg, rgba(0, 217, 255, 0.1) 0%, rgba(0, 217, 255, 0.05) 100%); border-radius: 15px; border: 1px solid rgba(0, 217, 255, 0.2); display: flex; align-items: center; justify-content: center; margin-bottom: 10px;">
1803
+ <span style="font-size: 32px;">🎥</span>
1804
+ </div>
1805
+ <b>VideoRAG</b><br>
1806
+ <sub>Extreme Long-Context Video RAG</sub>
1807
+ </a>
1808
+ </td>
1809
+ <td align="center">
1810
+ <a href="https://github.com/HKUDS/MiniRAG">
1811
+ <div style="width: 100px; height: 100px; background: linear-gradient(135deg, rgba(0, 217, 255, 0.1) 0%, rgba(0, 217, 255, 0.05) 100%); border-radius: 15px; border: 1px solid rgba(0, 217, 255, 0.2); display: flex; align-items: center; justify-content: center; margin-bottom: 10px;">
1812
+ <span style="font-size: 32px;">✨</span>
1813
+ </div>
1814
+ <b>MiniRAG</b><br>
1815
+ <sub>Extremely Simple RAG</sub>
1816
+ </a>
1817
+ </td>
1818
+ </tr>
1819
+ </table>
1820
+ </div>
1821
+
1822
+ ---
1823
+
1824
+ ## ⭐ Star History
1825
+
1826
+ <a href="https://star-history.com/#HKUDS/LightRAG&Date">
1827
+ <picture>
1828
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/LightRAG&type=Date&theme=dark" />
1829
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/LightRAG&type=Date" />
1830
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/LightRAG&type=Date" />
1831
+ </picture>
1832
+ </a>
1833
+
1834
+ ## 🤝 Contribution
1835
+
1836
+ <div align="center">
1837
+ We thank all our contributors for their valuable contributions.
1838
+ </div>
1839
+
1840
+ <div align="center">
1841
+ <a href="https://github.com/HKUDS/LightRAG/graphs/contributors">
1842
+ <img src="https://contrib.rocks/image?repo=HKUDS/LightRAG" style="border-radius: 15px; box-shadow: 0 0 20px rgba(0, 217, 255, 0.3);" />
1843
+ </a>
1844
+ </div>
1845
+
1846
+ ---
1847
+
1848
+
1849
+ ## 📖 Citation
1850
+
1851
+ ```python
1852
+ @article{guo2024lightrag,
1853
+ title={LightRAG: Simple and Fast Retrieval-Augmented Generation},
1854
+ author={Zirui Guo and Lianghao Xia and Yanhua Yu and Tu Ao and Chao Huang},
1855
+ year={2024},
1856
+ eprint={2410.05779},
1857
+ archivePrefix={arXiv},
1858
+ primaryClass={cs.IR}
1859
+ }
1860
+ ```
1861
+
1862
+ ---
1863
+
1864
+ <div align="center" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius: 15px; padding: 30px; margin: 30px 0;">
1865
+ <div>
1866
+ <img src="https://user-images.githubusercontent.com/74038190/212284100-561aa473-3905-4a80-b561-0d28506553ee.gif" width="500">
1867
+ </div>
1868
+ <div style="margin-top: 20px;">
1869
+ <a href="https://github.com/HKUDS/LightRAG" style="text-decoration: none;">
1870
+ <img src="https://img.shields.io/badge/⭐%20Star%20us%20on%20GitHub-1a1a2e?style=for-the-badge&logo=github&logoColor=white">
1871
+ </a>
1872
+ <a href="https://github.com/HKUDS/LightRAG/issues" style="text-decoration: none;">
1873
+ <img src="https://img.shields.io/badge/🐛%20Report%20Issues-ff6b6b?style=for-the-badge&logo=github&logoColor=white">
1874
+ </a>
1875
+ <a href="https://github.com/HKUDS/LightRAG/discussions" style="text-decoration: none;">
1876
+ <img src="https://img.shields.io/badge/💬%20Discussions-4ecdc4?style=for-the-badge&logo=github&logoColor=white">
1877
+ </a>
1878
+ </div>
1879
+ </div>
1880
+
1881
+ <div align="center">
1882
+ <div style="width: 100%; max-width: 600px; margin: 20px auto; padding: 20px; background: linear-gradient(135deg, rgba(0, 217, 255, 0.1) 0%, rgba(0, 217, 255, 0.05) 100%); border-radius: 15px; border: 1px solid rgba(0, 217, 255, 0.2);">
1883
+ <div style="display: flex; justify-content: center; align-items: center; gap: 15px;">
1884
+ <span style="font-size: 24px;">⭐</span>
1885
+ <span style="color: #00d9ff; font-size: 18px;">Thank you for visiting LightRAG!</span>
1886
+ <span style="font-size: 24px;">⭐</span>
1887
+ </div>
1888
+ </div>
1889
+ </div>
LightRAG/SECURITY.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Reporting Security Issues
2
+
3
+ The LightRAG team and community take security bugs seriously. We appreciate your efforts to responsibly disclose your findings, and will make every effort to acknowledge your contributions.
4
+
5
+ To report a security issue, please use the GitHub Security Advisory: [Report a Vulnerability](https://github.com/HKUDS/LightRAG/security/advisories/new)
6
+
7
+ The LightRAG team will send a response indicating the next steps in handling your report. After the initial reply to your report, the security team will keep you informed of the progress towards a fix and full announcement, and may ask for additional information or guidance.
8
+
9
+ Report security bugs in third-party modules to the person or team maintaining the module.
10
+
11
+ ### Supported Versions
12
+
13
+ The following versions currently being supported with security updates.
14
+
15
+ | Version | Supported |
16
+ | ------- | ------------------ |
17
+ | 1.2.x | :x: |
18
+ | 1.3.x | :white_check_mark: |
LightRAG/config.ini.example ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [neo4j]
2
+ uri = neo4j+s://xxxxxxxx.databases.neo4j.io
3
+ username = neo4j
4
+ password = your-password
5
+ connection_pool_size = 100
6
+ connection_timeout = 30.0
7
+ connection_acquisition_timeout = 30.0
8
+ max_transaction_retry_time = 30.0
9
+ max_connection_lifetime = 300.0
10
+ liveness_check_timeout = 30.0
11
+ keep_alive = true
12
+
13
+ [mongodb]
14
+ uri = mongodb+srv://name:password@your-cluster-address
15
+ database = lightrag
16
+
17
+ [redis]
18
+ uri=redis://localhost:6379/1
19
+
20
+ [qdrant]
21
+ uri = http://localhost:16333
22
+
23
+ [postgres]
24
+ host = localhost
25
+ port = 5432
26
+ user = your_username
27
+ password = your_password
28
+ database = your_database
29
+ # workspace = default
30
+ max_connections = 12
31
+ vector_index_type = HNSW # HNSW or IVFFLAT
32
+ hnsw_m = 16
33
+ hnsw_ef = 64
34
+ ivfflat_lists = 100
35
+
36
+ [memgraph]
37
+ uri = bolt://localhost:7687
LightRAG/docker-compose.yml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ lightrag:
3
+ container_name: lightrag
4
+ image: ghcr.io/hkuds/lightrag:latest
5
+ build:
6
+ context: .
7
+ dockerfile: Dockerfile
8
+ tags:
9
+ - ghcr.io/hkuds/lightrag:latest
10
+ ports:
11
+ - "${PORT:-9621}:9621"
12
+ volumes:
13
+ - ./data/rag_storage:/app/data/rag_storage
14
+ - ./data/inputs:/app/data/inputs
15
+ - ./data/tiktoken:/app/data/tiktoken
16
+ - ./config.ini:/app/config.ini
17
+ - ./.env:/app/.env
18
+ env_file:
19
+ - .env
20
+ environment:
21
+ - TIKTOKEN_CACHE_DIR=/app/data/tiktoken
22
+ restart: unless-stopped
23
+ extra_hosts:
24
+ - "host.docker.internal:host-gateway"
LightRAG/docs/Algorithm.md ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ![LightRAG Indexing Flowchart](https://learnopencv.com/wp-content/uploads/2024/11/LightRAG-VectorDB-Json-KV-Store-Indexing-Flowchart-scaled.jpg)
2
+ *Figure 1: LightRAG Indexing Flowchart - Img Caption : [Source](https://learnopencv.com/lightrag/)*
3
+ ![LightRAG Retrieval and Querying Flowchart](https://learnopencv.com/wp-content/uploads/2024/11/LightRAG-Querying-Flowchart-Dual-Level-Retrieval-Generation-Knowledge-Graphs-scaled.jpg)
4
+ *Figure 2: LightRAG Retrieval and Querying Flowchart - Img Caption : [Source](https://learnopencv.com/lightrag/)*
LightRAG/docs/DockerDeployment.md ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LightRAG
2
+
3
+ A lightweight Knowledge Graph Retrieval-Augmented Generation system with multiple LLM backend support.
4
+
5
+ ## 🚀 Installation
6
+
7
+ ### Prerequisites
8
+ - Python 3.10+
9
+ - Git
10
+ - Docker (optional for Docker deployment)
11
+
12
+ ### Native Installation
13
+
14
+ 1. Clone the repository:
15
+ ```bash
16
+ # Linux/MacOS
17
+ git clone https://github.com/HKUDS/LightRAG.git
18
+ cd LightRAG
19
+ ```
20
+ ```powershell
21
+ # Windows PowerShell
22
+ git clone https://github.com/HKUDS/LightRAG.git
23
+ cd LightRAG
24
+ ```
25
+
26
+ 2. Configure your environment:
27
+ ```bash
28
+ # Linux/MacOS
29
+ cp .env.example .env
30
+ # Edit .env with your preferred configuration
31
+ ```
32
+ ```powershell
33
+ # Windows PowerShell
34
+ Copy-Item .env.example .env
35
+ # Edit .env with your preferred configuration
36
+ ```
37
+
38
+ 3. Create and activate virtual environment:
39
+ ```bash
40
+ # Linux/MacOS
41
+ python -m venv venv
42
+ source venv/bin/activate
43
+ ```
44
+ ```powershell
45
+ # Windows PowerShell
46
+ python -m venv venv
47
+ .\venv\Scripts\Activate
48
+ ```
49
+
50
+ 4. Install dependencies:
51
+ ```bash
52
+ # Both platforms
53
+ pip install -r requirements.txt
54
+ ```
55
+
56
+ ## 🐳 Docker Deployment
57
+
58
+ Docker instructions work the same on all platforms with Docker Desktop installed.
59
+
60
+ 1. Build and start the container:
61
+ ```bash
62
+ docker-compose up -d
63
+ ```
64
+
65
+ ### Configuration Options
66
+
67
+ LightRAG can be configured using environment variables in the `.env` file:
68
+
69
+ #### Server Configuration
70
+ - `HOST`: Server host (default: 0.0.0.0)
71
+ - `PORT`: Server port (default: 9621)
72
+
73
+ #### LLM Configuration
74
+ - `LLM_BINDING`: LLM backend to use (lollms/ollama/openai)
75
+ - `LLM_BINDING_HOST`: LLM server host URL
76
+ - `LLM_MODEL`: Model name to use
77
+
78
+ #### Embedding Configuration
79
+ - `EMBEDDING_BINDING`: Embedding backend (lollms/ollama/openai)
80
+ - `EMBEDDING_BINDING_HOST`: Embedding server host URL
81
+ - `EMBEDDING_MODEL`: Embedding model name
82
+
83
+ #### RAG Configuration
84
+ - `MAX_ASYNC`: Maximum async operations
85
+ - `MAX_TOKENS`: Maximum token size
86
+ - `EMBEDDING_DIM`: Embedding dimensions
87
+
88
+ #### Security
89
+ - `LIGHTRAG_API_KEY`: API key for authentication
90
+
91
+ ### Data Storage Paths
92
+
93
+ The system uses the following paths for data storage:
94
+ ```
95
+ data/
96
+ ├── rag_storage/ # RAG data persistence
97
+ └── inputs/ # Input documents
98
+ ```
99
+
100
+ ### Example Deployments
101
+
102
+ 1. Using with Ollama:
103
+ ```env
104
+ LLM_BINDING=ollama
105
+ LLM_BINDING_HOST=http://host.docker.internal:11434
106
+ LLM_MODEL=mistral
107
+ EMBEDDING_BINDING=ollama
108
+ EMBEDDING_BINDING_HOST=http://host.docker.internal:11434
109
+ EMBEDDING_MODEL=bge-m3
110
+ ```
111
+
112
+ you can't just use localhost from docker, that's why you need to use host.docker.internal which is defined in the docker compose file and should allow you to access the localhost services.
113
+
114
+ 2. Using with OpenAI:
115
+ ```env
116
+ LLM_BINDING=openai
117
+ LLM_MODEL=gpt-3.5-turbo
118
+ EMBEDDING_BINDING=openai
119
+ EMBEDDING_MODEL=text-embedding-ada-002
120
+ OPENAI_API_KEY=your-api-key
121
+ ```
122
+
123
+ ### API Usage
124
+
125
+ Once deployed, you can interact with the API at `http://localhost:9621`
126
+
127
+ Example query using PowerShell:
128
+ ```powershell
129
+ $headers = @{
130
+ "X-API-Key" = "your-api-key"
131
+ "Content-Type" = "application/json"
132
+ }
133
+ $body = @{
134
+ query = "your question here"
135
+ } | ConvertTo-Json
136
+
137
+ Invoke-RestMethod -Uri "http://localhost:9621/query" -Method Post -Headers $headers -Body $body
138
+ ```
139
+
140
+ Example query using curl:
141
+ ```bash
142
+ curl -X POST "http://localhost:9621/query" \
143
+ -H "X-API-Key: your-api-key" \
144
+ -H "Content-Type: application/json" \
145
+ -d '{"query": "your question here"}'
146
+ ```
147
+
148
+ ## 🔒 Security
149
+
150
+ Remember to:
151
+ 1. Set a strong API key in production
152
+ 2. Use SSL in production environments
153
+ 3. Configure proper network security
154
+
155
+ ## 📦 Updates
156
+
157
+ To update the Docker container:
158
+ ```bash
159
+ docker-compose pull
160
+ docker-compose up -d --build
161
+ ```
162
+
163
+ To update native installation:
164
+ ```bash
165
+ # Linux/MacOS
166
+ git pull
167
+ source venv/bin/activate
168
+ pip install -r requirements.txt
169
+ ```
170
+ ```powershell
171
+ # Windows PowerShell
172
+ git pull
173
+ .\venv\Scripts\Activate
174
+ pip install -r requirements.txt
175
+ ```
LightRAG/docs/LightRAG_concurrent_explain.md ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## LightRAG Multi-Document Processing: Concurrent Control Strategy
2
+
3
+ LightRAG employs a multi-layered concurrent control strategy when processing multiple documents. This article provides an in-depth analysis of the concurrent control mechanisms at document level, chunk level, and LLM request level, helping you understand why specific concurrent behaviors occur.
4
+
5
+ ### 1. Document-Level Concurrent Control
6
+
7
+ **Control Parameter**: `max_parallel_insert`
8
+
9
+ This parameter controls the number of documents processed simultaneously. The purpose is to prevent excessive parallelism from overwhelming system resources, which could lead to extended processing times for individual files. Document-level concurrency is governed by the `max_parallel_insert` attribute within LightRAG, which defaults to 2 and is configurable via the `MAX_PARALLEL_INSERT` environment variable. `max_parallel_insert` is recommended to be set between 2 and 10, typically `llm_model_max_async/3`. Setting this value too high can increase the likelihood of naming conflicts among entities and relationships across different documents during the merge phase, thereby reducing its overall efficiency.
10
+
11
+ ### 2. Chunk-Level Concurrent Control
12
+
13
+ **Control Parameter**: `llm_model_max_async`
14
+
15
+ This parameter controls the number of chunks processed simultaneously in the extraction stage within a document. The purpose is to prevent a high volume of concurrent requests from monopolizing LLM processing resources, which would impede the efficient parallel processing of multiple files. Chunk-Level Concurrent Control is governed by the `llm_model_max_async` attribute within LightRAG, which defaults to 4 and is configurable via the `MAX_ASYNC` environment variable. The purpose of this parameter is to fully leverage the LLM's concurrency capabilities when processing individual documents.
16
+
17
+ In the `extract_entities` function, **each document independently creates** its own chunk semaphore. Since each document independently creates chunk semaphores, the theoretical chunk concurrency of the system is:
18
+ $$
19
+ ChunkConcurrency = Max Parallel Insert × LLM Model Max Async
20
+ $$
21
+ For example:
22
+ - `max_parallel_insert = 2` (process 2 documents simultaneously)
23
+ - `llm_model_max_async = 4` (maximum 4 chunk concurrency per document)
24
+ - Theoretical chunk-level concurrent: 2 × 4 = 8
25
+
26
+ ### 3. Graph-Level Concurrent Control
27
+
28
+ **Control Parameter**: `llm_model_max_async * 2`
29
+
30
+ This parameter controls the number of entities and relations processed simultaneously in the merging stage within a document. The purpose is to prevent a high volume of concurrent requests from monopolizing LLM processing resources, which would impede the efficient parallel processing of multiple files. Graph-level concurrency is governed by the `llm_model_max_async` attribute within LightRAG, which defaults to 4 and is configurable via the `MAX_ASYNC` environment variable. Graph-level parallelism control parameters are equally applicable to managing parallelism during the entity relationship reconstruction phase after document deletion.
31
+
32
+ Given that the entity relationship merging phase doesn't necessitate LLM interaction for every operation, its parallelism is set at double the LLM's parallelism. This optimizes machine utilization while concurrently preventing excessive queuing resource contention for the LLM.
33
+
34
+ ### 4. LLM-Level Concurrent Control
35
+
36
+ **Control Parameter**: `llm_model_max_async`
37
+
38
+ This parameter governs the **concurrent volume** of LLM requests dispatched by the entire LightRAG system, encompassing the document extraction stage, merging stage, and user query handling.
39
+
40
+ LLM request prioritization is managed via a global priority queue, which **systematically prioritizes user queries** over merging-related requests, and merging-related requests over extraction-related requests. This strategic prioritization **minimizes user query latency**.
41
+
42
+ LLM-level concurrency is governed by the `llm_model_max_async` attribute within LightRAG, which defaults to 4 and is configurable via the `MAX_ASYNC` environment variable.
43
+
44
+ ### 5. Complete Concurrent Hierarchy Diagram
45
+
46
+ ```mermaid
47
+ graph TD
48
+ classDef doc fill:#e6f3ff,stroke:#5b9bd5,stroke-width:2px;
49
+ classDef chunk fill:#fbe5d6,stroke:#ed7d31,stroke-width:1px;
50
+ classDef merge fill:#e2f0d9,stroke:#70ad47,stroke-width:2px;
51
+
52
+ A["Multiple Documents<br>max_parallel_insert = 2"] --> A1
53
+ A --> B1
54
+
55
+ A1[DocA: split to n chunks] --> A_chunk;
56
+ B1[DocB: split to m chunks] --> B_chunk;
57
+
58
+ subgraph A_chunk[Extraction Stage]
59
+ A_chunk_title[Entity Relation Extraction<br>llm_model_max_async = 4];
60
+ A_chunk_title --> A_chunk1[Chunk A1]:::chunk;
61
+ A_chunk_title --> A_chunk2[Chunk A2]:::chunk;
62
+ A_chunk_title --> A_chunk3[Chunk A3]:::chunk;
63
+ A_chunk_title --> A_chunk4[Chunk A4]:::chunk;
64
+ A_chunk1 & A_chunk2 & A_chunk3 & A_chunk4 --> A_chunk_done([Extraction Complete]);
65
+ end
66
+
67
+ subgraph B_chunk[Extraction Stage]
68
+ B_chunk_title[Entity Relation Extraction<br>llm_model_max_async = 4];
69
+ B_chunk_title --> B_chunk1[Chunk B1]:::chunk;
70
+ B_chunk_title --> B_chunk2[Chunk B2]:::chunk;
71
+ B_chunk_title --> B_chunk3[Chunk B3]:::chunk;
72
+ B_chunk_title --> B_chunk4[Chunk B4]:::chunk;
73
+ B_chunk1 & B_chunk2 & B_chunk3 & B_chunk4 --> B_chunk_done([Extraction Complete]);
74
+ end
75
+ A_chunk -.->|LLM Request| LLM_Queue;
76
+
77
+ A_chunk --> A_merge;
78
+ B_chunk --> B_merge;
79
+
80
+ subgraph A_merge[Merge Stage]
81
+ A_merge_title[Entity Relation Merging<br>llm_model_max_async * 2 = 8];
82
+ A_merge_title --> A1_entity[Ent a1]:::merge;
83
+ A_merge_title --> A2_entity[Ent a2]:::merge;
84
+ A_merge_title --> A3_entity[Rel a3]:::merge;
85
+ A_merge_title --> A4_entity[Rel a4]:::merge;
86
+ A1_entity & A2_entity & A3_entity & A4_entity --> A_done([Merge Complete])
87
+ end
88
+
89
+ subgraph B_merge[Merge Stage]
90
+ B_merge_title[Entity Relation Merging<br>llm_model_max_async * 2 = 8];
91
+ B_merge_title --> B1_entity[Ent b1]:::merge;
92
+ B_merge_title --> B2_entity[Ent b2]:::merge;
93
+ B_merge_title --> B3_entity[Rel b3]:::merge;
94
+ B_merge_title --> B4_entity[Rel b4]:::merge;
95
+ B1_entity & B2_entity & B3_entity & B4_entity --> B_done([Merge Complete])
96
+ end
97
+
98
+ A_merge -.->|LLM Request| LLM_Queue["LLM Request Prioritized Queue<br>llm_model_max_async = 4"];
99
+ B_merge -.->|LLM Request| LLM_Queue;
100
+ B_chunk -.->|LLM Request| LLM_Queue;
101
+
102
+ ```
103
+
104
+ > The extraction and merge stages share a global prioritized LLM queue, regulated by `llm_model_max_async`. While numerous entity and relation extraction and merging operations may be "actively processing", **only a limited number will concurrently execute LLM requests** the remainder will be queued and awaiting their turn.
105
+
106
+ ### 6. Performance Optimization Recommendations
107
+
108
+ * **Increase LLM Concurrent Setting based on the capabilities of your LLM server or API provider**
109
+
110
+ During the file processing phase, the performance and concurrency capabilities of the LLM are critical bottlenecks. When deploying LLMs locally, the service's concurrency capacity must adequately account for the context length requirements of LightRAG. LightRAG recommends that LLMs support a minimum context length of 32KB; therefore, server concurrency should be calculated based on this benchmark. For API providers, LightRAG will retry requests up to three times if the client's request is rejected due to concurrent request limits. Backend logs can be used to determine if LLM retries are occurring, thereby indicating whether `MAX_ASYNC` has exceeded the API provider's limits.
111
+
112
+ * **Align Parallel Document Insertion Settings with LLM Concurrency Configurations**
113
+
114
+ The recommended number of parallel document processing tasks is 1/4 of the LLM's concurrency, with a minimum of 2 and a maximum of 10. Setting a higher number of parallel document processing tasks typically does not accelerate overall document processing speed, as even a small number of concurrently processed documents can fully utilize the LLM's parallel processing capabilities. Excessive parallel document processing can significantly increase the processing time for each individual document. Since LightRAG commits processing results on a file-by-file basis, a large number of concurrent files would necessitate caching a substantial amount of data. In the event of a system error, all documents in the middle stage would require reprocessing, thereby increasing error handling costs. For instance, setting `MAX_PARALLEL_INSERT` to 3 is appropriate when `MAX_ASYNC` is configured to 12.
LightRAG/env.example ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### This is sample file of .env
2
+
3
+ ###########################
4
+ ### Server Configuration
5
+ ###########################
6
+ HOST=0.0.0.0
7
+ PORT=9621
8
+ WEBUI_TITLE='My Graph KB'
9
+ WEBUI_DESCRIPTION="Simple and Fast Graph Based RAG System"
10
+ # WORKERS=2
11
+ ### gunicorn worker timeout(as default LLM request timeout if LLM_TIMEOUT is not set)
12
+ # TIMEOUT=150
13
+ # CORS_ORIGINS=http://localhost:3000,http://localhost:8080
14
+
15
+ ### Optional SSL Configuration
16
+ # SSL=true
17
+ # SSL_CERTFILE=/path/to/cert.pem
18
+ # SSL_KEYFILE=/path/to/key.pem
19
+
20
+ ### Directory Configuration (defaults to current working directory)
21
+ ### Default value is ./inputs and ./rag_storage
22
+ # INPUT_DIR=<absolute_path_for_doc_input_dir>
23
+ # WORKING_DIR=<absolute_path_for_working_dir>
24
+
25
+ ### Tiktoken cache directory (Store cached files in this folder for offline deployment)
26
+ # TIKTOKEN_CACHE_DIR=./temp/tiktoken
27
+
28
+ ### Ollama Emulating Model and Tag
29
+ # OLLAMA_EMULATING_MODEL_NAME=lightrag
30
+ OLLAMA_EMULATING_MODEL_TAG=latest
31
+
32
+ ### Max nodes return from grap retrieval in webui
33
+ # MAX_GRAPH_NODES=1000
34
+
35
+ ### Logging level
36
+ # LOG_LEVEL=INFO
37
+ # VERBOSE=False
38
+ # LOG_MAX_BYTES=10485760
39
+ # LOG_BACKUP_COUNT=5
40
+ ### Logfile location (defaults to current working directory)
41
+ # LOG_DIR=/path/to/log/directory
42
+
43
+ #####################################
44
+ ### Login and API-Key Configuration
45
+ #####################################
46
+ # AUTH_ACCOUNTS='admin:admin123,user1:pass456'
47
+ # TOKEN_SECRET=Your-Key-For-LightRAG-API-Server
48
+ # TOKEN_EXPIRE_HOURS=48
49
+ # GUEST_TOKEN_EXPIRE_HOURS=24
50
+ # JWT_ALGORITHM=HS256
51
+
52
+ ### API-Key to access LightRAG Server API
53
+ # LIGHTRAG_API_KEY=your-secure-api-key-here
54
+ # WHITELIST_PATHS=/health,/api/*
55
+
56
+ ######################################################################################
57
+ ### Query Configuration
58
+ ###
59
+ ### How to control the context lenght sent to LLM:
60
+ ### MAX_ENTITY_TOKENS + MAX_RELATION_TOKENS < MAX_TOTAL_TOKENS
61
+ ### Chunk_Tokens = MAX_TOTAL_TOKENS - Actual_Entity_Tokens - Actual_Reation_Tokens
62
+ ######################################################################################
63
+ # LLM responde cache for query (Not valid for streaming response)
64
+ ENABLE_LLM_CACHE=true
65
+ # COSINE_THRESHOLD=0.2
66
+ ### Number of entities or relations retrieved from KG
67
+ # TOP_K=40
68
+ ### Maxmium number or chunks for naive vector search
69
+ # CHUNK_TOP_K=20
70
+ ### control the actual enties send to LLM
71
+ # MAX_ENTITY_TOKENS=6000
72
+ ### control the actual relations send to LLM
73
+ # MAX_RELATION_TOKENS=8000
74
+ ### control the maximum tokens send to LLM (include entities, raltions and chunks)
75
+ # MAX_TOTAL_TOKENS=30000
76
+
77
+ ### maximum number of related chunks per source entity or relation
78
+ ### The chunk picker uses this value to determine the total number of chunks selected from KG(knowledge graph)
79
+ ### Higher values increase re-ranking time
80
+ # RELATED_CHUNK_NUMBER=5
81
+
82
+ ### chunk selection strategies
83
+ ### VECTOR: Pick KG chunks by vector similarity, delivered chunks to the LLM aligning more closely with naive retrieval
84
+ ### WEIGHT: Pick KG chunks by entity and chunk weight, delivered more solely KG related chunks to the LLM
85
+ ### If reranking is enabled, the impact of chunk selection strategies will be diminished.
86
+ # KG_CHUNK_PICK_METHOD=VECTOR
87
+
88
+ #########################################################
89
+ ### Reranking configuration
90
+ ### RERANK_BINDING type: null, cohere, jina, aliyun
91
+ ### For rerank model deployed by vLLM use cohere binding
92
+ #########################################################
93
+ RERANK_BINDING=null
94
+ ### Enable rerank by default in query params when RERANK_BINDING is not null
95
+ # RERANK_BY_DEFAULT=True
96
+ ### rerank score chunk filter(set to 0.0 to keep all chunks, 0.6 or above if LLM is not strong enought)
97
+ # MIN_RERANK_SCORE=0.0
98
+
99
+ ### For local deployment with vLLM
100
+ # RERANK_MODEL=BAAI/bge-reranker-v2-m3
101
+ # RERANK_BINDING_HOST=http://localhost:8000/v1/rerank
102
+ # RERANK_BINDING_API_KEY=your_rerank_api_key_here
103
+
104
+ ### Default value for Cohere AI
105
+ # RERANK_MODEL=rerank-v3.5
106
+ # RERANK_BINDING_HOST=https://api.cohere.com/v2/rerank
107
+ # RERANK_BINDING_API_KEY=your_rerank_api_key_here
108
+
109
+ ### Default value for Jina AI
110
+ # RERANK_MODEL=jina-reranker-v2-base-multilingual
111
+ # RERANK_BINDING_HOST=https://api.jina.ai/v1/rerank
112
+ # RERANK_BINDING_API_KEY=your_rerank_api_key_here
113
+
114
+ ### Default value for Aliyun
115
+ # RERANK_MODEL=gte-rerank-v2
116
+ # RERANK_BINDING_HOST=https://dashscope.aliyuncs.com/api/v1/services/rerank/text-rerank/text-rerank
117
+ # RERANK_BINDING_API_KEY=your_rerank_api_key_here
118
+
119
+ ########################################
120
+ ### Document processing configuration
121
+ ########################################
122
+ ENABLE_LLM_CACHE_FOR_EXTRACT=true
123
+
124
+ ### Document processing output language: English, Chinese, French, German ...
125
+ SUMMARY_LANGUAGE=English
126
+
127
+ ### Entity types that the LLM will attempt to recognize
128
+ # ENTITY_TYPES='["Person", "Organization", "Location", "Event", "Concept", "Method", "Content", "Data", "Artifact", "NaturalObject"]'
129
+
130
+ ### Chunk size for document splitting, 500~1500 is recommended
131
+ # CHUNK_SIZE=1200
132
+ # CHUNK_OVERLAP_SIZE=100
133
+
134
+ ### Number of summary semgments or tokens to trigger LLM summary on entity/relation merge (at least 3 is recommented)
135
+ # FORCE_LLM_SUMMARY_ON_MERGE=8
136
+ ### Max description token size to trigger LLM summary
137
+ # SUMMARY_MAX_TOKENS = 1200
138
+ ### Recommended LLM summary output length in tokens
139
+ # SUMMARY_LENGTH_RECOMMENDED_=600
140
+ ### Maximum context size sent to LLM for description summary
141
+ # SUMMARY_CONTEXT_SIZE=12000
142
+
143
+ ###############################
144
+ ### Concurrency Configuration
145
+ ###############################
146
+ ### Max concurrency requests of LLM (for both query and document processing)
147
+ MAX_ASYNC=4
148
+ ### Number of parallel processing documents(between 2~10, MAX_ASYNC/3 is recommended)
149
+ MAX_PARALLEL_INSERT=2
150
+ ### Max concurrency requests for Embedding
151
+ # EMBEDDING_FUNC_MAX_ASYNC=8
152
+ ### Num of chunks send to Embedding in single request
153
+ # EMBEDDING_BATCH_NUM=10
154
+
155
+ ###########################################################
156
+ ### LLM Configuration
157
+ ### LLM_BINDING type: openai, ollama, lollms, azure_openai, aws_bedrock
158
+ ###########################################################
159
+ ### LLM request timeout setting for all llm (0 means no timeout for Ollma)
160
+ # LLM_TIMEOUT=180
161
+
162
+ LLM_BINDING=openai
163
+ LLM_MODEL=gpt-4o
164
+ LLM_BINDING_HOST=https://api.openai.com/v1
165
+ LLM_BINDING_API_KEY=your_api_key
166
+
167
+ ### Optional for Azure
168
+ # AZURE_OPENAI_API_VERSION=2024-08-01-preview
169
+ # AZURE_OPENAI_DEPLOYMENT=gpt-4o
170
+
171
+ ### Openrouter example
172
+ # LLM_MODEL=google/gemini-2.5-flash
173
+ # LLM_BINDING_HOST=https://openrouter.ai/api/v1
174
+ # LLM_BINDING_API_KEY=your_api_key
175
+ # LLM_BINDING=openai
176
+
177
+ ### OpenAI Compatible API Specific Parameters
178
+ ### Set the max_tokens to mitigate endless output of some LLM (less than LLM_TIMEOUT * llm_output_tokens/second, i.e. 9000 = 180s * 50 tokens/s)
179
+ ### Typically, max_tokens does not include prompt content, though some models, such as Gemini Models, are exceptions
180
+ ### For vLLM/SGLang doployed models, or most of OpenAI compatible API provider
181
+ # OPENAI_LLM_MAX_TOKENS=9000
182
+ ### For OpenAI o1-mini or newer modles
183
+ OPENAI_LLM_MAX_COMPLETION_TOKENS=9000
184
+
185
+ #### OpenAI's new API utilizes max_completion_tokens instead of max_tokens
186
+ # OPENAI_LLM_MAX_TOKENS=9000
187
+ # OPENAI_LLM_MAX_COMPLETION_TOKENS=9000
188
+
189
+ ### OpenRouter Specific Parameters
190
+ # OPENAI_LLM_EXTRA_BODY='{"reasoning": {"enabled": false}}'
191
+ ### Qwen3 Specific Parameters depoly by vLLM
192
+ # OPENAI_LLM_EXTRA_BODY='{"chat_template_kwargs": {"enable_thinking": false}}'
193
+
194
+ ### use the following command to see all support options for OpenAI, azure_openai or OpenRouter
195
+ ### lightrag-server --llm-binding openai --help
196
+
197
+ ### Ollama Server Specific Parameters
198
+ ### OLLAMA_LLM_NUM_CTX must be provided, and should at least larger than MAX_TOTAL_TOKENS + 2000
199
+ OLLAMA_LLM_NUM_CTX=32768
200
+ ### Set the max_output_tokens to mitigate endless output of some LLM (less than LLM_TIMEOUT * llm_output_tokens/second, i.e. 9000 = 180s * 50 tokens/s)
201
+ # OLLAMA_LLM_NUM_PREDICT=9000
202
+ ### Stop sequences for Ollama LLM
203
+ # OLLAMA_LLM_STOP='["</s>", "<|EOT|>"]'
204
+ ### use the following command to see all support options for Ollama LLM
205
+ ### lightrag-server --llm-binding ollama --help
206
+
207
+ ### Bedrock Specific Parameters
208
+ # BEDROCK_LLM_TEMPERATURE=1.0
209
+
210
+ ####################################################################################
211
+ ### Embedding Configuration (Should not be changed after the first file processed)
212
+ ### EMBEDDING_BINDING: ollama, openai, azure_openai, jina, lollms, aws_bedrock
213
+ ####################################################################################
214
+ # EMBEDDING_TIMEOUT=30
215
+ EMBEDDING_BINDING=ollama
216
+ EMBEDDING_MODEL=bge-m3:latest
217
+ EMBEDDING_DIM=1024
218
+ EMBEDDING_BINDING_API_KEY=your_api_key
219
+ # If the embedding service is deployed within the same Docker stack, use host.docker.internal instead of localhost
220
+ EMBEDDING_BINDING_HOST=http://localhost:11434
221
+
222
+ ### OpenAI compatible (VoyageAI embedding openai compatible)
223
+ # EMBEDDING_BINDING=openai
224
+ # EMBEDDING_MODEL=text-embedding-3-large
225
+ # EMBEDDING_DIM=3072
226
+ # EMBEDDING_BINDING_HOST=https://api.openai.com/v1
227
+ # EMBEDDING_BINDING_API_KEY=your_api_key
228
+
229
+ ### Optional for Azure
230
+ # AZURE_EMBEDDING_DEPLOYMENT=text-embedding-3-large
231
+ # AZURE_EMBEDDING_API_VERSION=2023-05-15
232
+ # AZURE_EMBEDDING_ENDPOINT=your_endpoint
233
+ # AZURE_EMBEDDING_API_KEY=your_api_key
234
+
235
+ ### Jina AI Embedding
236
+ # EMBEDDING_BINDING=jina
237
+ # EMBEDDING_BINDING_HOST=https://api.jina.ai/v1/embeddings
238
+ # EMBEDDING_MODEL=jina-embeddings-v4
239
+ # EMBEDDING_DIM=2048
240
+ # EMBEDDING_BINDING_API_KEY=your_api_key
241
+
242
+ ### Optional for Ollama embedding
243
+ OLLAMA_EMBEDDING_NUM_CTX=8192
244
+ ### use the following command to see all support options for Ollama embedding
245
+ ### lightrag-server --embedding-binding ollama --help
246
+
247
+ ####################################################################
248
+ ### WORKSPACE setting workspace name for all storage types
249
+ ### in the purpose of isolating data from LightRAG instances.
250
+ ### Valid workspace name constraints: a-z, A-Z, 0-9, and _
251
+ ####################################################################
252
+ # WORKSPACE=space1
253
+
254
+ ############################
255
+ ### Data storage selection
256
+ ############################
257
+ ### Default storage (Recommended for small scale deployment)
258
+ # LIGHTRAG_KV_STORAGE=JsonKVStorage
259
+ # LIGHTRAG_DOC_STATUS_STORAGE=JsonDocStatusStorage
260
+ # LIGHTRAG_GRAPH_STORAGE=NetworkXStorage
261
+ # LIGHTRAG_VECTOR_STORAGE=NanoVectorDBStorage
262
+
263
+ ### Redis Storage (Recommended for production deployment)
264
+ # LIGHTRAG_KV_STORAGE=RedisKVStorage
265
+ # LIGHTRAG_DOC_STATUS_STORAGE=RedisDocStatusStorage
266
+
267
+ ### Vector Storage (Recommended for production deployment)
268
+ # LIGHTRAG_VECTOR_STORAGE=MilvusVectorDBStorage
269
+ # LIGHTRAG_VECTOR_STORAGE=QdrantVectorDBStorage
270
+ # LIGHTRAG_VECTOR_STORAGE=FaissVectorDBStorage
271
+
272
+ ### Graph Storage (Recommended for production deployment)
273
+ # LIGHTRAG_GRAPH_STORAGE=Neo4JStorage
274
+ # LIGHTRAG_GRAPH_STORAGE=MemgraphStorage
275
+
276
+ ### PostgreSQL
277
+ # LIGHTRAG_KV_STORAGE=PGKVStorage
278
+ # LIGHTRAG_DOC_STATUS_STORAGE=PGDocStatusStorage
279
+ # LIGHTRAG_GRAPH_STORAGE=PGGraphStorage
280
+ # LIGHTRAG_VECTOR_STORAGE=PGVectorStorage
281
+
282
+ ### MongoDB (Vector storage only available on Atlas Cloud)
283
+ # LIGHTRAG_KV_STORAGE=MongoKVStorage
284
+ # LIGHTRAG_DOC_STATUS_STORAGE=MongoDocStatusStorage
285
+ # LIGHTRAG_GRAPH_STORAGE=MongoGraphStorage
286
+ # LIGHTRAG_VECTOR_STORAGE=MongoVectorDBStorage
287
+
288
+ ### PostgreSQL Configuration
289
+ POSTGRES_HOST=localhost
290
+ POSTGRES_PORT=5432
291
+ POSTGRES_USER=your_username
292
+ POSTGRES_PASSWORD='your_password'
293
+ POSTGRES_DATABASE=your_database
294
+ POSTGRES_MAX_CONNECTIONS=12
295
+ # POSTGRES_WORKSPACE=forced_workspace_name
296
+
297
+ ### PostgreSQL Vector Storage Configuration
298
+ ### Vector storage type: HNSW, IVFFlat
299
+ POSTGRES_VECTOR_INDEX_TYPE=HNSW
300
+ POSTGRES_HNSW_M=16
301
+ POSTGRES_HNSW_EF=200
302
+ POSTGRES_IVFFLAT_LISTS=100
303
+
304
+ ### PostgreSQL SSL Configuration (Optional)
305
+ # POSTGRES_SSL_MODE=require
306
+ # POSTGRES_SSL_CERT=/path/to/client-cert.pem
307
+ # POSTGRES_SSL_KEY=/path/to/client-key.pem
308
+ # POSTGRES_SSL_ROOT_CERT=/path/to/ca-cert.pem
309
+ # POSTGRES_SSL_CRL=/path/to/crl.pem
310
+
311
+ ### Neo4j Configuration
312
+ NEO4J_URI=neo4j+s://xxxxxxxx.databases.neo4j.io
313
+ NEO4J_USERNAME=neo4j
314
+ NEO4J_PASSWORD='your_password'
315
+ NEO4J_DATABASE=noe4j
316
+ NEO4J_MAX_CONNECTION_POOL_SIZE=100
317
+ NEO4J_CONNECTION_TIMEOUT=30
318
+ NEO4J_CONNECTION_ACQUISITION_TIMEOUT=30
319
+ NEO4J_MAX_TRANSACTION_RETRY_TIME=30
320
+ NEO4J_MAX_CONNECTION_LIFETIME=300
321
+ NEO4J_LIVENESS_CHECK_TIMEOUT=30
322
+ NEO4J_KEEP_ALIVE=true
323
+ # NEO4J_WORKSPACE=forced_workspace_name
324
+
325
+ ### MongoDB Configuration
326
+ MONGO_URI=mongodb://root:root@localhost:27017/
327
+ #MONGO_URI=mongodb+srv://xxxx
328
+ MONGO_DATABASE=LightRAG
329
+ # MONGODB_WORKSPACE=forced_workspace_name
330
+
331
+ ### Milvus Configuration
332
+ MILVUS_URI=http://localhost:19530
333
+ MILVUS_DB_NAME=lightrag
334
+ # MILVUS_USER=root
335
+ # MILVUS_PASSWORD=your_password
336
+ # MILVUS_TOKEN=your_token
337
+ # MILVUS_WORKSPACE=forced_workspace_name
338
+
339
+ ### Qdrant
340
+ QDRANT_URL=http://localhost:6333
341
+ # QDRANT_API_KEY=your-api-key
342
+ # QDRANT_WORKSPACE=forced_workspace_name
343
+
344
+ ### Redis
345
+ REDIS_URI=redis://localhost:6379
346
+ REDIS_SOCKET_TIMEOUT=30
347
+ REDIS_CONNECT_TIMEOUT=10
348
+ REDIS_MAX_CONNECTIONS=100
349
+ REDIS_RETRY_ATTEMPTS=3
350
+ # REDIS_WORKSPACE=forced_workspace_name
351
+
352
+ ### Memgraph Configuration
353
+ MEMGRAPH_URI=bolt://localhost:7687
354
+ MEMGRAPH_USERNAME=
355
+ MEMGRAPH_PASSWORD=
356
+ MEMGRAPH_DATABASE=memgraph
357
+ # MEMGRAPH_WORKSPACE=forced_workspace_name
LightRAG/env.ollama-binding-options.example ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ################################################################################
2
+ # Autogenerated .env entries list for LightRAG binding options
3
+ #
4
+ # To generate run:
5
+ # $ python -m lightrag.llm.binding_options
6
+ ################################################################################
7
+ # ollama_embedding -- Context window size (number of tokens)
8
+ # OLLAMA_EMBEDDING_NUM_CTX=4096
9
+
10
+ # ollama_embedding -- Maximum number of tokens to predict
11
+ # OLLAMA_EMBEDDING_NUM_PREDICT=128
12
+
13
+ # ollama_embedding -- Number of tokens to keep from the initial prompt
14
+ # OLLAMA_EMBEDDING_NUM_KEEP=0
15
+
16
+ # ollama_embedding -- Random seed for generation (-1 for random)
17
+ # OLLAMA_EMBEDDING_SEED=-1
18
+
19
+ # ollama_embedding -- Controls randomness (0.0-2.0, higher = more creative)
20
+ # OLLAMA_EMBEDDING_TEMPERATURE=0.8
21
+
22
+ # ollama_embedding -- Top-k sampling parameter (0 = disabled)
23
+ # OLLAMA_EMBEDDING_TOP_K=40
24
+
25
+ # ollama_embedding -- Top-p (nucleus) sampling parameter (0.0-1.0)
26
+ # OLLAMA_EMBEDDING_TOP_P=0.9
27
+
28
+ # ollama_embedding -- Tail free sampling parameter (1.0 = disabled)
29
+ # OLLAMA_EMBEDDING_TFS_Z=1.0
30
+
31
+ # ollama_embedding -- Typical probability mass (1.0 = disabled)
32
+ # OLLAMA_EMBEDDING_TYPICAL_P=1.0
33
+
34
+ # ollama_embedding -- Minimum probability threshold (0.0 = disabled)
35
+ # OLLAMA_EMBEDDING_MIN_P=0.0
36
+
37
+ # ollama_embedding -- Number of tokens to consider for repetition penalty
38
+ # OLLAMA_EMBEDDING_REPEAT_LAST_N=64
39
+
40
+ # ollama_embedding -- Penalty for repetition (1.0 = no penalty)
41
+ # OLLAMA_EMBEDDING_REPEAT_PENALTY=1.1
42
+
43
+ # ollama_embedding -- Penalty for token presence (-2.0 to 2.0)
44
+ # OLLAMA_EMBEDDING_PRESENCE_PENALTY=0.0
45
+
46
+ # ollama_embedding -- Penalty for token frequency (-2.0 to 2.0)
47
+ # OLLAMA_EMBEDDING_FREQUENCY_PENALTY=0.0
48
+
49
+ # ollama_embedding -- Mirostat sampling algorithm (0=disabled, 1=Mirostat 1.0, 2=Mirostat 2.0)
50
+ # OLLAMA_EMBEDDING_MIROSTAT=0
51
+
52
+ # ollama_embedding -- Mirostat target entropy
53
+ # OLLAMA_EMBEDDING_MIROSTAT_TAU=5.0
54
+
55
+ # ollama_embedding -- Mirostat learning rate
56
+ # OLLAMA_EMBEDDING_MIROSTAT_ETA=0.1
57
+
58
+ # ollama_embedding -- Enable NUMA optimization
59
+ # OLLAMA_EMBEDDING_NUMA=False
60
+
61
+ # ollama_embedding -- Batch size for processing
62
+ # OLLAMA_EMBEDDING_NUM_BATCH=512
63
+
64
+ # ollama_embedding -- Number of GPUs to use (-1 for auto)
65
+ # OLLAMA_EMBEDDING_NUM_GPU=-1
66
+
67
+ # ollama_embedding -- Main GPU index
68
+ # OLLAMA_EMBEDDING_MAIN_GPU=0
69
+
70
+ # ollama_embedding -- Optimize for low VRAM
71
+ # OLLAMA_EMBEDDING_LOW_VRAM=False
72
+
73
+ # ollama_embedding -- Number of CPU threads (0 for auto)
74
+ # OLLAMA_EMBEDDING_NUM_THREAD=0
75
+
76
+ # ollama_embedding -- Use half-precision for key/value cache
77
+ # OLLAMA_EMBEDDING_F16_KV=True
78
+
79
+ # ollama_embedding -- Return logits for all tokens
80
+ # OLLAMA_EMBEDDING_LOGITS_ALL=False
81
+
82
+ # ollama_embedding -- Only load vocabulary
83
+ # OLLAMA_EMBEDDING_VOCAB_ONLY=False
84
+
85
+ # ollama_embedding -- Use memory mapping for model files
86
+ # OLLAMA_EMBEDDING_USE_MMAP=True
87
+
88
+ # ollama_embedding -- Lock model in memory
89
+ # OLLAMA_EMBEDDING_USE_MLOCK=False
90
+
91
+ # ollama_embedding -- Only use for embeddings
92
+ # OLLAMA_EMBEDDING_EMBEDDING_ONLY=False
93
+
94
+ # ollama_embedding -- Penalize newline tokens
95
+ # OLLAMA_EMBEDDING_PENALIZE_NEWLINE=True
96
+
97
+ # ollama_embedding -- Stop sequences (comma-separated string)
98
+ # OLLAMA_EMBEDDING_STOP=
99
+
100
+ # ollama_llm -- Context window size (number of tokens)
101
+ # OLLAMA_LLM_NUM_CTX=4096
102
+
103
+ # ollama_llm -- Maximum number of tokens to predict
104
+ # OLLAMA_LLM_NUM_PREDICT=128
105
+
106
+ # ollama_llm -- Number of tokens to keep from the initial prompt
107
+ # OLLAMA_LLM_NUM_KEEP=0
108
+
109
+ # ollama_llm -- Random seed for generation (-1 for random)
110
+ # OLLAMA_LLM_SEED=-1
111
+
112
+ # ollama_llm -- Controls randomness (0.0-2.0, higher = more creative)
113
+ # OLLAMA_LLM_TEMPERATURE=0.8
114
+
115
+ # ollama_llm -- Top-k sampling parameter (0 = disabled)
116
+ # OLLAMA_LLM_TOP_K=40
117
+
118
+ # ollama_llm -- Top-p (nucleus) sampling parameter (0.0-1.0)
119
+ # OLLAMA_LLM_TOP_P=0.9
120
+
121
+ # ollama_llm -- Tail free sampling parameter (1.0 = disabled)
122
+ # OLLAMA_LLM_TFS_Z=1.0
123
+
124
+ # ollama_llm -- Typical probability mass (1.0 = disabled)
125
+ # OLLAMA_LLM_TYPICAL_P=1.0
126
+
127
+ # ollama_llm -- Minimum probability threshold (0.0 = disabled)
128
+ # OLLAMA_LLM_MIN_P=0.0
129
+
130
+ # ollama_llm -- Number of tokens to consider for repetition penalty
131
+ # OLLAMA_LLM_REPEAT_LAST_N=64
132
+
133
+ # ollama_llm -- Penalty for repetition (1.0 = no penalty)
134
+ # OLLAMA_LLM_REPEAT_PENALTY=1.1
135
+
136
+ # ollama_llm -- Penalty for token presence (-2.0 to 2.0)
137
+ # OLLAMA_LLM_PRESENCE_PENALTY=0.0
138
+
139
+ # ollama_llm -- Penalty for token frequency (-2.0 to 2.0)
140
+ # OLLAMA_LLM_FREQUENCY_PENALTY=0.0
141
+
142
+ # ollama_llm -- Mirostat sampling algorithm (0=disabled, 1=Mirostat 1.0, 2=Mirostat 2.0)
143
+ # OLLAMA_LLM_MIROSTAT=0
144
+
145
+ # ollama_llm -- Mirostat target entropy
146
+ # OLLAMA_LLM_MIROSTAT_TAU=5.0
147
+
148
+ # ollama_llm -- Mirostat learning rate
149
+ # OLLAMA_LLM_MIROSTAT_ETA=0.1
150
+
151
+ # ollama_llm -- Enable NUMA optimization
152
+ # OLLAMA_LLM_NUMA=False
153
+
154
+ # ollama_llm -- Batch size for processing
155
+ # OLLAMA_LLM_NUM_BATCH=512
156
+
157
+ # ollama_llm -- Number of GPUs to use (-1 for auto)
158
+ # OLLAMA_LLM_NUM_GPU=-1
159
+
160
+ # ollama_llm -- Main GPU index
161
+ # OLLAMA_LLM_MAIN_GPU=0
162
+
163
+ # ollama_llm -- Optimize for low VRAM
164
+ # OLLAMA_LLM_LOW_VRAM=False
165
+
166
+ # ollama_llm -- Number of CPU threads (0 for auto)
167
+ # OLLAMA_LLM_NUM_THREAD=0
168
+
169
+ # ollama_llm -- Use half-precision for key/value cache
170
+ # OLLAMA_LLM_F16_KV=True
171
+
172
+ # ollama_llm -- Return logits for all tokens
173
+ # OLLAMA_LLM_LOGITS_ALL=False
174
+
175
+ # ollama_llm -- Only load vocabulary
176
+ # OLLAMA_LLM_VOCAB_ONLY=False
177
+
178
+ # ollama_llm -- Use memory mapping for model files
179
+ # OLLAMA_LLM_USE_MMAP=True
180
+
181
+ # ollama_llm -- Lock model in memory
182
+ # OLLAMA_LLM_USE_MLOCK=False
183
+
184
+ # ollama_llm -- Only use for embeddings
185
+ # OLLAMA_LLM_EMBEDDING_ONLY=False
186
+
187
+ # ollama_llm -- Penalize newline tokens
188
+ # OLLAMA_LLM_PENALIZE_NEWLINE=True
189
+
190
+ # ollama_llm -- Stop sequences (comma-separated string)
191
+ # OLLAMA_LLM_STOP=
192
+
193
+ #
194
+ # End of .env entries for LightRAG binding options
195
+ ################################################################################
LightRAG/k8s-deploy/README-zh.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LightRAG Helm Chart
2
+
3
+ 这是用于在Kubernetes集群上部署LightRAG服务的Helm chart。
4
+
5
+ LightRAG有两种推荐的部署方法:
6
+ 1. **轻量级部署**:使用内置轻量级存储,适合测试和小规模使用
7
+ 2. **生产环境部署**:使用外部数据库(如PostgreSQL和Neo4J),适合生产环境和大规模使用
8
+
9
+ > 如果您想要部署过程的视频演示,可以查看[bilibili](https://www.bilibili.com/video/BV1bUJazBEq2/)上的视频教程,对于喜欢视觉指导的用户可能会有所帮助。
10
+
11
+ ## 前提条件
12
+
13
+ 确保安装和配置了以下工具:
14
+
15
+ * **Kubernetes集群**
16
+ * 需要一个运行中的Kubernetes集群。
17
+ * 对于本地开发或演示,可以使用[Minikube](https://minikube.sigs.k8s.io/docs/start/)(需要≥2个CPU,≥4GB内存,以及Docker/VM驱动支持)。
18
+ * 任何标准的云端或本地Kubernetes集群(EKS、GKE、AKS等)也可以使用。
19
+
20
+ * **kubectl**
21
+ * Kubernetes命令行工具,用于管理集群。
22
+ * 按照官方指南安装:[安装和设置kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl)。
23
+
24
+ * **Helm**(v3.x+)
25
+ * Kubernetes包管理器,用于安装LightRAG。
26
+ * 通过官方指南安装:[安装Helm](https://helm.sh/docs/intro/install/)。
27
+
28
+ ## 轻量级部署(无需外部数据库)
29
+
30
+ 这种部署选项使用内置的轻量级存储组件,非常适合测试、演示或小规模使用场景。无需外部数据库配置。
31
+
32
+ 您可以使用提供的便捷脚本或直接使用Helm命令部署LightRAG。两种方法都配置了`lightrag/values.yaml`文件中定义的相同环境变量。
33
+
34
+ ### 使用便捷脚本(推荐):
35
+
36
+ ```bash
37
+ export OPENAI_API_BASE=<您的OPENAI_API_BASE>
38
+ export OPENAI_API_KEY=<您的OPENAI_API_KEY>
39
+ bash ./install_lightrag_dev.sh
40
+ ```
41
+
42
+ ### 或直接使用Helm:
43
+
44
+ ```bash
45
+ # 您可以覆盖任何想要的环境参数
46
+ helm upgrade --install lightrag ./lightrag \
47
+ --namespace rag \
48
+ --set-string env.LIGHTRAG_KV_STORAGE=JsonKVStorage \
49
+ --set-string env.LIGHTRAG_VECTOR_STORAGE=NanoVectorDBStorage \
50
+ --set-string env.LIGHTRAG_GRAPH_STORAGE=NetworkXStorage \
51
+ --set-string env.LIGHTRAG_DOC_STATUS_STORAGE=JsonDocStatusStorage \
52
+ --set-string env.LLM_BINDING=openai \
53
+ --set-string env.LLM_MODEL=gpt-4o-mini \
54
+ --set-string env.LLM_BINDING_HOST=$OPENAI_API_BASE \
55
+ --set-string env.LLM_BINDING_API_KEY=$OPENAI_API_KEY \
56
+ --set-string env.EMBEDDING_BINDING=openai \
57
+ --set-string env.EMBEDDING_MODEL=text-embedding-ada-002 \
58
+ --set-string env.EMBEDDING_DIM=1536 \
59
+ --set-string env.EMBEDDING_BINDING_API_KEY=$OPENAI_API_KEY
60
+ ```
61
+
62
+ ### 访问应用程序:
63
+
64
+ ```bash
65
+ # 1. 在终端中运行此端口转发命令:
66
+ kubectl --namespace rag port-forward svc/lightrag-dev 9621:9621
67
+
68
+ # 2. 当命令运行时,打开浏览器并导航到:
69
+ # http://localhost:9621
70
+ ```
71
+
72
+ ## 生产环境部署(使用外部数据库)
73
+
74
+ ### 1. 安装数据库
75
+ > 如果您已经准备好了数据库,可以跳过此步骤。详细信息可以在:[README.md](databases%2FREADME.md)中找到。
76
+
77
+ 我们推荐使用KubeBlocks进行数据库部署。KubeBlocks是一个云原生数据库操作符,可以轻松地在Kubernetes上以生产规模运行任何数据库。
78
+
79
+ 首先,安装KubeBlocks和KubeBlocks-Addons(如已安装可跳过):
80
+ ```bash
81
+ bash ./databases/01-prepare.sh
82
+ ```
83
+
84
+ 然后安装所需的数据库。默认情况下,这将安装PostgreSQL和Neo4J,但您可以修改[00-config.sh](databases%2F00-config.sh)以根据需要选择不同的数据库:
85
+ ```bash
86
+ bash ./databases/02-install-database.sh
87
+ ```
88
+
89
+ 验证集群是否正在运行:
90
+ ```bash
91
+ kubectl get clusters -n rag
92
+ # 预期输出:
93
+ # NAME CLUSTER-DEFINITION TERMINATION-POLICY STATUS AGE
94
+ # neo4j-cluster Delete Running 39s
95
+ # pg-cluster postgresql Delete Running 42s
96
+
97
+ kubectl get po -n rag
98
+ # 预期输出:
99
+ # NAME READY STATUS RESTARTS AGE
100
+ # neo4j-cluster-neo4j-0 1/1 Running 0 58s
101
+ # pg-cluster-postgresql-0 4/4 Running 0 59s
102
+ # pg-cluster-postgresql-1 4/4 Running 0 59s
103
+ ```
104
+
105
+ ### 2. 安装LightRAG
106
+
107
+ LightRAG及其数据库部署在同一Kubernetes集群中,使配置变得简单。
108
+ 安装脚本会自动从KubeBlocks获取所有数据库连接信息,无需手动设置数据库凭证:
109
+
110
+ ```bash
111
+ export OPENAI_API_BASE=<您的OPENAI_API_BASE>
112
+ export OPENAI_API_KEY=<您的OPENAI_API_KEY>
113
+ bash ./install_lightrag.sh
114
+ ```
115
+
116
+ ### 访问应用程序:
117
+
118
+ ```bash
119
+ # 1. 在终端中运行此端口转发命令:
120
+ kubectl --namespace rag port-forward svc/lightrag 9621:9621
121
+
122
+ # 2. 当命令运行时,打开浏览器并导航到:
123
+ # http://localhost:9621
124
+ ```
125
+
126
+ ## 配置
127
+
128
+ ### 修改资源配置
129
+
130
+ 您可以通过修改`values.yaml`文件来配置LightRAG的资源使用:
131
+
132
+ ```yaml
133
+ replicaCount: 1 # 副本数量,可根据需要增加
134
+
135
+ resources:
136
+ limits:
137
+ cpu: 1000m # CPU限制,可根据需要调整
138
+ memory: 2Gi # 内存限制,可根据需要调整
139
+ requests:
140
+ cpu: 500m # CPU请求,可根据需要调整
141
+ memory: 1Gi # 内存请求,可根据需要调整
142
+ ```
143
+
144
+ ### 修改持久存储
145
+
146
+ ```yaml
147
+ persistence:
148
+ enabled: true
149
+ ragStorage:
150
+ size: 10Gi # RAG存储大小,可根据需要调整
151
+ inputs:
152
+ size: 5Gi # 输入数据存储大小,可根据需要调整
153
+ ```
154
+
155
+ ### 配置环境变量
156
+
157
+ `values.yaml`文件中的`env`部分包含LightRAG的所有环境配置,类似于`.env`文件。当使用helm upgrade或helm install命令时,可以使用--set标志覆盖这些变量。
158
+
159
+ ```yaml
160
+ env:
161
+ HOST: 0.0.0.0
162
+ PORT: 9621
163
+ WEBUI_TITLE: Graph RAG Engine
164
+ WEBUI_DESCRIPTION: Simple and Fast Graph Based RAG System
165
+
166
+ # LLM配置
167
+ LLM_BINDING: openai # LLM服务提供商
168
+ LLM_MODEL: gpt-4o-mini # LLM模型
169
+ LLM_BINDING_HOST: # API基础URL(可选)
170
+ LLM_BINDING_API_KEY: # API密钥
171
+
172
+ # 嵌入配置
173
+ EMBEDDING_BINDING: openai # 嵌入服务提供商
174
+ EMBEDDING_MODEL: text-embedding-ada-002 # 嵌入模型
175
+ EMBEDDING_DIM: 1536 # 嵌入维度
176
+ EMBEDDING_BINDING_API_KEY: # API密钥
177
+
178
+ # 存储配置
179
+ LIGHTRAG_KV_STORAGE: PGKVStorage # 键值存储类型
180
+ LIGHTRAG_VECTOR_STORAGE: PGVectorStorage # 向量存储类型
181
+ LIGHTRAG_GRAPH_STORAGE: Neo4JStorage # 图存储类型
182
+ LIGHTRAG_DOC_STATUS_STORAGE: PGDocStatusStorage # 文档状态存储类型
183
+ ```
184
+
185
+ ## 注意事项
186
+
187
+ - 在部署前确保设置了所有必要的环境变量(API密钥和数据库密码)
188
+ - 出于安全原因,建议使用环境变量传递敏感信息,而不是直接写入脚本或values文件
189
+ - 轻量级部署适合测试和小规模使用,但数据持久性和性能可能有限
190
+ - 生产环境部署(PostgreSQL + Neo4J)推荐用于生产环境和大规模使用
191
+ - 有关更多自定义配置,请参考LightRAG官方文档
LightRAG/k8s-deploy/README.md ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # LightRAG Helm Chart
2
+
3
+ This is the Helm chart for LightRAG, used to deploy LightRAG services on a Kubernetes cluster.
4
+
5
+ There are two recommended deployment methods for LightRAG:
6
+ 1. **Lightweight Deployment**: Using built-in lightweight storage, suitable for testing and small-scale usage
7
+ 2. **Production Deployment**: Using external databases (such as PostgreSQL and Neo4J), suitable for production environments and large-scale usage
8
+
9
+ > If you'd like a video walkthrough of the deployment process, feel free to check out this optional [video tutorial](https://youtu.be/JW1z7fzeKTw?si=vPzukqqwmdzq9Q4q) on YouTube. It might help clarify some steps for those who prefer visual guidance.
10
+
11
+ ## Prerequisites
12
+
13
+ Make sure the following tools are installed and configured:
14
+
15
+ * **Kubernetes cluster**
16
+ * A running Kubernetes cluster is required.
17
+ * For local development or demos you can use [Minikube](https://minikube.sigs.k8s.io/docs/start/) (needs ≥ 2 CPUs, ≥ 4 GB RAM, and Docker/VM-driver support).
18
+ * Any standard cloud or on-premises Kubernetes cluster (EKS, GKE, AKS, etc.) also works.
19
+
20
+ * **kubectl**
21
+ * The Kubernetes command-line tool for managing your cluster.
22
+ * Follow the official guide: [Install and Set Up kubectl](https://kubernetes.io/docs/tasks/tools/#kubectl).
23
+
24
+ * **Helm** (v3.x+)
25
+ * Kubernetes package manager used to install LightRAG.
26
+ * Install it via the official instructions: [Installing Helm](https://helm.sh/docs/intro/install/).
27
+
28
+ ## Lightweight Deployment (No External Databases Required)
29
+
30
+ This deployment option uses built-in lightweight storage components that are perfect for testing, demos, or small-scale usage scenarios. No external database configuration is required.
31
+
32
+ You can deploy LightRAG using either the provided convenience script or direct Helm commands. Both methods configure the same environment variables defined in the `lightrag/values.yaml` file.
33
+
34
+ ### Using the convenience script (recommended):
35
+
36
+ ```bash
37
+ export OPENAI_API_BASE=<YOUR_OPENAI_API_BASE>
38
+ export OPENAI_API_KEY=<YOUR_OPENAI_API_KEY>
39
+ bash ./install_lightrag_dev.sh
40
+ ```
41
+
42
+ ### Or using Helm directly:
43
+
44
+ ```bash
45
+ # You can override any env param you want
46
+ helm upgrade --install lightrag ./lightrag \
47
+ --namespace rag \
48
+ --set-string env.LIGHTRAG_KV_STORAGE=JsonKVStorage \
49
+ --set-string env.LIGHTRAG_VECTOR_STORAGE=NanoVectorDBStorage \
50
+ --set-string env.LIGHTRAG_GRAPH_STORAGE=NetworkXStorage \
51
+ --set-string env.LIGHTRAG_DOC_STATUS_STORAGE=JsonDocStatusStorage \
52
+ --set-string env.LLM_BINDING=openai \
53
+ --set-string env.LLM_MODEL=gpt-4o-mini \
54
+ --set-string env.LLM_BINDING_HOST=$OPENAI_API_BASE \
55
+ --set-string env.LLM_BINDING_API_KEY=$OPENAI_API_KEY \
56
+ --set-string env.EMBEDDING_BINDING=openai \
57
+ --set-string env.EMBEDDING_MODEL=text-embedding-ada-002 \
58
+ --set-string env.EMBEDDING_DIM=1536 \
59
+ --set-string env.EMBEDDING_BINDING_API_KEY=$OPENAI_API_KEY
60
+ ```
61
+
62
+ ### Accessing the application:
63
+
64
+ ```bash
65
+ # 1. Run this port-forward command in your terminal:
66
+ kubectl --namespace rag port-forward svc/lightrag-dev 9621:9621
67
+
68
+ # 2. While the command is running, open your browser and navigate to:
69
+ # http://localhost:9621
70
+ ```
71
+
72
+ ## Production Deployment (Using External Databases)
73
+
74
+ ### 1. Install Databases
75
+ > You can skip this step if you've already prepared databases. Detailed information can be found in: [README.md](databases%2FREADME.md).
76
+
77
+ We recommend KubeBlocks for database deployment. KubeBlocks is a cloud-native database operator that makes it easy to run any database on Kubernetes at production scale.
78
+
79
+ First, install KubeBlocks and KubeBlocks-Addons (skip if already installed):
80
+ ```bash
81
+ bash ./databases/01-prepare.sh
82
+ ```
83
+
84
+ Then install the required databases. By default, this will install PostgreSQL and Neo4J, but you can modify [00-config.sh](databases%2F00-config.sh) to select different databases based on your needs:
85
+ ```bash
86
+ bash ./databases/02-install-database.sh
87
+ ```
88
+
89
+ Verify that the clusters are up and running:
90
+ ```bash
91
+ kubectl get clusters -n rag
92
+ # Expected output:
93
+ # NAME CLUSTER-DEFINITION TERMINATION-POLICY STATUS AGE
94
+ # neo4j-cluster Delete Running 39s
95
+ # pg-cluster postgresql Delete Running 42s
96
+
97
+ kubectl get po -n rag
98
+ # Expected output:
99
+ # NAME READY STATUS RESTARTS AGE
100
+ # neo4j-cluster-neo4j-0 1/1 Running 0 58s
101
+ # pg-cluster-postgresql-0 4/4 Running 0 59s
102
+ # pg-cluster-postgresql-1 4/4 Running 0 59s
103
+ ```
104
+
105
+ ### 2. Install LightRAG
106
+
107
+ LightRAG and its databases are deployed within the same Kubernetes cluster, making configuration straightforward.
108
+ The installation script automatically retrieves all database connection information from KubeBlocks, eliminating the need to manually set database credentials:
109
+
110
+ ```bash
111
+ export OPENAI_API_BASE=<YOUR_OPENAI_API_BASE>
112
+ export OPENAI_API_KEY=<YOUR_OPENAI_API_KEY>
113
+ bash ./install_lightrag.sh
114
+ ```
115
+
116
+ ### Accessing the application:
117
+
118
+ ```bash
119
+ # 1. Run this port-forward command in your terminal:
120
+ kubectl --namespace rag port-forward svc/lightrag 9621:9621
121
+
122
+ # 2. While the command is running, open your browser and navigate to:
123
+ # http://localhost:9621
124
+ ```
125
+
126
+ ## Configuration
127
+
128
+ ### Modifying Resource Configuration
129
+
130
+ You can configure LightRAG's resource usage by modifying the `values.yaml` file:
131
+
132
+ ```yaml
133
+ replicaCount: 1 # Number of replicas, can be increased as needed
134
+
135
+ resources:
136
+ limits:
137
+ cpu: 1000m # CPU limit, can be adjusted as needed
138
+ memory: 2Gi # Memory limit, can be adjusted as needed
139
+ requests:
140
+ cpu: 500m # CPU request, can be adjusted as needed
141
+ memory: 1Gi # Memory request, can be adjusted as needed
142
+ ```
143
+
144
+ ### Modifying Persistent Storage
145
+
146
+ ```yaml
147
+ persistence:
148
+ enabled: true
149
+ ragStorage:
150
+ size: 10Gi # RAG storage size, can be adjusted as needed
151
+ inputs:
152
+ size: 5Gi # Input data storage size, can be adjusted as needed
153
+ ```
154
+
155
+ ### Configuring Environment Variables
156
+
157
+ The `env` section in the `values.yaml` file contains all environment configurations for LightRAG, similar to a `.env` file. When using helm upgrade or helm install commands, you can override these with the --set flag.
158
+
159
+ ```yaml
160
+ env:
161
+ HOST: 0.0.0.0
162
+ PORT: 9621
163
+ WEBUI_TITLE: Graph RAG Engine
164
+ WEBUI_DESCRIPTION: Simple and Fast Graph Based RAG System
165
+
166
+ # LLM Configuration
167
+ LLM_BINDING: openai # LLM service provider
168
+ LLM_MODEL: gpt-4o-mini # LLM model
169
+ LLM_BINDING_HOST: # API base URL (optional)
170
+ LLM_BINDING_API_KEY: # API key
171
+
172
+ # Embedding Configuration
173
+ EMBEDDING_BINDING: openai # Embedding service provider
174
+ EMBEDDING_MODEL: text-embedding-ada-002 # Embedding model
175
+ EMBEDDING_DIM: 1536 # Embedding dimension
176
+ EMBEDDING_BINDING_API_KEY: # API key
177
+
178
+ # Storage Configuration
179
+ LIGHTRAG_KV_STORAGE: PGKVStorage # Key-value storage type
180
+ LIGHTRAG_VECTOR_STORAGE: PGVectorStorage # Vector storage type
181
+ LIGHTRAG_GRAPH_STORAGE: Neo4JStorage # Graph storage type
182
+ LIGHTRAG_DOC_STATUS_STORAGE: PGDocStatusStorage # Document status storage type
183
+ ```
184
+
185
+ ## Notes
186
+
187
+ - Ensure all necessary environment variables (API keys and database passwords) are set before deployment
188
+ - For security reasons, it's recommended to pass sensitive information using environment variables rather than writing them directly in scripts or values files
189
+ - Lightweight deployment is suitable for testing and small-scale usage, but data persistence and performance may be limited
190
+ - Production deployment (PostgreSQL + Neo4J) is recommended for production environments and large-scale usage
191
+ - For more customized configurations, please refer to the official LightRAG documentation
LightRAG/k8s-deploy/databases/00-config.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Get the directory where this script is located
4
+ DATABASE_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
5
+ source "$DATABASE_SCRIPT_DIR/scripts/common.sh"
6
+
7
+ # Namespace configuration
8
+ NAMESPACE="rag"
9
+ # version
10
+ KB_VERSION="1.0.0-beta.48"
11
+ ADDON_CLUSTER_CHART_VERSION="1.0.0-alpha.0"
12
+ # Helm repository
13
+ HELM_REPO="https://apecloud.github.io/helm-charts"
14
+
15
+ # Set to true to enable the database, false to disable
16
+ ENABLE_POSTGRESQL=true
17
+ ENABLE_REDIS=false
18
+ ENABLE_QDRANT=false
19
+ ENABLE_NEO4J=true
20
+ ENABLE_ELASTICSEARCH=false
21
+ ENABLE_MONGODB=false
LightRAG/k8s-deploy/databases/01-prepare.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Get the directory where this script is located
4
+ DATABASE_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
5
+ # Load configuration file
6
+ source "$DATABASE_SCRIPT_DIR/00-config.sh"
7
+
8
+ check_dependencies
9
+
10
+ # Check if KubeBlocks is already installed, install it if it is not.
11
+ source "$DATABASE_SCRIPT_DIR/install-kubeblocks.sh"
12
+
13
+ # Create namespaces
14
+ print "Creating namespaces..."
15
+ kubectl create namespace $NAMESPACE 2>/dev/null || true
16
+
17
+ # Install database addons
18
+ print "Installing KubeBlocks database addons..."
19
+
20
+ # Add and update Helm repository
21
+ print "Adding and updating KubeBlocks Helm repository..."
22
+ helm repo add kubeblocks $HELM_REPO
23
+ helm repo update
24
+ # Install database addons based on configuration
25
+ [ "$ENABLE_POSTGRESQL" = true ] && print "Installing PostgreSQL addon..." && helm upgrade --install kb-addon-postgresql kubeblocks/postgresql --namespace kb-system --version $ADDON_CLUSTER_CHART_VERSION
26
+ [ "$ENABLE_REDIS" = true ] && print "Installing Redis addon..." && helm upgrade --install kb-addon-redis kubeblocks/redis --namespace kb-system --version $ADDON_CLUSTER_CHART_VERSION
27
+ [ "$ENABLE_ELASTICSEARCH" = true ] && print "Installing Elasticsearch addon..." && helm upgrade --install kb-addon-elasticsearch kubeblocks/elasticsearch --namespace kb-system --version $ADDON_CLUSTER_CHART_VERSION
28
+ [ "$ENABLE_QDRANT" = true ] && print "Installing Qdrant addon..." && helm upgrade --install kb-addon-qdrant kubeblocks/qdrant --namespace kb-system --version $ADDON_CLUSTER_CHART_VERSION
29
+ [ "$ENABLE_MONGODB" = true ] && print "Installing MongoDB addon..." && helm upgrade --install kb-addon-mongodb kubeblocks/mongodb --namespace kb-system --version $ADDON_CLUSTER_CHART_VERSION
30
+ [ "$ENABLE_NEO4J" = true ] && print "Installing Neo4j addon..." && helm upgrade --install kb-addon-neo4j kubeblocks/neo4j --namespace kb-system --version $ADDON_CLUSTER_CHART_VERSION
31
+
32
+ print_success "KubeBlocks database addons installation completed!"
33
+ print "Now you can run 02-install-database.sh to install database clusters"
LightRAG/k8s-deploy/databases/02-install-database.sh ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Get the directory where this script is located
4
+ DATABASE_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
5
+
6
+ # Load configuration file
7
+ source "$DATABASE_SCRIPT_DIR/00-config.sh"
8
+
9
+ print "Installing database clusters..."
10
+
11
+ # Install database clusters based on configuration
12
+ [ "$ENABLE_POSTGRESQL" = true ] && print "Installing PostgreSQL cluster..." && helm upgrade --install pg-cluster kubeblocks/postgresql-cluster -f "$DATABASE_SCRIPT_DIR/postgresql/values.yaml" --namespace $NAMESPACE --version $ADDON_CLUSTER_CHART_VERSION
13
+ [ "$ENABLE_REDIS" = true ] && print "Installing Redis cluster..." && helm upgrade --install redis-cluster kubeblocks/redis-cluster -f "$DATABASE_SCRIPT_DIR/redis/values.yaml" --namespace $NAMESPACE --version $ADDON_CLUSTER_CHART_VERSION
14
+ [ "$ENABLE_ELASTICSEARCH" = true ] && print "Installing Elasticsearch cluster..." && helm upgrade --install es-cluster kubeblocks/elasticsearch-cluster -f "$DATABASE_SCRIPT_DIR/elasticsearch/values.yaml" --namespace $NAMESPACE --version $ADDON_CLUSTER_CHART_VERSION
15
+ [ "$ENABLE_QDRANT" = true ] && print "Installing Qdrant cluster..." && helm upgrade --install qdrant-cluster kubeblocks/qdrant-cluster -f "$DATABASE_SCRIPT_DIR/qdrant/values.yaml" --namespace $NAMESPACE --version $ADDON_CLUSTER_CHART_VERSION
16
+ [ "$ENABLE_MONGODB" = true ] && print "Installing MongoDB cluster..." && helm upgrade --install mongodb-cluster kubeblocks/mongodb-cluster -f "$DATABASE_SCRIPT_DIR/mongodb/values.yaml" --namespace $NAMESPACE --version $ADDON_CLUSTER_CHART_VERSION
17
+ [ "$ENABLE_NEO4J" = true ] && print "Installing Neo4j cluster..." && helm upgrade --install neo4j-cluster kubeblocks/neo4j-cluster -f "$DATABASE_SCRIPT_DIR/neo4j/values.yaml" --namespace $NAMESPACE --version $ADDON_CLUSTER_CHART_VERSION
18
+
19
+ # Wait for databases to be ready
20
+ print "Waiting for databases to be ready..."
21
+ TIMEOUT=600 # Set timeout to 10 minutes
22
+ START_TIME=$(date +%s)
23
+
24
+ while true; do
25
+ CURRENT_TIME=$(date +%s)
26
+ ELAPSED=$((CURRENT_TIME - START_TIME))
27
+
28
+ if [ $ELAPSED -gt $TIMEOUT ]; then
29
+ print_error "Timeout waiting for databases to be ready. Please check database status manually and try again"
30
+ exit 1
31
+ fi
32
+
33
+ # Build wait conditions for enabled databases
34
+ WAIT_CONDITIONS=()
35
+ [ "$ENABLE_POSTGRESQL" = true ] && WAIT_CONDITIONS+=("kubectl wait --for=condition=ready pods -l app.kubernetes.io/instance=pg-cluster -n $NAMESPACE --timeout=10s")
36
+ [ "$ENABLE_REDIS" = true ] && WAIT_CONDITIONS+=("kubectl wait --for=condition=ready pods -l app.kubernetes.io/instance=redis-cluster -n $NAMESPACE --timeout=10s")
37
+ [ "$ENABLE_ELASTICSEARCH" = true ] && WAIT_CONDITIONS+=("kubectl wait --for=condition=ready pods -l app.kubernetes.io/instance=es-cluster -n $NAMESPACE --timeout=10s")
38
+ [ "$ENABLE_QDRANT" = true ] && WAIT_CONDITIONS+=("kubectl wait --for=condition=ready pods -l app.kubernetes.io/instance=qdrant-cluster -n $NAMESPACE --timeout=10s")
39
+ [ "$ENABLE_MONGODB" = true ] && WAIT_CONDITIONS+=("kubectl wait --for=condition=ready pods -l app.kubernetes.io/instance=mongodb-cluster -n $NAMESPACE --timeout=10s")
40
+ [ "$ENABLE_NEO4J" = true ] && WAIT_CONDITIONS+=("kubectl wait --for=condition=ready pods -l app.kubernetes.io/instance=neo4j-cluster -n $NAMESPACE --timeout=10s")
41
+
42
+ # Check if all enabled databases are ready
43
+ ALL_READY=true
44
+ for CONDITION in "${WAIT_CONDITIONS[@]}"; do
45
+ if ! eval "$CONDITION &> /dev/null"; then
46
+ ALL_READY=false
47
+ break
48
+ fi
49
+ done
50
+
51
+ if [ "$ALL_READY" = true ]; then
52
+ print "All database pods are ready, continuing with deployment..."
53
+ break
54
+ fi
55
+
56
+ print "Waiting for database pods to be ready (${ELAPSED}s elapsed)..."
57
+ sleep 10
58
+ done
59
+
60
+ print_success "Database clusters installation completed!"
61
+ print "Use the following command to check the status of installed clusters:"
62
+ print "kubectl get clusters -n $NAMESPACE"
LightRAG/k8s-deploy/databases/03-uninstall-database.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Get the directory where this script is located
4
+ DATABASE_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
5
+
6
+ # Load configuration file
7
+ source "$DATABASE_SCRIPT_DIR/00-config.sh"
8
+
9
+ print "Uninstalling database clusters..."
10
+
11
+ # Uninstall database clusters based on configuration
12
+ [ "$ENABLE_POSTGRESQL" = true ] && print "Uninstalling PostgreSQL cluster..." && helm uninstall pg-cluster --namespace $NAMESPACE 2>/dev/null || true
13
+ [ "$ENABLE_REDIS" = true ] && print "Uninstalling Redis cluster..." && helm uninstall redis-cluster --namespace $NAMESPACE 2>/dev/null || true
14
+ [ "$ENABLE_ELASTICSEARCH" = true ] && print "Uninstalling Elasticsearch cluster..." && helm uninstall es-cluster --namespace $NAMESPACE 2>/dev/null || true
15
+ [ "$ENABLE_QDRANT" = true ] && print "Uninstalling Qdrant cluster..." && helm uninstall qdrant-cluster --namespace $NAMESPACE 2>/dev/null || true
16
+ [ "$ENABLE_MONGODB" = true ] && print "Uninstalling MongoDB cluster..." && helm uninstall mongodb-cluster --namespace $NAMESPACE 2>/dev/null || true
17
+ [ "$ENABLE_NEO4J" = true ] && print "Uninstalling Neo4j cluster..." && helm uninstall neo4j-cluster --namespace $NAMESPACE 2>/dev/null || true
18
+
19
+ print_success "Database clusters uninstalled"
20
+ print "To uninstall database addons and KubeBlocks, run 04-cleanup.sh"
LightRAG/k8s-deploy/databases/04-cleanup.sh ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Get the directory where this script is located
4
+ DATABASE_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
5
+
6
+ # Load configuration file
7
+ source "$DATABASE_SCRIPT_DIR/00-config.sh"
8
+
9
+ print "Uninstalling KubeBlocks database addons..."
10
+
11
+ # Uninstall database addons based on configuration
12
+ [ "$ENABLE_POSTGRESQL" = true ] && print "Uninstalling PostgreSQL addon..." && helm uninstall kb-addon-postgresql --namespace kb-system 2>/dev/null || true
13
+ [ "$ENABLE_REDIS" = true ] && print "Uninstalling Redis addon..." && helm uninstall kb-addon-redis --namespace kb-system 2>/dev/null || true
14
+ [ "$ENABLE_ELASTICSEARCH" = true ] && print "Uninstalling Elasticsearch addon..." && helm uninstall kb-addon-elasticsearch --namespace kb-system 2>/dev/null || true
15
+ [ "$ENABLE_QDRANT" = true ] && print "Uninstalling Qdrant addon..." && helm uninstall kb-addon-qdrant --namespace kb-system 2>/dev/null || true
16
+ [ "$ENABLE_MONGODB" = true ] && print "Uninstalling MongoDB addon..." && helm uninstall kb-addon-mongodb --namespace kb-system 2>/dev/null || true
17
+ [ "$ENABLE_NEO4J" = true ] && print "Uninstalling Neo4j addon..." && helm uninstall kb-addon-neo4j --namespace kb-system 2>/dev/null || true
18
+
19
+ print_success "Database addons uninstallation completed!"
20
+
21
+ source "$DATABASE_SCRIPT_DIR/uninstall-kubeblocks.sh"
22
+
23
+ kubectl delete namespace $NAMESPACE
24
+ kubectl delete namespace kb-system
25
+
26
+ print_success "KubeBlocks uninstallation completed!"
LightRAG/k8s-deploy/databases/install-kubeblocks.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Get the directory where this script is located
4
+ DATABASE_SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
5
+ # Load configuration file
6
+ source "$DATABASE_SCRIPT_DIR/00-config.sh"
7
+
8
+ # Check dependencies
9
+ check_dependencies
10
+
11
+ # Function for installing KubeBlocks
12
+ install_kubeblocks() {
13
+ print "Ready to install KubeBlocks."
14
+
15
+ # Install CSI Snapshotter CRDs
16
+ kubectl create -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v8.2.0/client/config/crd/snapshot.storage.k8s.io_volumesnapshotclasses.yaml
17
+ kubectl create -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v8.2.0/client/config/crd/snapshot.storage.k8s.io_volumesnapshots.yaml
18
+ kubectl create -f https://raw.githubusercontent.com/kubernetes-csi/external-snapshotter/v8.2.0/client/config/crd/snapshot.storage.k8s.io_volumesnapshotcontents.yaml
19
+
20
+ # Add and update Piraeus repository
21
+ helm repo add piraeus-charts https://piraeus.io/helm-charts/
22
+ helm repo update
23
+
24
+ # Install snapshot controller
25
+ helm install snapshot-controller piraeus-charts/snapshot-controller -n kb-system --create-namespace
26
+ kubectl wait --for=condition=ready pods -l app.kubernetes.io/name=snapshot-controller -n kb-system --timeout=60s
27
+ print_success "snapshot-controller installation complete!"
28
+
29
+ # Install KubeBlocks CRDs
30
+ kubectl create -f https://github.com/apecloud/kubeblocks/releases/download/v${KB_VERSION}/kubeblocks_crds.yaml
31
+
32
+ # Add and update KubeBlocks repository
33
+ helm repo add kubeblocks $HELM_REPO
34
+ helm repo update
35
+
36
+ # Install KubeBlocks
37
+ helm install kubeblocks kubeblocks/kubeblocks --namespace kb-system --create-namespace --version=${KB_VERSION}
38
+
39
+ # Verify installation
40
+ print "Waiting for KubeBlocks to be ready..."
41
+ kubectl wait --for=condition=ready pods -l app.kubernetes.io/instance=kubeblocks -n kb-system --timeout=120s
42
+ print_success "KubeBlocks installation complete!"
43
+ }
44
+
45
+ # Check if KubeBlocks is already installed
46
+ print "Checking if KubeBlocks is already installed in kb-system namespace..."
47
+ if kubectl get namespace kb-system &>/dev/null && kubectl get deployment kubeblocks -n kb-system &>/dev/null; then
48
+ print_success "KubeBlocks is already installed in kb-system namespace."
49
+ else
50
+ # Call the function to install KubeBlocks
51
+ install_kubeblocks
52
+ fi
LightRAG/k8s-deploy/databases/postgresql/values.yaml ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## description: service version.
2
+ ## default: 15.7.0
3
+ version: 16.4.0
4
+
5
+ ## mode postgresql cluster topology mode replication
6
+ mode: replication
7
+
8
+ ## description: The number of replicas, for standalone mode, the replicas is 1, for replication mode, the default replicas is 2.
9
+ ## default: 1
10
+ ## minimum: 1
11
+ ## maximum: 5
12
+ replicas: 2
13
+
14
+ ## description: CPU cores.
15
+ ## default: 0.5
16
+ ## minimum: 0.5
17
+ ## maximum: 64
18
+ cpu: 1
19
+
20
+ ## description: Memory, the unit is Gi.
21
+ ## default: 0.5
22
+ ## minimum: 0.5
23
+ ## maximum: 1000
24
+ memory: 1
25
+
26
+ ## description: Storage size, the unit is Gi.
27
+ ## default: 20
28
+ ## minimum: 1
29
+ ## maximum: 10000
30
+ storage: 5
31
+
32
+ ## terminationPolicy define Cluster termination policy. One of DoNotTerminate, Delete, WipeOut.
33
+ terminationPolicy: Delete
LightRAG/k8s-deploy/install_lightrag.sh ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ NAMESPACE=rag
4
+
5
+ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
6
+
7
+ if [ -z "$OPENAI_API_KEY" ]; then
8
+ echo "OPENAI_API_KEY environment variable is not set"
9
+ read -s -p "Enter your OpenAI API key: " OPENAI_API_KEY
10
+ if [ -z "$OPENAI_API_KEY" ]; then
11
+ echo "Error: OPENAI_API_KEY must be provided"
12
+ exit 1
13
+ fi
14
+ export OPENAI_API_KEY=$OPENAI_API_KEY
15
+ fi
16
+
17
+ if [ -z "$OPENAI_API_BASE" ]; then
18
+ echo "OPENAI_API_BASE environment variable is not set, will use default value"
19
+ read -p "Enter OpenAI API base URL (press Enter to skip if not needed): " OPENAI_API_BASE
20
+ export OPENAI_API_BASE=$OPENAI_API_BASE
21
+ fi
22
+
23
+ # Install KubeBlocks (if not already installed)
24
+ bash "$SCRIPT_DIR/databases/01-prepare.sh"
25
+
26
+ # Install database clusters
27
+ bash "$SCRIPT_DIR/databases/02-install-database.sh"
28
+
29
+ # Create vector extension in PostgreSQL if enabled
30
+ print "Waiting for PostgreSQL pods to be ready..."
31
+ if kubectl wait --for=condition=ready pods -l kubeblocks.io/role=primary,app.kubernetes.io/instance=pg-cluster -n $NAMESPACE --timeout=300s; then
32
+ print "Creating vector extension in PostgreSQL..."
33
+ kubectl exec -it $(kubectl get pods -l kubeblocks.io/role=primary,app.kubernetes.io/instance=pg-cluster -n $NAMESPACE -o name) -n $NAMESPACE -- psql -c "CREATE EXTENSION vector;"
34
+ print_success "Vector extension created successfully."
35
+ else
36
+ print "Warning: PostgreSQL pods not ready within timeout. Vector extension not created."
37
+ fi
38
+
39
+ # Get database passwords from Kubernetes secrets
40
+ echo "Retrieving database credentials from Kubernetes secrets..."
41
+ POSTGRES_PASSWORD=$(kubectl get secrets -n rag pg-cluster-postgresql-account-postgres -o jsonpath='{.data.password}' | base64 -d)
42
+ if [ -z "$POSTGRES_PASSWORD" ]; then
43
+ echo "Error: Could not retrieve PostgreSQL password. Make sure PostgreSQL is deployed and the secret exists."
44
+ exit 1
45
+ fi
46
+ export POSTGRES_PASSWORD=$POSTGRES_PASSWORD
47
+
48
+ NEO4J_PASSWORD=$(kubectl get secrets -n rag neo4j-cluster-neo4j-account-neo4j -o jsonpath='{.data.password}' | base64 -d)
49
+ if [ -z "$NEO4J_PASSWORD" ]; then
50
+ echo "Error: Could not retrieve Neo4J password. Make sure Neo4J is deployed and the secret exists."
51
+ exit 1
52
+ fi
53
+ export NEO4J_PASSWORD=$NEO4J_PASSWORD
54
+
55
+ #REDIS_PASSWORD=$(kubectl get secrets -n rag redis-cluster-redis-account-default -o jsonpath='{.data.password}' | base64 -d)
56
+ #if [ -z "$REDIS_PASSWORD" ]; then
57
+ # echo "Error: Could not retrieve Redis password. Make sure Redis is deployed and the secret exists."
58
+ # exit 1
59
+ #fi
60
+ #export REDIS_PASSWORD=$REDIS_PASSWORD
61
+
62
+ echo "Deploying production LightRAG (using external databases)..."
63
+
64
+ if ! kubectl get namespace rag &> /dev/null; then
65
+ echo "creating namespace 'rag'..."
66
+ kubectl create namespace rag
67
+ fi
68
+
69
+ helm upgrade --install lightrag $SCRIPT_DIR/lightrag \
70
+ --namespace $NAMESPACE \
71
+ --set-string env.POSTGRES_PASSWORD=$POSTGRES_PASSWORD \
72
+ --set-string env.NEO4J_PASSWORD=$NEO4J_PASSWORD \
73
+ --set-string env.LLM_BINDING=openai \
74
+ --set-string env.LLM_MODEL=gpt-4o-mini \
75
+ --set-string env.LLM_BINDING_HOST=$OPENAI_API_BASE \
76
+ --set-string env.LLM_BINDING_API_KEY=$OPENAI_API_KEY \
77
+ --set-string env.EMBEDDING_BINDING=openai \
78
+ --set-string env.EMBEDDING_MODEL=text-embedding-ada-002 \
79
+ --set-string env.EMBEDDING_DIM=1536 \
80
+ --set-string env.EMBEDDING_BINDING_API_KEY=$OPENAI_API_KEY
81
+ # --set-string env.REDIS_URI="redis://default:${REDIS_PASSWORD}@redis-cluster-redis-redis:6379"
82
+
83
+ # Wait for LightRAG pod to be ready
84
+ echo ""
85
+ echo "Waiting for lightrag pod to be ready..."
86
+ kubectl wait --for=condition=ready pod -l app.kubernetes.io/instance=lightrag --timeout=300s -n rag
87
+ echo "lightrag pod is ready"
88
+ echo ""
89
+ echo "Running Port-Forward:"
90
+ echo " kubectl --namespace rag port-forward svc/lightrag 9621:9621"
91
+ echo "==========================================="
92
+ echo ""
93
+ echo "✅ You can visit LightRAG at: http://localhost:9621"
94
+ echo ""
95
+ kubectl --namespace rag port-forward svc/lightrag 9621:9621
LightRAG/k8s-deploy/install_lightrag_dev.sh ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ NAMESPACE=rag
4
+
5
+ SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
6
+
7
+ check_dependencies(){
8
+ echo "Checking dependencies..."
9
+ command -v kubectl >/dev/null 2>&1 || { echo "Error: kubectl command not found"; exit 1; }
10
+ command -v helm >/dev/null 2>&1 || { echo "Error: helm command not found"; exit 1; }
11
+
12
+ # Check if Kubernetes is available
13
+ echo "Checking if Kubernetes is available..."
14
+ kubectl cluster-info &>/dev/null
15
+ if [ $? -ne 0 ]; then
16
+ echo "Error: Kubernetes cluster is not accessible. Please ensure you have proper access to a Kubernetes cluster."
17
+ exit 1
18
+ fi
19
+ echo "Kubernetes cluster is accessible."
20
+ }
21
+
22
+ check_dependencies
23
+
24
+ if [ -z "$OPENAI_API_KEY" ]; then
25
+ echo "OPENAI_API_KEY environment variable is not set"
26
+ read -s -p "Enter your OpenAI API key: " OPENAI_API_KEY
27
+ if [ -z "$OPENAI_API_KEY" ]; then
28
+ echo "Error: OPENAI_API_KEY must be provided"
29
+ exit 1
30
+ fi
31
+ export OPENAI_API_KEY=$OPENAI_API_KEY
32
+ fi
33
+
34
+ if [ -z "$OPENAI_API_BASE" ]; then
35
+ echo "OPENAI_API_BASE environment variable is not set, will use default value"
36
+ read -p "Enter OpenAI API base URL (press Enter to skip if not needed): " OPENAI_API_BASE
37
+ export OPENAI_API_BASE=$OPENAI_API_BASE
38
+ fi
39
+
40
+ required_env_vars=("OPENAI_API_BASE" "OPENAI_API_KEY")
41
+
42
+ for var in "${required_env_vars[@]}"; do
43
+ if [ -z "${!var}" ]; then
44
+ echo "Error: $var environment variable is not set"
45
+ exit 1
46
+ fi
47
+ done
48
+
49
+ if ! kubectl get namespace rag &> /dev/null; then
50
+ echo "creating namespace 'rag'..."
51
+ kubectl create namespace rag
52
+ fi
53
+
54
+ helm upgrade --install lightrag-dev $SCRIPT_DIR/lightrag \
55
+ --namespace rag \
56
+ --set-string env.LIGHTRAG_KV_STORAGE=JsonKVStorage \
57
+ --set-string env.LIGHTRAG_VECTOR_STORAGE=NanoVectorDBStorage \
58
+ --set-string env.LIGHTRAG_GRAPH_STORAGE=NetworkXStorage \
59
+ --set-string env.LIGHTRAG_DOC_STATUS_STORAGE=JsonDocStatusStorage \
60
+ --set-string env.LLM_BINDING=openai \
61
+ --set-string env.LLM_MODEL=gpt-4o-mini \
62
+ --set-string env.LLM_BINDING_HOST=$OPENAI_API_BASE \
63
+ --set-string env.LLM_BINDING_API_KEY=$OPENAI_API_KEY \
64
+ --set-string env.EMBEDDING_BINDING=openai \
65
+ --set-string env.EMBEDDING_MODEL=text-embedding-ada-002 \
66
+ --set-string env.EMBEDDING_DIM=1536 \
67
+ --set-string env.EMBEDDING_BINDING_API_KEY=$OPENAI_API_KEY
68
+
69
+ # Wait for LightRAG pod to be ready
70
+ echo ""
71
+ echo "Waiting for lightrag-dev pod to be ready..."
72
+ kubectl wait --for=condition=ready pod -l app.kubernetes.io/instance=lightrag-dev --timeout=300s -n rag
73
+ echo "lightrag-dev pod is ready"
74
+ echo ""
75
+ echo "Running Port-Forward:"
76
+ echo " kubectl --namespace rag port-forward svc/lightrag-dev 9621:9621"
77
+ echo "==========================================="
78
+ echo ""
79
+ echo "✅ You can visit LightRAG at: http://localhost:9621"
80
+ echo ""
81
+ kubectl --namespace rag port-forward svc/lightrag-dev 9621:9621
LightRAG/k8s-deploy/uninstall_lightrag.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ NAMESPACE=rag
4
+ helm uninstall lightrag --namespace $NAMESPACE
LightRAG/k8s-deploy/uninstall_lightrag_dev.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ NAMESPACE=rag
4
+ helm uninstall lightrag-dev --namespace $NAMESPACE
LightRAG/lightrag-api ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ source /home/netman/lightrag-xyj/venv/bin/activate
4
+ lightrag-server
LightRAG/lightrag.service.example ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [Unit]
2
+ Description=LightRAG XYJ Ollama Service
3
+ After=network.target
4
+
5
+ [Service]
6
+ Type=simple
7
+ User=netman
8
+ # Memory settings
9
+ MemoryHigh=8G
10
+ MemoryMax=12G
11
+ WorkingDirectory=/home/netman/lightrag-xyj
12
+ ExecStart=/home/netman/lightrag-xyj/lightrag-api
13
+ Restart=always
14
+ RestartSec=10
15
+
16
+ [Install]
17
+ WantedBy=multi-user.target
LightRAG/paging.md ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 文档列表页面分页显示功能改造方案
2
+
3
+ ## 一、改造目标
4
+
5
+ ### 问题现状
6
+ - 当前文档页面一次性加载所有文档,导致大量文档时界面加载慢
7
+ - 前端内存占用过大,用户操作体验差
8
+ - 状态过滤和排序都在前端进行,效率低下
9
+
10
+ ### 改造目标
11
+ - 实现后端分页查询,减少单次数据传输量
12
+ - 添加分页控制组件,支持翻页和跳转功能
13
+ - 允许用户设置每页显示行数(10-200条)
14
+ - 保持现有状态过滤和排序功能不变
15
+ - 提升大数据量场景下的性能表现
16
+
17
+ ## 二、总体架构设计
18
+
19
+ ### 设计原则
20
+ 1. **统一分页接口**:后端提供统一的分页API,支持状态过滤和排序
21
+ 2. **智能刷新策略**:根据处理状态选择合适的刷新频率和范围
22
+ 3. **即时用户反馈**:状态切换、分页操作提供立即响应
23
+ 4. **向后兼容**:保持现有功能完整性,不影响现有操作流程
24
+ 5. **性能优化**:减少内存占用,优化网络请求
25
+
26
+ ### 技术方案
27
+ - **后端**:在现有存储层基础上添加分页查询接口
28
+ - **前端**:改造DocumentManager组件,添加分页控制
29
+ - **数据流**:统一分页查询 + 独立状态计数查询
30
+
31
+ ## 三、后端改造步骤
32
+
33
+ ### 步骤1:存储层接口扩展
34
+
35
+ **改动文件**:`lightrag/kg/base.py`
36
+
37
+ **关键思路**:
38
+ - 在BaseDocStatusStorage抽象类中添加分页查询方法
39
+ - 设计统一的分页接口,支持状态过滤、排序、分页参数
40
+ - 返回文档列表和总数量的元组
41
+
42
+ **接口设计要点**:
43
+ ```
44
+ get_docs_paginated(status_filter, page, page_size, sort_field, sort_direction) -> (documents, total_count)
45
+ count_by_status(status) -> int
46
+ get_all_status_counts() -> Dict[str, int]
47
+ ```
48
+
49
+ ### 步骤2:各存储后端实现
50
+
51
+ **改动文件**:
52
+ - `lightrag/kg/postgres_impl.py`
53
+ - `lightrag/kg/mongo_impl.py`
54
+ - `lightrag/kg/redis_impl.py`
55
+ - `lightrag/kg/json_doc_status_impl.py`
56
+
57
+ **PostgreSQL实现要点**:
58
+ - 使用LIMIT和OFFSET实现分页
59
+ - 构建动态WHERE条件支持状态过滤
60
+ - 使用COUNT查询获取总数量
61
+ - 添加合适的数据库索引优化查询性能
62
+
63
+ **MongoDB实现要点**:
64
+ - 使用skip()和limit()实现分页
65
+ - 使用聚合管道进行状态统计
66
+ - 优化查询条件和索引
67
+
68
+ **Redis 与 Json实现要点:**
69
+
70
+ * 考虑先用简单的方式实现,即把所有文件清单读到内存中后进行过滤和排序
71
+
72
+ **关键考虑**:
73
+
74
+ - 确保各存储后端的分页逻辑一致性
75
+ - 处理边界情况(空结果、超出页码范围等)
76
+ - 优化查询性能,避免全表扫描
77
+
78
+ ### 步骤3:API路由层改造
79
+
80
+ **改动文件**:`lightrag/api/routers/document_routes.py`
81
+
82
+ **新增接口**:
83
+ 1. `POST /documents/paginated` - 分页查询文档
84
+ 2. `GET /documents/status_counts` - 获取状态计数
85
+
86
+ **数据模型设计**:
87
+ - DocumentsRequest:分页请求参数
88
+ - PaginatedDocsResponse:分页响应数据
89
+ - PaginationInfo:分页元信息
90
+
91
+ **关键逻辑**:
92
+ - 参数验证(页码范围、页面大小限制)
93
+ - 并行查询分页数据和状态计数
94
+ - 错误处理和异常响应
95
+
96
+ ### 步骤4:数据库优化
97
+
98
+ **索引策略**:
99
+ - 为workspace + status + updated_at创建复合索引
100
+ - 为workspace + status + created_at创建复合索引
101
+ - 为workspace + updated_at创建索引
102
+ - 为workspace + created_at创建索引
103
+
104
+ **性能考虑**:
105
+ - 避免深度分页的性能问题
106
+ - 考虑添加缓存层优化状态计数查询
107
+ - 监控查询性能,必要时调整索引策略
108
+
109
+ ## 四、前端改造步骤
110
+
111
+ ### 步骤1:API客户端扩展
112
+
113
+ **改动文件**:`lightrag_webui/src/api/lightrag.ts`
114
+
115
+ **新增函数**:
116
+ - `getDocumentsPaginated()` - 分页查询文档
117
+ - `getDocumentStatusCounts()` - 获取状态计数
118
+
119
+ **类型定义**:
120
+ - 定义分页请求和响应的TypeScript类型
121
+ - 确保类型安全和代码提示
122
+
123
+ ### 步骤2:分页控制组件开发
124
+
125
+ **新增文件**:`lightrag_webui/src/components/ui/PaginationControls.tsx`
126
+
127
+ **组件功能**:
128
+ - 支持紧凑模式和完整模式
129
+ - 页码输入和跳转功能
130
+ - 每页显示数量选择(10-200)
131
+ - 总数信息显示
132
+ - 禁用状态处理
133
+
134
+ **设计要点**:
135
+ - 响应式设计,适配不同屏幕尺寸
136
+ - 防抖处理,避免频繁请求
137
+ - 错误处理和状态回滚
138
+ - 组件摆放位置:目前状态按钮上方,与scan按钮同一层,居中摆放
139
+
140
+ ### 步骤3:状态过滤按钮优化
141
+
142
+ **改动文件**:现有状态过滤相关组件
143
+
144
+ **优化要点**:
145
+
146
+ - 添加加载状态指示
147
+ - 数据不足时的智能提示
148
+ - 定期刷新数据,状态切换时如果最先的状态数据距离上次刷新数据超过5秒应即时刷新数据
149
+ - 防止重复点击和并发请求
150
+
151
+ ### 步骤4:主组件DocumentManager改造
152
+
153
+ **改动文件**:`lightrag_webui/src/features/DocumentManager.tsx`
154
+
155
+ **核心改动**:
156
+
157
+ **状态管理重构**:
158
+ - 将docs状态改为currentPageDocs(仅存储当前页数据)
159
+ - 添加pagination状态管理分页信息
160
+ - 添加statusCounts状态独立管理状态计数
161
+ - 添加加载状态管理(isStatusChanging, isRefreshing)
162
+
163
+ **数据获取策略**:
164
+ - 实现智能刷新:活跃期完整刷新,稳定期轻量刷新
165
+ - 状态切换时立即刷新数据
166
+ - 分页操作时立即更新数据
167
+ - 定期刷新与手动操作协调
168
+
169
+ **布局调整**:
170
+ - 将分页控制组件放置在顶部操作栏中间位置
171
+ - 保持状态过滤按钮在表格上方
172
+ - 确保响应式布局适配
173
+
174
+ **事件处理优化**:
175
+ - 状态切换时,如果当前页码数据不足,则重置到第一页
176
+ - 页面大小变更时智能计算新页码
177
+ - 错误时状态回滚机制
178
+
179
+ ## 五、用户体验优化
180
+
181
+ ### 即时反馈机制
182
+ - 状态切换时显示加载动画
183
+ - 分页操作时提供视觉反馈
184
+ - 数据不足时智能提示用户
185
+
186
+ ### 错误处理策略
187
+ - 网络错误时自动重试
188
+ - 操作失败时状态回滚
189
+ - 友好的错误提示信息
190
+
191
+ ### 性能优化措施
192
+ - 防抖处理频繁操作
193
+ - 智能刷新策略减少不必要请求
194
+ - 组件卸载时清理定时器和请求
195
+
196
+ ## 六、兼容性保障
197
+
198
+ ### 向后兼容
199
+ - 保留原有的/documents接口作为备用
200
+ - 现有功能(排序、过滤、选择)保持不变
201
+ - 渐进式升级,支持配置开关
202
+
203
+ ### 数据一致性
204
+ - 确保分页数据与状态计数同步
205
+ - 处理并发更新的数据一致性问题
206
+ - 定期刷新保持数据最新
207
+
208
+ ## 七、测试策略
209
+
210
+ ### 功能测试
211
+ - 各种分页场景测试
212
+ - 状态过滤组合测试
213
+ - 排序功能验证
214
+ - 边界条件测试
215
+
216
+ ### 性能测试
217
+ - 大数据量场景测试
218
+ - 并发访问压力测试
219
+ - 内存使用情况监控
220
+ - 响应时间测试
221
+
222
+ ### 兼容性测试
223
+ - 不同存储后端测试
224
+ - 不同浏览器兼容性
225
+ - 移动端响应式测试
226
+
227
+ ## 八、关键实现细节
228
+
229
+ ### 后端分页查询设计
230
+ - **统一接口**:所有存储后端实现相同的分页接口签名
231
+ - **参数验证**:严格验证页码、页面大小、排序参数的合法性
232
+ - **性能优化**:使用数据库原生分页功能,避免应用层分页
233
+ - **错误处理**:统一的错误响应格式和异常处理机制
234
+
235
+ ### 前端状态管理策略
236
+ - **数据分离**:当前页数据与状态计数分别管理
237
+ - **智能刷新**:根据文档处理状态选择刷新策略
238
+ - **状态同步**:确保UI状态与后端数据保持一致
239
+ - **错误恢复**:操作失败时自动回滚到之前状态
240
+
241
+ ### 分页控制组件设计
242
+ - **紧凑布局**:适配顶部操作栏的空间限制
243
+ - **响应式设计**:在不同屏幕尺寸下自适应布局
244
+ - **交互优化**:防抖处理、加载状态、禁用状态管理
245
+ - **可访问性**:支持键盘导航和屏幕阅读器
246
+
247
+ ### 数据库索引优化
248
+ - **复合索引**:workspace + status + sort_field的组合索引
249
+ - **覆盖索引**:尽可能使用覆盖索引减少回表查询
250
+ - **索引监控**:定期监控索引使用情况和查询性能
251
+ - **渐进优化**:根据实际使用情况调整索引策略
LightRAG/pyproject.toml ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=64", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lightrag-hku"
7
+ dynamic = ["version"]
8
+ authors = [
9
+ {name = "Zirui Guo"}
10
+ ]
11
+ description = "LightRAG: Simple and Fast Retrieval-Augmented Generation"
12
+ readme = "README.md"
13
+ license = {text = "MIT"}
14
+ requires-python = ">=3.10"
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Programming Language :: Python :: 3",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: OS Independent",
20
+ "Intended Audience :: Developers",
21
+ "Topic :: Software Development :: Libraries :: Python Modules",
22
+ ]
23
+ dependencies = [
24
+ "aiohttp",
25
+ "configparser",
26
+ "dotenv",
27
+ "future",
28
+ "json_repair",
29
+ "nano-vectordb",
30
+ "networkx",
31
+ "numpy",
32
+ "pandas>=2.0.0",
33
+ "pipmaster",
34
+ "pydantic",
35
+ "pypinyin",
36
+ "python-dotenv",
37
+ "setuptools",
38
+ "tenacity",
39
+ "tiktoken",
40
+ "xlsxwriter>=3.1.0",
41
+ ]
42
+
43
+ [project.optional-dependencies]
44
+ api = [
45
+ # Core dependencies
46
+ "aiohttp",
47
+ "configparser",
48
+ "dotenv",
49
+ "future",
50
+ "json_repair",
51
+ "nano-vectordb",
52
+ "networkx",
53
+ "numpy",
54
+ "openai",
55
+ "pandas>=2.0.0",
56
+ "pipmaster",
57
+ "pydantic",
58
+ "pypinyin",
59
+ "python-dotenv",
60
+ "setuptools",
61
+ "tenacity",
62
+ "tiktoken",
63
+ "xlsxwriter>=3.1.0",
64
+ # API-specific dependencies
65
+ "aiofiles",
66
+ "ascii_colors",
67
+ "asyncpg",
68
+ "distro",
69
+ "fastapi",
70
+ "httpcore",
71
+ "httpx",
72
+ "jiter",
73
+ "passlib[bcrypt]",
74
+ "psutil",
75
+ "PyJWT",
76
+ "python-jose[cryptography]",
77
+ "python-multipart",
78
+ "pytz",
79
+ "uvicorn",
80
+ ]
81
+
82
+ [project.scripts]
83
+ lightrag-server = "lightrag.api.lightrag_server:main"
84
+ lightrag-gunicorn = "lightrag.api.run_with_gunicorn:main"
85
+
86
+ [project.urls]
87
+ Homepage = "https://github.com/HKUDS/LightRAG"
88
+ Documentation = "https://github.com/HKUDS/LightRAG"
89
+ Repository = "https://github.com/HKUDS/LightRAG"
90
+ "Bug Tracker" = "https://github.com/HKUDS/LightRAG/issues"
91
+
92
+ [tool.setuptools.packages.find]
93
+ include = ["lightrag*"]
94
+
95
+ [tool.setuptools]
96
+ include-package-data = true
97
+
98
+ [tool.setuptools.dynamic]
99
+ version = {attr = "lightrag.__version__"}
100
+
101
+ [tool.setuptools.package-data]
102
+ lightrag = ["api/webui/**/*"]
103
+
104
+ [tool.ruff]
105
+ target-version = "py310"
LightRAG/setup.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Minimal setup.py for backward compatibility
2
+ # Primary configuration is now in pyproject.toml
3
+
4
+ from setuptools import setup
5
+
6
+ setup()
LightRAG/stgong.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Hello!
2
+ I am a 24-year-old boy.
3
+ I am persuing my PHD in DLUT.
gpt_bu2/qa_per_neg_batch/不二_neg.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
gpt_bu2/qa_per_neg_batch/加罗_neg.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
gpt_bu2/qa_per_role_gpt4o_cot/加罗.json ADDED
The diff for this file is too large to render. See raw diff