Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
3808 lines (3304 loc) · 136 KB
/
Copy pathcli.py
File metadata and controls
3808 lines (3304 loc) · 136 KB
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""OpenKB CLI — command-line interface for the knowledge base workflow."""
from __future__ import annotations
# Silence import-time warnings (e.g. pydub's missing-ffmpeg warning emitted
# when markitdown pulls it in). markitdown later clobbers the filters during
# its own import, so we re-apply after all imports below.
import warnings
warnings.filterwarnings("ignore")
import asyncio
import json
import logging
from dataclasses import dataclass
import shutil
import sys
import time
import uuid
from functools import wraps
from pathlib import Path
from typing import Any, Literal
import os
from agents import set_tracing_disabled
set_tracing_disabled(True)
# Use local model cost map — skip fetching from GitHub on every invocation
os.environ.setdefault("LITELLM_LOCAL_MODEL_COST_MAP", "True")
import click
# Silence LiteLLM's "could not pre-load <aws-service> response stream
# shape" warnings — they fire at import time when ``botocore`` isn't
# installed, but botocore is only needed for AWS Bedrock / SageMaker
# users. Filter must be attached before ``import litellm`` runs.
class _SuppressLiteLLMPreloadWarnings(logging.Filter):
def filter(self, record: logging.LogRecord) -> bool:
return "could not pre-load" not in record.getMessage()
logging.getLogger("LiteLLM").addFilter(_SuppressLiteLLMPreloadWarnings())
import litellm
litellm.suppress_debug_info = True
from dotenv import load_dotenv
from openkb.agent.compiler import DEFAULT_COMPILE_CONCURRENCY, compile_long_doc
from openkb.config import (
DEFAULT_CONFIG,
resolve_effective_config,
save_config,
load_global_config,
register_kb,
resolve_concurrency,
set_extra_headers,
resolve_parallel_tool_calls,
set_parallel_tool_calls,
set_timeout,
resolve_per_request_overrides,
)
from openkb.add_coordinator import _cleanup_staging_dirs
from openkb.converter import (
_registry_path,
_sanitize_stem,
convert_document,
resolve_doc_name_from_key,
)
from openkb.indexer import (
_cloud_display_stem,
_write_long_doc_artifacts,
prepare_cloud_import,
)
from openkb.locks import atomic_write_json, atomic_write_text, kb_ingest_lock, kb_read_lock
from openkb.log import append_log
from openkb.mutation import publish_staged_tree
from openkb.schema import AGENTS_MD, INDEX_SEED, PAGE_CONTENT_DIRS
# Suppress warnings after all imports — markitdown overrides filters at import time
import warnings
warnings.filterwarnings("ignore")
load_dotenv() # load from cwd (covers running inside the KB dir)
logger = logging.getLogger(__name__)
_KNOWN_PROVIDER_KEYS = (
"OPENAI_API_KEY",
"ANTHROPIC_API_KEY",
"GEMINI_API_KEY",
"DEEPSEEK_API_KEY",
"MISTRAL_API_KEY",
"MOONSHOT_API_KEY",
"ZHIPUAI_API_KEY",
"DASHSCOPE_API_KEY",
)
# Providers that authenticate via OAuth device flow (subscription login
# handled by LiteLLM itself) — no API key env var is needed, so the
# missing-key warning would be a false alarm for them.
_OAUTH_PROVIDERS = {"chatgpt", "github_copilot"}
def _extract_provider(model: str) -> str | None:
"""Extract the LiteLLM provider name from a model string.
``model`` uses ``provider/model`` LiteLLM format.
OpenAI models can omit the prefix; default to ``"openai"``.
"""
model = model.strip()
if not model:
return None
if "/" in model:
return model.split("/")[0].lower()
return "openai"
def _apply_litellm_settings(settings: dict) -> None:
"""Set each ``litellm:`` key verbatim onto the litellm module (process-wide
globals, so they reach every LiteLLM call). Skips with a warning a key the
installed litellm doesn't define, or one that is a litellm function (e.g.
``completion``) since overwriting it would break later calls. Applied, never
reset — the values persist for the life of the process.
"""
for key, value in settings.items():
if not hasattr(litellm, key):
logger.warning(
"config: LiteLLM has no setting %r — ignoring it "
"(check the spelling or your installed litellm version).",
key,
)
continue
if callable(getattr(litellm, key)):
logger.warning(
"config: 'litellm.%s' is a LiteLLM function, not a setting — "
"refusing to overwrite it from the litellm: config block.",
key,
)
continue
setattr(litellm, key, value)
def _setup_llm_key(kb_dir: Path | None = None) -> None:
"""Set LiteLLM API key from LLM_API_KEY env var if present.
Load order (override=False, so first one wins):
1. System environment variables (already set)
2. KB-local .env (kb_dir/.env)
3. Global .env (~/.config/openkb/.env)
Also propagates to provider-specific env vars (OPENAI_API_KEY, etc.)
so that the Agents SDK litellm provider can pick them up.
Provider is auto-detected from the KB config when available; otherwise
a common provider set is used as a fallback.
"""
if kb_dir is not None:
env_file = kb_dir / ".env"
if env_file.exists():
load_dotenv(env_file, override=False)
from openkb.config import GLOBAL_CONFIG_DIR
global_env = GLOBAL_CONFIG_DIR / ".env"
if global_env.exists():
load_dotenv(global_env, override=False)
api_key = os.environ.get("LLM_API_KEY", "")
# Try to resolve the active provider, extra headers, and request timeout
# from the KB config
provider: str | None = None
extra_headers: dict[str, str] = {}
timeout: float | None = None
parallel_tool_calls: bool | None = None
parallel_tool_calls_explicit = False
litellm_settings: dict = {}
if kb_dir is not None:
# Resolve model the same way the command bodies do (DEFAULT -> global.yaml
# -> KB config.yaml) so provider extraction sees the effective, global-
# layered model. Reading KB config.yaml alone would miss a global-only
# default model (or fall back to DEFAULT_CONFIG's model) and derive the
# wrong provider. resolve_effective_config handles a missing config.yaml
# internally, so no config_path.exists() gate is needed.
config = resolve_effective_config(kb_dir)[0]
model = config.get("model", DEFAULT_CONFIG["model"])
provider = _extract_provider(str(model))
extra_headers, timeout, litellm_settings = resolve_per_request_overrides(config)
parallel_tool_calls, parallel_tool_calls_explicit = resolve_parallel_tool_calls(config)
set_extra_headers(extra_headers)
set_timeout(timeout)
set_parallel_tool_calls(parallel_tool_calls, parallel_tool_calls_explicit)
_apply_litellm_settings(litellm_settings)
if not api_key:
# Check if any provider key is already set. OAuth-based providers
# (ChatGPT subscription, GitHub Copilot) don't use API keys at all,
# so the warning is skipped for them.
check_keys = (f"{provider.upper()}_API_KEY",) if provider else _KNOWN_PROVIDER_KEYS
has_key = any(os.environ.get(k) for k in check_keys)
if not has_key and provider not in _OAUTH_PROVIDERS:
click.echo(
"Warning: No LLM API key found. Set one of:\n"
f" 1. {kb_dir / '.env' if kb_dir else '<kb_dir>/.env'} — LLM_API_KEY=sk-...\n"
f" 2. {GLOBAL_CONFIG_DIR / '.env'} — LLM_API_KEY=sk-...\n"
" 3. Export LLM_API_KEY in your shell profile"
)
else:
litellm.api_key = api_key
# Dynamically set the provider-specific env var when possible
if provider:
provider_env = f"{provider.upper()}_API_KEY"
if not os.environ.get(provider_env):
os.environ[provider_env] = api_key
# Fallback: also set common provider keys so multi-provider
# configs (e.g. PageIndex Cloud) still work
for env_var in _KNOWN_PROVIDER_KEYS:
if not os.environ.get(env_var):
os.environ[env_var] = api_key
# Supported document extensions for the `add` command
SUPPORTED_EXTENSIONS = {
".pdf",
".md",
".markdown",
".docx",
".pptx",
".xlsx",
".xls",
".html",
".htm",
".txt",
".csv",
}
# Map raw doc types to display types
_TYPE_DISPLAY_MAP = {
"long_pdf": "pageindex",
"pageindex_cloud": "pageindex",
}
# Registry types that were compiled via the long-doc pipeline (tree + per-page
# JSON source), as opposed to short docs (markdown source). Both the local
# long-PDF type and cloud imports belong here — they share the long-doc
# summary/source layout and recompile path.
_LONG_DOC_TYPES = {"long_pdf", "pageindex_cloud"}
def _is_long_doc(meta: dict) -> bool:
return meta.get("type") in _LONG_DOC_TYPES
_SHORT_DOC_TYPES = {
"pdf",
"docx",
"md",
"markdown",
"html",
"htm",
"txt",
"csv",
"pptx",
"xlsx",
"xls",
}
def _display_type(raw_type: str) -> str:
"""Map a raw stored doc type to a display type string."""
if raw_type in _TYPE_DISPLAY_MAP:
return _TYPE_DISPLAY_MAP[raw_type]
if raw_type in _SHORT_DOC_TYPES:
return "short"
return raw_type
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _find_kb_dir(override: Path | None = None) -> Path | None:
"""Find the KB root: explicit override → walk up from cwd → global default_kb."""
# 0. Explicit override (--kb-dir or OPENKB_DIR)
if override is not None:
if (override / ".openkb").is_dir():
return override
return None
# 1. Walk up from cwd
current = Path.cwd().resolve()
while True:
if (current / ".openkb").is_dir():
return current
parent = current.parent
if parent == current:
break
current = parent
# 2. Fall back to global config default_kb
gc = load_global_config()
default = gc.get("default_kb")
if default:
p = Path(default)
if (p / ".openkb").is_dir():
return p
return None
def _validate_skill_name(name: str) -> str | None:
"""Validate a skill slug. Returns None if OK, an error message if not.
Rules: lowercase ``[a-z0-9-]``, no leading/trailing dash, no consecutive
dashes, 1-64 characters. This matches the directory name we'll create
under ``<kb>/output/skills/`` and the ``name:`` frontmatter field.
"""
if not name:
return "Skill name must not be empty."
if len(name) > 64:
return "Skill name must be at most 64 characters."
if not all(("a" <= c <= "z") or ("0" <= c <= "9") or c == "-" for c in name):
return "Skill name must contain only lowercase letters, digits, and dashes."
if name.startswith("-"):
return "Skill name must not have a leading dash."
if name.endswith("-"):
return "Skill name must not have a trailing dash."
if "--" in name:
return "Skill name must not contain consecutive dashes."
return None
def _preflight_skill_new(kb_dir: Path, name: str) -> str | None:
"""Run shared safety gates for ``openkb skill new`` / ``/skill new``.
Checks (in order):
* skill name is a valid kebab-case slug
* ``<kb>/wiki`` exists
* any of ``<kb>/wiki/{summaries,concepts,entities}`` has at least
one file (i.e. some document has been ingested + compiled)
Returns ``None`` if all gates pass, else a single-line error message
suitable to print to the user.
Overwrite handling is NOT done here — the CLI handles it with
``-y`` + ``click.confirm``; chat refuses overwrite outright.
"""
err = _validate_skill_name(name)
if err:
return err
wiki = kb_dir / "wiki"
if not wiki.is_dir():
return "No wiki found in this KB. Run `openkb add <source>` to ingest documents first."
has_content = any(
(wiki / sub).is_dir() and any((wiki / sub).iterdir()) for sub in PAGE_CONTENT_DIRS
)
if not has_content:
return (
"Wiki has no compiled content yet. Ingest at least one "
"document with `openkb add` first."
)
return None
def _clear_existing_skill_dir(kb_dir: Path, name: str) -> None:
"""Delete an existing ``<kb>/output/skills/<name>/`` directory."""
from openkb.skill import skill_dir
target = skill_dir(kb_dir, name)
if target.exists():
shutil.rmtree(target)
def _staging_dir_for(kb_dir: Path, file_path: Path) -> Path:
safe = _sanitize_stem(file_path.stem)
path = kb_dir / ".openkb" / "staging" / f"add-{safe}-{uuid.uuid4().hex[:8]}"
path.mkdir(parents=True, exist_ok=False)
return path
def _final_artifact_paths(result, kb_dir: Path) -> tuple[Path | None, Path | None]:
final_raw = None
final_source = None
if result.raw_path is not None:
final_raw = kb_dir / "raw" / result.raw_path.name
if result.source_path is not None:
final_source = kb_dir / "wiki" / "sources" / result.source_path.name
return final_raw, final_source
def _snapshot_add_paths(
kb_dir: Path,
doc_name: str,
final_raw: Path | None,
final_source: Path | None,
) -> list[Path]:
# NOTE: .openkb/files (the PageIndex blob store) is intentionally NOT
# snapshotted here. It is append-only by {doc_id}, and the doc_id is only
# assigned during indexing (after this snapshot). Eagerly snapshotting the
# whole tree cost one os.link per existing blob on every add; instead the
# long-doc add path registers just the new blob via snapshot.track_new()
# once indexing has run.
paths = [
kb_dir / ".openkb" / "hashes.json",
kb_dir / ".openkb" / "pageindex.db",
kb_dir / ".openkb" / "pageindex.db-wal",
kb_dir / ".openkb" / "pageindex.db-shm",
kb_dir / ".openkb" / "pageindex.db-journal",
kb_dir / "wiki" / "summaries" / f"{doc_name}.md",
kb_dir / "wiki" / "sources" / f"{doc_name}.json",
kb_dir / "wiki" / "sources" / "images" / doc_name,
kb_dir / "wiki" / "concepts",
kb_dir / "wiki" / "entities",
kb_dir / "wiki" / "index.md",
kb_dir / "wiki" / "log.md",
]
if final_raw is not None:
paths.append(final_raw)
if final_source is not None:
paths.append(final_source)
return paths
def _run_compile_with_retry(coro_factory, label: str) -> None:
click.echo(f" {label}...")
for attempt in range(2):
try:
asyncio.run(coro_factory())
return
except Exception as exc:
if attempt == 0:
click.echo(" Retrying compilation in 2s...")
time.sleep(2)
else:
click.echo(f" [ERROR] Compilation failed: {exc}")
logger.debug("Compilation traceback:", exc_info=True)
raise
def add_single_file(
file_path: Path, kb_dir: Path, *, stage: bool = True, bundle=None
) -> Literal["added", "skipped", "failed"]:
"""Convert, index, and compile a single document under the KB mutation lock."""
with kb_ingest_lock(kb_dir / ".openkb"):
return _add_single_file_locked(file_path, kb_dir, stage=stage, bundle=bundle)
def _add_single_file_locked(
file_path: Path, kb_dir: Path, *, stage: bool = True, bundle=None
) -> Literal["added", "skipped", "failed"]:
"""Convert, index, and compile a single document into the knowledge base.
Steps:
1. Load config to get the model name.
2. Convert the document (hash-check; skip if already known).
3. If long doc: run PageIndex then compile_long_doc.
4. Else: compile_short_doc.
Returns:
``"added"`` on full success, ``"skipped"`` when the file's hash
is already in the registry (dedup), or ``"failed"`` when any
pipeline stage raised. URL-ingest distinguishes these so it can
unlink the just-downloaded raw file on dedup (it would otherwise
be an orphan) while preserving it on failure so the user can
retry without re-downloading.
"""
from openkb.agent.compiler import compile_long_doc, compile_short_doc
from openkb.state import HashRegistry
openkb_dir = kb_dir / ".openkb"
config = resolve_effective_config(kb_dir)[0]
# The REST API passes a per-KB credential bundle so it never pollutes
# process-wide state; only the CLI path needs the legacy global setup.
if bundle is None:
_setup_llm_key(kb_dir)
model: str = config.get("model", DEFAULT_CONFIG["model"])
staging_dir = _staging_dir_for(kb_dir, file_path) if stage else None
# 2. Convert document into staging when possible.
click.echo(f"Adding: {file_path.name}")
try:
result = convert_document(file_path, kb_dir, staging_dir=staging_dir)
except Exception as exc:
click.echo(f" [ERROR] Conversion failed: {exc}")
logger.debug("Conversion traceback:", exc_info=True)
_cleanup_staging_dirs([staging_dir])
return "failed"
if result.skipped:
click.echo(f" [SKIP] Already in knowledge base: {file_path.name}")
_cleanup_staging_dirs([staging_dir])
return "skipped"
doc_name = result.doc_name or file_path.stem
index_result = None # populated only on the long-doc branch
final_raw, final_source = _final_artifact_paths(result, kb_dir)
def commit_body(snapshot) -> None:
nonlocal index_result
publish_staged_tree(staging_dir, kb_dir)
if final_raw is not None:
result.raw_path = final_raw
if final_source is not None:
result.source_path = final_source
if result.is_long_doc:
if result.raw_path is None:
raise RuntimeError(f"Converted long document has no raw artifact: {file_path.name}")
click.echo(" Long document detected — indexing with PageIndex...")
# PageIndex content-dedups: if the same content is already indexed
# (e.g. hashes.json and pageindex.db diverged after a remove whose
# PageIndex cleanup failed), col.add() returns the EXISTING doc_id
# and writes no new blob. Capture the blob set *before* indexing so
# we register only blobs THIS add actually created — otherwise
# rollback would delete a prior document's blob.
files_root = kb_dir / ".openkb" / "files"
blobs_before = set(files_root.glob("*/*")) if files_root.exists() else set()
try:
from openkb.indexer import index_long_document
index_result = index_long_document(result.raw_path, kb_dir, doc_name=doc_name)
except Exception as exc:
click.echo(f" [ERROR] Indexing failed: {exc}")
logger.debug("Indexing traceback:", exc_info=True)
raise
# Register only the newly-created blob artifacts for this doc (the
# {doc_id} file + its images dir) — the append-only store means the
# name isn't known until now — so rollback + crash recovery remove
# exactly this add's blob, never a pre-existing one, instead of
# snapshotting the whole store up front. The doc_id guard + the
# blobs_before diff keep a dedup hit (or an unexpected empty doc_id)
# from registering — and later deleting — existing blobs.
if index_result.doc_id and files_root.exists():
snapshot.track_new(
[
p
for p in files_root.glob(f"*/{index_result.doc_id}*")
if p not in blobs_before
]
)
summary_path = kb_dir / "wiki" / "summaries" / f"{doc_name}.md"
_run_compile_with_retry(
lambda: compile_long_doc(
doc_name,
summary_path,
index_result.doc_id,
kb_dir,
model,
doc_description=index_result.description,
max_concurrency=resolve_concurrency(config) or DEFAULT_COMPILE_CONCURRENCY,
bundle=bundle,
),
label=f"Compiling long doc (doc_id={index_result.doc_id})",
)
else:
if result.source_path is None:
raise RuntimeError(f"Converted docu
10BC8
ment has no source artifact: {file_path.name}")
source_path = result.source_path
_run_compile_with_retry(
lambda: compile_short_doc(
doc_name,
source_path,
kb_dir,
model,
max_concurrency=resolve_concurrency(config) or DEFAULT_COMPILE_CONCURRENCY,
bundle=bundle,
),
label="Compiling short doc",
)
# Register hash only after successful compilation.
if result.file_hash:
registry = HashRegistry(openkb_dir / "hashes.json")
doc_type = "long_pdf" if result.is_long_doc else file_path.suffix.lstrip(".")
meta = {
"name": file_path.name,
"doc_name": doc_name,
"type": doc_type,
"path": _registry_path(file_path, kb_dir),
}
if result.raw_path is not None:
meta["raw_path"] = _registry_path(result.raw_path, kb_dir)
if result.source_path is not None:
meta["source_path"] = _registry_path(result.source_path, kb_dir)
if index_result is not None:
meta["doc_id"] = index_result.doc_id
registry.remove_by_doc_name(doc_name)
for existing_hash, existing_meta in list(registry.all_entries().items()):
if (
existing_hash != result.file_hash
and not existing_meta.get("doc_name")
and existing_meta.get("name") == file_path.name
):
registry.remove_by_hash(existing_hash)
registry.add(result.file_hash, meta)
def append_ingest_log() -> None:
append_log(kb_dir / "wiki", "ingest", file_path.name)
from openkb.add_coordinator import AddMutationPlan, run_add_mutation
plan = AddMutationPlan(
operation="add",
details={
"file_hash": result.file_hash,
"name": file_path.name,
"doc_name": doc_name,
},
touched_paths=_snapshot_add_paths(kb_dir, doc_name, final_raw, final_source),
body=commit_body,
post_commit_hooks=[append_ingest_log],
hardlink_dirs={
kb_dir / "wiki" / "concepts",
kb_dir / "wiki" / "entities",
},
staging_dirs=[staging_dir],
)
if not run_add_mutation(kb_dir, plan):
return "failed"
click.echo(f" [OK] {file_path.name} added to knowledge base.")
return "added"
@dataclass
class AddFileResult:
"""Structured add outcome for the REST API.
Wraps the plain ``Literal`` returned by the locked ``add_single_file`` with
the original filename and a human-readable message, which the API's
``/add`` endpoint surfaces per file in its JSON/SSE response.
"""
original_name: str
saved_path: str | None
status: str
message: str
def _add_for_api(file_path: Path, kb_dir: Path, *, bundle=None) -> AddFileResult:
"""Run the locked add pipeline and return a structured result for the API.
Reuses the upstream ``add_single_file`` (which already holds the ingest
lock and handles cloud import / registry dedup) so the API and CLI share a
single ingest code path. Maps the ``Literal`` status to a message-bearing
``AddFileResult``; on ``skipped`` the caller (api._add_saved_file) deletes
the freshly uploaded raw copy to avoid orphaning it.
"""
status_str = add_single_file(file_path, kb_dir, bundle=bundle)
if status_str == "skipped":
message = f"Already in knowledge base: {file_path.name}"
elif status_str == "failed":
message = f"Failed to add: {file_path.name} (see server logs)"
else:
message = f"Added: {file_path.name}"
return AddFileResult(
original_name=file_path.name,
saved_path=str(file_path) if status_str == "added" else None,
status=status_str,
message=message,
)
def _cleanup_failed_cloud_import(kb_dir: Path, doc_name: str) -> None:
"""Best-effort wiki cleanup after a cloud import whose compilation failed.
import_cloud_document writes the summary + per-page JSON source before
compile, and compile_long_doc writes concept/entity pages incrementally — so
a compile failure (which happens before the registry entry is added) would
otherwise strand wiki artifacts that ``openkb remove`` cannot reach. Mirror
remove's wiki cleanup (by doc_name, idempotent) but touch neither the
registry (no entry was added) nor PageIndex (the cloud doc is the user's).
"""
from openkb.agent.compiler import (
remove_doc_from_concept_pages,
remove_doc_from_entity_pages,
remove_doc_from_index,
)
wiki_dir = kb_dir / "wiki"
(wiki_dir / "summaries" / f"{doc_name}.md").unlink(missing_ok=True)
(wiki_dir / "sources" / f"{doc_name}.json").unlink(missing_ok=True)
images_dir = wiki_dir / "sources" / "images" / doc_name
if images_dir.is_dir():
shutil.rmtree(images_dir, ignore_errors=True)
concept_result = remove_doc_from_concept_pages(wiki_dir, doc_name, keep_empty=False)
entity_result = remove_doc_from_entity_pages(wiki_dir, doc_name, keep_empty=False)
remove_doc_from_index(
wiki_dir,
doc_name,
concept_result["deleted"],
entity_slugs_deleted=entity_result["deleted"],
)
def import_from_pageindex_cloud(doc_id: str, kb_dir: Path) -> Literal["added", "skipped", "failed"]:
"""Import an existing PageIndex Cloud document into the KB by ``doc_id``.
Fetches structure + page content from the cloud (no local PDF), compiles
concepts, and registers a raw-less ``pageindex_cloud`` entry. Idempotent:
re-importing the same ``doc_id`` is skipped. The user's cloud corpus is
never modified.
"""
import hashlib
from openkb.state import HashRegistry
logger = logging.getLogger(__name__)
openkb_dir = kb_dir / ".openkb"
config = resolve_effective_config(kb_dir)[0]
_setup_llm_key(kb_dir)
model: str = config.get("model", DEFAULT_CONFIG["model"])
path_key = f"pageindex-cloud:{doc_id}"
synthetic_hash = hashlib.sha256(path_key.encode("utf-8")).hexdigest()
with kb_ingest_lock(kb_dir / ".openkb"):
registry = HashRegistry(openkb_dir / "hashes.json")
if registry.is_known(synthetic_hash):
click.echo(f" [SKIP] Already imported from PageIndex Cloud: {doc_id}")
return "skipped"
click.echo(f"Importing from PageIndex Cloud: {doc_id}")
doc_name = ""
from openkb.add_coordinator import AddMutationPlan, DirtyRollbackError, run_add_mutation
try:
try:
cloud = prepare_cloud_import(doc_id, kb_dir, path_key)
except Exception as exc:
click.echo(f" [ERROR] Import failed: {exc}")
logger.debug("Cloud import traceback:", exc_info=True)
return "failed"
with kb_ingest_lock(kb_dir / ".openkb"):
registry = HashRegistry(openkb_dir / "hashes.json")
if registry.is_known(synthetic_hash):
click.echo(f" [SKIP] Already imported from PageIndex Cloud: {doc_id}")
return "skipped"
stem = _cloud_display_stem(cloud.cloud_name, doc_id)
doc_name = resolve_doc_name_from_key(stem, path_key, registry)
def commit_body(_snapshot) -> None:
summary_path = _write_long_doc_artifacts(
cloud.tree,
cloud.all_pages,
doc_name,
doc_id,
kb_dir,
description=cloud.description,
)
_run_compile_with_retry(
lambda: compile_long_doc(
doc_name,
summary_path,
doc_id,
kb_dir,
model,
doc_description=cloud.description,
max_concurrency=resolve_concurrency(config) or DEFAULT_COMPILE_CONCURRENCY,
),
label=f"Compiling imported doc (doc_id={doc_id})",
)
# Register the raw-less cloud entry only after successful compilation.
registry = HashRegistry(openkb_dir / "hashes.json")
meta = {
"name": cloud.cloud_name,
"doc_name": doc_name,
"type": "pageindex_cloud",
"origin": "cloud",
"path": path_key,
"source_path": _registry_path(
kb_dir / "wiki" / "sources" / f"{doc_name}.json", kb_dir
),
"doc_id": doc_id,
}
registry.remove_by_doc_name(doc_name)
registry.add(synthetic_hash, meta)
def append_cloud_log() -> None:
append_log(kb_dir / "wiki", "ingest", doc_name)
plan = AddMutationPlan(
operation="cloud_import",
details={"doc_id": doc_id, "doc_name": doc_name},
touched_paths=_snapshot_add_paths(kb_dir, doc_name, None, None),
body=commit_body,
post_commit_hooks=[append_cloud_log],
# Cloud import reads from PageIndex Cloud and writes no local blob,
# so .openkb/files is never touched — nothing to snapshot there.
hardlink_dirs={
kb_dir / "wiki" / "concepts",
kb_dir / "wiki" / "entities",
},
)
if not run_add_mutation(kb_dir, plan):
return "failed"
except DirtyRollbackError:
raise
except Exception as exc:
# run_add_mutation handles snapshot/body failures itself (returns False),
# so this except only catches pre-mutation errors — surface the real cause
# instead of the old misleading "Failed to prepare mutation snapshot" label.
click.echo(f" [ERROR] Cloud import failed for {doc_id}: {exc}")
logger.debug("Cloud import mutation traceback:", exc_info=True)
return "failed"
click.echo(f" [OK] {doc_name} imported from PageIndex Cloud.")
return "added"
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
@click.group()
@click.version_option(package_name="openkb", prog_name="openkb", message="%(prog)s %(version)s")
@click.option("-v", "--verbose", is_flag=True, default=False, help="Enable verbose logging.")
@click.option(
"--kb-dir",
"kb_dir_override",
default=None,
type=click.Path(exists=True, file_okay=False, resolve_path=True),
help="Path to a KB root directory (overrides auto-detection).",
)
@click.pass_context
def cli(ctx, verbose, kb_dir_override):
"""OpenKB — Karpathy's LLM Knowledge Base workflow, powered by PageIndex."""
logging.basicConfig(
format="%(name)s %(levelname)s: %(message)s",
level=logging.WARNING,
)
if verbose:
logging.getLogger("openkb").setLevel(logging.DEBUG)
ctx.ensure_object(dict)
if kb_dir_override:
ctx.obj["kb_dir_override"] = Path(kb_dir_override)
else:
env_kb = os.environ.get("OPENKB_DIR")
if env_kb:
ctx.obj["kb_dir_override"] = Path(env_kb).resolve()
else:
ctx.obj["kb_dir_override"] = None
def _with_kb_lock(*, exclusive: bool):
"""Wrap a Click command in the appropriate KB lock when a KB exists."""
def decorator(fn):
@wraps(fn)
def wrapper(ctx, *args, **kwargs):
kb_dir = _find_kb_dir(ctx.obj.get("kb_dir_override"))
if kb_dir is None:
return fn(ctx, *args, **kwargs)
if exclusive:
with kb_ingest_lock(kb_dir / ".openkb"):
return fn(ctx, *args, **kwargs)
with kb_read_lock(kb_dir / ".openkb"):
return fn(ctx, *args, **kwargs)
return wrapper
return decorator
@cli.command()
@click.argument("path", default=".")
def use(path):
"""Set PATH as the default knowledge base."""
target = Path(path).resolve()
if not (target / ".openkb").is_dir():
click.echo(f"Not a knowledge base: {target}")
return
register_kb(target)
click.echo(f"Default KB set to: {target}")
_LANGUAGE_MAX_LEN = 50
_MODEL_MAX_LEN = 100
def _coerce_language(value: str | None) -> str | None:
"""Strip a language string; treat blanks as unset; reject unsafe values.
The language string is interpolated into LLM system prompts (see
``_SYSTEM_TEMPLATE`` in ``openkb/agent/compiler.py`` and the query agent's
instructions), so values with newlines or excessive length would let an
external caller smuggle instructions into the prompt. Capping at
``_LANGUAGE_MAX_LEN`` and rejecting control characters is enough to close
that vector while still allowing common forms ("en", "ko", "Korean",
"Simplified Chinese").
Returns the cleaned string, or ``None`` if the input was missing or blank
after stripping. Raises ``click.BadParameter`` on unsafe input.
"""
if value is None:
return None
value = value.strip()
if not value:
return None
if len(value) > _LANGUAGE_MAX_LEN or any(c in value for c in "\n\r\t"):
raise click.BadParameter(
f"language must be {_LANGUAGE_MAX_LEN} characters or fewer with no control characters",
param_hint="'--language'",
)
return value
def _language_option_callback(_ctx, _param, value):
return _coerce_language(value)
def _coerce_model(value: str | None) -> str | None:
"""Strip a model string; treat blanks as unset; reject unsafe values.
Mirrors ``_coerce_language``. The model string is passed to LiteLLM and
also echoed in logs/CLI output, so embedded control characters would
corrupt that output. Capping length keeps pathological values out of
config.yaml.
Returns the cleaned string, or ``None`` if the input was missing or blank
after stripping. Raises ``click.BadParameter`` on unsafe input.
"""
if value is None:
return None
value = value.strip()
if not value:
return None
if len(value) > _MODEL_MAX_LEN or any(c in value for c in "\n\r\t"):
raise click.BadParameter(
f"model must be {_MODEL_MAX_LEN} characters or fewer with no control characters",
param_hint="'--model'",
)
return value
def _model_option_callback(_ctx, _param, value):
return _coerce_model(value)
def _stdin_is_tty() -> bool:
"""Return True when stdin is a real terminal.
Used to skip optional ``openkb init`` prompts when input is piped or
redirected, so existing automation (e.g. ``printf '\\n\\n' | openkb init``)
keeps working as new prompts are added. Mirrors ``_stream_to_tty`` from #45.
"""
return sys.stdin.isatty()
@cli.command()
@click.option(
"--model",
"-m",
"model",
default=None,
metavar="MODEL",
callback=_model_option_callback,
help=(
"LLM in LiteLLM provider/model format "
"(e.g. 'gpt-5.4', 'anthropic/claude-sonnet-4-6'). "
"Skips the interactive prompt when set."
),
)
@click.option(
"--language",
"-l",
"language",
default=None,
metavar="LANG",
callback=_language_option_callback,
help="Wiki output language (e.g. 'en', 'ko'). Skips the interactive prompt when set.",
)
def init(model, language):
"""Initialise a new knowledge base in the current directory."""
openkb_dir = Path(".openkb")
if openkb_dir.exists():
click.echo("Knowledge base already initialized.")
return
# Interactive prompts
click.echo("Pick an LLM in `provider/model` LiteLLM format:")
click.echo(" OpenAI: gpt-5.4, gpt-5.4-mini")
click.echo(" Anthropic: anthropic/claude-sonnet-4-6, anthropic/claude-opus-4-6")
click.echo(" Gemini: gemini/gemini-3.1-pro-preview, gemini/gemini-3-flash-preview")
click.echo(" DeepSeek: deepseek/deepseek-v4-flash, deepseek/deepseek-v4-pro")
click.echo(" Others: see https://docs.litellm.ai/docs/providers")
click.echo()