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/client.py ADDED
@@ -0,0 +1,585 @@
1
+ """Thin async REST client for ``lightrag-server``.
2
+
3
+ Targets one server instance (and therefore one workspace, per
4
+ ``docs/design/ServerInstanceContract.md``) via ``base_url`` and authenticates
5
+ with ``X-API-Key``. Keeps runtime imports restricted to the standard library
6
+ and ``aiohttp``: this package must never import ``lightrag``, so it runs where
7
+ only the ``lightrag-cli`` distribution is installed.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import math
14
+ import mimetypes
15
+ from dataclasses import dataclass, field
16
+ from pathlib import Path
17
+ from typing import Any, Sequence
18
+ from urllib.parse import quote, urlparse
19
+
20
+ import aiohttp
21
+
22
+ from lightrag_cli._version import __version__
23
+
24
+ DEFAULT_SERVER_URL = "http://127.0.0.1:9621"
25
+ DEFAULT_TIMEOUT_SECONDS = 120.0
26
+ _ERROR_BODY_PREVIEW_CHARS = 500
27
+
28
+ QUERY_MODES: tuple[str, ...] = (
29
+ "local",
30
+ "global",
31
+ "hybrid",
32
+ "naive",
33
+ "mix",
34
+ "bypass",
35
+ )
36
+ RETRIEVE_MODES: tuple[str, ...] = ("local", "global", "hybrid", "naive", "mix")
37
+ # Mirrors DocStatus in lightrag/base.py, excluding deprecated "preprocessed".
38
+ DOC_STATUSES: tuple[str, ...] = (
39
+ "pending",
40
+ "parsing",
41
+ "analyzing",
42
+ "processing",
43
+ "processed",
44
+ "failed",
45
+ "deleting",
46
+ )
47
+ SORT_FIELDS: tuple[str, ...] = ("created_at", "updated_at", "id", "file_path")
48
+ SORT_DIRECTIONS: tuple[str, ...] = ("asc", "desc")
49
+
50
+
51
+ class LightRAGConfigError(ValueError):
52
+ """Raised when client configuration is invalid."""
53
+
54
+
55
+ class LightRAGValidationError(ValueError):
56
+ """Raised when an API call receives invalid arguments."""
57
+
58
+
59
+ class LightRAGConnectionError(RuntimeError):
60
+ """Raised when ``lightrag-server`` cannot be reached or times out."""
61
+
62
+
63
+ class LightRAGAPIError(RuntimeError):
64
+ """Raised when ``lightrag-server`` returns an error status or invalid JSON."""
65
+
66
+ def __init__(self, status: int, detail: str, path: str) -> None:
67
+ self.status = status
68
+ self.detail = detail
69
+ self.path = path
70
+ super().__init__(f"LightRAG API {path} returned HTTP {status}: {detail}")
71
+
72
+
73
+ # ``_request``'s default: the configured per-request timeout.
74
+ _CONFIG_TIMEOUT = object()
75
+
76
+
77
+ def _validate_base_url(url: str) -> str:
78
+ if not isinstance(url, str) or not url.strip():
79
+ raise LightRAGConfigError("base_url must be a non-empty http(s) URL")
80
+ cleaned = url.strip()
81
+ if any(ch.isspace() for ch in cleaned):
82
+ raise LightRAGConfigError("base_url must not contain whitespace")
83
+ try:
84
+ parsed = urlparse(cleaned)
85
+ parsed.port # noqa: B018 -- raises ValueError on a malformed port
86
+ except ValueError as exc:
87
+ raise LightRAGConfigError(f"base_url is not a valid URL: {exc}") from exc
88
+ if parsed.scheme not in ("http", "https"):
89
+ raise LightRAGConfigError(
90
+ f"base_url must use http or https scheme, got {parsed.scheme!r}"
91
+ )
92
+ if not parsed.hostname:
93
+ raise LightRAGConfigError("base_url must include a host")
94
+ if parsed.username is not None or parsed.password is not None:
95
+ raise LightRAGConfigError(
96
+ "base_url must not embed credentials; pass api_key instead"
97
+ )
98
+ if parsed.query or parsed.fragment:
99
+ raise LightRAGConfigError(
100
+ "base_url must not include a query string or fragment"
101
+ )
102
+ return cleaned.rstrip("/")
103
+
104
+
105
+ @dataclass(frozen=True)
106
+ class LightRAGClientConfig:
107
+ """Validated connection settings for a single ``lightrag-server`` instance."""
108
+
109
+ base_url: str = DEFAULT_SERVER_URL
110
+ api_key: str | None = field(default=None, repr=False)
111
+ timeout_seconds: float = DEFAULT_TIMEOUT_SECONDS
112
+
113
+ def __post_init__(self) -> None:
114
+ object.__setattr__(self, "base_url", _validate_base_url(self.base_url))
115
+
116
+ if self.api_key is not None:
117
+ if not isinstance(self.api_key, str):
118
+ raise LightRAGConfigError("api_key must be a string")
119
+ object.__setattr__(self, "api_key", self.api_key.strip() or None)
120
+
121
+ if (
122
+ isinstance(self.timeout_seconds, bool)
123
+ or not isinstance(self.timeout_seconds, (int, float))
124
+ or not math.isfinite(self.timeout_seconds)
125
+ or self.timeout_seconds <= 0
126
+ ):
127
+ raise LightRAGConfigError(
128
+ "timeout_seconds must be a finite positive number"
129
+ )
130
+ object.__setattr__(self, "timeout_seconds", float(self.timeout_seconds))
131
+
132
+
133
+ def _require_non_empty_str(value: Any, name: str) -> str:
134
+ if not isinstance(value, str) or not value.strip():
135
+ raise LightRAGValidationError(f"'{name}' must be a non-empty string")
136
+ return value.strip()
137
+
138
+
139
+ def _optional_non_empty_str(value: Any, name: str) -> str | None:
140
+ if value is None:
141
+ return None
142
+ if not isinstance(value, str) or not value.strip():
143
+ raise LightRAGValidationError(
144
+ f"'{name}' must be a non-empty string when provided"
145
+ )
146
+ return value.strip()
147
+
148
+
149
+ def _validate_int(value: Any, name: str) -> int:
150
+ if isinstance(value, bool) or not isinstance(value, int):
151
+ raise LightRAGValidationError(f"'{name}' must be an integer")
152
+ return value
153
+
154
+
155
+ def _optional_int(value: Any, name: str) -> int | None:
156
+ if value is None:
157
+ return None
158
+ return _validate_int(value, name)
159
+
160
+
161
+ def validate_upload_path(file_path: str | Path) -> Path:
162
+ """Validate that ``file_path`` points to an existing regular file."""
163
+ path = Path(file_path)
164
+ try:
165
+ # Before Python 3.13 these raise PermissionError (e.g. under an
166
+ # unreadable directory) instead of returning False.
167
+ exists = path.exists()
168
+ is_file = exists and path.is_file()
169
+ except OSError as exc:
170
+ raise LightRAGValidationError(f"Cannot access {path}: {exc}") from exc
171
+ if not exists:
172
+ raise LightRAGValidationError(f"File not found: {path}")
173
+ if not is_file:
174
+ raise LightRAGValidationError(f"Path is not a regular file: {path}")
175
+ return path
176
+
177
+
178
+ def _optional_bool(value: Any, name: str) -> bool | None:
179
+ if value is None:
180
+ return None
181
+ if not isinstance(value, bool):
182
+ raise LightRAGValidationError(f"'{name}' must be a boolean")
183
+ return value
184
+
185
+
186
+ def _validate_enum(value: Any, name: str, choices: tuple[str, ...]) -> str:
187
+ if not isinstance(value, str) or value not in choices:
188
+ raise LightRAGValidationError(f"'{name}' must be one of: {', '.join(choices)}")
189
+ return value
190
+
191
+
192
+ def _optional_str_list(
193
+ value: Sequence[str] | None,
194
+ name: str,
195
+ *,
196
+ choices: tuple[str, ...] | None = None,
197
+ ) -> list[str] | None:
198
+ if value is None:
199
+ return None
200
+ if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
201
+ raise LightRAGValidationError(f"'{name}' must be a list of strings")
202
+ items: list[str] = []
203
+ for entry in value:
204
+ if not isinstance(entry, str) or not entry.strip():
205
+ raise LightRAGValidationError(f"'{name}' entries must be non-empty strings")
206
+ cleaned = entry.strip()
207
+ if choices is not None and cleaned not in choices:
208
+ raise LightRAGValidationError(
209
+ f"'{name}' entries must be in: {', '.join(choices)}"
210
+ )
211
+ items.append(cleaned)
212
+ return items
213
+
214
+
215
+ def _extract_error_detail(payload: Any, fallback_text: str) -> str:
216
+ if isinstance(payload, dict) and "detail" in payload:
217
+ detail = payload["detail"]
218
+ if isinstance(detail, str) and detail.strip():
219
+ return detail.strip()
220
+ if isinstance(detail, list):
221
+ parts: list[str] = []
222
+ for item in detail:
223
+ if isinstance(item, dict):
224
+ loc = ".".join(str(x) for x in item.get("loc", ()))
225
+ msg = str(item.get("msg", "")).strip()
226
+ parts.append(f"{loc}: {msg}" if loc and msg else (msg or str(item)))
227
+ else:
228
+ parts.append(str(item))
229
+ joined = "; ".join(p for p in parts if p)
230
+ if joined:
231
+ return joined[:_ERROR_BODY_PREVIEW_CHARS]
232
+ if detail is not None:
233
+ return str(detail)[:_ERROR_BODY_PREVIEW_CHARS]
234
+ text = fallback_text.strip()
235
+ return text[:_ERROR_BODY_PREVIEW_CHARS] if text else "no error detail provided"
236
+
237
+
238
+ class LightRAGClient:
239
+ """Async REST client wrapping ``lightrag-server`` public endpoints."""
240
+
241
+ def __init__(
242
+ self,
243
+ config: LightRAGClientConfig,
244
+ *,
245
+ session: aiohttp.ClientSession | None = None,
246
+ ) -> None:
247
+ self.config = config
248
+ self._session = session
249
+ self._owns_session = session is None
250
+
251
+ async def __aenter__(self) -> LightRAGClient:
252
+ self._ensure_session()
253
+ return self
254
+
255
+ async def __aexit__(self, *_exc: object) -> None:
256
+ await self.close()
257
+
258
+ def _ensure_session(self) -> aiohttp.ClientSession:
259
+ if self._session is None or self._session.closed:
260
+ timeout = aiohttp.ClientTimeout(total=self.config.timeout_seconds)
261
+ self._session = aiohttp.ClientSession(timeout=timeout)
262
+ self._owns_session = True
263
+ return self._session
264
+
265
+ async def close(self) -> None:
266
+ """Close the HTTP session if this client created it."""
267
+ if (
268
+ self._owns_session
269
+ and self._session is not None
270
+ and not self._session.closed
271
+ ):
272
+ await self._session.close()
273
+
274
+ def _headers(self) -> dict[str, str]:
275
+ headers: dict[str, str] = {
276
+ "Accept": "application/json",
277
+ "User-Agent": f"lightrag-cli/{__version__}",
278
+ }
279
+ if self.config.api_key:
280
+ headers["X-API-Key"] = self.config.api_key
281
+ return headers
282
+
283
+ async def _request(
284
+ self,
285
+ method: str,
286
+ path: str,
287
+ *,
288
+ params: dict[str, Any] | None = None,
289
+ json_body: dict[str, Any] | None = None,
290
+ data: Any | None = None,
291
+ timeout_seconds: float | None | object = _CONFIG_TIMEOUT,
292
+ ) -> Any:
293
+ """Send one request; ``timeout_seconds=None`` means no time limit."""
294
+ url = f"{self.config.base_url}{path}"
295
+ session = self._ensure_session()
296
+ limit = (
297
+ self.config.timeout_seconds
298
+ if timeout_seconds is _CONFIG_TIMEOUT
299
+ else timeout_seconds
300
+ )
301
+ try:
302
+ async with session.request(
303
+ method,
304
+ url,
305
+ headers=self._headers(),
306
+ params=params,
307
+ json=json_body,
308
+ data=data,
309
+ timeout=aiohttp.ClientTimeout(total=limit),
310
+ ) as resp:
311
+ raw_text = await resp.text()
312
+ try:
313
+ parsed_json = await resp.json(content_type=None)
314
+ except Exception:
315
+ parsed_json = None
316
+
317
+ if resp.status >= 400:
318
+ raise LightRAGAPIError(
319
+ resp.status, _extract_error_detail(parsed_json, raw_text), path
320
+ )
321
+ if parsed_json is None and raw_text.strip():
322
+ raise LightRAGAPIError(
323
+ resp.status,
324
+ f"expected JSON response body, got: {raw_text.strip()[:200]}",
325
+ path,
326
+ )
327
+ return parsed_json
328
+ except LightRAGAPIError:
329
+ raise
330
+ except asyncio.TimeoutError as exc:
331
+ after = f" after {limit:g}s" if limit is not None else ""
332
+ message = f"LightRAG request {method} {path} timed out{after}"
333
+ if method != "GET":
334
+ # The server does not stop when the client gives up.
335
+ message += (
336
+ "; the request may have reached the server, which may still"
337
+ " be carrying it out: its outcome is unknown"
338
+ )
339
+ raise LightRAGConnectionError(message) from exc
340
+ except aiohttp.ClientError as exc:
341
+ raise LightRAGConnectionError(
342
+ f"Failed to reach LightRAG server at {self.config.base_url} "
343
+ f"({method} {path}): {exc}"
344
+ ) from exc
345
+
346
+ async def delete_documents(
347
+ self,
348
+ doc_ids: Sequence[str],
349
+ *,
350
+ delete_file: bool = False,
351
+ delete_llm_cache: bool = False,
352
+ ) -> dict[str, Any]:
353
+ """Start deleting documents via ``DELETE /documents/delete_document``.
354
+
355
+ The server answers HTTP 200 whether it starts the deletion or refuses
356
+ it: read ``status`` (``deletion_started``, ``busy``, ``not_allowed``).
357
+ ``deletion_started`` means a background job began, not that it
358
+ finished.
359
+ """
360
+ if isinstance(doc_ids, str) or not doc_ids:
361
+ raise LightRAGValidationError("doc_ids must be a non-empty list")
362
+ body = {
363
+ "doc_ids": [_require_non_empty_str(d, "doc_id") for d in doc_ids],
364
+ "delete_file": delete_file,
365
+ "delete_llm_cache": delete_llm_cache,
366
+ }
367
+ return await self._request(
368
+ "DELETE", "/documents/delete_document", json_body=body
369
+ )
370
+
371
+ async def clear_documents(
372
+ self,
373
+ *,
374
+ delete_parsed_files: bool = False,
375
+ clear_llm_cache: bool = False,
376
+ timeout_seconds: float | None = None,
377
+ ) -> dict[str, Any]:
378
+ """Delete every document of the workspace via ``DELETE /documents``.
379
+
380
+ Synchronous on the server and possibly long, so it has no time limit
381
+ unless ``timeout_seconds`` sets one. The server answers HTTP 200 with
382
+ ``status`` ``success``, ``partial_success``, ``busy`` or ``fail``.
383
+ """
384
+ params = {
385
+ key: "true"
386
+ for key, enabled in (
387
+ ("delete_parsed_files", delete_parsed_files),
388
+ ("clear_llm_cache", clear_llm_cache),
389
+ )
390
+ if enabled
391
+ }
392
+ return await self._request(
393
+ "DELETE",
394
+ "/documents",
395
+ params=params or None,
396
+ timeout_seconds=timeout_seconds,
397
+ )
398
+
399
+ async def health(self) -> dict[str, Any]:
400
+ return await self._request("GET", "/health")
401
+
402
+ async def get_status_counts(self) -> dict[str, Any]:
403
+ return await self._request("GET", "/documents/status_counts")
404
+
405
+ async def get_pipeline_status(self) -> dict[str, Any]:
406
+ return await self._request("GET", "/documents/pipeline_status")
407
+
408
+ async def get_supported_file_types(self) -> dict[str, Any]:
409
+ return await self._request("GET", "/documents/supported_file_types")
410
+
411
+ async def status(self) -> dict[str, Any]:
412
+ """Fetch ``/health``, status counts and pipeline status together, unchanged.
413
+
414
+ ``lightrag_cli.views.status_view`` turns the result into a summary.
415
+ """
416
+ health, counts, pipeline = await asyncio.gather(
417
+ self.health(),
418
+ self.get_status_counts(),
419
+ self.get_pipeline_status(),
420
+ )
421
+ return {"health": health, "status_counts": counts, "pipeline": pipeline}
422
+
423
+ async def query(
424
+ self,
425
+ query: str,
426
+ *,
427
+ mode: str = "mix",
428
+ top_k: int | None = None,
429
+ chunk_top_k: int | None = None,
430
+ response_type: str | None = None,
431
+ hl_keywords: Sequence[str] | None = None,
432
+ ll_keywords: Sequence[str] | None = None,
433
+ user_prompt: str | None = None,
434
+ enable_rerank: bool | None = None,
435
+ include_references: bool | None = None,
436
+ include_chunk_content: bool | None = None,
437
+ max_total_tokens: int | None = None,
438
+ ) -> dict[str, Any]:
439
+ payload: dict[str, Any] = {
440
+ "query": _require_non_empty_str(query, "query"),
441
+ "mode": _validate_enum(mode, "mode", QUERY_MODES),
442
+ }
443
+ for key, raw in (
444
+ ("top_k", top_k),
445
+ ("chunk_top_k", chunk_top_k),
446
+ ("max_total_tokens", max_total_tokens),
447
+ ):
448
+ if (val := _optional_int(raw, key)) is not None:
449
+ payload[key] = val
450
+ for key, raw in (
451
+ ("response_type", response_type),
452
+ ("user_prompt", user_prompt),
453
+ ):
454
+ if (val := _optional_non_empty_str(raw, key)) is not None:
455
+ payload[key] = val
456
+ for key, raw in (("hl_keywords", hl_keywords), ("ll_keywords", ll_keywords)):
457
+ if (val := _optional_str_list(raw, key)) is not None:
458
+ payload[key] = val
459
+ for key, raw in (
460
+ ("enable_rerank", enable_rerank),
461
+ ("include_references", include_references),
462
+ ("include_chunk_content", include_chunk_content),
463
+ ):
464
+ if (val := _optional_bool(raw, key)) is not None:
465
+ payload[key] = val
466
+ return await self._request("POST", "/query", json_body=payload)
467
+
468
+ async def retrieve(
469
+ self,
470
+ query: str,
471
+ *,
472
+ mode: str = "mix",
473
+ top_k: int | None = None,
474
+ chunk_top_k: int | None = None,
475
+ hl_keywords: Sequence[str] | None = None,
476
+ ll_keywords: Sequence[str] | None = None,
477
+ enable_rerank: bool | None = None,
478
+ max_entity_tokens: int | None = None,
479
+ max_relation_tokens: int | None = None,
480
+ max_total_tokens: int | None = None,
481
+ ) -> dict[str, Any]:
482
+ payload: dict[str, Any] = {
483
+ "query": _require_non_empty_str(query, "query"),
484
+ "mode": _validate_enum(mode, "mode", RETRIEVE_MODES),
485
+ }
486
+ for key, raw in (
487
+ ("top_k", top_k),
488
+ ("chunk_top_k", chunk_top_k),
489
+ ("max_entity_tokens", max_entity_tokens),
490
+ ("max_relation_tokens", max_relation_tokens),
491
+ ("max_total_tokens", max_total_tokens),
492
+ ):
493
+ if (val := _optional_int(raw, key)) is not None:
494
+ payload[key] = val
495
+ for key, raw in (("hl_keywords", hl_keywords), ("ll_keywords", ll_keywords)):
496
+ if (val := _optional_str_list(raw, key)) is not None:
497
+ payload[key] = val
498
+ if (rerank := _optional_bool(enable_rerank, "enable_rerank")) is not None:
499
+ payload["enable_rerank"] = rerank
500
+ return await self._request("POST", "/query/data", json_body=payload)
501
+
502
+ async def search_graph_labels(self, query: str, *, limit: int = 20) -> list[str]:
503
+ cleaned = _require_non_empty_str(query, "query")
504
+ validated_limit = _validate_int(limit, "limit")
505
+ return await self._request(
506
+ "GET",
507
+ "/graph/label/search",
508
+ params={"q": cleaned, "limit": validated_limit},
509
+ )
510
+
511
+ async def get_knowledge_graph(
512
+ self, label: str, *, max_depth: int = 2, max_nodes: int = 100
513
+ ) -> dict[str, Any]:
514
+ cleaned = _require_non_empty_str(label, "label")
515
+ depth = _validate_int(max_depth, "max_depth")
516
+ nodes = _validate_int(max_nodes, "max_nodes")
517
+ return await self._request(
518
+ "GET",
519
+ "/graphs",
520
+ params={"label": cleaned, "max_depth": depth, "max_nodes": nodes},
521
+ )
522
+
523
+ async def list_documents(
524
+ self,
525
+ *,
526
+ page: int = 1,
527
+ page_size: int = 20,
528
+ status_filters: Sequence[str] | None = None,
529
+ sort_field: str = "updated_at",
530
+ sort_direction: str = "desc",
531
+ ) -> dict[str, Any]:
532
+ payload: dict[str, Any] = {
533
+ "page": _validate_int(page, "page"),
534
+ "page_size": _validate_int(page_size, "page_size"),
535
+ "sort_field": _validate_enum(sort_field, "sort_field", SORT_FIELDS),
536
+ "sort_direction": _validate_enum(
537
+ sort_direction, "sort_direction", SORT_DIRECTIONS
538
+ ),
539
+ }
540
+ statuses = _optional_str_list(
541
+ status_filters, "status_filters", choices=DOC_STATUSES
542
+ )
543
+ if statuses is not None:
544
+ payload["status_filters"] = statuses
545
+ return await self._request("POST", "/documents/paginated", json_body=payload)
546
+
547
+ async def get_track_status(self, track_id: str) -> dict[str, Any]:
548
+ cleaned = _require_non_empty_str(track_id, "track_id")
549
+ encoded = quote(cleaned, safe="")
550
+ return await self._request("GET", f"/documents/track_status/{encoded}")
551
+
552
+ async def insert_text(self, text: str, *, file_source: str) -> dict[str, Any]:
553
+ """Queue ``text`` via ``POST /documents/text``.
554
+
555
+ ``file_source`` is required: the server rejects text without one (its
556
+ request model marks the field optional, but the handler does not).
557
+ """
558
+ body: dict[str, Any] = {
559
+ "text": _require_non_empty_str(text, "text"),
560
+ "file_source": _require_non_empty_str(file_source, "file_source"),
561
+ }
562
+ return await self._request("POST", "/documents/text", json_body=body)
563
+
564
+ async def upload_file(self, file_path: str | Path) -> dict[str, Any]:
565
+ """Upload a local file via multipart ``POST /documents/upload``."""
566
+ path = validate_upload_path(file_path)
567
+
568
+ content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
569
+ try:
570
+ fh = path.open("rb")
571
+ except OSError as exc:
572
+ # Nothing has been sent yet, so this is a local input error.
573
+ raise LightRAGValidationError(f"Cannot open file {path}: {exc}") from exc
574
+ with fh:
575
+ # quote_fields=False sends the basename as is: the server does not
576
+ # percent-decode it, so quoting would break non-ASCII names and the
577
+ # parser hints carried in the filename.
578
+ form = aiohttp.FormData(quote_fields=False)
579
+ form.add_field(
580
+ "file",
581
+ fh,
582
+ filename=path.name,
583
+ content_type=content_type,
584
+ )
585
+ return await self._request("POST", "/documents/upload", data=form)