rag-kit-dev 0.0.0 → 0.1.2
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.
- package/LICENSE +21 -0
- package/README.md +78 -3
- package/bin/rag-kit-dev.js +17 -0
- package/lib/args.js +90 -0
- package/lib/cli.js +146 -0
- package/lib/install.js +125 -0
- package/lib/process.js +45 -0
- package/lib/prompt.js +74 -0
- package/lib/python.js +64 -0
- package/lib/scaffold.js +95 -0
- package/lib/validate.js +70 -0
- package/lib/version.js +7 -0
- package/package.json +31 -3
- package/templates/default/README.md +70 -0
- package/templates/default/_env.example +28 -0
- package/templates/default/_gitignore +14 -0
- package/templates/default/data/_gitkeep +1 -0
- package/templates/default/example.py +46 -0
- package/templates/default/rag-kit.toml +3 -0
- package/templates/default/requirements.txt.tmpl +2 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Riyad
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,5 +1,80 @@
|
|
|
1
1
|
# rag-kit-dev
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
Create a [rag-kit](https://github.com/shamiulriyad/rag-learning) project with
|
|
4
|
+
one command: a folder with settings, a document folder and an example, plus a
|
|
5
|
+
`.venv` with rag-kit installed (the `ragkit-dev` package from PyPI).
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npx rag-kit-dev my-rag
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
You need **Node.js 20+** and **Python 3.11 or 3.12** (3.11 is preferred when
|
|
12
|
+
both are installed). [uv](https://docs.astral.sh/uv/) is used when it is
|
|
13
|
+
installed; otherwise pip.
|
|
14
|
+
|
|
15
|
+
## The embedding choice
|
|
16
|
+
|
|
17
|
+
You are asked how the project creates embeddings, with what each option costs,
|
|
18
|
+
before anything is installed. There is no default; in scripts and CI pass
|
|
19
|
+
`--embeddings`.
|
|
20
|
+
|
|
21
|
+
- **`local`** - BAAI/bge-m3 on your computer. No API key for embeddings.
|
|
22
|
+
Installs PyTorch and sentence-transformers: about 1 GB on disk (measured on
|
|
23
|
+
Windows); actual disk use varies by platform and dependency versions. On Linux
|
|
24
|
+
the CPU-only PyTorch build is used unless you pass `--gpu`. The BGE-M3 model
|
|
25
|
+
(about 2.3 GB) is downloaded separately into the Hugging Face cache the first
|
|
26
|
+
time you ingest a document, never during setup.
|
|
27
|
+
- **`gemini`** - Google's embedding API. Small install, no model download.
|
|
28
|
+
Needs a `GOOGLE_API_KEY` with embedding quota; document text is sent to
|
|
29
|
+
Google.
|
|
30
|
+
|
|
31
|
+
Either way, answers are written by Gemini and need `GOOGLE_API_KEY`.
|
|
32
|
+
|
|
33
|
+
## What you get
|
|
34
|
+
|
|
35
|
+
```
|
|
36
|
+
my-rag/
|
|
37
|
+
rag-kit.toml marks the project folder
|
|
38
|
+
.env.example settings template - copy it to .env and add your key
|
|
39
|
+
.gitignore keeps .env, qdrant_data/ and .venv/ out of git
|
|
40
|
+
requirements.txt ragkit-dev[...]==<this generator's version>
|
|
41
|
+
data/ put your documents here
|
|
42
|
+
example.py ingest and ask from Python
|
|
43
|
+
README.md next steps
|
|
44
|
+
.venv/ unless --no-install
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
rag-kit-dev **never creates `.env` and never asks for an API key**. Copy
|
|
48
|
+
`.env.example` to `.env` (`cp .env.example .env`, or
|
|
49
|
+
`Copy-Item .env.example .env` in PowerShell) and add the key yourself.
|
|
50
|
+
|
|
51
|
+
## Options
|
|
52
|
+
|
|
53
|
+
```
|
|
54
|
+
--embeddings local|gemini choose without being asked (required when not interactive)
|
|
55
|
+
--gpu local embeddings on Linux: keep PyTorch's CUDA build
|
|
56
|
+
--python PATH use this Python 3.11/3.12 interpreter
|
|
57
|
+
--no-uv use pip even if uv is installed
|
|
58
|
+
--no-install only write the project files
|
|
59
|
+
-y, --yes never prompt (needs --embeddings)
|
|
60
|
+
-h, --help / -v, --version
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Testing only: `--package-spec SPEC` installs rag-kit from a local wheel (a
|
|
64
|
+
relative path is taken from the folder you run the command in) or a
|
|
65
|
+
requirement such as `ragkit-dev==0.1.0rc1`; `--test-pypi` takes ragkit-dev (and
|
|
66
|
+
only ragkit-dev) from TestPyPI.
|
|
67
|
+
|
|
68
|
+
## Safety
|
|
69
|
+
|
|
70
|
+
- The project name must be a plain folder name; paths, `..`, and Windows
|
|
71
|
+
device names are refused, and an existing folder must be empty. These checks,
|
|
72
|
+
the embedding choice and finding Python all happen before any file is written.
|
|
73
|
+
- Existing files are never overwritten, and nothing is ever deleted. If the
|
|
74
|
+
install fails, the project is kept and the exact commands to finish are printed.
|
|
75
|
+
- External programs are started without a shell, and environment values are
|
|
76
|
+
never printed.
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
MIT
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Entry point for `npx rag-kit-dev <project-name>`. The Node version check runs
|
|
3
|
+
// before any module that needs Node 20 is loaded.
|
|
4
|
+
|
|
5
|
+
const major = Number(process.versions.node.split(".")[0]);
|
|
6
|
+
if (major < 20) {
|
|
7
|
+
process.stderr.write(`rag-kit-dev needs Node.js 20 or newer (this is ${process.versions.node}).\n`);
|
|
8
|
+
process.exit(1);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const { main } = await import("../lib/cli.js");
|
|
12
|
+
try {
|
|
13
|
+
process.exitCode = await main(process.argv.slice(2));
|
|
14
|
+
} catch (error) {
|
|
15
|
+
process.stderr.write(`rag-kit-dev failed unexpectedly: ${error?.stack ?? error}\n`);
|
|
16
|
+
process.exitCode = 1;
|
|
17
|
+
}
|
package/lib/args.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Command-line arguments for `npx rag-kit-dev <name> [options]`.
|
|
2
|
+
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
|
|
5
|
+
import { legacyPackageSpecError } from "./install.js";
|
|
6
|
+
|
|
7
|
+
export const EMBEDDING_CHOICES = ["local", "gemini"];
|
|
8
|
+
|
|
9
|
+
export const USAGE = `Usage: npx rag-kit-dev <project-name> [options]
|
|
10
|
+
|
|
11
|
+
Creates a new folder <project-name> with a rag-kit project and, unless
|
|
12
|
+
--no-install is given, a .venv with rag-kit installed.
|
|
13
|
+
|
|
14
|
+
Options:
|
|
15
|
+
--embeddings local|gemini how the project creates embeddings (asked if omitted;
|
|
16
|
+
required when not running in an interactive terminal)
|
|
17
|
+
--gpu local embeddings on Linux: keep PyTorch's CUDA build
|
|
18
|
+
(default: CPU-only PyTorch)
|
|
19
|
+
--python PATH Python 3.11 or 3.12 interpreter to use
|
|
20
|
+
--no-uv use pip even if uv is installed
|
|
21
|
+
--no-install only write the project files
|
|
22
|
+
-y, --yes never prompt (needs --embeddings)
|
|
23
|
+
-h, --help show this help
|
|
24
|
+
-v, --version show the generator version
|
|
25
|
+
|
|
26
|
+
Testing only (before ragkit-dev is published, or for release candidates):
|
|
27
|
+
--package-spec SPEC install rag-kit from SPEC instead of PyPI, e.g. a
|
|
28
|
+
local wheel path or "ragkit-dev==0.1.0rc1"
|
|
29
|
+
--test-pypi install from TestPyPI (dependencies from PyPI)
|
|
30
|
+
`;
|
|
31
|
+
|
|
32
|
+
export class UsageError extends Error {}
|
|
33
|
+
|
|
34
|
+
const OPTIONS = {
|
|
35
|
+
embeddings: { type: "string" },
|
|
36
|
+
gpu: { type: "boolean" },
|
|
37
|
+
python: { type: "string" },
|
|
38
|
+
"no-uv": { type: "boolean" },
|
|
39
|
+
"no-install": { type: "boolean" },
|
|
40
|
+
yes: { type: "boolean", short: "y" },
|
|
41
|
+
"package-spec": { type: "string" },
|
|
42
|
+
"test-pypi": { type: "boolean" },
|
|
43
|
+
help: { type: "boolean", short: "h" },
|
|
44
|
+
version: { type: "boolean", short: "v" },
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export function parseCliArgs(argv) {
|
|
48
|
+
let parsed;
|
|
49
|
+
try {
|
|
50
|
+
parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true });
|
|
51
|
+
} catch (error) {
|
|
52
|
+
throw new UsageError(error.message);
|
|
53
|
+
}
|
|
54
|
+
const { values, positionals } = parsed;
|
|
55
|
+
const options = {
|
|
56
|
+
help: Boolean(values.help),
|
|
57
|
+
version: Boolean(values.version),
|
|
58
|
+
name: positionals[0],
|
|
59
|
+
embeddings: values.embeddings,
|
|
60
|
+
gpu: Boolean(values.gpu),
|
|
61
|
+
python: values.python,
|
|
62
|
+
useUv: !values["no-uv"],
|
|
63
|
+
install: !values["no-install"],
|
|
64
|
+
yes: Boolean(values.yes),
|
|
65
|
+
packageSpec: values["package-spec"],
|
|
66
|
+
testPypi: Boolean(values["test-pypi"]),
|
|
67
|
+
};
|
|
68
|
+
if (options.help || options.version) {
|
|
69
|
+
return options;
|
|
70
|
+
}
|
|
71
|
+
if (positionals.length === 0) {
|
|
72
|
+
throw new UsageError("Missing the project name, e.g. `npx rag-kit-dev my-rag`.");
|
|
73
|
+
}
|
|
74
|
+
if (positionals.length > 1) {
|
|
75
|
+
throw new UsageError(`Expected one project name, got ${positionals.length}: ${positionals.join(" ")}`);
|
|
76
|
+
}
|
|
77
|
+
if (options.embeddings !== undefined && !EMBEDDING_CHOICES.includes(options.embeddings)) {
|
|
78
|
+
throw new UsageError(`--embeddings must be "local" or "gemini", got "${options.embeddings}".`);
|
|
79
|
+
}
|
|
80
|
+
for (const key of ["python", "packageSpec"]) {
|
|
81
|
+
if (options[key] !== undefined && options[key].trim() === "") {
|
|
82
|
+
throw new UsageError(`--${key === "python" ? "python" : "package-spec"} needs a value.`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
const legacy = options.packageSpec === undefined ? null : legacyPackageSpecError(options.packageSpec);
|
|
86
|
+
if (legacy) {
|
|
87
|
+
throw new UsageError(legacy);
|
|
88
|
+
}
|
|
89
|
+
return options;
|
|
90
|
+
}
|
package/lib/cli.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// `npx rag-kit-dev <name>`: validate, choose embeddings, find Python, write the
|
|
2
|
+
// project, install it. Nothing is written before every check has passed, and
|
|
3
|
+
// nothing is ever deleted - a failed install leaves the project for a retry.
|
|
4
|
+
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
|
|
7
|
+
import { parseCliArgs, USAGE, UsageError } from "./args.js";
|
|
8
|
+
import { installEnv, installPlan, resolvePackageSpec, runSteps } from "./install.js";
|
|
9
|
+
import { formatCommand, run as realRun } from "./process.js";
|
|
10
|
+
import { CancelledError, chooseEmbeddings, disclosure } from "./prompt.js";
|
|
11
|
+
import { findPython, PythonNotFoundError } from "./python.js";
|
|
12
|
+
import { scaffold, templateValues } from "./scaffold.js";
|
|
13
|
+
import { checkTarget, resolveTarget, validateName, ValidationError } from "./validate.js";
|
|
14
|
+
import { RAG_KIT_VERSION } from "./version.js";
|
|
15
|
+
|
|
16
|
+
export async function main(argv, deps = {}) {
|
|
17
|
+
const {
|
|
18
|
+
platform = process.platform,
|
|
19
|
+
cwd = process.cwd(),
|
|
20
|
+
env = process.env,
|
|
21
|
+
stdin = process.stdin,
|
|
22
|
+
stdout = process.stdout,
|
|
23
|
+
stderr = process.stderr,
|
|
24
|
+
interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY),
|
|
25
|
+
run = realRun,
|
|
26
|
+
} = deps;
|
|
27
|
+
const say = (text = "") => stdout.write(`${text}\n`);
|
|
28
|
+
const fail = (text) => stderr.write(`error: ${text}\n`);
|
|
29
|
+
|
|
30
|
+
let options;
|
|
31
|
+
try {
|
|
32
|
+
options = parseCliArgs(argv);
|
|
33
|
+
} catch (error) {
|
|
34
|
+
if (!(error instanceof UsageError)) throw error;
|
|
35
|
+
fail(error.message);
|
|
36
|
+
stderr.write(`\n${USAGE}`);
|
|
37
|
+
return 2;
|
|
38
|
+
}
|
|
39
|
+
if (options.help) { stdout.write(USAGE); return 0; }
|
|
40
|
+
if (options.version) { say(RAG_KIT_VERSION); return 0; }
|
|
41
|
+
|
|
42
|
+
// 1. Name and folder - before anything else.
|
|
43
|
+
let target;
|
|
44
|
+
try {
|
|
45
|
+
validateName(options.name);
|
|
46
|
+
target = resolveTarget(options.name, cwd);
|
|
47
|
+
await checkTarget(target);
|
|
48
|
+
} catch (error) {
|
|
49
|
+
if (!(error instanceof ValidationError)) throw error;
|
|
50
|
+
fail(error.message);
|
|
51
|
+
return 2;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// 2. Embeddings, explained before anything is installed.
|
|
55
|
+
let embeddings;
|
|
56
|
+
try {
|
|
57
|
+
embeddings = await chooseEmbeddings(options, { interactive, input: stdin, output: stdout, platform });
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (error instanceof UsageError) { fail(error.message); return 2; }
|
|
60
|
+
if (error instanceof CancelledError) { fail(error.message); return 130; }
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
say(`\nEmbeddings: ${embeddings}\n${disclosure(embeddings, { platform, gpu: options.gpu })}`);
|
|
64
|
+
if (options.gpu && embeddings === "gemini") say("(--gpu has no effect with Gemini embeddings.)");
|
|
65
|
+
|
|
66
|
+
// 3. Installer and Python - still before writing, so a missing Python leaves nothing behind.
|
|
67
|
+
let python = null;
|
|
68
|
+
let useUv = false;
|
|
69
|
+
if (options.install) {
|
|
70
|
+
if (options.useUv) {
|
|
71
|
+
useUv = (await run("uv", ["--version"], { timeoutMs: 30000 })).code === 0;
|
|
72
|
+
}
|
|
73
|
+
try {
|
|
74
|
+
python = await findPython({ platform, explicit: options.python, run });
|
|
75
|
+
} catch (error) {
|
|
76
|
+
if (!(error instanceof PythonNotFoundError)) throw error;
|
|
77
|
+
fail(`${error.message}\nNothing was created.`);
|
|
78
|
+
return 1;
|
|
79
|
+
}
|
|
80
|
+
say(`\nPython: ${python.version} (${python.executable})`);
|
|
81
|
+
say(`Installer: ${useUv ? "uv" : "pip"}${options.useUv && !useUv ? " (uv not found)" : ""}`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 4. Project files.
|
|
85
|
+
const values = templateValues({ name: options.name, embeddings, version: RAG_KIT_VERSION });
|
|
86
|
+
let files;
|
|
87
|
+
try {
|
|
88
|
+
files = await scaffold({ target, values });
|
|
89
|
+
} catch (error) {
|
|
90
|
+
fail(`Could not write the project files in ${target}: ${error.message}\n` +
|
|
91
|
+
"Files written before the error were kept; nothing was deleted.");
|
|
92
|
+
return 1;
|
|
93
|
+
}
|
|
94
|
+
say(`\nCreated ${target}\n ${files.join("\n ")}`);
|
|
95
|
+
|
|
96
|
+
if (!options.install) {
|
|
97
|
+
say("\nSkipped installation (--no-install).");
|
|
98
|
+
printNextSteps(say, { name: options.name, platform, installed: false, embeddings });
|
|
99
|
+
return 0;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// 5. Install into the project's .venv.
|
|
103
|
+
const packageSpec = options.packageSpec && resolvePackageSpec(options.packageSpec, cwd, platform);
|
|
104
|
+
const steps = installPlan({
|
|
105
|
+
platform, pythonExecutable: python.executable, useUv, embeddings, gpu: options.gpu,
|
|
106
|
+
packageSpec, testPypi: options.testPypi, version: RAG_KIT_VERSION,
|
|
107
|
+
});
|
|
108
|
+
const result = await runSteps(steps, { cwd: target, env: installEnv(env), run, log: say });
|
|
109
|
+
if (!result.ok) {
|
|
110
|
+
fail(`"${result.failed.label}" failed${result.error ? ` (${result.error.message})` : ""}.`);
|
|
111
|
+
say(`\nThe project files in ${target} were kept${result.completed.length
|
|
112
|
+
? `, and these steps finished: ${result.completed.map((s) => s.label).join("; ")}` : ""}.`);
|
|
113
|
+
say(`To finish, fix the problem above and run, from ${target}:`);
|
|
114
|
+
for (const step of result.remaining) say(` ${formatCommand(step.command, step.args)}`);
|
|
115
|
+
return 1;
|
|
116
|
+
}
|
|
117
|
+
if (options.packageSpec || options.testPypi) {
|
|
118
|
+
say(`\nNote: requirements.txt pins ${values.RAG_KIT_REQUIREMENT} (the published release); ` +
|
|
119
|
+
"this .venv was installed from the testing source you chose.");
|
|
120
|
+
}
|
|
121
|
+
printNextSteps(say, { name: options.name, platform, installed: true, embeddings });
|
|
122
|
+
return 0;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function printNextSteps(say, { name, platform, installed, embeddings }) {
|
|
126
|
+
const windows = platform === "win32";
|
|
127
|
+
say("\nNext steps:");
|
|
128
|
+
say(` cd ${name}`);
|
|
129
|
+
say(windows ? " Copy-Item .env.example .env (cmd: copy .env.example .env)"
|
|
130
|
+
: " cp .env.example .env");
|
|
131
|
+
say(" # open .env and set GOOGLE_API_KEY (needed for answers); never commit .env");
|
|
132
|
+
if (!installed) {
|
|
133
|
+
say(windows ? " py -3.11 -m venv .venv" : " python3.11 -m venv .venv");
|
|
134
|
+
if (embeddings === "local" && platform === "linux") {
|
|
135
|
+
say(" .venv/bin/python -m pip install torch --index-url https://download.pytorch.org/whl/cpu");
|
|
136
|
+
}
|
|
137
|
+
say(windows ? " .venv\\Scripts\\python.exe -m pip install -r requirements.txt"
|
|
138
|
+
: " .venv/bin/python -m pip install -r requirements.txt");
|
|
139
|
+
}
|
|
140
|
+
say(windows ? " .venv\\Scripts\\Activate.ps1 (cmd: .venv\\Scripts\\activate.bat)"
|
|
141
|
+
: " source .venv/bin/activate");
|
|
142
|
+
say(" rag-kit check");
|
|
143
|
+
say(" rag-kit ingest data/your-document.pdf");
|
|
144
|
+
say(' rag-kit ask "your question"');
|
|
145
|
+
say(`\nSee ${path.join(name, "README.md")} for more.`);
|
|
146
|
+
}
|
package/lib/install.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Builds the install steps as plain data, so every platform's commands can be
|
|
2
|
+
// tested anywhere; runSteps() executes them.
|
|
3
|
+
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
import { formatCommand } from "./process.js";
|
|
7
|
+
|
|
8
|
+
export const CPU_TORCH_INDEX = "https://download.pytorch.org/whl/cpu";
|
|
9
|
+
export const TEST_PYPI_INDEX = "https://test.pypi.org/simple/";
|
|
10
|
+
|
|
11
|
+
export function extrasFor(embeddings) {
|
|
12
|
+
return embeddings === "local" ? ["local", "gemini"] : ["gemini"];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// The dependency written to requirements.txt: always the published release.
|
|
16
|
+
export function pinnedRequirement(embeddings, version) {
|
|
17
|
+
return `ragkit-dev[${extrasFor(embeddings).join(",")}]==${version}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// A requirement (not a file name such as rag_kit-0.1.0-py3-none-any.whl) that names
|
|
21
|
+
// the old distribution name rag-kit, which is never published.
|
|
22
|
+
const LEGACY_REQUIREMENT = /^\s*rag[-_.]+kit\s*(\[[^\]]*\])?\s*($|[=<>!~;@])/i;
|
|
23
|
+
|
|
24
|
+
// The message for a --package-spec that names rag-kit, or null.
|
|
25
|
+
export function legacyPackageSpecError(spec) {
|
|
26
|
+
if (!LEGACY_REQUIREMENT.test(spec)) {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
const suggestion = spec.trim().replace(/^rag[-_.]+kit/i, "ragkit-dev");
|
|
30
|
+
return `--package-spec "${spec.trim()}": the Python distribution is ragkit-dev, not rag-kit; ` +
|
|
31
|
+
`use "${suggestion}".`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The install runs inside the new project folder, so a local path given to
|
|
35
|
+
// --package-spec (as pip tells paths from requirements: a path separator, a
|
|
36
|
+
// leading ".", or an archive name) is made absolute from the folder the command
|
|
37
|
+
// was run in. Requirements and URLs are returned unchanged.
|
|
38
|
+
export function resolvePackageSpec(spec, cwd, platform = process.platform) {
|
|
39
|
+
const text = spec.trim();
|
|
40
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text) || text.includes("@")) {
|
|
41
|
+
return spec;
|
|
42
|
+
}
|
|
43
|
+
if (/[\\/]/.test(text) || text.startsWith(".") || /\.(whl|tar\.gz|zip)$/i.test(text)) {
|
|
44
|
+
return (platform === "win32" ? path.win32 : path.posix).resolve(cwd, text);
|
|
45
|
+
}
|
|
46
|
+
return spec;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// What to install for --package-spec: a requirement string gets the extras
|
|
50
|
+
// added after its name; anything else (a wheel, an sdist, a folder) gets them appended.
|
|
51
|
+
export function packageSpecWithExtras(spec, embeddings) {
|
|
52
|
+
const legacy = legacyPackageSpecError(spec);
|
|
53
|
+
if (legacy) {
|
|
54
|
+
throw new Error(legacy);
|
|
55
|
+
}
|
|
56
|
+
const extras = `[${extrasFor(embeddings).join(",")}]`;
|
|
57
|
+
const named = spec.match(/^\s*ragkit[-_.]+dev\s*(\[[^\]]*\])?\s*(.*)$/i);
|
|
58
|
+
if (named) {
|
|
59
|
+
return `ragkit-dev${extras}${named[2] ? named[2].trim() : ""}`;
|
|
60
|
+
}
|
|
61
|
+
return `${spec}${extras}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function venvPython(platform) {
|
|
65
|
+
return platform === "win32" ? path.win32.join(".venv", "Scripts", "python.exe") : ".venv/bin/python";
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
// Ordered steps, each { label, command, args }. All run inside the project folder.
|
|
69
|
+
export function installPlan({ platform, pythonExecutable, useUv, embeddings, gpu, packageSpec, testPypi, version }) {
|
|
70
|
+
const python = venvPython(platform);
|
|
71
|
+
const pipInstall = useUv
|
|
72
|
+
? (args) => ({ command: "uv", args: ["pip", "install", "--python", python, ...args] })
|
|
73
|
+
: (args) => ({ command: python, args: ["-m", "pip", "install", "--disable-pip-version-check", ...args] });
|
|
74
|
+
|
|
75
|
+
const steps = [];
|
|
76
|
+
steps.push(useUv
|
|
77
|
+
? { label: "Create .venv (uv)", command: "uv", args: ["venv", ".venv", "--python", pythonExecutable] }
|
|
78
|
+
: { label: "Create .venv", command: pythonExecutable, args: ["-m", "venv", ".venv"] });
|
|
79
|
+
|
|
80
|
+
if (embeddings === "local" && platform === "linux" && !gpu) {
|
|
81
|
+
steps.push({ label: "Install CPU-only PyTorch", ...pipInstall(["torch", "--index-url", CPU_TORCH_INDEX]) });
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
if (testPypi) {
|
|
85
|
+
// rag-kit itself from TestPyPI without dependencies, then everything else from
|
|
86
|
+
// PyPI: TestPyPI must never supply third-party packages.
|
|
87
|
+
const spec = packageSpec ? packageSpecWithExtras(packageSpec, embeddings).replace(/\[[^\]]*\]/, "")
|
|
88
|
+
: `ragkit-dev==${version}`;
|
|
89
|
+
steps.push({ label: "Install rag-kit from TestPyPI (no dependencies)",
|
|
90
|
+
...pipInstall(["--no-deps", "--index-url", TEST_PYPI_INDEX, spec]) });
|
|
91
|
+
steps.push({ label: "Install rag-kit's dependencies from PyPI",
|
|
92
|
+
...pipInstall([packageSpec ? packageSpecWithExtras(packageSpec, embeddings) : pinnedRequirement(embeddings, version)]) });
|
|
93
|
+
} else if (packageSpec) {
|
|
94
|
+
steps.push({ label: "Install rag-kit from --package-spec",
|
|
95
|
+
...pipInstall([packageSpecWithExtras(packageSpec, embeddings)]) });
|
|
96
|
+
} else {
|
|
97
|
+
steps.push({ label: "Install rag-kit (requirements.txt)", ...pipInstall(["-r", "requirements.txt"]) });
|
|
98
|
+
}
|
|
99
|
+
return steps;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Environment for the install commands: never let uv download its own Python.
|
|
103
|
+
export function installEnv(baseEnv) {
|
|
104
|
+
return { ...baseEnv, UV_PYTHON_DOWNLOADS: "never" };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Runs steps in order and stops at the first failure.
|
|
108
|
+
// Returns { ok, completed: [step], failed: step|null, remaining: [step] }.
|
|
109
|
+
export async function runSteps(steps, { cwd, env, run, log }) {
|
|
110
|
+
const completed = [];
|
|
111
|
+
for (let i = 0; i < steps.length; i += 1) {
|
|
112
|
+
const step = steps[i];
|
|
113
|
+
log(`\n> ${step.label}\n ${formatCommand(step.command, step.args)}`);
|
|
114
|
+
// A relative program path (.venv/bin/python) is the project's: resolve it here
|
|
115
|
+
// instead of relying on how each OS resolves relative executables.
|
|
116
|
+
const command = /[\\/]/.test(step.command) && !path.isAbsolute(step.command)
|
|
117
|
+
? path.resolve(cwd, step.command) : step.command;
|
|
118
|
+
const result = await run(command, step.args, { cwd, env, inherit: true });
|
|
119
|
+
if (result.code !== 0) {
|
|
120
|
+
return { ok: false, completed, failed: step, remaining: steps.slice(i), error: result.error };
|
|
121
|
+
}
|
|
122
|
+
completed.push(step);
|
|
123
|
+
}
|
|
124
|
+
return { ok: true, completed, failed: null, remaining: [] };
|
|
125
|
+
}
|
package/lib/process.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Runs external programs. Always an argument array and shell: false - nothing
|
|
2
|
+
// the user typed is ever interpreted by a shell.
|
|
3
|
+
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
|
|
6
|
+
// Resolves (never rejects) with { code, stdout, stderr, error }. code is null
|
|
7
|
+
// when the program could not be started or timed out.
|
|
8
|
+
export function run(command, args, { cwd, env, timeoutMs, inherit = false } = {}) {
|
|
9
|
+
return new Promise((resolve) => {
|
|
10
|
+
let child;
|
|
11
|
+
try {
|
|
12
|
+
child = spawn(command, args, {
|
|
13
|
+
cwd,
|
|
14
|
+
env,
|
|
15
|
+
shell: false,
|
|
16
|
+
windowsHide: true,
|
|
17
|
+
stdio: inherit ? "inherit" : ["ignore", "pipe", "pipe"],
|
|
18
|
+
});
|
|
19
|
+
} catch (error) {
|
|
20
|
+
resolve({ code: null, stdout: "", stderr: "", error });
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
let stdout = "";
|
|
24
|
+
let stderr = "";
|
|
25
|
+
child.stdout?.on("data", (chunk) => { stdout += chunk; });
|
|
26
|
+
child.stderr?.on("data", (chunk) => { stderr += chunk; });
|
|
27
|
+
const timer = timeoutMs
|
|
28
|
+
? setTimeout(() => { child.kill(); resolve({ code: null, stdout, stderr, error: new Error("timed out") }); },
|
|
29
|
+
timeoutMs)
|
|
30
|
+
: null;
|
|
31
|
+
child.on("error", (error) => {
|
|
32
|
+
if (timer) clearTimeout(timer);
|
|
33
|
+
resolve({ code: null, stdout, stderr, error });
|
|
34
|
+
});
|
|
35
|
+
child.on("close", (code) => {
|
|
36
|
+
if (timer) clearTimeout(timer);
|
|
37
|
+
resolve({ code, stdout, stderr, error: null });
|
|
38
|
+
});
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// How a command line looks to a person who wants to re-run it by hand.
|
|
43
|
+
export function formatCommand(command, args) {
|
|
44
|
+
return [command, ...args].map((part) => (/[\s"'&|<>^()]/.test(part) ? `"${part}"` : part)).join(" ");
|
|
45
|
+
}
|
package/lib/prompt.js
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// The embedding choice, with what each option costs, shown before anything is installed.
|
|
2
|
+
|
|
3
|
+
import { createInterface } from "node:readline/promises";
|
|
4
|
+
|
|
5
|
+
import { UsageError } from "./args.js";
|
|
6
|
+
|
|
7
|
+
export class CancelledError extends Error {}
|
|
8
|
+
|
|
9
|
+
export function disclosure(choice, { platform, gpu }) {
|
|
10
|
+
const local = [
|
|
11
|
+
"Local BGE-M3 (EMBEDDING_PROVIDER=huggingface, model BAAI/bge-m3)",
|
|
12
|
+
" - Embeddings are computed on this computer; no API key is needed for them.",
|
|
13
|
+
platform === "linux"
|
|
14
|
+
? gpu
|
|
15
|
+
? " - Installs PyTorch with CUDA (--gpu) and sentence-transformers: several GB."
|
|
16
|
+
: " - Installs CPU-only PyTorch and sentence-transformers: about 1 GB on disk (measured on Windows)."
|
|
17
|
+
: " - Installs PyTorch and sentence-transformers: about 1 GB on disk (measured on Windows).",
|
|
18
|
+
" Actual disk use varies by platform and dependency versions.",
|
|
19
|
+
" - The BGE-M3 model (about 2.3 GB) is downloaded separately into the Hugging Face",
|
|
20
|
+
" cache the first time you ingest a document - not during this setup.",
|
|
21
|
+
];
|
|
22
|
+
const gemini = [
|
|
23
|
+
"Gemini (EMBEDDING_PROVIDER=google, model models/gemini-embedding-001)",
|
|
24
|
+
" - Small install; no model download.",
|
|
25
|
+
" - Needs a GOOGLE_API_KEY with embedding quota. On the free tier rag-kit pauses",
|
|
26
|
+
" 60 s between batches (EMBED_SLEEP), so large documents ingest slowly.",
|
|
27
|
+
" - Document text is sent to Google's API.",
|
|
28
|
+
];
|
|
29
|
+
const both = [
|
|
30
|
+
"Either way: answers (rag-kit ask / serve) use Gemini and need GOOGLE_API_KEY;",
|
|
31
|
+
"the question and the retrieved passages are sent to Google to write the answer.",
|
|
32
|
+
"You add the key to .env yourself; rag-kit-dev never asks for it.",
|
|
33
|
+
"A collection built with one provider cannot be searched with the other.",
|
|
34
|
+
];
|
|
35
|
+
if (choice === "local") return [...local, "", ...both].join("\n");
|
|
36
|
+
if (choice === "gemini") return [...gemini, "", ...both].join("\n");
|
|
37
|
+
return [" 1) " + local[0], ...local.slice(1).map((l) => " " + l), "",
|
|
38
|
+
" 2) " + gemini[0], ...gemini.slice(1).map((l) => " " + l), "", ...both].join("\n");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const ANSWERS = { 1: "local", local: "local", 2: "gemini", gemini: "gemini" };
|
|
42
|
+
|
|
43
|
+
// Returns "local" or "gemini". Asks only in an interactive terminal; there is no default.
|
|
44
|
+
export async function chooseEmbeddings(options, { interactive, input, output, platform }) {
|
|
45
|
+
if (options.embeddings) {
|
|
46
|
+
return options.embeddings;
|
|
47
|
+
}
|
|
48
|
+
if (!interactive || options.yes) {
|
|
49
|
+
throw new UsageError(
|
|
50
|
+
"Choose how the project creates embeddings: add --embeddings local or --embeddings gemini " +
|
|
51
|
+
"(required when not running in an interactive terminal or with --yes).",
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
output.write(`\nHow should this project create embeddings?\n\n${disclosure(null, { platform, gpu: options.gpu })}\n\n`);
|
|
55
|
+
const rl = createInterface({ input, output, terminal: false });
|
|
56
|
+
// End of input (Ctrl+D / Ctrl+Z, a closed pipe) must cancel, not hang.
|
|
57
|
+
const ended = new AbortController();
|
|
58
|
+
rl.on("close", () => ended.abort());
|
|
59
|
+
try {
|
|
60
|
+
for (;;) {
|
|
61
|
+
let answer;
|
|
62
|
+
try {
|
|
63
|
+
answer = (await rl.question("Type 1 (local) or 2 (gemini): ", { signal: ended.signal }))
|
|
64
|
+
.trim().toLowerCase();
|
|
65
|
+
} catch {
|
|
66
|
+
throw new CancelledError("Cancelled: no embedding choice was made.");
|
|
67
|
+
}
|
|
68
|
+
if (ANSWERS[answer]) return ANSWERS[answer];
|
|
69
|
+
output.write(`"${answer}" is not 1 or 2.\n`);
|
|
70
|
+
}
|
|
71
|
+
} finally {
|
|
72
|
+
rl.close();
|
|
73
|
+
}
|
|
74
|
+
}
|
package/lib/python.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// Finds a Python 3.11 or 3.12 interpreter. 3.11 is preferred (the version
|
|
2
|
+
// rag-kit is tested on most), then 3.12.
|
|
3
|
+
|
|
4
|
+
export const SUPPORTED = ["3.11", "3.12"];
|
|
5
|
+
|
|
6
|
+
export class PythonNotFoundError extends Error {}
|
|
7
|
+
|
|
8
|
+
const PROBE =
|
|
9
|
+
"import json, sys; print(json.dumps({'version': '%d.%d.%d' % sys.version_info[:3], " +
|
|
10
|
+
"'executable': sys.executable}))";
|
|
11
|
+
|
|
12
|
+
export function candidates(platform, explicit) {
|
|
13
|
+
if (explicit) {
|
|
14
|
+
return [{ command: explicit, args: [] }];
|
|
15
|
+
}
|
|
16
|
+
if (platform === "win32") {
|
|
17
|
+
return [
|
|
18
|
+
{ command: "py", args: ["-3.11"] },
|
|
19
|
+
{ command: "py", args: ["-3.12"] },
|
|
20
|
+
{ command: "python", args: [] },
|
|
21
|
+
{ command: "python3", args: [] },
|
|
22
|
+
];
|
|
23
|
+
}
|
|
24
|
+
return [
|
|
25
|
+
{ command: "python3.11", args: [] },
|
|
26
|
+
{ command: "python3.12", args: [] },
|
|
27
|
+
{ command: "python3", args: [] },
|
|
28
|
+
{ command: "python", args: [] },
|
|
29
|
+
];
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// run(command, args, options) -> { code, stdout } (see process.js); injected for tests.
|
|
33
|
+
export async function findPython({ platform, explicit, run }) {
|
|
34
|
+
const tried = [];
|
|
35
|
+
for (const candidate of candidates(platform, explicit)) {
|
|
36
|
+
const label = [candidate.command, ...candidate.args].join(" ");
|
|
37
|
+
const result = await run(candidate.command, [...candidate.args, "-c", PROBE], { timeoutMs: 30000 });
|
|
38
|
+
let info = null;
|
|
39
|
+
if (result.code === 0) {
|
|
40
|
+
try {
|
|
41
|
+
info = JSON.parse(result.stdout.trim().split(/\r?\n/).pop());
|
|
42
|
+
} catch {
|
|
43
|
+
info = null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (!info?.version || !info?.executable) {
|
|
47
|
+
tried.push(`${label}: not available`);
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const minor = info.version.split(".").slice(0, 2).join(".");
|
|
51
|
+
if (SUPPORTED.includes(minor)) {
|
|
52
|
+
return { executable: info.executable, version: info.version, label };
|
|
53
|
+
}
|
|
54
|
+
tried.push(`${label}: Python ${info.version} (rag-kit needs 3.11 or 3.12)`);
|
|
55
|
+
}
|
|
56
|
+
const how = explicit
|
|
57
|
+
? `--python ${explicit} is not a Python 3.11 or 3.12 interpreter.`
|
|
58
|
+
: "No Python 3.11 or 3.12 interpreter was found.";
|
|
59
|
+
throw new PythonNotFoundError(
|
|
60
|
+
`${how}\n Tried:\n ${tried.join("\n ")}\n` +
|
|
61
|
+
" Install Python 3.11 (https://www.python.org/downloads/) or pass --python PATH, " +
|
|
62
|
+
"or re-run with --no-install to only create the project files.",
|
|
63
|
+
);
|
|
64
|
+
}
|
package/lib/scaffold.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Writes the project files from templates/default. Never overwrites a file and
|
|
2
|
+
// never writes .env.
|
|
3
|
+
|
|
4
|
+
import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { fileURLToPath } from "node:url";
|
|
7
|
+
|
|
8
|
+
import { CPU_TORCH_INDEX, pinnedRequirement } from "./install.js";
|
|
9
|
+
|
|
10
|
+
export const TEMPLATE_DIR = fileURLToPath(new URL("../templates/default/", import.meta.url));
|
|
11
|
+
|
|
12
|
+
// npm drops or mangles dot-files in packages, so templates use these names.
|
|
13
|
+
export const RENAMES = {
|
|
14
|
+
_gitignore: ".gitignore",
|
|
15
|
+
"_env.example": ".env.example",
|
|
16
|
+
_gitkeep: ".gitkeep",
|
|
17
|
+
"requirements.txt.tmpl": "requirements.txt",
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const EMBEDDINGS = {
|
|
21
|
+
local: {
|
|
22
|
+
label: "local BGE-M3",
|
|
23
|
+
provider: "huggingface",
|
|
24
|
+
model: "BAAI/bge-m3",
|
|
25
|
+
note: "Embeddings are computed on this computer (no key needed for them); the model " +
|
|
26
|
+
"(about 2.3 GB) is downloaded into the Hugging Face cache on the first ingest.",
|
|
27
|
+
geminiNote: "",
|
|
28
|
+
extra: "# Where the local model is cached (default: the Hugging Face cache in your home folder):\n" +
|
|
29
|
+
"# HF_HOME=\n",
|
|
30
|
+
},
|
|
31
|
+
gemini: {
|
|
32
|
+
label: "Gemini",
|
|
33
|
+
provider: "google",
|
|
34
|
+
model: "models/gemini-embedding-001",
|
|
35
|
+
note: "Embeddings come from Google's API and need GOOGLE_API_KEY with embedding quota; " +
|
|
36
|
+
"document text is sent to Google.",
|
|
37
|
+
geminiNote: " and the embeddings",
|
|
38
|
+
extra: "# Seconds to pause between embedding batches (Gemini free tier: about 100 texts/minute):\n" +
|
|
39
|
+
"EMBED_SLEEP=60\n",
|
|
40
|
+
},
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export function templateValues({ name, embeddings, version }) {
|
|
44
|
+
const choice = EMBEDDINGS[embeddings];
|
|
45
|
+
return {
|
|
46
|
+
PROJECT_NAME: name,
|
|
47
|
+
RAG_KIT_VERSION: version,
|
|
48
|
+
RAG_KIT_REQUIREMENT: pinnedRequirement(embeddings, version),
|
|
49
|
+
EMBEDDINGS_LABEL: choice.label,
|
|
50
|
+
EMBEDDINGS_NOTE: choice.note,
|
|
51
|
+
EMBEDDING_PROVIDER: choice.provider,
|
|
52
|
+
EMBEDDING_MODEL: choice.model,
|
|
53
|
+
EMBEDDING_EXTRA: choice.extra,
|
|
54
|
+
GEMINI_EMBEDDING_NOTE: choice.geminiNote,
|
|
55
|
+
MANUAL_TORCH_STEP: embeddings === "local"
|
|
56
|
+
? `.venv/bin/python -m pip install torch --index-url ${CPU_TORCH_INDEX} # Linux only: CPU-only PyTorch\n`
|
|
57
|
+
: "",
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function render(text, values, source) {
|
|
62
|
+
const out = text.replace(/\{\{([A-Z_]+)\}\}/g, (match, key) => {
|
|
63
|
+
if (!(key in values)) throw new Error(`Template ${source} uses unknown placeholder ${match}`);
|
|
64
|
+
return values[key];
|
|
65
|
+
});
|
|
66
|
+
if (out.includes("{{")) throw new Error(`Template ${source} has an unfinished placeholder`);
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function* templateFiles(dir, relative = "") {
|
|
71
|
+
for (const entry of await readdir(path.join(dir, relative), { withFileTypes: true })) {
|
|
72
|
+
const rel = path.join(relative, entry.name);
|
|
73
|
+
if (entry.isDirectory()) yield* templateFiles(dir, rel);
|
|
74
|
+
else yield rel;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// Returns the project-relative paths written, sorted.
|
|
79
|
+
export async function scaffold({ target, values, templateDir = TEMPLATE_DIR }) {
|
|
80
|
+
await mkdir(target, { recursive: true });
|
|
81
|
+
const written = [];
|
|
82
|
+
for await (const rel of templateFiles(templateDir)) {
|
|
83
|
+
const parts = rel.split(path.sep);
|
|
84
|
+
parts[parts.length - 1] = RENAMES[parts.at(-1)] ?? parts.at(-1);
|
|
85
|
+
const destRel = parts.join(path.sep);
|
|
86
|
+
if (path.basename(destRel).toLowerCase() === ".env") {
|
|
87
|
+
throw new Error("Refusing to write .env: projects only get .env.example.");
|
|
88
|
+
}
|
|
89
|
+
const text = render(await readFile(path.join(templateDir, rel), "utf8"), values, rel);
|
|
90
|
+
await mkdir(path.dirname(path.join(target, destRel)), { recursive: true });
|
|
91
|
+
await writeFile(path.join(target, destRel), text, { encoding: "utf8", flag: "wx" }); // never overwrite
|
|
92
|
+
written.push(destRel.split(path.sep).join("/"));
|
|
93
|
+
}
|
|
94
|
+
return written.sort();
|
|
95
|
+
}
|
package/lib/validate.js
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Project name and target folder checks. Everything here runs before any file is written.
|
|
2
|
+
|
|
3
|
+
import { readdir, stat } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
|
|
6
|
+
export class ValidationError extends Error {}
|
|
7
|
+
|
|
8
|
+
const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,213}$/;
|
|
9
|
+
// Device names Windows reserves in every folder, with or without an extension.
|
|
10
|
+
const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(\..*)?$/i;
|
|
11
|
+
|
|
12
|
+
export function validateName(name) {
|
|
13
|
+
if (name === "." || name === "..") {
|
|
14
|
+
throw new ValidationError(
|
|
15
|
+
`"${name}" is not supported: rag-kit-dev creates a new folder. Pass a name such as my-rag.`,
|
|
16
|
+
);
|
|
17
|
+
}
|
|
18
|
+
if (/[\\/:]/.test(name)) {
|
|
19
|
+
throw new ValidationError(
|
|
20
|
+
`"${name}" looks like a path. Pass only a folder name; it is created in the current directory.`,
|
|
21
|
+
);
|
|
22
|
+
}
|
|
23
|
+
if (!NAME_PATTERN.test(name)) {
|
|
24
|
+
throw new ValidationError(
|
|
25
|
+
`"${name}" is not a valid project name. Use letters, digits, ".", "_" and "-", ` +
|
|
26
|
+
"starting with a letter or digit (at most 214 characters).",
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
if (name.endsWith(".")) {
|
|
30
|
+
throw new ValidationError(`"${name}" ends with "." which Windows cannot use as a folder name.`);
|
|
31
|
+
}
|
|
32
|
+
if (WINDOWS_RESERVED.test(name)) {
|
|
33
|
+
throw new ValidationError(`"${name}" is a reserved device name on Windows. Choose another name.`);
|
|
34
|
+
}
|
|
35
|
+
return name;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// The folder to create: directly inside `cwd`, never anywhere else.
|
|
39
|
+
export function resolveTarget(name, cwd) {
|
|
40
|
+
const base = path.resolve(cwd);
|
|
41
|
+
const target = path.resolve(base, name);
|
|
42
|
+
if (path.dirname(target) !== base) {
|
|
43
|
+
throw new ValidationError(`"${name}" would not be created inside ${base}.`);
|
|
44
|
+
}
|
|
45
|
+
return target;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// A missing folder or an empty one is fine; anything else is refused.
|
|
49
|
+
export async function checkTarget(target) {
|
|
50
|
+
let info;
|
|
51
|
+
try {
|
|
52
|
+
info = await stat(target);
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (error.code === "ENOENT") {
|
|
55
|
+
return { exists: false };
|
|
56
|
+
}
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
if (!info.isDirectory()) {
|
|
60
|
+
throw new ValidationError(`${target} already exists and is not a folder.`);
|
|
61
|
+
}
|
|
62
|
+
const entries = await readdir(target);
|
|
63
|
+
if (entries.length > 0) {
|
|
64
|
+
throw new ValidationError(
|
|
65
|
+
`${target} already exists and is not empty (${entries.length} entries). ` +
|
|
66
|
+
"Choose another name or an empty folder; nothing was changed.",
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
return { exists: true };
|
|
70
|
+
}
|
package/lib/version.js
ADDED
package/package.json
CHANGED
|
@@ -1,11 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rag-kit-dev",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "0.1.2",
|
|
4
|
+
"description": "Create a rag-kit project with one command: npx rag-kit-dev my-rag",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"rag-kit-dev": "bin/rag-kit-dev.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin/",
|
|
11
|
+
"lib/",
|
|
12
|
+
"templates/"
|
|
13
|
+
],
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=20"
|
|
16
|
+
},
|
|
17
|
+
"scripts": {
|
|
18
|
+
"test": "node --test"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"rag",
|
|
22
|
+
"retrieval-augmented-generation",
|
|
23
|
+
"generator",
|
|
24
|
+
"scaffold",
|
|
25
|
+
"qdrant",
|
|
26
|
+
"python"
|
|
27
|
+
],
|
|
28
|
+
"author": "Riyad",
|
|
5
29
|
"license": "MIT",
|
|
6
30
|
"repository": {
|
|
7
31
|
"type": "git",
|
|
8
32
|
"url": "git+https://github.com/shamiulriyad/rag-learning.git",
|
|
9
33
|
"directory": "generator"
|
|
10
|
-
}
|
|
34
|
+
},
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/shamiulriyad/rag-learning/issues"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://github.com/shamiulriyad/rag-learning/tree/main/generator#readme"
|
|
11
39
|
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# {{PROJECT_NAME}}
|
|
2
|
+
|
|
3
|
+
A retrieval-augmented generation (RAG) project built on
|
|
4
|
+
[rag-kit](https://github.com/shamiulriyad/rag-learning) {{RAG_KIT_VERSION}}:
|
|
5
|
+
index your documents into a local Qdrant store, then ask questions and get
|
|
6
|
+
answers that cite the passages (and PDF pages) they came from.
|
|
7
|
+
|
|
8
|
+
Embeddings: **{{EMBEDDINGS_LABEL}}**. {{EMBEDDINGS_NOTE}}
|
|
9
|
+
|
|
10
|
+
## Set up
|
|
11
|
+
|
|
12
|
+
1. **Create `.env` from the template** (this project never contains a real key
|
|
13
|
+
until you add one):
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
cp .env.example .env # PowerShell: Copy-Item .env.example .env
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Open `.env` and set `GOOGLE_API_KEY`
|
|
20
|
+
([get a key](https://aistudio.google.com/app/apikey)). Answers always need
|
|
21
|
+
it. Never commit `.env`; it is already in `.gitignore`.
|
|
22
|
+
|
|
23
|
+
2. **Activate the virtual environment** created by rag-kit-dev:
|
|
24
|
+
|
|
25
|
+
```bash
|
|
26
|
+
source .venv/bin/activate # Windows PowerShell: .venv\Scripts\Activate.ps1
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
No `.venv` yet (created with `--no-install`)? See "Install manually" below.
|
|
30
|
+
|
|
31
|
+
3. **Check the setup:**
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
rag-kit check
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Use
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
rag-kit ingest data/your-document.pdf # .pdf, .txt or .md; re-ingesting replaces
|
|
41
|
+
rag-kit ask "What does the document say about ...?"
|
|
42
|
+
rag-kit search "..." # retrieval only, no LLM call
|
|
43
|
+
rag-kit documents # what is indexed
|
|
44
|
+
python example.py data/your-document.pdf "Your question" # the same from Python
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Optional extras: `pip install "ragkit-dev[api]=={{RAG_KIT_VERSION}}"` for
|
|
48
|
+
`rag-kit serve` (HTTP API on 127.0.0.1), `pip install "ragkit-dev[ui]=={{RAG_KIT_VERSION}}"`
|
|
49
|
+
for `rag-kit ui` (Streamlit test UI).
|
|
50
|
+
|
|
51
|
+
## Files
|
|
52
|
+
|
|
53
|
+
| Path | Purpose |
|
|
54
|
+
| ---- | ------- |
|
|
55
|
+
| `rag-kit.toml` | marks this folder as a rag-kit project |
|
|
56
|
+
| `.env.example` | settings template; copy it to `.env` |
|
|
57
|
+
| `requirements.txt` | the rag-kit version and extras this project uses |
|
|
58
|
+
| `data/` | put your documents here |
|
|
59
|
+
| `example.py` | ingest and ask from Python |
|
|
60
|
+
| `qdrant_data/` | the local vector store, created on the first ingest (git-ignored) |
|
|
61
|
+
|
|
62
|
+
## Install manually
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
python3.11 -m venv .venv # Windows: py -3.11 -m venv .venv
|
|
66
|
+
{{MANUAL_TORCH_STEP}}.venv/bin/python -m pip install -r requirements.txt # Windows: .venv\Scripts\python.exe -m pip ...
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
See the [rag-kit README](https://github.com/shamiulriyad/rag-learning#readme)
|
|
70
|
+
for all settings and troubleshooting.
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# Settings for {{PROJECT_NAME}}. Copy this file to .env, then fill it in:
|
|
2
|
+
# macOS/Linux: cp .env.example .env
|
|
3
|
+
# PowerShell: Copy-Item .env.example .env
|
|
4
|
+
# Never commit .env (it is listed in .gitignore). Relative paths are resolved
|
|
5
|
+
# from this folder, whatever the current directory is.
|
|
6
|
+
|
|
7
|
+
# --- Gemini: writes the answers (rag-kit ask / serve){{GEMINI_EMBEDDING_NOTE}} ---
|
|
8
|
+
# Get a key at https://aistudio.google.com/app/apikey and paste it after "=".
|
|
9
|
+
GOOGLE_API_KEY=
|
|
10
|
+
LLM_MODEL=gemini-2.5-flash
|
|
11
|
+
|
|
12
|
+
# --- Embeddings ({{EMBEDDINGS_LABEL}}) ---
|
|
13
|
+
# Changing the provider or model later needs a new COLLECTION_NAME or
|
|
14
|
+
# `rag-kit ingest FILE --recreate`: vectors from different models do not mix.
|
|
15
|
+
EMBEDDING_PROVIDER={{EMBEDDING_PROVIDER}}
|
|
16
|
+
EMBEDDING_MODEL={{EMBEDDING_MODEL}}
|
|
17
|
+
{{EMBEDDING_EXTRA}}
|
|
18
|
+
# --- Local Qdrant store: a folder inside this project ---
|
|
19
|
+
QDRANT_PATH=qdrant_data
|
|
20
|
+
COLLECTION_NAME=pdf_rag
|
|
21
|
+
|
|
22
|
+
# --- Optional ---
|
|
23
|
+
# Default file for `rag-kit ingest` with no arguments:
|
|
24
|
+
# PDF_PATH=data/sample.pdf
|
|
25
|
+
# TOP_K=4
|
|
26
|
+
# MIN_SCORE=
|
|
27
|
+
# CHUNK_SIZE=1000
|
|
28
|
+
# CHUNK_OVERLAP=150
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# Keeps this folder in version control. Put your documents (.pdf, .txt, .md) here.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Ingest one document and ask a question about it with rag-kit.
|
|
2
|
+
|
|
3
|
+
python example.py data/your-document.pdf "What is this document about?"
|
|
4
|
+
|
|
5
|
+
Run it inside this project (the folder with rag-kit.toml) after creating
|
|
6
|
+
.env from .env.example. Asking needs GOOGLE_API_KEY in .env.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import sys
|
|
10
|
+
|
|
11
|
+
from rag_kit import Pipeline, Settings
|
|
12
|
+
from rag_kit.env import export_env_file
|
|
13
|
+
from rag_kit.errors import RagError
|
|
14
|
+
from rag_kit.log import show_progress
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def main(argv) -> int:
|
|
18
|
+
if len(argv) != 3:
|
|
19
|
+
print(__doc__)
|
|
20
|
+
return 2
|
|
21
|
+
document, question = argv[1], argv[2]
|
|
22
|
+
|
|
23
|
+
settings = Settings.load() # this project's .env, found from rag-kit.toml
|
|
24
|
+
export_env_file(settings) # HF_HOME, proxies etc. from .env, as the rag-kit command does
|
|
25
|
+
show_progress() # print each pipeline step
|
|
26
|
+
|
|
27
|
+
pipeline = Pipeline(settings=settings)
|
|
28
|
+
try:
|
|
29
|
+
pipeline.ingest(document) # re-ingesting the same file replaces its chunks
|
|
30
|
+
result = pipeline.ask(question)
|
|
31
|
+
except RagError as exc:
|
|
32
|
+
print(f"error: {exc}", file=sys.stderr)
|
|
33
|
+
return 1
|
|
34
|
+
finally:
|
|
35
|
+
pipeline.close()
|
|
36
|
+
|
|
37
|
+
print()
|
|
38
|
+
print(result.answer_without_markers)
|
|
39
|
+
for source in result.sources:
|
|
40
|
+
page = f", page {source['page']}" if source["page"] else ""
|
|
41
|
+
print(f"[{source['marker']}] {source['file']}{page} (score {source['score']:.3f})")
|
|
42
|
+
return 0
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
sys.exit(main(sys.argv))
|