pilotrag 0.1.0__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.
Files changed (94) hide show
  1. pilotrag/__init__.py +55 -0
  2. pilotrag/_langchain.py +33 -0
  3. pilotrag/_version.py +1 -0
  4. pilotrag/bootstrap.py +383 -0
  5. pilotrag/cli/__init__.py +1 -0
  6. pilotrag/cli/exit_codes.py +6 -0
  7. pilotrag/cli/main.py +135 -0
  8. pilotrag/cli/rendering.py +57 -0
  9. pilotrag/core/__init__.py +1 -0
  10. pilotrag/core/config.py +117 -0
  11. pilotrag/core/config_errors.py +55 -0
  12. pilotrag/core/config_loader.py +144 -0
  13. pilotrag/core/config_schema.py +12 -0
  14. pilotrag/core/exceptions.py +171 -0
  15. pilotrag/core/fingerprint.py +39 -0
  16. pilotrag/core/ids.py +36 -0
  17. pilotrag/core/registry.py +238 -0
  18. pilotrag/core/retry.py +134 -0
  19. pilotrag/core/runtime_defaults.py +22 -0
  20. pilotrag/core/secrets.py +124 -0
  21. pilotrag/core/types.py +165 -0
  22. pilotrag/embeddings/__init__.py +1 -0
  23. pilotrag/embeddings/factory.py +28 -0
  24. pilotrag/embeddings/providers/__init__.py +29 -0
  25. pilotrag/embeddings/providers/huggingface.py +262 -0
  26. pilotrag/embeddings/providers/ollama.py +145 -0
  27. pilotrag/evaluation/__init__.py +1 -0
  28. pilotrag/evaluation/datasets.py +38 -0
  29. pilotrag/evaluation/retrieval_metrics.py +19 -0
  30. pilotrag/evaluation/runner.py +78 -0
  31. pilotrag/facade.py +141 -0
  32. pilotrag/generation/__init__.py +1 -0
  33. pilotrag/generation/factory.py +13 -0
  34. pilotrag/generation/providers/__init__.py +19 -0
  35. pilotrag/generation/providers/ollama.py +98 -0
  36. pilotrag/ingestion/__init__.py +1 -0
  37. pilotrag/ingestion/chunking/__init__.py +18 -0
  38. pilotrag/ingestion/chunking/factory.py +16 -0
  39. pilotrag/ingestion/chunking/recursive_markdown.py +277 -0
  40. pilotrag/ingestion/loaders/__init__.py +1 -0
  41. pilotrag/ingestion/loaders/factory.py +10 -0
  42. pilotrag/ingestion/loaders/providers/__init__.py +18 -0
  43. pilotrag/ingestion/loaders/providers/markdown.py +131 -0
  44. pilotrag/ingestion/sources/__init__.py +1 -0
  45. pilotrag/ingestion/sources/factory.py +14 -0
  46. pilotrag/ingestion/sources/providers/__init__.py +18 -0
  47. pilotrag/ingestion/sources/providers/local_directory.py +89 -0
  48. pilotrag/interfaces/__init__.py +43 -0
  49. pilotrag/interfaces/chunker.py +22 -0
  50. pilotrag/interfaces/document_loader.py +19 -0
  51. pilotrag/interfaces/document_source.py +18 -0
  52. pilotrag/interfaces/embeddings.py +21 -0
  53. pilotrag/interfaces/index_layout.py +9 -0
  54. pilotrag/interfaces/llm.py +23 -0
  55. pilotrag/interfaces/progress.py +15 -0
  56. pilotrag/interfaces/prompt_builder.py +20 -0
  57. pilotrag/interfaces/query_rewriter.py +17 -0
  58. pilotrag/interfaces/reranker.py +23 -0
  59. pilotrag/interfaces/retriever.py +17 -0
  60. pilotrag/interfaces/runtime.py +31 -0
  61. pilotrag/interfaces/vector_store.py +62 -0
  62. pilotrag/observability/__init__.py +1 -0
  63. pilotrag/observability/logging.py +70 -0
  64. pilotrag/observability/metrics.py +13 -0
  65. pilotrag/pipelines/__init__.py +1 -0
  66. pilotrag/pipelines/health.py +105 -0
  67. pilotrag/pipelines/index_lifecycle.py +321 -0
  68. pilotrag/pipelines/indexing.py +264 -0
  69. pilotrag/pipelines/query.py +177 -0
  70. pilotrag/pipelines/rag.py +161 -0
  71. pilotrag/prompts/__init__.py +1 -0
  72. pilotrag/prompts/base.py +46 -0
  73. pilotrag/prompts/templates.py +14 -0
  74. pilotrag/py.typed +0 -0
  75. pilotrag/retrieval/__init__.py +27 -0
  76. pilotrag/retrieval/dense.py +53 -0
  77. pilotrag/retrieval/factory.py +25 -0
  78. pilotrag/retrieval/fusion.py +29 -0
  79. pilotrag/retrieval/query_rewriter.py +27 -0
  80. pilotrag/retrieval/rerankers/__init__.py +18 -0
  81. pilotrag/retrieval/rerankers/factory.py +10 -0
  82. pilotrag/retrieval/rerankers/none.py +36 -0
  83. pilotrag/testing/__init__.py +17 -0
  84. pilotrag/testing/contracts.py +559 -0
  85. pilotrag/testing/fakes.py +238 -0
  86. pilotrag/vector_stores/__init__.py +1 -0
  87. pilotrag/vector_stores/factory.py +16 -0
  88. pilotrag/vector_stores/providers/__init__.py +20 -0
  89. pilotrag/vector_stores/providers/chroma.py +318 -0
  90. pilotrag-0.1.0.dist-info/METADATA +413 -0
  91. pilotrag-0.1.0.dist-info/RECORD +94 -0
  92. pilotrag-0.1.0.dist-info/WHEEL +4 -0
  93. pilotrag-0.1.0.dist-info/entry_points.txt +30 -0
  94. pilotrag-0.1.0.dist-info/licenses/LICENSE +21 -0
pilotrag/__init__.py ADDED
@@ -0,0 +1,55 @@
1
+ """PilotRAG: Markdown-first, local-first Retrieval-Augmented Generation."""
2
+
3
+ import logging
4
+
5
+ from pilotrag._version import __version__
6
+ from pilotrag.core.exceptions import (
7
+ ConfigurationError,
8
+ DocumentReadError,
9
+ IndexIncompatibleError,
10
+ IndexLockedError,
11
+ IndexNotFoundError,
12
+ IngestionError,
13
+ InvalidQueryError,
14
+ MissingCredentialError,
15
+ MissingExtraError,
16
+ NoDocumentsFoundError,
17
+ PilotRAGError,
18
+ ProviderError,
19
+ QueryError,
20
+ RateLimitError,
21
+ UnknownProviderError,
22
+ )
23
+ from pilotrag.core.types import (
24
+ Answer,
25
+ AnswerStatus,
26
+ IngestionReport,
27
+ SourceReference,
28
+ )
29
+ from pilotrag.facade import RAG
30
+
31
+ logging.getLogger(__name__).addHandler(logging.NullHandler())
32
+
33
+ __all__ = [
34
+ "RAG",
35
+ "Answer",
36
+ "AnswerStatus",
37
+ "ConfigurationError",
38
+ "DocumentReadError",
39
+ "IndexIncompatibleError",
40
+ "IndexLockedError",
41
+ "IndexNotFoundError",
42
+ "IngestionError",
43
+ "IngestionReport",
44
+ "InvalidQueryError",
45
+ "MissingCredentialError",
46
+ "MissingExtraError",
47
+ "NoDocumentsFoundError",
48
+ "PilotRAGError",
49
+ "ProviderError",
50
+ "QueryError",
51
+ "RateLimitError",
52
+ "SourceReference",
53
+ "UnknownProviderError",
54
+ "__version__",
55
+ ]
pilotrag/_langchain.py ADDED
@@ -0,0 +1,33 @@
1
+ """LangChain message/response translation helpers (the only LangChain-coupled module)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Sequence
6
+ from typing import Any
7
+
8
+ from pilotrag.core.types import ChatResult, Message, Usage
9
+
10
+
11
+ def to_lc_messages(messages: Sequence[Message]) -> list[Any]:
12
+ """Convert domain messages into LangChain message objects."""
13
+ from langchain_core.messages import AIMessage, HumanMessage, SystemMessage
14
+
15
+ constructors = {
16
+ "system": SystemMessage,
17
+ "user": HumanMessage,
18
+ "assistant": AIMessage,
19
+ }
20
+ return [constructors[message.role](content=message.content) for message in messages]
21
+
22
+
23
+ def chat_result_from_lc(response: Any, model_id: str) -> ChatResult:
24
+ """Convert a LangChain chat response into a domain ChatResult."""
25
+ usage = None
26
+ usage_metadata = getattr(response, "usage_metadata", None)
27
+ if isinstance(usage_metadata, dict):
28
+ usage = Usage(
29
+ prompt_tokens=usage_metadata.get("input_tokens"),
30
+ completion_tokens=usage_metadata.get("output_tokens"),
31
+ total_tokens=usage_metadata.get("total_tokens"),
32
+ )
33
+ return ChatResult(text=str(response.text), model_id=model_id, usage=usage)
pilotrag/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
pilotrag/bootstrap.py ADDED
@@ -0,0 +1,383 @@
1
+ """Composition root: resolve configuration into a fully wired Engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ from collections.abc import Mapping
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from pydantic import SecretStr
12
+
13
+ from pilotrag.core.config import PilotRAGSettings, StrategySection
14
+ from pilotrag.core.exceptions import ConfigurationError, PilotRAGError
15
+ from pilotrag.core.fingerprint import IndexFingerprint
16
+ from pilotrag.core.retry import translate_provider_error
17
+ from pilotrag.core.runtime_defaults import SystemClock, SystemIdGenerator
18
+ from pilotrag.core.secrets import global_secret_registry
19
+ from pilotrag.interfaces.chunker import Chunker
20
+ from pilotrag.interfaces.document_loader import DocumentLoader
21
+ from pilotrag.interfaces.embeddings import EmbeddingModel
22
+ from pilotrag.observability.metrics import NoOpTelemetry
23
+ from pilotrag.pipelines.index_lifecycle import IndexLifecycle
24
+ from pilotrag.pipelines.indexing import IngestionService
25
+ from pilotrag.pipelines.query import QueryService
26
+ from pilotrag.pipelines.rag import Engine
27
+ from pilotrag.prompts.base import DefaultPromptBuilder
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ COMPONENT_KEYS = (
32
+ "source",
33
+ "loaders",
34
+ "chunker",
35
+ "embeddings",
36
+ "chat",
37
+ "store_factory",
38
+ "retriever",
39
+ "reranker",
40
+ "query_rewriter",
41
+ "prompt_builder",
42
+ "telemetry",
43
+ )
44
+
45
+
46
+ def _register_builtins() -> None:
47
+ """Register all built-in provider and strategy specs (lazy imports)."""
48
+ from pilotrag.embeddings.providers import register as register_embeddings
49
+ from pilotrag.generation.providers import register as register_chat_models
50
+ from pilotrag.ingestion.chunking import register as register_chunkers
51
+ from pilotrag.ingestion.loaders.providers import register as register_loaders
52
+ from pilotrag.ingestion.sources.providers import register as register_sources
53
+ from pilotrag.retrieval import register as register_retrieval
54
+ from pilotrag.retrieval.rerankers import register as register_rerankers
55
+ from pilotrag.vector_stores.providers import register as register_vector_stores
56
+
57
+ register_chat_models()
58
+ register_embeddings()
59
+ register_vector_stores()
60
+ register_sources()
61
+ register_loaders()
62
+ register_chunkers()
63
+ register_retrieval()
64
+ register_rerankers()
65
+
66
+
67
+ def build_engine(
68
+ settings: PilotRAGSettings,
69
+ *,
70
+ overrides_components: Mapping[str, Any] | None = None,
71
+ ) -> Engine:
72
+ """Resolve every provider and strategy and wire the Engine.
73
+
74
+ Args:
75
+ settings: Validated configuration.
76
+ overrides_components: Optional ready-made port instances keyed by
77
+ component name (used for testing and custom integrations). Keys
78
+ must be among ``COMPONENT_KEYS``.
79
+
80
+ Returns:
81
+ The fully wired engine.
82
+
83
+ Raises:
84
+ ConfigurationError: If a required provider or strategy cannot be resolved,
85
+ or ``overrides_components`` contains an unknown key.
86
+ MissingExtraError: If an implementation's dependencies are missing.
87
+ """
88
+ from pilotrag.core.registry import FactoryContext
89
+
90
+ _register_builtins()
91
+ overrides = _validated_overrides(overrides_components)
92
+
93
+ embeddings = _component(overrides, "embeddings") or _resolve_provider(
94
+ "embeddings",
95
+ settings.embeddings,
96
+ )
97
+ chat = _component(overrides, "chat") or _resolve_provider("chat_models", settings.llm)
98
+ store_factory = _component(overrides, "store_factory") or _resolve_provider(
99
+ "vector_stores",
100
+ settings.vector_store,
101
+ )
102
+ chunker = _component(overrides, "chunker") or _resolve_strategy(
103
+ "chunkers",
104
+ settings.chunking,
105
+ )
106
+ lifecycle = IndexLifecycle(str(_index_path(settings)), store_factory)
107
+ retriever = _component(overrides, "retriever") or _resolve_strategy(
108
+ "retrievers",
109
+ settings.retrieval,
110
+ context=FactoryContext(embeddings=embeddings, lifecycle=lifecycle),
111
+ )
112
+ reranker = _component(overrides, "reranker") or _resolve_strategy(
113
+ "rerankers",
114
+ settings.reranking,
115
+ )
116
+ rewriter = _component(overrides, "query_rewriter") or _resolve_strategy(
117
+ "query_rewriters",
118
+ StrategySection(strategy="identity"),
119
+ )
120
+ prompt_builder = _component(overrides, "prompt_builder") or DefaultPromptBuilder()
121
+ source = _component(overrides, "source") or _resolve_provider(
122
+ "sources",
123
+ _documents_as_provider_section(settings),
124
+ )
125
+ loaders = _component(overrides, "loaders") or _resolve_loaders(settings)
126
+ telemetry = _component(overrides, "telemetry")
127
+
128
+ _register_secrets_for_redaction(settings)
129
+
130
+ fingerprint = _compute_fingerprint(settings, embeddings, chunker, loaders)
131
+ lifecycle.compute_fingerprint(fingerprint)
132
+
133
+ ingestion = IngestionService(
134
+ source=source,
135
+ loaders=loaders,
136
+ chunker=chunker,
137
+ embeddings=embeddings,
138
+ lifecycle=lifecycle,
139
+ fingerprint=fingerprint,
140
+ on_error=settings.documents.on_error,
141
+ embed_batch_size=_embed_batch_size(settings),
142
+ )
143
+ query_service = QueryService(
144
+ rewriter=rewriter,
145
+ retriever=retriever,
146
+ reranker=reranker,
147
+ prompt_builder=prompt_builder,
148
+ chat=chat,
149
+ top_k=_retrieval_top_k(retriever),
150
+ min_score=_retrieval_min_score(retriever),
151
+ max_context_chunks=settings.generation.max_context_chunks,
152
+ insufficient_evidence_message=settings.generation.insufficient_evidence_message,
153
+ clock=SystemClock(),
154
+ id_generator=SystemIdGenerator(),
155
+ telemetry=telemetry if telemetry is not None else NoOpTelemetry(),
156
+ )
157
+ return Engine(
158
+ settings=settings.documents,
159
+ source=source,
160
+ embeddings=embeddings,
161
+ lifecycle=lifecycle,
162
+ ingestion=ingestion,
163
+ query_service=query_service,
164
+ fingerprint=fingerprint,
165
+ telemetry=telemetry,
166
+ )
167
+
168
+
169
+ def _validated_overrides(overrides: Mapping[str, Any] | None) -> dict[str, Any]:
170
+ """Return a copy of ``overrides`` after rejecting unknown component keys.
171
+
172
+ Raises:
173
+ ConfigurationError: If a key is not one of ``COMPONENT_KEYS``.
174
+ """
175
+ result = dict(overrides or {})
176
+ unknown = sorted(key for key in result if key not in COMPONENT_KEYS)
177
+ if unknown:
178
+ raise ConfigurationError(
179
+ f"Unknown component override key(s): {', '.join(repr(key) for key in unknown)}.",
180
+ hint=f"Valid keys: {', '.join(COMPONENT_KEYS)}.",
181
+ )
182
+ return result
183
+
184
+
185
+ def _component(overrides: Mapping[str, Any], key: str) -> Any | None:
186
+ """Return an explicit component override for ``key``, if any."""
187
+ return overrides.get(key)
188
+
189
+
190
+ def _resolve_provider(kind: str, section: Any) -> Any:
191
+ """Resolve a provider section through the registry."""
192
+ from pilotrag.core.registry import resolve
193
+
194
+ options = dict(section.model_dump())
195
+ provider = options.pop("provider")
196
+ factory, typed_settings = resolve(kind, provider, options)
197
+ try:
198
+ return factory(typed_settings)
199
+ except PilotRAGError:
200
+ raise
201
+ except Exception as exc:
202
+ raise translate_provider_error(exc, f"{kind}:{provider}") from exc
203
+
204
+
205
+ def _resolve_strategy(
206
+ kind: str,
207
+ section: StrategySection,
208
+ *,
209
+ context: object = None,
210
+ ) -> Any:
211
+ """Resolve a strategy section through the registry with an optional context."""
212
+ from pilotrag.core.registry import resolve
213
+
214
+ options = dict(section.model_dump())
215
+ factory, typed_settings = resolve(kind, options.pop("strategy"), options)
216
+ try:
217
+ return factory(typed_settings, context)
218
+ except PilotRAGError:
219
+ raise
220
+ except Exception as exc:
221
+ raise translate_provider_error(exc, f"{kind}:{section.strategy}") from exc
222
+
223
+
224
+ def _documents_as_provider_section(settings: PilotRAGSettings) -> Any:
225
+ """Adapt the typed documents settings into a provider section for the registry."""
226
+ return _SimpleSection("local_directory", settings.documents.model_dump())
227
+
228
+
229
+ class _SimpleSection:
230
+ """Minimal provider-section stand-in with a provider key and options."""
231
+
232
+ def __init__(self, provider: str, options: dict[str, Any]) -> None:
233
+ """Store the provider name and options."""
234
+ self.provider = provider
235
+ self._options = options
236
+
237
+ def model_dump(self) -> dict[str, Any]:
238
+ """Return provider plus options for registry validation."""
239
+ return {"provider": self.provider, **self._options}
240
+
241
+
242
+ def _resolve_loaders(settings: PilotRAGSettings) -> list[DocumentLoader]:
243
+ """Resolve one loader per configured extension via the loader registry."""
244
+ from pilotrag.core.registry import REGISTRIES
245
+
246
+ available = REGISTRIES.names("loaders")
247
+ loaders: dict[str, DocumentLoader] = {}
248
+ for extension in settings.documents.extensions:
249
+ normalized = extension.lower()
250
+ resolved = _loader_for_extension(normalized, available)
251
+ if resolved is None:
252
+ raise ConfigurationError(
253
+ f"No loader supports extension '{normalized}'.",
254
+ hint=f"Available loaders cover: {', '.join(available)}.",
255
+ )
256
+ name, loader = resolved
257
+ if name not in loaders:
258
+ loaders[name] = loader
259
+ return list(loaders.values())
260
+
261
+
262
+ def _loader_for_extension(
263
+ extension: str,
264
+ available: list[str],
265
+ ) -> tuple[str, DocumentLoader] | None:
266
+ """Return the first registered loader instance covering ``extension``."""
267
+ from pilotrag.core.registry import resolve
268
+
269
+ for name in available:
270
+ try:
271
+ factory, typed = resolve("loaders", name, {})
272
+ loader = factory(typed)
273
+ except PilotRAGError:
274
+ continue
275
+ if extension in loader.extensions:
276
+ return name, loader
277
+ return None
278
+
279
+
280
+ def _compute_fingerprint(
281
+ settings: PilotRAGSettings,
282
+ embeddings: EmbeddingModel,
283
+ chunker: Chunker,
284
+ loaders: list[DocumentLoader],
285
+ ) -> IndexFingerprint:
286
+ """Compute the index fingerprint from resolved components."""
287
+ dimension = embeddings.dimension
288
+ if dimension is None:
289
+ dimension = _probe_dimension(embeddings)
290
+ return IndexFingerprint(
291
+ embedding_provider=settings.embeddings.provider,
292
+ embedding_model=embeddings.model_id,
293
+ embedding_dimension=dimension,
294
+ embedding_params=_embedding_params(embeddings),
295
+ chunker_name=chunker.name,
296
+ chunker_params=dict(chunker.fingerprint()),
297
+ reader_names=sorted(loader.name for loader in loaders),
298
+ )
299
+
300
+
301
+ def _embedding_params(embeddings: EmbeddingModel) -> dict[str, Any]:
302
+ """Return vector-shaping settings from an optional ``fingerprint_params()`` hook.
303
+
304
+ The hook is optional so existing third-party embedders keep working; without
305
+ it, only provider, model and dimension identify the embedding space.
306
+ """
307
+ hook = getattr(embeddings, "fingerprint_params", None)
308
+ if not callable(hook):
309
+ return {}
310
+ return dict(hook())
311
+
312
+
313
+ def _probe_dimension(embeddings: EmbeddingModel) -> int:
314
+ """Learn the embedding dimension with one tiny request.
315
+
316
+ Raises:
317
+ ProviderError: If the provider cannot be reached.
318
+ """
319
+ try:
320
+ embeddings.embed_query("pilotrag dimension probe")
321
+ except PilotRAGError:
322
+ raise
323
+ except Exception as exc:
324
+ raise translate_provider_error(exc, "embeddings") from exc
325
+ if embeddings.dimension is None:
326
+ raise ConfigurationError(
327
+ "Embedding provider did not report a dimension.",
328
+ hint="Check the provider response; the model may not support embeddings.",
329
+ )
330
+ return embeddings.dimension
331
+
332
+
333
+ def _register_secrets_for_redaction(settings: PilotRAGSettings) -> None:
334
+ """Register configured secrets with the global redaction registry.
335
+
336
+ Secrets are derived from the validated provider sections only: every
337
+ ``SecretStr`` option (secret-named keys are wrapped on validation) plus the
338
+ value of any environment variable named by an ``api_key_env`` option.
339
+ """
340
+ secrets: list[str] = []
341
+ for section in (settings.embeddings, settings.llm, settings.vector_store):
342
+ secrets.extend(_section_secrets(section.model_dump()))
343
+ global_secret_registry().register(secrets)
344
+
345
+
346
+ def _section_secrets(options: Mapping[str, Any]) -> list[str]:
347
+ """Return the secret values configured in one provider section's options."""
348
+ secrets = [
349
+ value.get_secret_value() for value in options.values() if isinstance(value, SecretStr)
350
+ ]
351
+ env_name = options.get("api_key_env")
352
+ if isinstance(env_name, str) and env_name:
353
+ env_value = os.environ.get(env_name)
354
+ if env_value:
355
+ secrets.append(env_value)
356
+ return secrets
357
+
358
+
359
+ def _embed_batch_size(settings: PilotRAGSettings) -> int:
360
+ """Extract the embedding batch size from provider options when present."""
361
+ options = settings.embeddings.model_dump()
362
+ value = options.get("batch_size")
363
+ return int(value) if isinstance(value, int) and value > 0 else 32
364
+
365
+
366
+ def _retrieval_top_k(retriever: Any) -> int:
367
+ """Read top_k from the resolved retriever settings when available."""
368
+ settings = getattr(retriever, "settings", None)
369
+ value = getattr(settings, "top_k", None)
370
+ return int(value) if value is not None else 5
371
+
372
+
373
+ def _retrieval_min_score(retriever: Any) -> float | None:
374
+ """Read min_score from the resolved retriever settings when available."""
375
+ settings = getattr(retriever, "settings", None)
376
+ value = getattr(settings, "min_score", None)
377
+ return float(value) if value is not None else None
378
+
379
+
380
+ def _index_path(settings: PilotRAGSettings) -> Path:
381
+ """Return the index base path from vector store options."""
382
+ options = settings.vector_store.model_dump()
383
+ return Path(str(options.get("path", "./.pilotrag/index")))
@@ -0,0 +1 @@
1
+ """Command-line interface for PilotRAG (Phase 1: ingest and query)."""
@@ -0,0 +1,6 @@
1
+ """Exit codes used by the PilotRAG CLI."""
2
+
3
+ EXIT_OK = 0
4
+ EXIT_FAILURE = 1
5
+ EXIT_USAGE_OR_CONFIG = 2
6
+ EXIT_PARTIAL = 3
pilotrag/cli/main.py ADDED
@@ -0,0 +1,135 @@
1
+ """Typer application wiring the ingest and query commands."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING
7
+
8
+ import typer
9
+
10
+ from pilotrag._version import __version__
11
+ from pilotrag.cli.exit_codes import (
12
+ EXIT_FAILURE,
13
+ EXIT_OK,
14
+ EXIT_PARTIAL,
15
+ EXIT_USAGE_OR_CONFIG,
16
+ )
17
+ from pilotrag.cli.rendering import render_answer, render_error, render_ingestion_report
18
+ from pilotrag.core.config_loader import load_config
19
+ from pilotrag.core.exceptions import ConfigurationError, PilotRAGError
20
+
21
+ if TYPE_CHECKING:
22
+ from pilotrag.pipelines.rag import Engine
23
+
24
+ app = typer.Typer(
25
+ name="pilotrag",
26
+ help="Markdown-first, local-first Retrieval-Augmented Generation.",
27
+ no_args_is_help=True,
28
+ add_completion=False,
29
+ )
30
+
31
+
32
+ def _version_callback(value: bool) -> None:
33
+ """Print the version and exit when --version is passed."""
34
+ if value:
35
+ typer.echo(f"pilotrag {__version__}")
36
+ raise typer.Exit(EXIT_OK)
37
+
38
+
39
+ @app.callback()
40
+ def main(
41
+ version: bool | None = typer.Option(
42
+ None,
43
+ "--version",
44
+ callback=_version_callback,
45
+ is_eager=True,
46
+ help="Show the version and exit.",
47
+ ),
48
+ ) -> None:
49
+ """PilotRAG command line interface."""
50
+ return None
51
+
52
+
53
+ def _build_engine_or_exit(config: Path) -> Engine:
54
+ """Load the config and wire the engine, rendering any failure as a CLI error.
55
+
56
+ Configuration problems exit with the usage/config code; provider failures
57
+ while wiring (e.g. Ollama unreachable during the dimension probe, or a
58
+ Hugging Face model download failure) exit with the generic failure code
59
+ instead of escaping as a traceback.
60
+ """
61
+ from pilotrag.bootstrap import build_engine
62
+ from pilotrag.observability.logging import configure_logging
63
+
64
+ try:
65
+ settings = load_config(config)
66
+ configure_logging(settings.logging)
67
+ return build_engine(settings)
68
+ except ConfigurationError as exc:
69
+ render_error(exc, typer.get_text_stream("stderr"))
70
+ raise typer.Exit(EXIT_USAGE_OR_CONFIG) from None
71
+ except PilotRAGError as exc:
72
+ render_error(exc, typer.get_text_stream("stderr"))
73
+ raise typer.Exit(EXIT_FAILURE) from None
74
+
75
+
76
+ @app.command(name="ingest")
77
+ def ingest_command(
78
+ config: Path = typer.Option(
79
+ Path("pilotrag.yaml"),
80
+ "--config",
81
+ "-c",
82
+ help="Path to the YAML configuration file.",
83
+ ),
84
+ dry_run: bool = typer.Option(
85
+ False,
86
+ "--dry-run",
87
+ help="Plan the ingestion without embedding or writing the index.",
88
+ ),
89
+ ) -> None:
90
+ """Index the configured documents into the persistent vector store."""
91
+ engine = _build_engine_or_exit(config)
92
+ try:
93
+ with engine:
94
+ report = engine.ingest(dry_run=dry_run)
95
+ except PilotRAGError as exc:
96
+ render_error(exc, typer.get_text_stream("stderr"))
97
+ raise typer.Exit(EXIT_FAILURE) from None
98
+ render_ingestion_report(report, str(config), typer.get_text_stream("stdout"))
99
+ if report.status == "failed":
100
+ raise typer.Exit(EXIT_FAILURE)
101
+ if report.failed:
102
+ raise typer.Exit(EXIT_PARTIAL)
103
+ raise typer.Exit(EXIT_OK)
104
+
105
+
106
+ @app.command(name="query")
107
+ def query_command(
108
+ question: str = typer.Argument(..., help="The question to answer."),
109
+ config: Path = typer.Option(
110
+ Path("pilotrag.yaml"),
111
+ "--config",
112
+ "-c",
113
+ help="Path to the YAML configuration file.",
114
+ ),
115
+ top_k: int | None = typer.Option(
116
+ None,
117
+ "--top-k",
118
+ min=1,
119
+ help="Override the configured number of retrieved chunks.",
120
+ ),
121
+ ) -> None:
122
+ """Answer a one-off question from the ingested index."""
123
+ engine = _build_engine_or_exit(config)
124
+ try:
125
+ with engine:
126
+ answer = engine.query(question, top_k=top_k)
127
+ except PilotRAGError as exc:
128
+ render_error(exc, typer.get_text_stream("stderr"))
129
+ raise typer.Exit(EXIT_FAILURE) from None
130
+ render_answer(answer, typer.get_text_stream("stdout"))
131
+ raise typer.Exit(EXIT_OK)
132
+
133
+
134
+ if __name__ == "__main__":
135
+ app()
@@ -0,0 +1,57 @@
1
+ """Console rendering of ingestion reports and answers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import IO
6
+
7
+ import typer
8
+
9
+ from pilotrag.core.types import Answer, IngestionReport
10
+
11
+
12
+ def render_ingestion_report(report: IngestionReport, config_path: str, stdout: IO[str]) -> None:
13
+ """Print the ingestion summary in the documented output shape."""
14
+ typer.secho("PilotRAG ingestion", fg=typer.colors.CYAN, file=stdout)
15
+ typer.echo(f"Configuration: {config_path}", file=stdout)
16
+ typer.echo(f"Run id: {report.run_id}", file=stdout)
17
+ if report.dry_run:
18
+ typer.secho("Mode: dry run (no index changes)", fg=typer.colors.YELLOW, file=stdout)
19
+ typer.echo(f"Documents discovered: {report.discovered}", file=stdout)
20
+ typer.echo(f"Documents processed: {report.processed}", file=stdout)
21
+ typer.echo(f"Documents skipped: {report.skipped}", file=stdout)
22
+ typer.echo(f"Chunks indexed: {report.chunks_indexed}", file=stdout)
23
+ typer.echo(f"Duration: {report.duration_s}s", file=stdout)
24
+ for failure in report.failed:
25
+ typer.secho(
26
+ f"FAILED {failure.relative_path}: [{failure.error_code}] {failure.message}",
27
+ fg=typer.colors.RED,
28
+ file=stdout,
29
+ )
30
+ color = typer.colors.GREEN if report.status != "failed" else typer.colors.RED
31
+ typer.secho(f"Status: {report.status}", fg=color, file=stdout)
32
+
33
+
34
+ def render_answer(answer: Answer, stdout: IO[str]) -> None:
35
+ """Print the answer text and its source references."""
36
+ typer.echo(answer.text, file=stdout)
37
+ if answer.status == "insufficient_evidence":
38
+ typer.secho(
39
+ "Status: insufficient evidence (no relevant documents retrieved)",
40
+ fg=typer.colors.YELLOW,
41
+ file=stdout,
42
+ )
43
+ return
44
+ typer.secho("Sources:", fg=typer.colors.CYAN, file=stdout)
45
+ for source in answer.sources:
46
+ heading = f"#{source.heading_path}" if source.heading_path else ""
47
+ score = f" (score {source.score:.3f})" if source.score is not None else ""
48
+ typer.echo(f" - {source.document}{heading}{score}", file=stdout)
49
+
50
+
51
+ def render_error(error: Exception, stderr: IO[str]) -> None:
52
+ """Print an actionable error message with its code and hint."""
53
+ code = getattr(error, "code", "error")
54
+ hint = getattr(error, "hint", "")
55
+ typer.secho(f"Error [{code}]: {error}", fg=typer.colors.RED, file=stderr)
56
+ if hint:
57
+ typer.secho(f"Hint: {hint}", fg=typer.colors.YELLOW, file=stderr)
@@ -0,0 +1 @@
1
+ """Core layer: configuration, domain types, ids, errors and the provider registry."""