agentic-rag-mcp 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.
@@ -0,0 +1,3 @@
1
+ """Agentic RAG over your own documents, served as an MCP server."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,119 @@
1
+ """
2
+ Agentic RAG: let the model drive retrieval instead of retrieving once up front.
3
+
4
+ Naive RAG embeds the question, pulls the top-k chunks, puts them in the prompt
5
+ and answers. It works until a question needs more than one lookup. "How do I
6
+ authenticate a SqlSource after 3.0, and is the old way still supported?" needs
7
+ the migration guide AND the changelog, and a single top-k search often returns
8
+ one and misses the other.
9
+
10
+ Agentic RAG gives the model a search tool and lets it decide: search, read what
11
+ came back, notice the gap, search again, then answer. Same retrieval backend;
12
+ the difference is that the model does the multi-hop lookups itself.
13
+
14
+ Three entry points:
15
+ - naive_context(question) one retrieval, returned as text. No API key.
16
+ - naive_answer(question) one retrieval, then one model call. This is the
17
+ fair baseline: same model, same rules, one search.
18
+ - agentic_answer(question) the tool-using loop.
19
+
20
+ The trade-off is real: the agent costs several model round-trips and can wander
21
+ or over-search. For a single-fact question naive RAG is cheaper and just as
22
+ good - `agentic-rag-mcp eval` measures where that line falls on the demo
23
+ documents. Don't reach for the agent if one search does it.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ from collections.abc import Callable
29
+ from typing import Any
30
+
31
+ from .knowledge_base import Hit, KnowledgeBase
32
+ from .llm import Tool, complete, run_agent
33
+
34
+ SYSTEM = """You answer questions using only a knowledge base of documents, which
35
+ you reach through the kb_search tool.
36
+
37
+ How to work:
38
+ - Search for what you need. If the results leave a gap - a second part of the
39
+ question, a version detail, a follow-up - search again with a more specific
40
+ query before answering. Several searches are normal.
41
+ - Answer only from what the searches return. If the documents do not cover
42
+ something, say so plainly instead of guessing.
43
+ - Cite the chunk_ids you used, like (changelog.md#1), so the answer can be
44
+ checked.
45
+ - Keep the answer tight."""
46
+
47
+ NAIVE_SYSTEM = """You answer questions using only the excerpts provided with the
48
+ question. If they do not cover something, say so plainly instead of guessing.
49
+ Cite the chunk_ids you used, like (changelog.md#1). Keep the answer tight."""
50
+
51
+ Recorder = Callable[[str, list[Hit]], None]
52
+
53
+
54
+ def search_tool(kb: KnowledgeBase, *, record: Recorder | None = None) -> Tool:
55
+ """kb_search as a tool for the agent loop.
56
+
57
+ `record(query, hits)` sees every search the agent makes, which is how the
58
+ evaluation scores what the agent actually retrieved.
59
+ """
60
+
61
+ def kb_search(query: str, k: int = 4) -> list[dict]:
62
+ hits = kb.search(query, k=max(1, min(int(k), 20)))
63
+ if record is not None:
64
+ record(query, hits)
65
+ return [{"chunk_id": h.chunk.chunk_id, "score": round(h.score, 3),
66
+ "text": h.chunk.text} for h in hits]
67
+
68
+ return Tool(
69
+ name="kb_search",
70
+ description="Semantic search over the knowledge base. Returns chunks with a "
71
+ "chunk_id and text. Call it as many times as you need.",
72
+ input_schema={
73
+ "type": "object",
74
+ "properties": {
75
+ "query": {"type": "string", "description": "What to look for."},
76
+ "k": {"type": "integer", "description": "How many chunks, 1-20 (default 4)."},
77
+ },
78
+ "required": ["query"],
79
+ },
80
+ fn=kb_search,
81
+ )
82
+
83
+
84
+ def format_context(hits: list[Hit]) -> str:
85
+ return "\n\n".join(f"({h.chunk.chunk_id}) {h.chunk.text}" for h in hits)
86
+
87
+
88
+ def naive_context(question: str, kb: KnowledgeBase, k: int = 4) -> str:
89
+ """Single-shot retrieval with no model: the context naive RAG would use."""
90
+ return format_context(kb.search(question, k=k))
91
+
92
+
93
+ def naive_answer(
94
+ question: str,
95
+ kb: KnowledgeBase,
96
+ k: int = 4,
97
+ *,
98
+ client: Any = None,
99
+ model: str | None = None,
100
+ ) -> str:
101
+ """Retrieve once, then answer with one model call."""
102
+ context = naive_context(question, kb, k)
103
+ return complete(NAIVE_SYSTEM, f"QUESTION:\n{question}\n\nEXCERPTS:\n{context}",
104
+ client=client, model=model)
105
+
106
+
107
+ def agentic_answer(
108
+ question: str,
109
+ kb: KnowledgeBase,
110
+ *,
111
+ client: Any = None,
112
+ model: str | None = None,
113
+ max_turns: int = 8,
114
+ on_event: Callable[[str, dict], None] | None = None,
115
+ record: Recorder | None = None,
116
+ ) -> str:
117
+ """The tool-using loop: the model searches as many times as it needs."""
118
+ return run_agent(SYSTEM, [search_tool(kb, record=record)], question,
119
+ client=client, model=model, max_turns=max_turns, on_event=on_event)
@@ -0,0 +1,112 @@
1
+ """
2
+ Where things are kept between runs, and the on-disk cache of chunk embeddings.
3
+
4
+ Embedding a corpus is the slow part of starting up, and an MCP client launches
5
+ the server fresh for every session. So the vectors are cached, keyed by a hash
6
+ of the model and every chunk's id and text: change one character of one file
7
+ and the key changes, so a stale vector can never be served.
8
+
9
+ The cache is an optimisation and never a source of truth. Anything wrong with
10
+ it - missing, truncated, the wrong shape, unreadable - means "re-embed", not an
11
+ error. Files are loaded with pickling disabled, so a planted cache file cannot
12
+ run code.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import logging
19
+ import os
20
+ import sys
21
+ import tempfile
22
+ from collections.abc import Iterable
23
+ from pathlib import Path
24
+
25
+ import numpy as np
26
+
27
+ log = logging.getLogger(__name__)
28
+
29
+ APP_NAME = "agentic-rag-mcp"
30
+
31
+
32
+ def cache_root() -> Path:
33
+ """A persistent per-user cache folder, overridable with AGENTIC_RAG_CACHE_DIR."""
34
+ override = os.environ.get("AGENTIC_RAG_CACHE_DIR")
35
+ if override:
36
+ return Path(override).expanduser()
37
+ if sys.platform == "win32":
38
+ base = Path(os.environ.get("LOCALAPPDATA") or Path.home() / "AppData" / "Local")
39
+ return base / APP_NAME / "Cache"
40
+ if sys.platform == "darwin":
41
+ return Path.home() / "Library" / "Caches" / APP_NAME
42
+ base = os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache"
43
+ return Path(base) / APP_NAME
44
+
45
+
46
+ def corpus_key(model: str, chunks: Iterable[tuple[str, str]]) -> str:
47
+ """Hash of the model and every (chunk_id, text) pair, in order."""
48
+ h = hashlib.sha256()
49
+ h.update(model.encode())
50
+ for chunk_id, text in chunks:
51
+ h.update(b"\x00")
52
+ h.update(chunk_id.encode())
53
+ h.update(b"\x01")
54
+ h.update(text.encode())
55
+ return h.hexdigest()
56
+
57
+
58
+ def _group(docs_dir: Path) -> str:
59
+ """Short stable name for one docs folder, so its old caches can be pruned."""
60
+ return hashlib.sha256(str(Path(docs_dir).resolve()).encode()).hexdigest()[:16]
61
+
62
+
63
+ def _vectors_dir() -> Path:
64
+ return cache_root() / "vectors"
65
+
66
+
67
+ def _path(docs_dir: Path, key: str) -> Path:
68
+ return _vectors_dir() / f"{_group(docs_dir)}-{key[:32]}.npy"
69
+
70
+
71
+ def load_vectors(docs_dir: Path, key: str, expected_rows: int) -> np.ndarray | None:
72
+ path = _path(docs_dir, key)
73
+ if not path.exists():
74
+ return None
75
+ try:
76
+ vecs = np.load(path, allow_pickle=False)
77
+ except (OSError, ValueError) as exc:
78
+ log.warning("ignoring unreadable cache %s: %s", path, exc)
79
+ return None
80
+ if vecs.ndim != 2 or vecs.shape[0] != expected_rows or vecs.dtype != np.float32:
81
+ log.warning("ignoring cache %s: shape %s does not match %d chunks",
82
+ path, vecs.shape, expected_rows)
83
+ return None
84
+ return vecs
85
+
86
+
87
+ def save_vectors(docs_dir: Path, key: str, vecs: np.ndarray) -> Path | None:
88
+ """Write atomically, then drop older caches for the same folder.
89
+
90
+ Returns the path, or None if the cache could not be written; a read-only
91
+ home directory should cost a re-embed next time, not a crash now.
92
+ """
93
+ target = _path(docs_dir, key)
94
+ try:
95
+ target.parent.mkdir(parents=True, exist_ok=True)
96
+ fd, tmp = tempfile.mkstemp(dir=target.parent, suffix=".tmp")
97
+ try:
98
+ with os.fdopen(fd, "wb") as fh:
99
+ np.save(fh, np.ascontiguousarray(vecs, dtype=np.float32))
100
+ os.replace(tmp, target)
101
+ except BaseException:
102
+ Path(tmp).unlink(missing_ok=True)
103
+ raise
104
+ except OSError as exc:
105
+ log.warning("could not write embedding cache: %s", exc)
106
+ return None
107
+
108
+ prefix = f"{_group(docs_dir)}-"
109
+ for old in target.parent.glob(f"{prefix}*.npy"):
110
+ if old != target:
111
+ old.unlink(missing_ok=True)
112
+ return target
agentic_rag_mcp/cli.py ADDED
@@ -0,0 +1,230 @@
1
+ """
2
+ Command line for the server, the index, and the agents.
3
+
4
+ agentic-rag-mcp serve [--docs DIR] MCP server on stdio
5
+ agentic-rag-mcp index [--docs DIR] build the cache, show what is indexed
6
+ agentic-rag-mcp search QUERY [--docs DIR] [-k 4]
7
+ agentic-rag-mcp ask QUESTION [--docs DIR] [--naive | --pipeline]
8
+ agentic-rag-mcp eval [-k 4] [--agent] [--json]
9
+
10
+ The docs folder comes from --docs, then AGENTIC_RAG_DOCS, then the bundled
11
+ demo documents.
12
+
13
+ `serve` writes nothing to stdout. On stdio that channel belongs to the
14
+ protocol, and a stray print would corrupt it; logs go to stderr.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import json
21
+ import logging
22
+ import os
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ from . import __version__
27
+ from .corpus import DOC_SUFFIXES, find_documents
28
+ from .embedding import Embedder
29
+
30
+
31
+ def _docs_dir(args: argparse.Namespace) -> Path | None:
32
+ value = getattr(args, "docs", None) or os.environ.get("AGENTIC_RAG_DOCS")
33
+ return Path(value).expanduser().resolve() if value else None
34
+
35
+
36
+ def _check_docs(docs: Path | None) -> str | None:
37
+ """A message if the folder cannot be served, else None."""
38
+ if docs is None:
39
+ return None
40
+ if not docs.is_dir():
41
+ return f"docs folder not found: {docs}"
42
+ if not find_documents(docs):
43
+ return f"no {', '.join(DOC_SUFFIXES)} files under {docs}"
44
+ return None
45
+
46
+
47
+ def _kb(args: argparse.Namespace, embedder: Embedder | None):
48
+ from .knowledge_base import KnowledgeBase
49
+
50
+ return KnowledgeBase(_docs_dir(args), embedder=embedder)
51
+
52
+
53
+ def _serve(args: argparse.Namespace, embedder: Embedder | None) -> int:
54
+ from .server import RagServer
55
+
56
+ logging.basicConfig(level=logging.INFO if args.verbose else logging.WARNING,
57
+ stream=sys.stderr, format="%(levelname)s %(name)s: %(message)s")
58
+ docs = _docs_dir(args)
59
+ # Fail at launch, where the person configuring the client sees it, rather
60
+ # than at the first tool call, where only the model does.
61
+ problem = _check_docs(docs)
62
+ if problem:
63
+ print(f"agentic-rag-mcp: {problem}", file=sys.stderr)
64
+ return 2
65
+ RagServer(docs, embedder=embedder).run()
66
+ return 0
67
+
68
+
69
+ def _index(args: argparse.Namespace, embedder: Embedder | None) -> int:
70
+ kb = _kb(args, embedder)
71
+ stats = kb.stats()
72
+ if args.json:
73
+ print(json.dumps({**stats, "sources": kb.sources()}, indent=2))
74
+ return 0
75
+ print(f"{stats['documents']} documents, {stats['chunks']} chunks from {stats['docs_dir']}")
76
+ print(f"model {stats['embedding_model']} ({stats['dimensions']} dimensions), "
77
+ f"{'loaded from cache' if stats['loaded_from_cache'] else 'embedded and cached'}")
78
+ for source in kb.sources():
79
+ print(f" {source}")
80
+ return 0
81
+
82
+
83
+ def _search(args: argparse.Namespace, embedder: Embedder | None) -> int:
84
+ hits = _kb(args, embedder).search(args.query, k=args.k)
85
+ if args.json:
86
+ print(json.dumps([{"chunk_id": h.chunk.chunk_id, "source": h.chunk.source,
87
+ "score": round(h.score, 4), "text": h.chunk.text} for h in hits],
88
+ indent=2))
89
+ return 0
90
+ for h in hits:
91
+ print(f"{h.score:.3f} {h.chunk.chunk_id}")
92
+ print(f" {h.chunk.text[:160]}{'...' if len(h.chunk.text) > 160 else ''}")
93
+ return 0
94
+
95
+
96
+ def _ask(args: argparse.Namespace, embedder: Embedder | None) -> int:
97
+ from .agentic import agentic_answer, naive_answer, naive_context
98
+ from .llm import AgentStopped, have_credentials
99
+ from .multi_agent import llm_roles, orchestrate, stub_roles
100
+
101
+ kb = _kb(args, embedder)
102
+ if not have_credentials():
103
+ print("No Anthropic credentials found (ANTHROPIC_API_KEY, or `ant auth login`).",
104
+ file=sys.stderr)
105
+ if args.pipeline:
106
+ print("Running the pipeline with stub roles: retrieval is real, the model "
107
+ "is faked.\n", file=sys.stderr)
108
+ print(orchestrate(args.question, stub_roles(kb),
109
+ log=lambda m: print(m, file=sys.stderr)))
110
+ else:
111
+ print("Showing what a single search retrieves instead.\n", file=sys.stderr)
112
+ print(naive_context(args.question, kb, k=args.k))
113
+ return 0
114
+
115
+ calls = {"requests": 0, "input_tokens": 0, "output_tokens": 0, "cache_read_input_tokens": 0}
116
+
117
+ def trace(kind: str, payload: dict) -> None:
118
+ if kind == "tool_call":
119
+ print(f" search: {payload['input'].get('query')!r}", file=sys.stderr)
120
+ elif kind == "response":
121
+ calls["requests"] += 1
122
+ for key in ("input_tokens", "output_tokens", "cache_read_input_tokens"):
123
+ calls[key] += payload["usage"][key]
124
+
125
+ try:
126
+ if args.pipeline:
127
+ answer = orchestrate(args.question, llm_roles(kb),
128
+ log=lambda m: print(m, file=sys.stderr))
129
+ elif args.naive:
130
+ answer = naive_answer(args.question, kb, k=args.k)
131
+ else:
132
+ answer = agentic_answer(args.question, kb, on_event=trace)
133
+ except AgentStopped as exc:
134
+ print(f"stopped: {exc}", file=sys.stderr)
135
+ if exc.partial:
136
+ print(exc.partial)
137
+ return 1
138
+
139
+ print(answer)
140
+ if calls["requests"]:
141
+ print(f"\n[{calls['requests']} model requests, {calls['input_tokens']} input tokens "
142
+ f"({calls['cache_read_input_tokens']} from cache), "
143
+ f"{calls['output_tokens']} output tokens]", file=sys.stderr)
144
+ return 0
145
+
146
+
147
+ def _eval(args: argparse.Namespace, embedder: Embedder | None) -> int:
148
+ from .evaluation import DEMO_QUESTIONS, STRATEGIES, agent_strategy, evaluate, format_report
149
+ from .knowledge_base import KnowledgeBase
150
+
151
+ # The questions are about the bundled demo documents, so that is the
152
+ # corpus, whatever --docs or AGENTIC_RAG_DOCS say.
153
+ kb = KnowledgeBase(None, embedder=embedder)
154
+ strategies = dict(STRATEGIES)
155
+ if args.agent:
156
+ from .llm import have_credentials
157
+
158
+ if not have_credentials():
159
+ print("--agent needs Anthropic credentials (ANTHROPIC_API_KEY, or `ant auth "
160
+ "login`).", file=sys.stderr)
161
+ return 2
162
+ print(f"--agent makes real API calls: one agent run per question "
163
+ f"({len(DEMO_QUESTIONS)} questions).", file=sys.stderr)
164
+ strategies["agent"] = agent_strategy()
165
+ report = evaluate(kb, k=args.k, strategies=strategies)
166
+ print(json.dumps(report, indent=2) if args.json else format_report(report))
167
+ return 0
168
+
169
+
170
+ def build_parser() -> argparse.ArgumentParser:
171
+ parser = argparse.ArgumentParser(
172
+ prog="agentic-rag-mcp",
173
+ description="Agentic RAG over your own documents, served over MCP.",
174
+ )
175
+ parser.add_argument("--version", action="version", version=f"agentic-rag-mcp {__version__}")
176
+ sub = parser.add_subparsers(dest="command", required=True)
177
+
178
+ def docs_arg(p: argparse.ArgumentParser) -> None:
179
+ p.add_argument("--docs", metavar="DIR",
180
+ help="folder of .md/.txt/.rst files (default: $AGENTIC_RAG_DOCS, "
181
+ "then the bundled demo docs)")
182
+
183
+ p = sub.add_parser("serve", help="run the MCP server on stdio")
184
+ docs_arg(p)
185
+ p.add_argument("-v", "--verbose", action="store_true", help="log to stderr at INFO")
186
+
187
+ p = sub.add_parser("index", help="build the index cache and show what is indexed")
188
+ docs_arg(p)
189
+ p.add_argument("--json", action="store_true")
190
+
191
+ p = sub.add_parser("search", help="semantic search from the command line")
192
+ p.add_argument("query")
193
+ docs_arg(p)
194
+ p.add_argument("-k", type=int, default=4)
195
+ p.add_argument("--json", action="store_true")
196
+
197
+ p = sub.add_parser("ask", help="answer a question with the agent (needs credentials)")
198
+ p.add_argument("question")
199
+ docs_arg(p)
200
+ p.add_argument("-k", type=int, default=4, help="chunks per search for --naive")
201
+ mode = p.add_mutually_exclusive_group()
202
+ mode.add_argument("--naive", action="store_true", help="one search, one model call")
203
+ mode.add_argument("--pipeline", action="store_true",
204
+ help="retriever -> synthesizer -> verifier")
205
+
206
+ p = sub.add_parser("eval", help="measure single-search recall on the demo documents")
207
+ p.add_argument("-k", type=int, default=4)
208
+ p.add_argument("--agent", action="store_true",
209
+ help="also score a real agent's searches (makes API calls)")
210
+ p.add_argument("--json", action="store_true")
211
+ return parser
212
+
213
+
214
+ _COMMANDS = {"serve": _serve, "index": _index, "search": _search, "ask": _ask, "eval": _eval}
215
+
216
+
217
+ def main(argv: list[str] | None = None, *, embedder: Embedder | None = None) -> int:
218
+ args = build_parser().parse_args(argv)
219
+ if getattr(args, "k", 1) < 1:
220
+ print("agentic-rag-mcp: -k must be at least 1", file=sys.stderr)
221
+ return 2
222
+ if args.command != "serve":
223
+ problem = _check_docs(_docs_dir(args)) if args.command != "eval" else None
224
+ if problem:
225
+ print(f"agentic-rag-mcp: {problem}", file=sys.stderr)
226
+ return 2
227
+ try:
228
+ return _COMMANDS[args.command](args, embedder)
229
+ except KeyboardInterrupt:
230
+ return 130
@@ -0,0 +1,124 @@
1
+ """
2
+ Loading documents and cutting them into chunks.
3
+
4
+ Kept deliberately plain: fixed-size character windows with overlap, over text
5
+ whose whitespace has been collapsed. No semantic chunking and no markdown-aware
6
+ splitting. Those are real upgrades on a large corpus, but they would be noise
7
+ for what this project is about, which is the orchestration on top.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import logging
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ log = logging.getLogger(__name__)
17
+
18
+ CHUNK_SIZE = 700
19
+ CHUNK_OVERLAP = 120
20
+
21
+ # Plain-text formats only. PDFs and office documents need a parser each, and a
22
+ # bad extraction quietly poisons retrieval, so they are left to a later release.
23
+ DOC_SUFFIXES = (".md", ".markdown", ".txt", ".rst")
24
+
25
+ # A single file this large is almost always a log or a data dump that got caught
26
+ # by the glob, not documentation.
27
+ MAX_FILE_BYTES = 5 * 1024 * 1024
28
+
29
+ _SKIP_DIRS = {"node_modules", "__pycache__", "site-packages"}
30
+
31
+ DEMO_DOCS_DIR = Path(__file__).resolve().parent / "demo_docs"
32
+
33
+
34
+ @dataclass(frozen=True)
35
+ class Chunk:
36
+ chunk_id: str # e.g. "changelog.md#2"
37
+ source: str # path relative to the docs folder, always with forward slashes
38
+ text: str
39
+
40
+
41
+ def chunk_text(
42
+ source: str,
43
+ text: str,
44
+ size: int = CHUNK_SIZE,
45
+ overlap: int = CHUNK_OVERLAP,
46
+ ) -> list[Chunk]:
47
+ """Cut one document into overlapping fixed-size windows.
48
+
49
+ The loop stops as soon as a window reaches the end of the text. Stepping
50
+ blindly over range(0, len, step) instead emits a final window that lies
51
+ entirely inside the one before it whenever the tail is shorter than the
52
+ overlap - a duplicate that crowds a real result out of the top k.
53
+ """
54
+ if size <= 0:
55
+ raise ValueError("chunk size must be positive")
56
+ if not 0 <= overlap < size:
57
+ raise ValueError("overlap must be at least 0 and smaller than the chunk size")
58
+
59
+ text = " ".join(text.split())
60
+ if not text:
61
+ return []
62
+
63
+ step = size - overlap
64
+ chunks: list[Chunk] = []
65
+ start = 0
66
+ while True:
67
+ chunks.append(
68
+ Chunk(
69
+ chunk_id=f"{source}#{len(chunks)}",
70
+ source=source,
71
+ text=text[start : start + size],
72
+ )
73
+ )
74
+ if start + size >= len(text):
75
+ return chunks
76
+ start += step
77
+
78
+
79
+ def _skipped(rel: Path) -> bool:
80
+ return any(part.startswith(".") or part in _SKIP_DIRS for part in rel.parts[:-1])
81
+
82
+
83
+ def find_documents(docs_dir: Path) -> list[Path]:
84
+ """Every indexable file under docs_dir, in a stable order."""
85
+ root = Path(docs_dir)
86
+ if not root.is_dir():
87
+ raise FileNotFoundError(f"docs folder not found: {root}")
88
+ found = []
89
+ for path in root.rglob("*"):
90
+ if not path.is_file() or path.suffix.lower() not in DOC_SUFFIXES:
91
+ continue
92
+ rel = path.relative_to(root)
93
+ if _skipped(rel) or rel.name.startswith("."):
94
+ continue
95
+ found.append(path)
96
+ return sorted(found, key=lambda p: p.relative_to(root).as_posix())
97
+
98
+
99
+ def load_documents(docs_dir: Path) -> list[tuple[str, str]]:
100
+ """Read every document as (source, text), where source is its relative path."""
101
+ root = Path(docs_dir)
102
+ docs = []
103
+ for path in find_documents(root):
104
+ size = path.stat().st_size
105
+ if size > MAX_FILE_BYTES:
106
+ log.warning("skipping %s: %d bytes is over the %d byte limit",
107
+ path, size, MAX_FILE_BYTES)
108
+ continue
109
+ # Decode leniently: one stray byte in one file should not stop the
110
+ # whole corpus from loading.
111
+ text = path.read_bytes().decode("utf-8", errors="replace")
112
+ docs.append((path.relative_to(root).as_posix(), text))
113
+ return docs
114
+
115
+
116
+ def build_chunks(
117
+ docs_dir: Path,
118
+ size: int = CHUNK_SIZE,
119
+ overlap: int = CHUNK_OVERLAP,
120
+ ) -> list[Chunk]:
121
+ chunks: list[Chunk] = []
122
+ for source, text in load_documents(docs_dir):
123
+ chunks.extend(chunk_text(source, text, size, overlap))
124
+ return chunks
@@ -0,0 +1,28 @@
1
+ # Halyard — API reference (selected)
2
+
3
+ ## Pipeline(stages, checkpoint=None)
4
+ Construct a pipeline. `stages` is a list of callables/`Stage` objects.
5
+ `checkpoint` is an optional `Checkpoint` backend; if omitted, no checkpointing.
6
+
7
+ - `pipeline.run(source, *, batch_size=256, max_retries=3)` — run the pipeline over
8
+ a source. Returns a `RunResult` with `.records_in`, `.records_out`, `.failed`.
9
+ - `max_retries` applies per stage, per batch. Backoff is exponential, base 0.5s.
10
+
11
+ ## connect(dsn, *, pool_size=5, timeout=30)
12
+ Open a database connection for `SqlSource`. `dsn` is a connection string. Returns a
13
+ `Connection`. **As of 3.0 this is the only supported way to authenticate a
14
+ `SqlSource`** — see the migration guide.
15
+
16
+ ## SqlSource(connection, query)
17
+ A source that streams rows from a SQL query. Requires a `Connection` from
18
+ `connect()`. Added in 3.0.
19
+
20
+ ## FileSource(path, *, format="jsonl")
21
+ Stream records from a file. Supported formats: `jsonl`, `csv`.
22
+
23
+ ## Checkpoint backends
24
+ - `FileCheckpoint(dir)` — stores progress on local disk.
25
+ - `MemoryCheckpoint()` — in-process only; useful for tests, lost on exit.
26
+
27
+ Checkpointing records the index of the last completed stage and the offset within
28
+ the source. On resume, completed stages are skipped.
@@ -0,0 +1,22 @@
1
+ # Halyard — changelog
2
+
3
+ ## 3.1
4
+ - Added `SqlSource` streaming with server-side cursors (lower memory on big queries).
5
+ - `RunResult` now includes `.failed`, a list of records that exhausted retries.
6
+
7
+ ## 3.0 (breaking)
8
+ - **Breaking:** `SqlSource` no longer accepts a raw `dsn=` argument. You must now
9
+ pass a `Connection` created with `connect(dsn)`. This was done so connection
10
+ pooling and timeouts are configured in one place.
11
+ - **Breaking:** the old `auth=` keyword on `SqlSource` was removed. Credentials now
12
+ live in the DSN passed to `connect()`.
13
+ - Added `connect()`, connection pooling, and `pool_size` / `timeout` options.
14
+ - `Pipeline.run` default `batch_size` changed from 1000 to 256.
15
+
16
+ ## 2.4
17
+ - Added `MemoryCheckpoint`.
18
+ - Deprecated the `auth=` keyword on `SqlSource` (removed in 3.0).
19
+
20
+ ## 2.3
21
+ - A bug in `FileCheckpoint` could double-process the final batch after a resume.
22
+ Fixed in 2.3.1. If you are on 2.3.0, upgrade.
@@ -0,0 +1,26 @@
1
+ # Halyard — FAQ
2
+
3
+ **Q: A run failed halfway. Do I lose everything?**
4
+ Only if you ran without a checkpoint. With a `FileCheckpoint`, re-running resumes
5
+ from the last completed stage and the last source offset. With `MemoryCheckpoint`,
6
+ progress is lost when the process exits, so it only helps within a single run.
7
+
8
+ **Q: Why are some records in `RunResult.failed`?**
9
+ A record lands in `.failed` when a stage raised on it for every retry attempt
10
+ (`max_retries`, default 3, exponential backoff). Failed records do not stop the
11
+ run; they are collected so you can inspect or replay them.
12
+
13
+ **Q: My SqlSource code broke after upgrading to 3.0.**
14
+ Almost certainly the auth change. `SqlSource` no longer takes `dsn=` or `auth=`;
15
+ create a `Connection` with `connect(dsn)` first and pass that. See the migration
16
+ guide.
17
+
18
+ **Q: Can stages run in parallel?**
19
+ No. Stages run in order, one after another. Within a stage you can do whatever you
20
+ like (including your own threading), but Halyard itself does not parallelise across
21
+ stages — it is a straight line, not a DAG.
22
+
23
+ **Q: How big should batch_size be?**
24
+ Bigger batches amortise per-batch overhead but use more memory and make retries
25
+ coarser (a whole batch retries together). The 3.0 default is 256; 1000 was the old
26
+ default.