lightrag-cli 1.5.9rc1__py3-none-any.whl

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.
lightrag_cli/cli.py ADDED
@@ -0,0 +1,763 @@
1
+ """JSON-emitting CLI for ``lightrag-server`` (console script ``lightrag``).
2
+
3
+ All command outputs are printed as one JSON document on ``stdout``; errors go
4
+ to ``stderr`` with non-zero exit codes (``2`` for configuration or input
5
+ validation errors before any request is sent, ``1`` for upstream API or
6
+ connection errors, including partial multi-file upload failures).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import asyncio
13
+ import codecs
14
+ from dataclasses import dataclass
15
+ import json
16
+ import os
17
+ import sys
18
+ import time
19
+ from typing import Any, Awaitable, Callable, Mapping, Sequence, TextIO
20
+
21
+ from lightrag_cli._version import __version__
22
+ from lightrag_cli.client import (
23
+ DEFAULT_SERVER_URL,
24
+ DEFAULT_TIMEOUT_SECONDS,
25
+ DOC_STATUSES,
26
+ QUERY_MODES,
27
+ RETRIEVE_MODES,
28
+ SORT_DIRECTIONS,
29
+ SORT_FIELDS,
30
+ LightRAGAPIError,
31
+ LightRAGClient,
32
+ LightRAGClientConfig,
33
+ LightRAGConfigError,
34
+ LightRAGConnectionError,
35
+ LightRAGValidationError,
36
+ validate_upload_path,
37
+ )
38
+ from lightrag_cli import views
39
+
40
+ # A ``--wait`` that ran out of time; the last state observed is still printed.
41
+ EXIT_WAIT_TIMEOUT = 3
42
+ DEFAULT_WAIT_INTERVAL_SECONDS = 5.0
43
+ # Delay before the poll that confirms an idle pipeline (capped by --interval).
44
+ IDLE_CONFIRM_SECONDS = 2.0
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class DispatchOutcome:
49
+ """Result payload and process exit code produced by a CLI command."""
50
+
51
+ payload: Any
52
+ exit_code: int = 0
53
+
54
+
55
+ def _omit_none(**kwargs: Any) -> dict[str, Any]:
56
+ return {k: v for k, v in kwargs.items() if v is not None}
57
+
58
+
59
+ def _parse_float_env(name: str, raw: str | None, default: float) -> float:
60
+ if raw is None or not raw.strip():
61
+ return default
62
+ try:
63
+ return float(raw.strip())
64
+ except ValueError as exc:
65
+ raise LightRAGConfigError(f"Invalid number for {name}: {raw!r}") from exc
66
+
67
+
68
+ def build_parser() -> argparse.ArgumentParser:
69
+ parser = argparse.ArgumentParser(
70
+ prog="lightrag",
71
+ description=(
72
+ "JSON CLI for querying and managing a running lightrag-server "
73
+ "instance. Each server instance serves one workspace; select a "
74
+ "workspace by pointing --url at the corresponding instance."
75
+ ),
76
+ )
77
+ parser.add_argument(
78
+ "--version",
79
+ action="version",
80
+ version=f"lightrag-cli {__version__}",
81
+ )
82
+ parser.add_argument(
83
+ "--url",
84
+ default=None,
85
+ help=(
86
+ f"Base URL of lightrag-server (env: LIGHTRAG_URL, "
87
+ f"default: {DEFAULT_SERVER_URL})"
88
+ ),
89
+ )
90
+ parser.add_argument(
91
+ "--api-key",
92
+ default=None,
93
+ help="X-API-Key header value (env: LIGHTRAG_API_KEY)",
94
+ )
95
+ parser.add_argument(
96
+ "--timeout",
97
+ type=float,
98
+ default=None,
99
+ help=(
100
+ f"HTTP request timeout in seconds (env: LIGHTRAG_TIMEOUT, "
101
+ f"default: {int(DEFAULT_TIMEOUT_SECONDS)})"
102
+ ),
103
+ )
104
+ parser.add_argument(
105
+ "--compact",
106
+ action="store_true",
107
+ help="Emit compact single-line JSON instead of indented JSON",
108
+ )
109
+
110
+ subparsers = parser.add_subparsers(dest="command", required=True)
111
+
112
+ # status
113
+ p_status = subparsers.add_parser(
114
+ "status",
115
+ help="Summarize server version, models, storage, document counts and pipeline",
116
+ )
117
+ _add_full_flag(p_status)
118
+
119
+ # pipeline
120
+ p_pipe = subparsers.add_parser(
121
+ "pipeline",
122
+ help="Show what the indexing pipeline is doing and what blocks an enqueue",
123
+ )
124
+ p_pipe.add_argument(
125
+ "--history",
126
+ type=int,
127
+ default=None,
128
+ metavar="N",
129
+ help="Include the last N pipeline history messages",
130
+ )
131
+ _add_full_flag(p_pipe)
132
+ _add_wait_flags(p_pipe, "until the pipeline is idle (exit 1 if it is fenced)")
133
+
134
+ # query
135
+ p_query = subparsers.add_parser(
136
+ "query",
137
+ help="Query LightRAG and return a synthesized answer with references",
138
+ )
139
+ p_query.add_argument("query", help="Question to answer")
140
+ p_query.add_argument(
141
+ "--mode", choices=QUERY_MODES, default=None, help="Retrieval mode"
142
+ )
143
+ p_query.add_argument("--top-k", type=int, default=None)
144
+ p_query.add_argument("--chunk-top-k", type=int, default=None)
145
+ p_query.add_argument("--response-type", default=None)
146
+ p_query.add_argument(
147
+ "--hl-keyword",
148
+ dest="hl_keywords",
149
+ action="append",
150
+ default=None,
151
+ help="High-level keyword (repeatable)",
152
+ )
153
+ p_query.add_argument(
154
+ "--ll-keyword",
155
+ dest="ll_keywords",
156
+ action="append",
157
+ default=None,
158
+ help="Low-level entity keyword (repeatable)",
159
+ )
160
+ p_query.add_argument("--user-prompt", default=None)
161
+ p_query.add_argument(
162
+ "--enable-rerank", action=argparse.BooleanOptionalAction, default=None
163
+ )
164
+ p_query.add_argument(
165
+ "--include-references", action=argparse.BooleanOptionalAction, default=None
166
+ )
167
+ p_query.add_argument(
168
+ "--include-chunk-content", action=argparse.BooleanOptionalAction, default=None
169
+ )
170
+ p_query.add_argument("--max-total-tokens", type=int, default=None)
171
+
172
+ # retrieve (/query/data)
173
+ p_ret = subparsers.add_parser(
174
+ "retrieve",
175
+ help="Retrieve raw entities, relationships, chunks, and references (/query/data)",
176
+ )
177
+ p_ret.add_argument("query", help="Retrieval query")
178
+ p_ret.add_argument(
179
+ "--mode", choices=RETRIEVE_MODES, default=None, help="Retrieval mode"
180
+ )
181
+ p_ret.add_argument("--top-k", type=int, default=None)
182
+ p_ret.add_argument("--chunk-top-k", type=int, default=None)
183
+ p_ret.add_argument(
184
+ "--hl-keyword", dest="hl_keywords", action="append", default=None
185
+ )
186
+ p_ret.add_argument(
187
+ "--ll-keyword", dest="ll_keywords", action="append", default=None
188
+ )
189
+ p_ret.add_argument(
190
+ "--enable-rerank", action=argparse.BooleanOptionalAction, default=None
191
+ )
192
+ p_ret.add_argument("--max-entity-tokens", type=int, default=None)
193
+ p_ret.add_argument("--max-relation-tokens", type=int, default=None)
194
+ p_ret.add_argument("--max-total-tokens", type=int, default=None)
195
+
196
+ # graph
197
+ p_graph = subparsers.add_parser("graph", help="Inspect the knowledge graph")
198
+ graph_sub = p_graph.add_subparsers(dest="graph_command", required=True)
199
+
200
+ p_gsearch = graph_sub.add_parser(
201
+ "search", help="Fuzzy-search entity labels in the knowledge graph"
202
+ )
203
+ p_gsearch.add_argument("query", help="Partial or full entity label")
204
+ p_gsearch.add_argument("--limit", type=int, default=None)
205
+
206
+ p_gsub = graph_sub.add_parser(
207
+ "subgraph", help="Fetch a connected subgraph around an entity label"
208
+ )
209
+ p_gsub.add_argument("label", help="Starting entity label")
210
+ p_gsub.add_argument("--max-depth", type=int, default=None)
211
+ p_gsub.add_argument("--max-nodes", type=int, default=None)
212
+
213
+ # documents
214
+ p_docs = subparsers.add_parser(
215
+ "documents", help="List, track, insert, or upload documents"
216
+ )
217
+ docs_sub = p_docs.add_subparsers(dest="documents_command", required=True)
218
+
219
+ p_dlist = docs_sub.add_parser("list", help="List indexed documents")
220
+ p_dlist.add_argument("--page", type=int, default=None)
221
+ p_dlist.add_argument("--page-size", type=int, default=None)
222
+ p_dlist.add_argument(
223
+ "--status",
224
+ dest="status_filters",
225
+ action="append",
226
+ choices=DOC_STATUSES,
227
+ default=None,
228
+ help="Filter by document status (repeatable)",
229
+ )
230
+ p_dlist.add_argument("--sort-field", choices=SORT_FIELDS, default=None)
231
+ p_dlist.add_argument("--sort-direction", choices=SORT_DIRECTIONS, default=None)
232
+
233
+ p_dstatus = docs_sub.add_parser("status", help="Track ingestion status by track_id")
234
+ p_dstatus.add_argument("track_id", help="Tracking ID returned by insert/upload")
235
+ _add_full_flag(p_dstatus)
236
+ _add_wait_flags(
237
+ p_dstatus, "until every document is processed or failed (exit 1 if any failed)"
238
+ )
239
+
240
+ p_dfailed = docs_sub.add_parser(
241
+ "failed", help="List failed documents with their error messages"
242
+ )
243
+ p_dfailed.add_argument("--page", type=int, default=None)
244
+ p_dfailed.add_argument("--page-size", type=int, default=None)
245
+ _add_full_flag(p_dfailed)
246
+
247
+ docs_sub.add_parser(
248
+ "types", help="Show the file types and parser engines the server accepts"
249
+ )
250
+
251
+ p_dtext = docs_sub.add_parser(
252
+ "insert-text",
253
+ help="Insert text for asynchronous indexing (pass '-' to read stdin)",
254
+ )
255
+ p_dtext.add_argument(
256
+ "text",
257
+ help="Text content to index, or '-' to read UTF-8 text from stdin",
258
+ )
259
+ p_dtext.add_argument(
260
+ "--file-source",
261
+ required=True,
262
+ help="Source label recorded as the document's file path (server requires it)",
263
+ )
264
+
265
+ p_dupload = docs_sub.add_parser(
266
+ "upload", help="Upload one or more local files for asynchronous indexing"
267
+ )
268
+ p_dupload.add_argument(
269
+ "files", nargs="+", help="Local file path(s) to upload to /documents/upload"
270
+ )
271
+
272
+ p_ddelete = docs_sub.add_parser(
273
+ "delete",
274
+ help="Delete documents and everything indexed from them (asynchronous)",
275
+ )
276
+ p_ddelete.add_argument("doc_ids", nargs="+", metavar="doc_id")
277
+ p_ddelete.add_argument(
278
+ "--delete-file",
279
+ action="store_true",
280
+ help="Also delete the source file in the server's input directory",
281
+ )
282
+ p_ddelete.add_argument(
283
+ "--delete-llm-cache",
284
+ action="store_true",
285
+ help="Also delete the documents' cached LLM extraction results",
286
+ )
287
+ _add_yes_flag(p_ddelete)
288
+
289
+ p_dclear = docs_sub.add_parser(
290
+ "clear",
291
+ help=(
292
+ "Delete every document, the knowledge graph and the input files of "
293
+ "the server's workspace (synchronous)"
294
+ ),
295
+ )
296
+ p_dclear.add_argument(
297
+ "--delete-parsed-files",
298
+ action="store_true",
299
+ help="Also delete parsed artifacts (kept by default for re-adding files)",
300
+ )
301
+ p_dclear.add_argument(
302
+ "--clear-llm-cache",
303
+ action="store_true",
304
+ help="Also drop the whole LLM response cache (only when every storage drop succeeds)",
305
+ )
306
+ _add_yes_flag(p_dclear)
307
+
308
+ return parser
309
+
310
+
311
+ def _add_yes_flag(parser: argparse.ArgumentParser) -> None:
312
+ parser.add_argument(
313
+ "--yes",
314
+ action="store_true",
315
+ help="Required: confirm the deletion (there is no interactive prompt)",
316
+ )
317
+
318
+
319
+ def _require_yes(args: argparse.Namespace) -> None:
320
+ if not args.yes:
321
+ raise LightRAGValidationError(
322
+ f"documents {args.documents_command} deletes data and needs --yes; "
323
+ "nothing was sent"
324
+ )
325
+
326
+
327
+ def _add_full_flag(parser: argparse.ArgumentParser) -> None:
328
+ parser.add_argument(
329
+ "--full",
330
+ action="store_true",
331
+ help="Print the server's raw response instead of the compact view",
332
+ )
333
+
334
+
335
+ def _add_wait_flags(parser: argparse.ArgumentParser, what: str) -> None:
336
+ parser.add_argument("--wait", action="store_true", help=f"Poll {what}")
337
+ parser.add_argument(
338
+ "--interval",
339
+ type=float,
340
+ default=None,
341
+ metavar="SECONDS",
342
+ help=f"Seconds between polls (default {DEFAULT_WAIT_INTERVAL_SECONDS:g})",
343
+ )
344
+ parser.add_argument(
345
+ "--wait-timeout",
346
+ type=float,
347
+ default=None,
348
+ metavar="SECONDS",
349
+ help=f"Give up after this many seconds with exit {EXIT_WAIT_TIMEOUT} "
350
+ "(default: no limit)",
351
+ )
352
+
353
+
354
+ def resolve_client_config(
355
+ args: argparse.Namespace,
356
+ env: Mapping[str, str] | None = None,
357
+ ) -> LightRAGClientConfig:
358
+ """Resolve CLI flags and environment variables into ``LightRAGClientConfig``."""
359
+ environ = os.environ if env is None else env
360
+ # An explicit --url, even an empty one (``--url "$UNSET"``), wins and is
361
+ # validated: falling back would send writes to a server nobody named.
362
+ base_url = (
363
+ args.url
364
+ if args.url is not None
365
+ else environ.get("LIGHTRAG_URL") or DEFAULT_SERVER_URL
366
+ )
367
+ api_key = (
368
+ args.api_key if args.api_key is not None else environ.get("LIGHTRAG_API_KEY")
369
+ )
370
+ timeout = (
371
+ args.timeout
372
+ if args.timeout is not None
373
+ else _parse_float_env(
374
+ "LIGHTRAG_TIMEOUT",
375
+ environ.get("LIGHTRAG_TIMEOUT"),
376
+ DEFAULT_TIMEOUT_SECONDS,
377
+ )
378
+ )
379
+ return LightRAGClientConfig(
380
+ base_url=base_url,
381
+ api_key=api_key,
382
+ timeout_seconds=timeout,
383
+ )
384
+
385
+
386
+ Sleep = Callable[[float], Awaitable[Any]]
387
+ Clock = Callable[[], float]
388
+
389
+
390
+ @dataclass(frozen=True)
391
+ class _WaitPlan:
392
+ interval: float
393
+ deadline: float | None
394
+
395
+
396
+ def _wait_plan(args: argparse.Namespace, clock: Clock) -> _WaitPlan | None:
397
+ """Validate the wait flags before anything is sent; ``None`` = no wait."""
398
+ if not getattr(args, "wait", False):
399
+ if args.interval is not None or args.wait_timeout is not None:
400
+ raise LightRAGValidationError("--interval and --wait-timeout need --wait")
401
+ return None
402
+ interval = DEFAULT_WAIT_INTERVAL_SECONDS if args.interval is None else args.interval
403
+ if not interval > 0:
404
+ raise LightRAGValidationError("--interval must be > 0")
405
+ if args.wait_timeout is not None and not args.wait_timeout > 0:
406
+ raise LightRAGValidationError("--wait-timeout must be > 0")
407
+ deadline = None if args.wait_timeout is None else clock() + args.wait_timeout
408
+ return _WaitPlan(interval=interval, deadline=deadline)
409
+
410
+
411
+ _WAIT_EXPIRED = object()
412
+
413
+
414
+ async def _fetch_within(
415
+ plan: _WaitPlan, clock: Clock, fetch: Callable[[], Awaitable[Any]]
416
+ ) -> Any:
417
+ """Run one poll, cut short at the wait deadline (``_WAIT_EXPIRED``)."""
418
+ if plan.deadline is None:
419
+ return await fetch()
420
+ remaining = plan.deadline - clock()
421
+ if remaining <= 0:
422
+ return _WAIT_EXPIRED
423
+ try:
424
+ return await asyncio.wait_for(fetch(), remaining)
425
+ except asyncio.TimeoutError:
426
+ return _WAIT_EXPIRED
427
+
428
+
429
+ def _wait_expired(stderr: TextIO, payload: Any) -> DispatchOutcome:
430
+ _progress(stderr, "gave up waiting (--wait-timeout)")
431
+ return DispatchOutcome(payload, exit_code=EXIT_WAIT_TIMEOUT)
432
+
433
+
434
+ def _progress(stream: TextIO, line: str) -> None:
435
+ print(f"lightrag: {line}", file=stream, flush=True)
436
+
437
+
438
+ def _pipeline_line(raw: Mapping[str, Any]) -> str:
439
+ if views.pipeline_is_idle(raw):
440
+ return "pipeline idle"
441
+ gates = [k for k in ("scanning", "destructive_busy") if raw.get(k)] + (
442
+ ["pending_enqueues"] if (raw.get("pending_enqueues") or 0) > 0 else []
443
+ )
444
+ batch = f"batch {raw.get('cur_batch')}/{raw.get('batchs')}"
445
+ extra = f" [{', '.join(gates)}]" if gates else ""
446
+ return (
447
+ f"pipeline busy: {raw.get('job_name')} {batch}{extra}: "
448
+ f"{raw.get('latest_message') or ''}"
449
+ ).rstrip(": ")
450
+
451
+
452
+ def _track_line(raw: Mapping[str, Any]) -> str:
453
+ summary = raw.get("status_summary") or {}
454
+ counts = (
455
+ ", ".join(f"{k} {v}" for k, v in sorted(summary.items())) or "no documents yet"
456
+ )
457
+ return f"track {raw.get('track_id')}: {counts}"
458
+
459
+
460
+ async def _pipeline_command(
461
+ client: LightRAGClient,
462
+ args: argparse.Namespace,
463
+ plan: _WaitPlan | None,
464
+ *,
465
+ stderr: TextIO,
466
+ sleep: Sleep,
467
+ clock: Clock,
468
+ ) -> DispatchOutcome:
469
+ def render(raw: Mapping[str, Any]) -> Any:
470
+ return raw if args.full else views.pipeline_view(raw, history=args.history)
471
+
472
+ if plan is None:
473
+ return DispatchOutcome(render(await client.get_pipeline_status()))
474
+ fetch = lambda: client.get_pipeline_status() # noqa: E731
475
+ raw = await _fetch_within(plan, clock, fetch)
476
+ if raw is _WAIT_EXPIRED:
477
+ # Nothing was observed before the deadline: there is no state to show.
478
+ return _wait_expired(stderr, None)
479
+ idle_seen = False
480
+ while True:
481
+ _progress(stderr, _pipeline_line(raw))
482
+ if views.pipeline_is_fenced(raw):
483
+ _progress(stderr, "workspace is fenced pending recovery; not waiting")
484
+ return DispatchOutcome(render(raw), exit_code=1)
485
+ if views.pipeline_is_idle(raw):
486
+ # An enqueue can leave the pipeline idle for a moment before
487
+ # processing starts: idle must hold on two consecutive polls. The
488
+ # confirming poll comes after a short fixed delay, not a full
489
+ # --interval, so an idle pipeline answers in about two seconds.
490
+ if idle_seen:
491
+ return DispatchOutcome(render(raw))
492
+ idle_seen = True
493
+ else:
494
+ idle_seen = False
495
+ delay = min(plan.interval, IDLE_CONFIRM_SECONDS) if idle_seen else plan.interval
496
+ if plan.deadline is not None and clock() + delay > plan.deadline:
497
+ return _wait_expired(stderr, render(raw))
498
+ await sleep(delay)
499
+ latest = await _fetch_within(plan, clock, fetch)
500
+ if latest is _WAIT_EXPIRED:
501
+ return _wait_expired(stderr, render(raw))
502
+ raw = latest
503
+
504
+
505
+ async def _track_command(
506
+ client: LightRAGClient,
507
+ args: argparse.Namespace,
508
+ plan: _WaitPlan | None,
509
+ *,
510
+ stderr: TextIO,
511
+ sleep: Sleep,
512
+ clock: Clock,
513
+ ) -> DispatchOutcome:
514
+ def render(raw: Mapping[str, Any]) -> Any:
515
+ return raw if args.full else views.track_view(raw)
516
+
517
+ if plan is None:
518
+ return DispatchOutcome(render(await client.get_track_status(args.track_id)))
519
+ fetch = lambda: client.get_track_status(args.track_id) # noqa: E731
520
+ raw = await _fetch_within(plan, clock, fetch)
521
+ if raw is _WAIT_EXPIRED:
522
+ # Nothing was observed before the deadline: there is no state to show.
523
+ return _wait_expired(stderr, None)
524
+ while True:
525
+ _progress(stderr, _track_line(raw))
526
+ if views.track_is_finished(raw):
527
+ failed = views.track_has_failures(raw)
528
+ return DispatchOutcome(render(raw), exit_code=1 if failed else 0)
529
+ if plan.deadline is not None and clock() + plan.interval > plan.deadline:
530
+ return _wait_expired(stderr, render(raw))
531
+ await sleep(plan.interval)
532
+ latest = await _fetch_within(plan, clock, fetch)
533
+ if latest is _WAIT_EXPIRED:
534
+ return _wait_expired(stderr, render(raw))
535
+ raw = latest
536
+
537
+
538
+ async def dispatch_command(
539
+ client: LightRAGClient,
540
+ args: argparse.Namespace,
541
+ *,
542
+ stdin: TextIO | None = None,
543
+ stderr: TextIO | None = None,
544
+ sleep: Sleep = asyncio.sleep,
545
+ clock: Clock = time.monotonic,
546
+ ) -> DispatchOutcome:
547
+ """Execute the parsed CLI subcommand against ``client``."""
548
+ cmd = args.command
549
+ err = stderr or sys.stderr
550
+ if cmd == "status":
551
+ raw = await client.status()
552
+ if args.full:
553
+ return DispatchOutcome(raw)
554
+ return DispatchOutcome(
555
+ views.status_view(
556
+ raw["health"],
557
+ raw["status_counts"],
558
+ raw["pipeline"],
559
+ client_version=__version__,
560
+ )
561
+ )
562
+
563
+ if cmd == "pipeline":
564
+ if args.history is not None and args.history < 1:
565
+ raise LightRAGValidationError("--history must be >= 1")
566
+ plan = _wait_plan(args, clock)
567
+ return await _pipeline_command(
568
+ client, args, plan, stderr=err, sleep=sleep, clock=clock
569
+ )
570
+
571
+ if cmd == "query":
572
+ kwargs = _omit_none(
573
+ mode=args.mode,
574
+ top_k=args.top_k,
575
+ chunk_top_k=args.chunk_top_k,
576
+ response_type=args.response_type,
577
+ hl_keywords=args.hl_keywords,
578
+ ll_keywords=args.ll_keywords,
579
+ user_prompt=args.user_prompt,
580
+ enable_rerank=args.enable_rerank,
581
+ include_references=args.include_references,
582
+ include_chunk_content=args.include_chunk_content,
583
+ max_total_tokens=args.max_total_tokens,
584
+ )
585
+ return DispatchOutcome(await client.query(args.query, **kwargs))
586
+
587
+ if cmd == "retrieve":
588
+ kwargs = _omit_none(
589
+ mode=args.mode,
590
+ top_k=args.top_k,
591
+ chunk_top_k=args.chunk_top_k,
592
+ hl_keywords=args.hl_keywords,
593
+ ll_keywords=args.ll_keywords,
594
+ enable_rerank=args.enable_rerank,
595
+ max_entity_tokens=args.max_entity_tokens,
596
+ max_relation_tokens=args.max_relation_tokens,
597
+ max_total_tokens=args.max_total_tokens,
598
+ )
599
+ return DispatchOutcome(await client.retrieve(args.query, **kwargs))
600
+
601
+ if cmd == "graph":
602
+ if args.graph_command == "search":
603
+ kwargs = _omit_none(limit=args.limit)
604
+ labels = await client.search_graph_labels(args.query, **kwargs)
605
+ return DispatchOutcome(
606
+ {"query": args.query.strip(), "count": len(labels), "labels": labels}
607
+ )
608
+ if args.graph_command == "subgraph":
609
+ kwargs = _omit_none(
610
+ max_depth=args.max_depth,
611
+ max_nodes=args.max_nodes,
612
+ )
613
+ return DispatchOutcome(
614
+ await client.get_knowledge_graph(args.label, **kwargs)
615
+ )
616
+
617
+ if cmd == "documents":
618
+ sub = args.documents_command
619
+ if sub == "list":
620
+ kwargs = _omit_none(
621
+ page=args.page,
622
+ page_size=args.page_size,
623
+ status_filters=args.status_filters,
624
+ sort_field=args.sort_field,
625
+ sort_direction=args.sort_direction,
626
+ )
627
+ return DispatchOutcome(await client.list_documents(**kwargs))
628
+ if sub == "status":
629
+ plan = _wait_plan(args, clock)
630
+ return await _track_command(
631
+ client, args, plan, stderr=err, sleep=sleep, clock=clock
632
+ )
633
+ if sub == "failed":
634
+ kwargs = _omit_none(page=args.page, page_size=args.page_size)
635
+ raw = await client.list_documents(status_filters=["failed"], **kwargs)
636
+ return DispatchOutcome(raw if args.full else views.failed_view(raw))
637
+ if sub == "types":
638
+ return DispatchOutcome(await client.get_supported_file_types())
639
+ if sub == "insert-text":
640
+ text = (
641
+ _read_stdin_text(stdin or sys.stdin) if args.text == "-" else args.text
642
+ )
643
+ return DispatchOutcome(
644
+ await client.insert_text(text, file_source=args.file_source)
645
+ )
646
+ if sub == "upload":
647
+ # Validate every local file before sending the first request.
648
+ paths = [validate_upload_path(p) for p in args.files]
649
+ if len(paths) == 1:
650
+ return DispatchOutcome(await client.upload_file(paths[0]))
651
+ results: list[dict[str, Any]] = []
652
+ had_error = False
653
+ for raw_path, path in zip(args.files, paths):
654
+ try:
655
+ response = await client.upload_file(path)
656
+ except (
657
+ LightRAGAPIError,
658
+ LightRAGConnectionError,
659
+ # A file that became unreadable or vanished after the
660
+ # pre-flight check: earlier files are already sent.
661
+ LightRAGValidationError,
662
+ ) as exc:
663
+ had_error = True
664
+ results.append({"file": raw_path, "error": str(exc)})
665
+ else:
666
+ results.append({"file": raw_path, "response": response})
667
+ return DispatchOutcome(
668
+ payload={"results": results},
669
+ exit_code=1 if had_error else 0,
670
+ )
671
+ if sub == "delete":
672
+ _require_yes(args)
673
+ raw = await client.delete_documents(
674
+ args.doc_ids,
675
+ delete_file=args.delete_file,
676
+ delete_llm_cache=args.delete_llm_cache,
677
+ )
678
+ # HTTP 200 also carries a refusal (busy, not_allowed).
679
+ started = raw.get("status") == "deletion_started"
680
+ return DispatchOutcome(raw, exit_code=0 if started else 1)
681
+ if sub == "clear":
682
+ _require_yes(args)
683
+ raw = await client.clear_documents(
684
+ delete_parsed_files=args.delete_parsed_files,
685
+ clear_llm_cache=args.clear_llm_cache,
686
+ # Only an explicit --timeout limits a clear: LIGHTRAG_TIMEOUT
687
+ # and the default are for ordinary requests.
688
+ timeout_seconds=args.timeout,
689
+ )
690
+ done = raw.get("status") == "success"
691
+ return DispatchOutcome(raw, exit_code=0 if done else 1)
692
+
693
+ raise LightRAGValidationError(f"Unsupported command: {cmd}")
694
+
695
+
696
+ def _read_stdin_text(stream: TextIO) -> str:
697
+ """Read piped text as UTF-8, whatever the locale's stdin encoding.
698
+
699
+ A leading BOM is dropped. Invalid UTF-8 is rejected before anything is
700
+ sent rather than indexed as mojibake.
701
+ """
702
+ raw = getattr(stream, "buffer", None)
703
+ if raw is None: # an in-memory text stream: already decoded
704
+ return stream.read()
705
+ try:
706
+ return raw.read().decode("utf-8-sig")
707
+ except UnicodeDecodeError as exc:
708
+ raise LightRAGValidationError(f"stdin is not valid UTF-8: {exc}") from exc
709
+
710
+
711
+ def _emit_json(payload: Any, *, compact: bool) -> None:
712
+ """Print ``payload`` as one JSON document, whatever ``stdout``'s encoding.
713
+
714
+ Non-ASCII text is kept readable when ``stdout`` is UTF-8; on any other
715
+ encoding (a cp1252 or ASCII pipe) it is ASCII-escaped, which is still the
716
+ same JSON: the output stays valid UTF-8 for a JSON consumer, and a
717
+ completed write is never lost to a ``UnicodeEncodeError``.
718
+ """
719
+ dump_kwargs: dict[str, Any] = (
720
+ {"separators": (",", ":")} if compact else {"indent": 2}
721
+ )
722
+ encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
723
+ try:
724
+ utf8 = codecs.lookup(encoding).name == "utf-8"
725
+ except LookupError:
726
+ utf8 = False
727
+ print(json.dumps(payload, ensure_ascii=not utf8, **dump_kwargs))
728
+
729
+
730
+ async def _run(
731
+ config: LightRAGClientConfig, args: argparse.Namespace
732
+ ) -> DispatchOutcome:
733
+ async with LightRAGClient(config) as client:
734
+ return await dispatch_command(client, args)
735
+
736
+
737
+ def main(
738
+ argv: Sequence[str] | None = None,
739
+ *,
740
+ env: Mapping[str, str] | None = None,
741
+ ) -> int:
742
+ """Entry point for the ``lightrag`` console script."""
743
+ parser = build_parser()
744
+ args = parser.parse_args(list(argv) if argv is not None else None)
745
+
746
+ try:
747
+ config = resolve_client_config(args, env=env)
748
+ outcome = asyncio.run(_run(config, args))
749
+ except (LightRAGConfigError, LightRAGValidationError) as exc:
750
+ print(f"lightrag error: {exc}", file=sys.stderr)
751
+ return 2
752
+ except (LightRAGAPIError, LightRAGConnectionError) as exc:
753
+ print(f"lightrag error: {exc}", file=sys.stderr)
754
+ return 1
755
+ except KeyboardInterrupt:
756
+ return 130
757
+
758
+ _emit_json(outcome.payload, compact=args.compact)
759
+ return outcome.exit_code
760
+
761
+
762
+ if __name__ == "__main__":
763
+ raise SystemExit(main())