Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,10 @@ make start # opens a demo project with six AI papers already ingested

Nothing is sent anywhere unless you pick a provider that is not offline.

Ingestion analyzes up to two sources at a time by default. Set `ingestion_workers`
in your project's `settings/settings.json` to `1` for serial ingestion or `3`
to allow three sources at a time. Wiki updates are applied in queue order.

## How it compares

| | gknowledge | LLM Wiki | Tolaria | OpenKnowledge | Reor (archived) | Khoj |
Expand Down
15 changes: 12 additions & 3 deletions gknowledge/core/extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,16 @@ def alias_of(key: str) -> str | None:
# -- orchestration -------------------------------------------------------
def ingest_source(self, source: Source, text: str) -> ExtractionResult:
analysis = self.analyze(text)
result = self.persist_analysis(source, text, analysis, fallback=self.last_fallback)
self.rebuild_catalog()
return result

def persist_analysis(self, source: Source, text: str, analysis: dict, *,
fallback: str = "") -> ExtractionResult:
"""Generate and write one source's pages against the current wiki."""
existing = {p.slug for p in self.project.store.list_pages()}
result = self.generate(source, analysis, existing, text)
result.fallback = self.last_fallback
result.fallback = fallback

source_slug = None
for page in result.pages:
Expand All @@ -303,8 +310,6 @@ def ingest_source(self, source: Source, text: str) -> ExtractionResult:
for item in result.reviews:
self.project.store.upsert_review(item)

self.writer.rebuild_index()
self.writer.rebuild_overview()
self.writer.append_log(
"ingest",
f"{source.title}: {len(result.pages)} pages, {len(result.reviews)} reviews"
Expand All @@ -313,6 +318,10 @@ def ingest_source(self, source: Source, text: str) -> ExtractionResult:
)
return result

def rebuild_catalog(self) -> None:
self.writer.rebuild_index()
self.writer.rebuild_overview()


# -- helpers -----------------------------------------------------------------
def _render_source_summary(source: Source, analysis: dict,
Expand Down
153 changes: 113 additions & 40 deletions gknowledge/core/ingestion.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
"""Ingestion queue: import → parse → extract, with persistence and recovery.

Jobs live in the store, so a queue survives restarts and can be resumed. Import
is cache-aware: a file whose SHA-256 already exists is skipped (its job is
marked ``SKIPPED``) instead of re-spending an LLM call. Processing is serial to
avoid concurrent provider calls, and can run synchronously (tests, CLI) or on a
background thread (UI) via :meth:`process_pending`.
is cache-aware: a file whose SHA-256 already exists is skipped instead of
re-spending an LLM call. Sources are analyzed concurrently and applied to the
wiki in queue order. Processing can run synchronously or on a background thread.
"""

from __future__ import annotations
Expand All @@ -13,6 +12,7 @@
import re
import shutil
import threading
from concurrent.futures import Future, ThreadPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import Callable
Expand All @@ -25,7 +25,7 @@
from .knowledge import KnowledgeWriter
from .lint import origin_of
from .models import Job, JobState, PageKind, Source, SourceStatus, new_id, now
from .project import Project
from .project import DEFAULT_INGESTION_WORKERS, Project

# progress(event: str, job: Job, message: str) -> None
Progress = Callable[[str, Job, str], None]
Expand All @@ -42,13 +42,20 @@ class ImportOutcome:
skipped: list[Source] # duplicate content (same hash)


class CatalogRefreshError(OSError):
def __init__(self, completed: int, cause: OSError):
super().__init__(f"Could not refresh the knowledge index and overview: {cause}")
self.completed = completed


class IngestionManager:
def __init__(self, project: Project, provider: LLMProvider | None = None):
self.project = project
self.store = project.store
self.provider = provider or build_provider(project.settings.as_dict())
self._cancel = threading.Event()
self._thread: threading.Thread | None = None
self._run_lock = project._ingestion_lock
self._catalog_dirty = project.cache_dir / "ingestion-catalog-dirty"

def set_provider(self, provider: LLMProvider) -> None:
self.provider = provider
Expand Down Expand Up @@ -261,41 +268,48 @@ def queue_all_pending_sources(self) -> int:
return count

# -- processing ----------------------------------------------------------
def _process_job(self, job: Job, pipeline: ExtractionPipeline, progress: Progress | None):
def _start_job(self, job: Job, progress: Progress | None) -> Source | None:
source = self.store.get_source(job.source_id)
if source is None:
job.state = JobState.FAILED
job.error = "source missing"
job.updated_at = now()
self.store.upsert_job(job)
return
return None

job.state = JobState.RUNNING
job.attempts += 1
job.updated_at = now()
self.store.upsert_job(job)
_emit(progress, "start", job, source.title)
return source

def _analyze_source(self, source: Source, provider: LLMProvider) -> tuple[str, dict, str]:
text = parsers.parse(self.project.sources_dir / source.rel_path)
if not text.strip():
raise ValueError("no extractable text")
pipeline = ExtractionPipeline(self.project, provider)
return text, pipeline.analyze(text), pipeline.last_fallback

def _finish_job(self, job: Job, source: Source, analysis: Future[tuple[str, dict, str]],
pipeline: ExtractionPipeline, progress: Progress | None) -> bool:
try:
fp = self.project.sources_dir / source.rel_path
text = parsers.parse(fp)
if not text.strip():
raise ValueError("no extractable text")
text, data, fallback = analysis.result()
source.status = SourceStatus.PARSED
self.store.upsert_source(source)

result = pipeline.ingest_source(source, text)
# Keep catalog repair possible even if the process stops after this job.
if not self._catalog_dirty.exists():
self._catalog_dirty.parent.mkdir(parents=True, exist_ok=True)
self._catalog_dirty.touch()
result = pipeline.persist_analysis(source, text, data, fallback=fallback)
source.status = SourceStatus.INGESTED
self.store.upsert_source(source)

job.state = JobState.DONE
job.error = ""
job.updated_at = now()
self.store.upsert_job(job)
_emit(progress, "done", job,
f"{source.title}: {len(result.pages)} pages")
if result.fallback:
_emit(progress, "warning", job, f"{source.title}: {result.fallback}")
except Exception as exc: # noqa: BLE001 - surface, don't crash the queue
source.status = SourceStatus.FAILED
self.store.upsert_source(source)
Expand All @@ -305,45 +319,104 @@ def _process_job(self, job: Job, pipeline: ExtractionPipeline, progress: Progres
job.updated_at = now()
self.store.upsert_job(job)
_emit(progress, "error", job, str(exc))
return False

_emit(progress, "done", job, f"{source.title}: {len(result.pages)} pages")
if result.fallback:
_emit(progress, "warning", job, f"{source.title}: {result.fallback}")
return True

def process_pending(self, progress: Progress | None = None, *, max_jobs: int | None = None) -> int:
"""Process queued jobs serially. Returns number of jobs completed."""
pipeline = ExtractionPipeline(self.project, self.provider)
"""Process queued jobs and return the number completed by this run."""
if not self._run_lock.acquire(blocking=False):
return 0
try:
return self._drain(progress, max_jobs)
finally:
self._run_lock.release()

def _drain(self, progress: Progress | None, max_jobs: int | None) -> int:
provider = self.provider
pipeline = ExtractionPipeline(self.project, provider)
workers = self.project.settings.ingestion_workers
if type(workers) is not int or not 1 <= workers <= 3:
workers = DEFAULT_INGESTION_WORKERS
done = 0
while not self._cancel.is_set():
pending = [j for j in self.store.pending_jobs()
if j.state != JobState.FAILED]
# Only pick genuinely queued jobs whose attempts are under the cap.
queued = [j for j in pending if j.attempts < 3]
if not queued:
break
job = queued[0]
self._process_job(job, pipeline, progress)
if job.state == JobState.DONE:
done += 1
if max_jobs and done >= max_jobs:
break
with ThreadPoolExecutor(max_workers=workers, thread_name_prefix="ingest-analysis") as executor:
while not self._cancel.is_set():
# RUNNING rows from an interrupted run are eligible for retry.
queued = [job for job in self.store.pending_jobs() if job.attempts < 3]
if not queued:
break
# Reserve a completion slot for each job we start.
slots = min(workers, max(1, max_jobs - done)) if max_jobs else workers
batch = []
for job in queued[:slots]:
if self._cancel.is_set():
break
source = self._start_job(job, progress)
if source is not None:
future = executor.submit(self._analyze_source, source, provider)
batch.append((job, source, future))

# Apply in queue order, even if a source needs another attempt.
for job, source, future in batch:
while True:
if self._finish_job(job, source, future, pipeline, progress):
done += 1
break
if job.state != JobState.QUEUED or self._cancel.is_set():
break
source = self._start_job(job, progress)
if source is None:
break
future = executor.submit(self._analyze_source, source, provider)
if max_jobs and done >= max_jobs:
break

try:
if self.needs_catalog_refresh():
pipeline.rebuild_catalog()
self._catalog_dirty.unlink(missing_ok=True)
except OSError as exc:
raise CatalogRefreshError(done, exc) from exc
return done

# -- threaded (UI) -------------------------------------------------------
def start(self, progress: Progress | None = None, on_finish: Callable[[int], None] | None = None) -> None:
if self._thread and self._thread.is_alive():
def start(self, progress: Progress | None = None, on_finish: Callable[[int], None] | None = None,
*, on_error: Callable[[str], None] | None = None) -> None:
if not self._run_lock.acquire(blocking=False):
return
self._cancel.clear()

def _run():
count = self.process_pending(progress)
if on_finish:
on_finish(count)
count = 0
try:
count = self._drain(progress, None)
except CatalogRefreshError as exc:
count = exc.completed
if on_error is None:
raise
on_error(str(exc))
finally:
self._run_lock.release()
if on_finish:
on_finish(count)

self._thread = threading.Thread(target=_run, daemon=True, name="ingest")
self._thread.start()
try:
threading.Thread(target=_run, daemon=True, name="ingest").start()
except BaseException:
self._run_lock.release()
raise

def cancel(self) -> None:
self._cancel.set()

def is_running(self) -> bool:
return bool(self._thread and self._thread.is_alive())
return self._run_lock.locked()

def needs_catalog_refresh(self) -> bool:
return self._catalog_dirty.exists()


def _emit(progress: Progress | None, event: str, job: Job, message: str) -> None:
Expand Down
4 changes: 4 additions & 0 deletions gknowledge/core/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from __future__ import annotations

import json
import threading
from dataclasses import asdict, dataclass, field
from pathlib import Path

Expand All @@ -31,6 +32,7 @@

MANIFEST = "gknowledge.json"
FORMAT_VERSION = 1
DEFAULT_INGESTION_WORKERS = 2

KNOWLEDGE_SUBDIRS = {
PageKind.SOURCE: "sources",
Expand All @@ -50,6 +52,7 @@ class Settings:
model: str = "gpt-4o-mini"
embed_model: str = ""
language: str = "English"
ingestion_workers: int = DEFAULT_INGESTION_WORKERS

def as_dict(self) -> dict:
return asdict(self)
Expand All @@ -64,6 +67,7 @@ class Project:
def __init__(self, root: str | Path):
self.root = Path(root)
self.store = Store(self.index_dir / "knowledge.db")
self._ingestion_lock = threading.Lock()
self._settings = self._load_settings()

# -- lifecycle -----------------------------------------------------------
Expand Down
28 changes: 21 additions & 7 deletions gknowledge/providers/chatgpt.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,11 +360,13 @@ def __init__(self, model: str = "", *, auth: ChatGPTAuth | None = None,
self.api_base = api_base.rstrip("/")
self.configured_model = model
self._model: str | None = None
self._session_lock = threading.Lock()
self.name = (f"ChatGPT plan · {model}" if model
else "ChatGPT plan · automatic model")

def available(self) -> bool:
return self.auth.store.load().sharing
with self._session_lock:
return self.auth.store.load().sharing

# -- model resolution --------------------------------------------------------------
def list_models(self) -> list[dict]:
Expand All @@ -373,9 +375,13 @@ def list_models(self) -> list[dict]:
The endpoint returns ``{"models": [{slug, display_name, visibility,
priority, ...}]}``; only ``visibility == "list"`` entries are shown.
"""
acct = self.auth.valid_account()
with self._session_lock:
acct = self.auth.valid_account()
return self._list_models(acct.access_token)

def _list_models(self, token: str) -> list[dict]:
data = _http_json(f"{self.api_base}/models",
headers={"Authorization": f"Bearer {acct.access_token}"},
headers={"Authorization": f"Bearer {token}"},
timeout=20)
models = [m for m in data.get("models", [])
if m.get("visibility", "list") == "list" and m.get("slug")]
Expand All @@ -388,7 +394,7 @@ def _resolve_model(self, token: str) -> str:
if self._model:
return self._model
try:
slugs = [m["slug"] for m in self.list_models()]
slugs = [m["slug"] for m in self._list_models(token)]
except (ProviderError, KeyError):
slugs = []
if self.configured_model and (not slugs or self.configured_model in slugs):
Expand All @@ -405,7 +411,11 @@ def complete(self, messages: list[LLMMessage], *, json_object: bool = False,
temperature: float = 0.2, max_tokens: int | None = None) -> LLMResponse:
# Plan usage rejects explicit system items, temperature and
# max_output_tokens: system text goes in `instructions`.
acct = self.auth.valid_account()
# Account refresh and model selection share state across requests.
# Streaming can proceed independently with the chosen token and model.
with self._session_lock:
acct = self.auth.valid_account()
model = self._resolve_model(acct.access_token)
instructions = "\n\n".join(m.content for m in messages if m.role == "system")
if json_object:
instructions += "\n\nRespond with a single valid JSON object and nothing else."
Expand All @@ -416,7 +426,7 @@ def complete(self, messages: list[LLMMessage], *, json_object: bool = False,
ctype = "output_text" if m.role == "assistant" else "input_text"
items.append({"role": m.role,
"content": [{"type": ctype, "text": m.content}]})
payload = {"model": self._resolve_model(acct.access_token),
payload = {"model": model,
"instructions": instructions.strip() or "You are a helpful assistant.",
"input": items, "store": False, "stream": True}

Expand All @@ -426,7 +436,11 @@ def complete(self, messages: list[LLMMessage], *, json_object: bool = False,
except _Unauthorized:
if attempt:
raise ProviderError("ChatGPT rejected the access token.")
acct = self.auth.refresh()
with self._session_lock:
current = self.auth.valid_account()
if current.access_token == acct.access_token:
current = self.auth.refresh()
acct = current
raise ProviderError("Unreachable") # pragma: no cover

def _stream(self, payload: dict, token: str) -> LLMResponse:
Expand Down
Loading
Loading