Spaces:
Sleeping
Sleeping
File size: 9,223 Bytes
cf450f7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 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 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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | # Knowledge Graph Example
This example builds a simple **knowledge graph** on top of **SurrealDB** from
uploaded documents, using a **data-flow pattern** to drive ingestion.
At a high level:
1. You upload a document to the FastAPI server (`/upload`).
2. The server stores it in SurrealDB as a `document` record.
3. A background ingestion worker runs *flows* that:
- chunk documents into embedded `chunk` records
- infer `concept` nodes from each chunk and create `MENTIONS_CONCEPT` edges
4. A separate chat agent can retrieve relevant chunks (vector + graph context)
and answer using the ingested documents.
## Code layout
The package lives under `examples/knowledge-graph/src/knowledge_graph/`:
- `server.py`
- FastAPI application and lifecycle management.
- Starts the background ingestion loop on startup and stops it on shutdown.
- Creates a `flow.Executor` bound to the SurrealDB connection.
- `ingestion.py`
- Defines the ingestion pipeline by registering flow handlers with
`@exe.flow(...)`.
- Current flows:
- `chunk`: processes `document` records that have not been chunked yet
- `infer_concepts`: processes `chunk` records that have not had concepts
inferred yet
- `flow/`
- `executor.py`: generic runtime for the data-flow pattern (polls DB for work,
executes handlers, applies backoff when idle).
- `definitions.py`: `Flow` (Pydantic model) and shared types.
- `handlers/`
- `upload.py`: receives a file and stores it as an original document in DB.
- `chunk.py`: converts and chunks documents, embeds chunks, inserts them.
- `inference.py`: uses the configured LLM to extract concepts and write
`concept` nodes + `MENTIONS_CONCEPT` edges.
- `agent.py`
- PydanticAI agent with a `retrieve` tool.
- Runs SurrealQL from `surql/search_chunks.surql` to fetch relevant chunks and
supplies them as context to the model.
- `surql/`
- SurrealQL files for schema definition and retrieval queries.
## Data-flow pattern (flow/stamp) used here
This example uses a **database-driven data flow**:
- Each step (“flow”) queries a DB table for records that are eligible for
processing.
- The step writes results back to the DB.
- The step marks completion by setting a *stamp field* on the record.
### Flow definition
Flows are registered via the `@exe.flow(table=..., stamp=..., dependencies=..., priority=...)`
decorator. Under the hood:
- The executor stores flow metadata in the `flow` table.
- Each handler is assigned a **stable hash** derived from its compiled code.
This hash is written into the record’s stamp field after processing.
### Eligibility and dependencies
A record becomes a candidate when:
- its stamp field is `NONE` (meaning “not yet processed by this flow”), and
- all dependency fields (if any) are present (not `NONE`).
This makes the pipeline **restart-safe** and **incremental**:
if the server stops, it resumes based on DB state rather than in-memory state.
### Stamping and idempotency
Each handler must set its stamp field, e.g.:
- `document.chunked = <flow_hash>`
- `chunk.concepts_inferred = <flow_hash>`
This prevents reprocessing the same record and also makes changes traceable:
if you update a flow function, its hash changes and you can see which records
were processed by which version of the flow.
## Run:
### DB:
```bash
surreal start -u root -p root rocksdb:dbs/knowledge-graph
```
or use the helper script:
```bash
./scripts/run_surrealdb.sh
```
or `just knowledge-graph-db` from the repo base directory.
### LLM + embeddings (Blablador)
This example uses OpenAI-compatible APIs. For Blablador, set:
```bash
export OPENAI_API_KEY="$BLABLADOR_API_KEY"
export OPENAI_BASE_URL="${BLABLADOR_BASE_URL:-https://api.helmholtz-blablador.fz-juelich.de/v1/}"
```
Defaults are `alias-fast` for chat and local sentence-transformers embeddings.
Override chat model and fallbacks if needed:
```bash
export KG_LLM_MODEL=alias-fast
export KG_LLM_FALLBACK_MODELS=alias-large,alias-code
export KG_CHAT_MODEL=alias-fast
```
To use local embeddings explicitly:
```bash
export KG_EMBEDDINGS_PROVIDER=sentence-transformers
export KG_LOCAL_EMBEDDINGS_MODEL=sentence-transformers/all-MiniLM-L6-v2
```
To try Blablador embeddings (may be unstable):
```bash
export KG_EMBEDDINGS_PROVIDER=openai
export KG_EMBEDDINGS_MODEL=alias-embeddings
```
### Server and ingestion worker
```bash
DB_NAME=test_db uv run --env-file .env -- fastapi run examples/knowledge-graph/src/knowledge_graph/server.py --port 8080
```
By default, ingestion is disabled so the server can start quickly. To enable
ingestion at startup:
```bash
export KG_ENABLE_INGESTION=true
```
Recommended flow for large uploads:
1) Upload documents.
2) Run ingestion separately.
To run ingestion separately (recommended for large backlogs):
```bash
./scripts/start_ingestion.sh
```
If you see WebSocket disconnects, switch to HTTP for the DB client:
```bash
export KG_DB_URL=http://localhost:8000
```
### PDF converter selection
By default, the ingestion flow prefers Docling with no fallback. You can
override the order with:
```bash
export KG_PDF_CONVERTER=docling
```
Other values: `kreuzberg` (prefer Kreuzberg), `auto` (try Kreuzberg first).
To enable fallback converters:
```bash
export KG_PDF_FALLBACK=true
```
Docling tokenizer configuration:
```bash
export KG_DOCLING_TOKENIZER=cl100k_base
```
### Markdown ingestion
You can upload `.md` files directly; they are chunked locally without PDF
conversion. The uploader also guesses content types by filename when missing.
If a file comes through as `application/octet-stream`, the ingestion pipeline
will attempt to guess the type from the filename before converting.
### Party plan metadata
The knowledge-graph example includes a metadata file for the 2026 party plan
PDFs. It is used to expand acronyms and to surface plan URLs in answers:
- `examples/knowledge-graph/data/party_plan_metadata.json`
or `just knowledge-graph test_db` from the repo base directory.
### Chat agent
```bash
DB_NAME=test_db uv run --env-file .env uvicorn knowledge_graph.agent:app --host 127.0.0.1 --port 7932
```
### Status check
```bash
./scripts/status_check.sh
```
This script now acts as a status checker and log tail helper. Logs are written
to `logs/server.log` and `logs/ui.log`.
### Quickstart scripts
Start SurrealDB:
```bash
./scripts/run_surrealdb.sh
```
Start server (foreground):
```bash
./scripts/start_server.sh
```
Start server in background:
```bash
./scripts/start_server.sh -b
```
Upload PDFs/Markdowns:
```bash
./scripts/upload_pdfs.sh /path/to/folder
```
Run ingestion (process backlog):
```bash
./scripts/start_ingestion.sh
```
Start UI:
```bash
source scripts/start_ui.sh
```
### Streamlit app (query-first)
Run locally (requires SurrealDB running):
```bash
export DB_NAME=test_db
streamlit run examples/knowledge-graph/streamlit_app.py
```
Uploads are limited to one PDF/Markdown at a time (default max 50 MB).
Ingestion runs in a background thread and writes logs to `logs/ingestion.log`.
The Streamlit UI can display party banner images using `images/metadata.json`.
Set the limit explicitly:
```bash
export KG_MAX_UPLOAD_MB=50
export STREAMLIT_SERVER_MAX_UPLOAD_SIZE=50
```
Docker (single container with SurrealDB inside):
```bash
docker build -f Dockerfile.streamlit -t kaig-streamlit .
docker run -p 8501:8501 \
-e BLABLADOR_API_KEY=... \
-e BLABLADOR_BASE_URL=https://api.helmholtz-blablador.fz-juelich.de/v1/ \
kaig-streamlit
```
The build expects `dbs/knowledge-graph/` to be present in the build context.
SurrealDB retry settings (optional):
```bash
export KG_DB_RETRY_ATTEMPTS=3
export KG_DB_RETRY_DELAY=1.0
```
Check status:
```bash
./scripts/status_check.sh
```
Limit retrieval tool calls per question (default: 10):
```bash
export KG_MAX_RETRIEVE_CALLS=1
```
Tune search threshold and fallback:
```bash
export KG_SEARCH_THRESHOLD=0.15
export KG_SEARCH_FALLBACK=true
```
or `just knowledge-graph-agent test_db` from the repo base directory.
## SurrealQL queries:
**Visualise the graph:**
```surql
SELECT *,
->MENTIONS_CONCEPT->concept as concepts
FROM chunk;
```
**Flow status**
This will show how many records have been processed by and are pending for each "flow".
```surql
LET $flows = SELECT * FROM flow;
RETURN $flows.fold([], |$a, $flow| {
LET $b = SELECT
$flow.id as flow,
type::field($flow.stamp) as flow_hash,
count() as count,
$flow.table as table
FROM type::table($flow.table)
GROUP BY flow_hash;
RETURN $a.concat($b)
});
```
Output example:
```surql
[
{
count: 1,
flow: flow:chunk,
flow_hash: NONE,
table: 'document'
},
{
count: 2,
flow: flow:chunk,
flow_hash: 'bbb6fe4b55cce1b3c8af0e7713a33d75',
table: 'document'
},
{
count: 4,
flow: flow:infer_concepts,
flow_hash: NONE,
table: 'chunk'
},
{
count: 27,
flow: flow:infer_concepts,
flow_hash: '75f90c71db9aeb2cf6f871ba1f75828c',
table: 'chunk'
}
]
```
Different hashes mean the records have been processed by different versions of the flow function. This can happen if the flow function has been updated.
|