post-graph-rag 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- post_graph_rag-0.1.0/.github/workflows/publish.yml +65 -0
- post_graph_rag-0.1.0/.gitignore +222 -0
- post_graph_rag-0.1.0/LICENSE +21 -0
- post_graph_rag-0.1.0/PKG-INFO +245 -0
- post_graph_rag-0.1.0/README.md +229 -0
- post_graph_rag-0.1.0/demo_rag.py +101 -0
- post_graph_rag-0.1.0/post_graph_rag/__init__.py +21 -0
- post_graph_rag-0.1.0/post_graph_rag/config.py +13 -0
- post_graph_rag-0.1.0/post_graph_rag/engine.py +184 -0
- post_graph_rag-0.1.0/post_graph_rag/extractor.py +102 -0
- post_graph_rag-0.1.0/post_graph_rag/graph_store.py +128 -0
- post_graph_rag-0.1.0/post_graph_rag/llm.py +65 -0
- post_graph_rag-0.1.0/post_graph_rag/models.py +41 -0
- post_graph_rag-0.1.0/pyproject.toml +24 -0
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
name: Publish to PyPI
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
tags:
|
|
6
|
+
- "v[0-9]+.[0-9]+.[0-9]+*"
|
|
7
|
+
- "v*"
|
|
8
|
+
|
|
9
|
+
jobs:
|
|
10
|
+
publish:
|
|
11
|
+
name: Build & Publish post-graph-rag to PyPI
|
|
12
|
+
runs-on: ubuntu-latest
|
|
13
|
+
permissions:
|
|
14
|
+
id-token: write # Required for PyPI Trusted Publisher OIDC
|
|
15
|
+
contents: write
|
|
16
|
+
|
|
17
|
+
steps:
|
|
18
|
+
- name: Checkout repository
|
|
19
|
+
uses: actions/checkout@v4
|
|
20
|
+
|
|
21
|
+
- name: Set up Python
|
|
22
|
+
uses: actions/setup-python@v5
|
|
23
|
+
with:
|
|
24
|
+
python-version: "3.11"
|
|
25
|
+
|
|
26
|
+
- name: Update module and package version from git tag
|
|
27
|
+
run: |
|
|
28
|
+
# Extract version (e.g. v1.2.3 -> 1.2.3)
|
|
29
|
+
TAG_NAME="${GITHUB_REF#refs/tags/}"
|
|
30
|
+
export VERSION="${TAG_NAME#v}"
|
|
31
|
+
echo "Release version: $VERSION"
|
|
32
|
+
|
|
33
|
+
# Update version in pyproject.toml and post_graph_rag/__init__.py
|
|
34
|
+
python -c "
|
|
35
|
+
import os, re
|
|
36
|
+
ver = os.environ['VERSION']
|
|
37
|
+
|
|
38
|
+
with open('pyproject.toml', 'r') as f:
|
|
39
|
+
content = f.read()
|
|
40
|
+
updated = re.sub(r'version\s*=\s*\"[^\"]+\"', 'version = \"' + ver + '\"', content, count=1)
|
|
41
|
+
with open('pyproject.toml', 'w') as f:
|
|
42
|
+
f.write(updated)
|
|
43
|
+
|
|
44
|
+
with open('post_graph_rag/__init__.py', 'r') as f:
|
|
45
|
+
content = f.read()
|
|
46
|
+
updated = re.sub(r'__version__\s*=\s*\"[^\"]+\"', '__version__ = \"' + ver + '\"', content, count=1)
|
|
47
|
+
with open('post_graph_rag/__init__.py', 'w') as f:
|
|
48
|
+
f.write(updated)
|
|
49
|
+
"
|
|
50
|
+
|
|
51
|
+
echo "Updated pyproject.toml and post_graph_rag/__init__.py to version ${VERSION}"
|
|
52
|
+
|
|
53
|
+
- name: Install uv
|
|
54
|
+
uses: astral-sh/setup-uv@v3
|
|
55
|
+
with:
|
|
56
|
+
enable-cache: false
|
|
57
|
+
|
|
58
|
+
- name: Build package artifacts
|
|
59
|
+
run: uv build
|
|
60
|
+
|
|
61
|
+
- name: Publish to PyPI
|
|
62
|
+
uses: pypa/gh-action-pypi-publish@release/v1
|
|
63
|
+
with:
|
|
64
|
+
password: ${{ secrets.PYPI_API_TOKEN }}
|
|
65
|
+
skip-existing: true
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
# Secrets and keys
|
|
2
|
+
**/*secret*
|
|
3
|
+
**/*key*
|
|
4
|
+
|
|
5
|
+
# Byte-compiled / optimized / DLL files
|
|
6
|
+
__pycache__/
|
|
7
|
+
*.py[codz]
|
|
8
|
+
*$py.class
|
|
9
|
+
|
|
10
|
+
# C extensions
|
|
11
|
+
*.so
|
|
12
|
+
|
|
13
|
+
# Distribution / packaging
|
|
14
|
+
.Python
|
|
15
|
+
build/
|
|
16
|
+
develop-eggs/
|
|
17
|
+
dist/
|
|
18
|
+
downloads/
|
|
19
|
+
eggs/
|
|
20
|
+
.eggs/
|
|
21
|
+
lib/
|
|
22
|
+
lib64/
|
|
23
|
+
parts/
|
|
24
|
+
sdist/
|
|
25
|
+
var/
|
|
26
|
+
wheels/
|
|
27
|
+
share/python-wheels/
|
|
28
|
+
*.egg-info/
|
|
29
|
+
.installed.cfg
|
|
30
|
+
*.egg
|
|
31
|
+
MANIFEST
|
|
32
|
+
|
|
33
|
+
# PyInstaller
|
|
34
|
+
# Usually these files are written by a python script from a template
|
|
35
|
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
|
36
|
+
*.manifest
|
|
37
|
+
*.spec
|
|
38
|
+
|
|
39
|
+
# Installer logs
|
|
40
|
+
pip-log.txt
|
|
41
|
+
pip-delete-this-directory.txt
|
|
42
|
+
|
|
43
|
+
# Unit test / coverage reports
|
|
44
|
+
htmlcov/
|
|
45
|
+
.tox/
|
|
46
|
+
.nox/
|
|
47
|
+
.coverage
|
|
48
|
+
.coverage.*
|
|
49
|
+
.cache
|
|
50
|
+
nosetests.xml
|
|
51
|
+
coverage.xml
|
|
52
|
+
*.cover
|
|
53
|
+
*.py.cover
|
|
54
|
+
.hypothesis/
|
|
55
|
+
.pytest_cache/
|
|
56
|
+
cover/
|
|
57
|
+
|
|
58
|
+
# Translations
|
|
59
|
+
*.mo
|
|
60
|
+
*.pot
|
|
61
|
+
|
|
62
|
+
# Django stuff:
|
|
63
|
+
*.log
|
|
64
|
+
local_settings.py
|
|
65
|
+
db.sqlite3
|
|
66
|
+
db.sqlite3-journal
|
|
67
|
+
|
|
68
|
+
# Flask stuff:
|
|
69
|
+
instance/
|
|
70
|
+
.webassets-cache
|
|
71
|
+
|
|
72
|
+
# Scrapy stuff:
|
|
73
|
+
.scrapy
|
|
74
|
+
|
|
75
|
+
# Sphinx documentation
|
|
76
|
+
docs/_build/
|
|
77
|
+
|
|
78
|
+
# PyBuilder
|
|
79
|
+
.pybuilder/
|
|
80
|
+
target/
|
|
81
|
+
|
|
82
|
+
# Jupyter Notebook
|
|
83
|
+
.ipynb_checkpoints
|
|
84
|
+
|
|
85
|
+
# IPython
|
|
86
|
+
profile_default/
|
|
87
|
+
ipython_config.py
|
|
88
|
+
|
|
89
|
+
# pyenv
|
|
90
|
+
# For a library or package, you might want to ignore these files since the code is
|
|
91
|
+
# intended to run in multiple environments; otherwise, check them in:
|
|
92
|
+
# .python-version
|
|
93
|
+
|
|
94
|
+
# pipenv
|
|
95
|
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
|
96
|
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
|
97
|
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
|
98
|
+
# install all needed dependencies.
|
|
99
|
+
# Pipfile.lock
|
|
100
|
+
|
|
101
|
+
# UV
|
|
102
|
+
# Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control.
|
|
103
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
104
|
+
# commonly ignored for libraries.
|
|
105
|
+
# uv.lock
|
|
106
|
+
|
|
107
|
+
# poetry
|
|
108
|
+
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
|
109
|
+
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
|
110
|
+
# commonly ignored for libraries.
|
|
111
|
+
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
|
112
|
+
# poetry.lock
|
|
113
|
+
# poetry.toml
|
|
114
|
+
|
|
115
|
+
# pdm
|
|
116
|
+
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
|
117
|
+
# pdm recommends including project-wide configuration in pdm.toml, but excluding .pdm-python.
|
|
118
|
+
# https://pdm-project.org/en/latest/usage/project/#working-with-version-control
|
|
119
|
+
# pdm.lock
|
|
120
|
+
# pdm.toml
|
|
121
|
+
.pdm-python
|
|
122
|
+
.pdm-build/
|
|
123
|
+
|
|
124
|
+
# pixi
|
|
125
|
+
# Similar to Pipfile.lock, it is generally recommended to include pixi.lock in version control.
|
|
126
|
+
# pixi.lock
|
|
127
|
+
# Pixi creates a virtual environment in the .pixi directory, just like venv module creates one
|
|
128
|
+
# in the .venv directory. It is recommended not to include this directory in version control.
|
|
129
|
+
.pixi
|
|
130
|
+
|
|
131
|
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
|
132
|
+
__pypackages__/
|
|
133
|
+
|
|
134
|
+
# Celery stuff
|
|
135
|
+
celerybeat-schedule
|
|
136
|
+
celerybeat.pid
|
|
137
|
+
|
|
138
|
+
# Redis
|
|
139
|
+
*.rdb
|
|
140
|
+
*.aof
|
|
141
|
+
*.pid
|
|
142
|
+
|
|
143
|
+
# RabbitMQ
|
|
144
|
+
mnesia/
|
|
145
|
+
rabbitmq/
|
|
146
|
+
rabbitmq-data/
|
|
147
|
+
|
|
148
|
+
# ActiveMQ
|
|
149
|
+
activemq-data/
|
|
150
|
+
|
|
151
|
+
# SageMath parsed files
|
|
152
|
+
*.sage.py
|
|
153
|
+
|
|
154
|
+
# Environments
|
|
155
|
+
.env
|
|
156
|
+
.envrc
|
|
157
|
+
.venv
|
|
158
|
+
env/
|
|
159
|
+
venv/
|
|
160
|
+
ENV/
|
|
161
|
+
env.bak/
|
|
162
|
+
venv.bak/
|
|
163
|
+
|
|
164
|
+
# Spyder project settings
|
|
165
|
+
.spyderproject
|
|
166
|
+
.spyproject
|
|
167
|
+
|
|
168
|
+
# Rope project settings
|
|
169
|
+
.ropeproject
|
|
170
|
+
|
|
171
|
+
# mkdocs documentation
|
|
172
|
+
/site
|
|
173
|
+
|
|
174
|
+
# mypy
|
|
175
|
+
.mypy_cache/
|
|
176
|
+
.dmypy.json
|
|
177
|
+
dmypy.json
|
|
178
|
+
|
|
179
|
+
# Pyre type checker
|
|
180
|
+
.pyre/
|
|
181
|
+
|
|
182
|
+
# pytype static type analyzer
|
|
183
|
+
.pytype/
|
|
184
|
+
|
|
185
|
+
# Cython debug symbols
|
|
186
|
+
cython_debug/
|
|
187
|
+
|
|
188
|
+
# PyCharm
|
|
189
|
+
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
190
|
+
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
191
|
+
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
192
|
+
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
193
|
+
# .idea/
|
|
194
|
+
|
|
195
|
+
# Abstra
|
|
196
|
+
# Abstra is an AI-powered process automation framework.
|
|
197
|
+
# Ignore directories containing user credentials, local state, and settings.
|
|
198
|
+
# Learn more at https://abstra.io/docs
|
|
199
|
+
.abstra/
|
|
200
|
+
|
|
201
|
+
# Visual Studio Code
|
|
202
|
+
# Visual Studio Code specific template is maintained in a separate VisualStudioCode.gitignore
|
|
203
|
+
# that can be found at https://github.com/github/gitignore/blob/main/Global/VisualStudioCode.gitignore
|
|
204
|
+
# and can be added to the global gitignore or merged into this file. However, if you prefer,
|
|
205
|
+
# you could uncomment the following to ignore the entire vscode folder
|
|
206
|
+
# .vscode/
|
|
207
|
+
# Temporary file for partial code execution
|
|
208
|
+
tempCodeRunnerFile.py
|
|
209
|
+
|
|
210
|
+
# Ruff stuff:
|
|
211
|
+
.ruff_cache/
|
|
212
|
+
|
|
213
|
+
# PyPI configuration file
|
|
214
|
+
.pypirc
|
|
215
|
+
|
|
216
|
+
# Marimo
|
|
217
|
+
marimo/_static/
|
|
218
|
+
marimo/_lsp/
|
|
219
|
+
__marimo__/
|
|
220
|
+
|
|
221
|
+
# Streamlit
|
|
222
|
+
.streamlit/secrets.toml
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Chandan Rajah
|
|
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.
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: post-graph-rag
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Graph RAG library leveraging post-graph and pgvector on PostgreSQL with OpenAI-compatible LLMs.
|
|
5
|
+
Project-URL: Homepage, https://github.com/crajah/post-graph-rag
|
|
6
|
+
Project-URL: Repository, https://github.com/crajah/post-graph-rag
|
|
7
|
+
Author-email: Chandan Rajah <chandan.rajah@gmail.com>
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: graph-rag,knowledge-graph,llm,openai,pgvector,post-graph,rag
|
|
11
|
+
Requires-Python: >=3.9
|
|
12
|
+
Requires-Dist: openai>=1.0.0
|
|
13
|
+
Requires-Dist: post-graph>=0.1.4
|
|
14
|
+
Requires-Dist: pydantic>=2.0.0
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# post-graph-rag
|
|
18
|
+
|
|
19
|
+
[](https://pypi.org/project/post-graph-rag/)
|
|
20
|
+
[](https://opensource.org/licenses/MIT)
|
|
21
|
+
[](https://www.python.org/downloads/)
|
|
22
|
+
|
|
23
|
+
**Production-Grade, High-Performance Knowledge Graph RAG Engine Native to PostgreSQL.**
|
|
24
|
+
|
|
25
|
+
`post-graph-rag` seamlessly combines **automated LLM-based entity & triple extraction**, **vector similarity search via `pgvector`**, and **graph relationship traversal** directly on PostgreSQL using the [`post-graph`](https://pypi.org/project/post-graph/) graph database library.
|
|
26
|
+
|
|
27
|
+
It connects to **any OpenAI-compatible API** (LiteLLM, vLLM, Ollama, DeepSeek, OpenAI) for zero-shot domain-agnostic knowledge extraction, structured document metadata tracking, and context-aware answer synthesis.
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## 🌟 Why `post-graph-rag`?
|
|
32
|
+
|
|
33
|
+
Traditional Vector RAG systems suffer from **"chunk isolation"**—they retrieve isolated text passages based purely on semantic similarity, missing higher-level relationships and cross-document entity connections.
|
|
34
|
+
|
|
35
|
+
`post-graph-rag` solves this by building a **dual representation** inside PostgreSQL:
|
|
36
|
+
1. **Unstructured Vector Passages**: Full document chunks indexed with `pgvector` HNSW embeddings.
|
|
37
|
+
2. **Knowledge Graph Triples**: Extracted Subject-Predicate-Object entities connected by graph edges.
|
|
38
|
+
3. **Structured Document Metadata**: Rich metadata tracking (`source`, `category`, `collection`, `document`, `page`, `paragraph`).
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
## 🏗️ Architecture Workflow
|
|
43
|
+
|
|
44
|
+
```mermaid
|
|
45
|
+
graph TD
|
|
46
|
+
subgraph INDEXING ["1. Knowledge Graph & Vector Indexing"]
|
|
47
|
+
A[Document Text + Metadata] --> B[Embedding Service]
|
|
48
|
+
A --> C[LLM GraphExtractor]
|
|
49
|
+
|
|
50
|
+
B -->|Vectors| D[post-graph Store]
|
|
51
|
+
C -->|Entities & Triples| D
|
|
52
|
+
|
|
53
|
+
D --> E[(PostgreSQL + pgvector)]
|
|
54
|
+
E -->|Tables| E1[documents]
|
|
55
|
+
E -->|Tables| E2[entities]
|
|
56
|
+
E -->|Edges| E3[relations]
|
|
57
|
+
E -->|Edges| E4[doc_mentions]
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
subgraph RETRIEVAL ["2. Hybrid Retrieval & Synthesis"]
|
|
61
|
+
Q[User Question] --> R[GraphRAG Query Engine]
|
|
62
|
+
R -->|Embedding| S[pgvector Similarity Search]
|
|
63
|
+
E1 & E2 -->|Top-K Passages & Entities| S
|
|
64
|
+
S --> T[1-Hop Graph Relationship Traversal]
|
|
65
|
+
E3 -->|Subject-Predicate-Object| T
|
|
66
|
+
|
|
67
|
+
S & T --> U[LLM Answer Synthesis]
|
|
68
|
+
U --> V[Final Answer + Citations + Graph Triples]
|
|
69
|
+
end
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## 📦 Installation
|
|
75
|
+
|
|
76
|
+
Install `post-graph-rag` via `pip` or `uv`:
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
pip install post-graph-rag
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Or using `uv`:
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
uv add post-graph-rag
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
### PostgreSQL Requirements
|
|
89
|
+
Ensure PostgreSQL is running with the `pgvector` extension installed:
|
|
90
|
+
|
|
91
|
+
```sql
|
|
92
|
+
CREATE EXTENSION IF NOT EXISTS vector;
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## 🚀 Quick Start
|
|
98
|
+
|
|
99
|
+
### 1. Basic Indexing & Querying
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
import asyncio
|
|
103
|
+
from post_graph_rag import GraphRAG, RAGConfig, DocumentMetadata
|
|
104
|
+
|
|
105
|
+
async def main():
|
|
106
|
+
# 1. Configure GraphRAG engine
|
|
107
|
+
config = RAGConfig(
|
|
108
|
+
api_base="http://localhost:4000/v1", # OpenAI-compatible router endpoint
|
|
109
|
+
api_key="BEVZ-6L81-OZ8Y", # Master or OpenAI API Key
|
|
110
|
+
model="DeepSeek-V3.2", # LLM model for extraction & synthesis
|
|
111
|
+
embedding_model="text-embedding-3-small", # Embedding model
|
|
112
|
+
embedding_dim=1536, # Vector dimensionality
|
|
113
|
+
db_uri="postgresql://user:password@localhost:5432/postgres",
|
|
114
|
+
realm="enterprise_kb"
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
rag = GraphRAG(config)
|
|
118
|
+
|
|
119
|
+
# 2. Connect & initialize PostgreSQL graph schema
|
|
120
|
+
await rag.initialize()
|
|
121
|
+
|
|
122
|
+
# 3. Index unstructured documents
|
|
123
|
+
doc_text = (
|
|
124
|
+
"Zeus is the king of the Olympian gods, ruling sky and thunder from Mount Olympus. "
|
|
125
|
+
"He is the son of Cronus and Rhea, and married to Hera. "
|
|
126
|
+
"Zeus defeated the Titans in the Titanomachy to establish his rule."
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
result = await rag.index_document(doc_text, metadata={"source": "greek_mythology.txt"})
|
|
130
|
+
print(f"Indexed document {result['document_id']}: Extracted {result['entities_extracted']} entities.")
|
|
131
|
+
|
|
132
|
+
# 4. Perform Hybrid RAG Query
|
|
133
|
+
response = await rag.query("Who are the parents of Zeus and what did he defeat?")
|
|
134
|
+
|
|
135
|
+
print("\n=== SYNTHESIZED ANSWER ===")
|
|
136
|
+
print(response["answer"])
|
|
137
|
+
|
|
138
|
+
print("\n=== RETRIEVED GRAPH TRIPLES ===")
|
|
139
|
+
for triple in response["retrieved_graph_triples"]:
|
|
140
|
+
print(f" - {triple}")
|
|
141
|
+
|
|
142
|
+
# 5. Clean up
|
|
143
|
+
await rag.close()
|
|
144
|
+
|
|
145
|
+
if __name__ == "__main__":
|
|
146
|
+
asyncio.run(main())
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## 📋 Document Metadata (`DocumentMetadata`)
|
|
152
|
+
|
|
153
|
+
`post-graph-rag` includes structured document metadata tracking via the `DocumentMetadata` model:
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from post_graph_rag import DocumentMetadata
|
|
157
|
+
|
|
158
|
+
metadata = DocumentMetadata(
|
|
159
|
+
source="https://mythology.org/zeus.html", # Document origin (URL, filepath, API)
|
|
160
|
+
category="greek_mythology", # Document category/topic
|
|
161
|
+
collection="olympian_deities", # Collection namespace
|
|
162
|
+
document="zeus_overview.pdf", # Title or filename
|
|
163
|
+
page=1, # 1-based page number
|
|
164
|
+
paragraph=2, # 1-based paragraph index
|
|
165
|
+
extra={"author": "Homer", "year": -700} # Custom metadata key-value pairs
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
await rag.index_document(chunk_text, metadata=metadata)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
### Design Rationale: Optional vs. Required
|
|
172
|
+
- **All metadata fields are optional** with default `None`. This allows seamless indexing of raw strings, short code snippets, webhooks, or unformatted text, while offering rich structural provenance tracking when indexing multi-page PDFs or categorized enterprise documents.
|
|
173
|
+
|
|
174
|
+
---
|
|
175
|
+
|
|
176
|
+
## ⚙️ Configuration Reference (`RAGConfig`)
|
|
177
|
+
|
|
178
|
+
`RAGConfig` can be configured explicitly or automatically loaded from environment variables:
|
|
179
|
+
|
|
180
|
+
| Option | Environment Variable | Default Value | Description |
|
|
181
|
+
| :--- | :--- | :--- | :--- |
|
|
182
|
+
| `api_base` | `OPENAI_API_BASE` | `http://localhost:4000/v1` | Base URL for OpenAI-compatible LLM endpoint |
|
|
183
|
+
| `api_key` | `OPENAI_API_KEY` | `BEVZ-6L81-OZ8Y` | API Key for authorization |
|
|
184
|
+
| `model` | `RAG_MODEL` | `DeepSeek-V3.2` | Primary LLM model for triple extraction & synthesis |
|
|
185
|
+
| `embedding_model` | `RAG_EMBEDDING_MODEL` | `text-embedding-3-small` | Model for vector embedding generation |
|
|
186
|
+
| `embedding_dim` | `RAG_EMBEDDING_DIM` | `1536` | Dimensionality of embedding vectors |
|
|
187
|
+
| `db_uri` | `POSTGRES_URI` | `postgresql://crajah@localhost:5432/postgres` | PostgreSQL connection DSN |
|
|
188
|
+
| `realm` | `RAG_REALM` | `default` | Multi-tenant graph namespace |
|
|
189
|
+
|
|
190
|
+
---
|
|
191
|
+
|
|
192
|
+
## 📖 API Reference
|
|
193
|
+
|
|
194
|
+
### `GraphRAG`
|
|
195
|
+
The main orchestrator class for indexing and querying.
|
|
196
|
+
|
|
197
|
+
- `await initialize()`: Connects to PostgreSQL and creates necessary graph tables (`documents`, `entities`, `relations`, `doc_mentions`).
|
|
198
|
+
- `await index_document(text: str, metadata: Optional[Union[Dict[str, Any], DocumentMetadata]] = None) -> Dict[str, Any]`: Computes document embeddings, extracts entity/triple structures via LLM, and persists graph nodes/edges into PostgreSQL.
|
|
199
|
+
- `await query(question: str, top_k: int = 5) -> Dict[str, Any]`: Executes hybrid vector similarity search over documents and entities, traverses 1-hop graph relationship edges, and synthesizes a comprehensive answer. Returns dictionary with `question`, `answer`, `retrieved_documents`, `retrieved_entities`, and `retrieved_graph_triples`.
|
|
200
|
+
- `await close()`: Closes database connection pools.
|
|
201
|
+
|
|
202
|
+
### `DocumentMetadata`
|
|
203
|
+
Data container for structured document metadata.
|
|
204
|
+
|
|
205
|
+
- `source: Optional[str]`: Document URL, path, or origin.
|
|
206
|
+
- `category: Optional[str]`: Document category or domain.
|
|
207
|
+
- `collection: Optional[str]`: Document collection or folder.
|
|
208
|
+
- `document: Optional[str]`: File title or filename.
|
|
209
|
+
- `page: Optional[int]`: 1-based page number.
|
|
210
|
+
- `paragraph: Optional[int]`: 1-based paragraph index.
|
|
211
|
+
- `extra: Dict[str, Any]`: Custom user metadata.
|
|
212
|
+
- `to_dict() -> Dict[str, Any]`: Serializes non-None fields to dictionary representation.
|
|
213
|
+
- `from_dict(data: Dict[str, Any]) -> DocumentMetadata`: Deserializes dictionary data.
|
|
214
|
+
|
|
215
|
+
### `RAGGraphStore`
|
|
216
|
+
Database layer wrapping `post-graph`.
|
|
217
|
+
|
|
218
|
+
- `add_document(text, embedding, metadata)`: Inserts a document vertex into the `documents` table.
|
|
219
|
+
- `upsert_entity(name, entity_type, description, embedding)`: Upserts an entity vertex into the `entities` table.
|
|
220
|
+
- `add_relation(from_entity, to_entity, relation_type, description)`: Connects entity vertices with a directed relation edge.
|
|
221
|
+
- `search_similar_entities(query_vec, top_k)`: Executes `pgvector` HNSW similarity search over `entities`.
|
|
222
|
+
- `search_similar_documents(query_vec, top_k)`: Executes `pgvector` HNSW similarity search over `documents`.
|
|
223
|
+
|
|
224
|
+
---
|
|
225
|
+
|
|
226
|
+
## 🗄️ PostgreSQL Database Schema
|
|
227
|
+
|
|
228
|
+
`post-graph-rag` automatically provisions and manages the following graph schema in PostgreSQL powered by `post-graph`:
|
|
229
|
+
|
|
230
|
+
| Table Name | Type | Key Columns | Description |
|
|
231
|
+
| :--- | :--- | :--- | :--- |
|
|
232
|
+
| `{realm}_documents` | Vertex Table | `id`, `payload`, `embedding` (`vector`) | Stores raw text chunks and `DocumentMetadata` payloads |
|
|
233
|
+
| `{realm}_entities` | Vertex Table | `id`, `payload`, `embedding` (`vector`) | Canonical entity nodes (`name`, `type`, `description`) |
|
|
234
|
+
| `{realm}_relations` | Edge Table | `from_id`, `to_id`, `relation_type`, `payload` | Directed edges representing entity-to-entity triples |
|
|
235
|
+
| `{realm}_doc_mentions` | Edge Table | `from_id`, `to_id`, `relation_type` | Directed edges connecting document chunks to mentioned entities |
|
|
236
|
+
| `{table}_audit` | Audit Table | `audit_id`, `action`, `changed_by`, `changed_at` | Automatic shadow audit logging for all graph mutations |
|
|
237
|
+
| `{table}_data` | History Table | `data_id`, `payload`, `timestamp`, `embedding` | Append-only historical records for vertices and edges |
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## 📄 License
|
|
242
|
+
|
|
243
|
+
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
244
|
+
|
|
245
|
+
Developed by **Chandan Rajah** (<chandan.rajah@gmail.com>).
|