palito 0.0.0-stage → 0.7.0
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 +24 -2
- package/index.d.ts +61 -0
- package/index.js +296 -0
- package/package.json +12 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Natan Loterio
|
|
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,3 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# palito (Node.js)
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Node.js binding for [Palito](../../README.md), built on [koffi](https://koffi.dev). Generation runs on a worker thread, so the event loop stays free.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install ./bindings/node
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
const { Palito } = require('palito');
|
|
11
|
+
|
|
12
|
+
const llm = await Palito.open('model.gguf');
|
|
13
|
+
const reply = await llm.chat([{ role: 'user', content: 'Hello!' }], {
|
|
14
|
+
onText: (text) => process.stdout.write(text),
|
|
15
|
+
});
|
|
16
|
+
for await (const text of llm.streamChat([{ role: 'user', content: 'A haiku about tea' }],
|
|
17
|
+
{ temperature: 0.7, stop: ['\n\n'] })) {
|
|
18
|
+
process.stdout.write(text);
|
|
19
|
+
}
|
|
20
|
+
await llm.close();
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
- **Types:** included (`index.d.ts`).
|
|
24
|
+
- **Concurrency:** calls on one engine are queued.
|
|
25
|
+
- **Stopping early:** a `break` in `for await` stops generation.
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
export type Device = 'default' | 'cpu' | 'cuda';
|
|
2
|
+
export type FinishReason = 'stop' | 'length' | 'context_full' | 'cancelled';
|
|
3
|
+
|
|
4
|
+
export interface OpenOptions {
|
|
5
|
+
/** Default: CUDA when the library has it, else CPU. */
|
|
6
|
+
device?: Device;
|
|
7
|
+
/** 0 or omitted: the model's trained context, fitted to GPU memory. */
|
|
8
|
+
contextTokens?: number;
|
|
9
|
+
threads?: number;
|
|
10
|
+
gpuDevice?: number;
|
|
11
|
+
gpuMemoryLimitBytes?: number | bigint;
|
|
12
|
+
kernelCacheDir?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface GenerationOptions {
|
|
16
|
+
/** 0 or omitted: until the model stops or the context is full. */
|
|
17
|
+
maxTokens?: number;
|
|
18
|
+
/** Reasoning for templates that support it (Qwen3). Default true. */
|
|
19
|
+
thinking?: boolean;
|
|
20
|
+
/** 0 (default): greedy. */
|
|
21
|
+
temperature?: number;
|
|
22
|
+
topP?: number;
|
|
23
|
+
topK?: number;
|
|
24
|
+
/** Omitted or negative: a different seed each call. */
|
|
25
|
+
seed?: number;
|
|
26
|
+
/** Generation ends at the first of these; it is not part of the text. */
|
|
27
|
+
stop?: string[];
|
|
28
|
+
/** Receives text as it is generated; return false to stop. */
|
|
29
|
+
onText?: (text: string) => boolean | void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface Message {
|
|
33
|
+
role: 'system' | 'user' | 'assistant' | string;
|
|
34
|
+
content: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export interface Completion {
|
|
38
|
+
text: string;
|
|
39
|
+
finishReason: FinishReason;
|
|
40
|
+
promptTokens: number;
|
|
41
|
+
generatedTokens: number;
|
|
42
|
+
ttftMs: number;
|
|
43
|
+
tokensPerSecond: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export class PalitoError extends Error {}
|
|
47
|
+
|
|
48
|
+
export class Palito {
|
|
49
|
+
static open(modelPath: string, options?: OpenOptions): Promise<Palito>;
|
|
50
|
+
readonly contextTokens: number;
|
|
51
|
+
readonly profile: string;
|
|
52
|
+
chat(messages: Message[], options?: GenerationOptions): Promise<Completion>;
|
|
53
|
+
complete(prompt: string, options?: GenerationOptions): Promise<Completion>;
|
|
54
|
+
streamChat(messages: Message[], options?: Omit<GenerationOptions, 'onText'>): AsyncGenerator<string>;
|
|
55
|
+
streamComplete(prompt: string, options?: Omit<GenerationOptions, 'onText'>): AsyncGenerator<string>;
|
|
56
|
+
close(): Promise<void>;
|
|
57
|
+
[Symbol.asyncDispose](): Promise<void>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function version(): string;
|
|
61
|
+
export function libraryPath(): string;
|
package/index.js
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Node.js binding for Palito: fast local LLM inference for GGUF models.
|
|
3
|
+
//
|
|
4
|
+
// Generation runs on a worker thread (the event loop stays free); streamed text
|
|
5
|
+
// arrives through `onText` or the async iterators. The library is found via
|
|
6
|
+
// $PALITO_LIBRARY, then the installed `palito` command (<bundle>/lib), then the
|
|
7
|
+
// system loader.
|
|
8
|
+
|
|
9
|
+
const fs = require('node:fs');
|
|
10
|
+
const path = require('node:path');
|
|
11
|
+
const koffi = require('koffi');
|
|
12
|
+
|
|
13
|
+
const DEVICES = { default: 0, cpu: 1, cuda: 2 };
|
|
14
|
+
const FINISH_REASONS = ['stop', 'length', 'context_full', 'cancelled'];
|
|
15
|
+
const LIBRARY_NAME = { darwin: 'libpalito.dylib', win32: 'palito.dll' }[process.platform] || 'libpalito.so';
|
|
16
|
+
|
|
17
|
+
class PalitoError extends Error {
|
|
18
|
+
constructor(message) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = 'PalitoError';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function libraryPath() {
|
|
25
|
+
if (process.env.PALITO_LIBRARY) return process.env.PALITO_LIBRARY;
|
|
26
|
+
const separator = process.platform === 'win32' ? ';' : ':';
|
|
27
|
+
for (const dir of (process.env.PATH || '').split(separator)) {
|
|
28
|
+
const command = path.join(dir, 'palito');
|
|
29
|
+
try {
|
|
30
|
+
const bundled = path.join(path.dirname(fs.realpathSync(command)), 'lib', LIBRARY_NAME);
|
|
31
|
+
if (fs.statSync(bundled).isFile()) return bundled;
|
|
32
|
+
} catch {
|
|
33
|
+
// not here
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return LIBRARY_NAME;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
let api = null;
|
|
40
|
+
|
|
41
|
+
function load() {
|
|
42
|
+
if (api) return api;
|
|
43
|
+
const file = libraryPath();
|
|
44
|
+
let lib;
|
|
45
|
+
try {
|
|
46
|
+
lib = koffi.load(file);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
throw new PalitoError(`cannot load ${file}: ${error.message}. Install Palito or set PALITO_LIBRARY`);
|
|
49
|
+
}
|
|
50
|
+
const Options = koffi.struct('palito_options', {
|
|
51
|
+
device: 'int',
|
|
52
|
+
context_tokens: 'uint32_t',
|
|
53
|
+
threads: 'uint32_t',
|
|
54
|
+
gpu_device: 'uint32_t',
|
|
55
|
+
gpu_memory_limit_bytes: 'uint64_t',
|
|
56
|
+
kernel_cache_dir: 'const char *',
|
|
57
|
+
});
|
|
58
|
+
const Message = koffi.struct('palito_message', { role: 'const char *', content: 'const char *' });
|
|
59
|
+
const Generation = koffi.struct('palito_generation', {
|
|
60
|
+
max_tokens: 'uint32_t',
|
|
61
|
+
enable_thinking: 'int',
|
|
62
|
+
temperature: 'float',
|
|
63
|
+
top_p: 'float',
|
|
64
|
+
top_k: 'uint32_t',
|
|
65
|
+
seed: 'int64_t',
|
|
66
|
+
stop: 'const char **',
|
|
67
|
+
stop_count: 'size_t',
|
|
68
|
+
});
|
|
69
|
+
const Result = koffi.struct('palito_result', {
|
|
70
|
+
text: 'void *',
|
|
71
|
+
finish_reason: 'int',
|
|
72
|
+
prompt_tokens: 'uint32_t',
|
|
73
|
+
generated_tokens: 'uint32_t',
|
|
74
|
+
ttft_ms: 'double',
|
|
75
|
+
tokens_per_second: 'double',
|
|
76
|
+
});
|
|
77
|
+
const TextCallback = koffi.proto('int palito_text_callback(const uint8_t *text, size_t length, void *user_data)');
|
|
78
|
+
api = {
|
|
79
|
+
Options,
|
|
80
|
+
Generation,
|
|
81
|
+
Result,
|
|
82
|
+
TextCallback,
|
|
83
|
+
version: lib.func('const char *palito_version(void)'),
|
|
84
|
+
optionsInit: lib.func('void palito_options_init(_Out_ palito_options *options)'),
|
|
85
|
+
generationInit: lib.func('void palito_generation_init(_Out_ palito_generation *generation)'),
|
|
86
|
+
open: lib.func('void *palito_open(const char *path, const palito_options *options, _Out_ void **error)'),
|
|
87
|
+
close: lib.func('void palito_close(void *engine)'),
|
|
88
|
+
contextTokens: lib.func('uint32_t palito_context_tokens(void *engine)'),
|
|
89
|
+
profile: lib.func('const char *palito_profile(void *engine)'),
|
|
90
|
+
chat: lib.func('int palito_chat(void *engine, const palito_message *messages, size_t count, ' +
|
|
91
|
+
'const palito_generation *generation, palito_text_callback *callback, void *user_data, ' +
|
|
92
|
+
'_Out_ palito_result *result, _Out_ void **error)'),
|
|
93
|
+
complete: lib.func('int palito_complete(void *engine, const char *prompt, ' +
|
|
94
|
+
'const palito_generation *generation, palito_text_callback *callback, void *user_data, ' +
|
|
95
|
+
'_Out_ palito_result *result, _Out_ void **error)'),
|
|
96
|
+
resultFree: lib.func('void palito_result_free(_Inout_ palito_result *result)'),
|
|
97
|
+
stringFree: lib.func('void palito_string_free(void *string)'),
|
|
98
|
+
};
|
|
99
|
+
return api;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function takeError(pointer) {
|
|
103
|
+
if (!pointer) return 'unknown error';
|
|
104
|
+
const message = koffi.decode(pointer, 'char', -1);
|
|
105
|
+
load().stringFree(pointer);
|
|
106
|
+
return message;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function callAsync(fn, ...args) {
|
|
110
|
+
return new Promise((resolve, reject) => {
|
|
111
|
+
fn.async(...args, (error, value) => (error ? reject(error) : resolve(value)));
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** A model opened once; chat() and complete() run one at a time per engine. */
|
|
116
|
+
class Palito {
|
|
117
|
+
/**
|
|
118
|
+
* Opens a GGUF model on a worker thread.
|
|
119
|
+
* options: { device: 'default'|'cpu'|'cuda', contextTokens, threads, gpuDevice,
|
|
120
|
+
* gpuMemoryLimitBytes, kernelCacheDir }
|
|
121
|
+
*/
|
|
122
|
+
static async open(modelPath, options = {}) {
|
|
123
|
+
const native = load();
|
|
124
|
+
const raw = {};
|
|
125
|
+
native.optionsInit(raw);
|
|
126
|
+
const device = DEVICES[options.device || 'default'];
|
|
127
|
+
if (device === undefined) throw new PalitoError(`unknown device ${options.device}`);
|
|
128
|
+
Object.assign(raw, {
|
|
129
|
+
device,
|
|
130
|
+
context_tokens: options.contextTokens || 0,
|
|
131
|
+
threads: options.threads || 0,
|
|
132
|
+
gpu_device: options.gpuDevice || 0,
|
|
133
|
+
gpu_memory_limit_bytes: options.gpuMemoryLimitBytes || 0,
|
|
134
|
+
kernel_cache_dir: options.kernelCacheDir || null,
|
|
135
|
+
});
|
|
136
|
+
const error = [null];
|
|
137
|
+
const engine = await callAsync(native.open, modelPath, raw, error);
|
|
138
|
+
if (!engine) throw new PalitoError(takeError(error[0]));
|
|
139
|
+
return new Palito(engine);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
constructor(engine) {
|
|
143
|
+
this._engine = engine;
|
|
144
|
+
this._queue = Promise.resolve();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
get contextTokens() {
|
|
148
|
+
return load().contextTokens(this._handle());
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 'cpu', 'int8-fast', 'f32-tiled' or 'f32'. */
|
|
152
|
+
get profile() {
|
|
153
|
+
return load().profile(this._handle());
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Replies to messages ([{role, content}]) with the model's chat template.
|
|
158
|
+
* options: { maxTokens, thinking (true), temperature (0: greedy), topP, topK, seed,
|
|
159
|
+
* stop: string[], onText(text) → return false to stop }
|
|
160
|
+
*/
|
|
161
|
+
chat(messages, options = {}) {
|
|
162
|
+
const rows = messages.map((m) => ({ role: m.role, content: m.content }));
|
|
163
|
+
return this._run(options, (native, generation, callback, result, error) =>
|
|
164
|
+
callAsync(native.chat, this._handle(), rows, rows.length, generation, callback, null, result, error));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Continues prompt without a chat template; options as in chat(). */
|
|
168
|
+
complete(prompt, options = {}) {
|
|
169
|
+
return this._run(options, (native, generation, callback, result, error) =>
|
|
170
|
+
callAsync(native.complete, this._handle(), prompt, generation, callback, null, result, error));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Async iterator over the reply text; breaking out of the loop stops generation. */
|
|
174
|
+
streamChat(messages, options = {}) {
|
|
175
|
+
return this._stream((onText) => this.chat(messages, { ...options, onText }));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
streamComplete(prompt, options = {}) {
|
|
179
|
+
return this._stream((onText) => this.complete(prompt, { ...options, onText }));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async *_stream(start) {
|
|
183
|
+
const pieces = [];
|
|
184
|
+
let wake = null;
|
|
185
|
+
let stopped = false;
|
|
186
|
+
let finished = false;
|
|
187
|
+
let failure = null;
|
|
188
|
+
const notify = () => wake && wake();
|
|
189
|
+
const run = start((text) => {
|
|
190
|
+
pieces.push(text);
|
|
191
|
+
notify();
|
|
192
|
+
return !stopped;
|
|
193
|
+
}).then(
|
|
194
|
+
() => { finished = true; notify(); },
|
|
195
|
+
(error) => { failure = error; finished = true; notify(); },
|
|
196
|
+
);
|
|
197
|
+
try {
|
|
198
|
+
while (true) {
|
|
199
|
+
if (pieces.length) {
|
|
200
|
+
yield pieces.shift();
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (finished) break;
|
|
204
|
+
await new Promise((resolve) => { wake = resolve; });
|
|
205
|
+
wake = null;
|
|
206
|
+
}
|
|
207
|
+
if (failure) throw failure;
|
|
208
|
+
} finally {
|
|
209
|
+
stopped = true;
|
|
210
|
+
await run;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
_run(options, call) {
|
|
215
|
+
const task = this._queue.then(() => this._generate(options, call));
|
|
216
|
+
this._queue = task.catch(() => {});
|
|
217
|
+
return task;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async _generate(options, call) {
|
|
221
|
+
const native = load();
|
|
222
|
+
const generation = {};
|
|
223
|
+
native.generationInit(generation);
|
|
224
|
+
const stop = options.stop || [];
|
|
225
|
+
Object.assign(generation, {
|
|
226
|
+
max_tokens: options.maxTokens || 0,
|
|
227
|
+
enable_thinking: options.thinking === false ? 0 : 1,
|
|
228
|
+
temperature: options.temperature ?? 0,
|
|
229
|
+
top_p: options.topP ?? 1,
|
|
230
|
+
top_k: options.topK ?? 0,
|
|
231
|
+
seed: options.seed ?? -1,
|
|
232
|
+
stop: stop.length ? stop : null,
|
|
233
|
+
stop_count: stop.length,
|
|
234
|
+
});
|
|
235
|
+
let failure = null;
|
|
236
|
+
const onText = options.onText;
|
|
237
|
+
const callback = koffi.register((text, length) => {
|
|
238
|
+
if (!onText) return 0;
|
|
239
|
+
try {
|
|
240
|
+
const bytes = koffi.decode(text, 'uint8_t', Number(length));
|
|
241
|
+
return onText(Buffer.from(bytes).toString('utf8')) === false ? 1 : 0;
|
|
242
|
+
} catch (error) {
|
|
243
|
+
failure = error;
|
|
244
|
+
return 1;
|
|
245
|
+
}
|
|
246
|
+
}, koffi.pointer(native.TextCallback));
|
|
247
|
+
const result = {};
|
|
248
|
+
const error = [null];
|
|
249
|
+
let status;
|
|
250
|
+
try {
|
|
251
|
+
status = await call(native, generation, callback, result, error);
|
|
252
|
+
} finally {
|
|
253
|
+
koffi.unregister(callback);
|
|
254
|
+
}
|
|
255
|
+
if (status !== 0) throw new PalitoError(takeError(error[0]));
|
|
256
|
+
let completion;
|
|
257
|
+
try {
|
|
258
|
+
completion = {
|
|
259
|
+
text: koffi.decode(result.text, 'char', -1),
|
|
260
|
+
finishReason: FINISH_REASONS[result.finish_reason],
|
|
261
|
+
promptTokens: result.prompt_tokens,
|
|
262
|
+
generatedTokens: result.generated_tokens,
|
|
263
|
+
ttftMs: result.ttft_ms,
|
|
264
|
+
tokensPerSecond: result.tokens_per_second,
|
|
265
|
+
};
|
|
266
|
+
} finally {
|
|
267
|
+
native.resultFree(result);
|
|
268
|
+
}
|
|
269
|
+
if (failure) throw failure;
|
|
270
|
+
return completion;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
_handle() {
|
|
274
|
+
if (!this._engine) throw new PalitoError('engine is closed');
|
|
275
|
+
return this._engine;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Waits for queued requests, then releases the model. */
|
|
279
|
+
async close() {
|
|
280
|
+
await this._queue;
|
|
281
|
+
if (this._engine) {
|
|
282
|
+
load().close(this._engine);
|
|
283
|
+
this._engine = null;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
async [Symbol.asyncDispose]() {
|
|
288
|
+
await this.close();
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function version() {
|
|
293
|
+
return load().version();
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
module.exports = { Palito, PalitoError, version, libraryPath };
|
package/package.json
CHANGED
|
@@ -1,6 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "palito",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "Node.js binding for Palito, fast local LLM inference for GGUF models",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://github.com/natanloterio/palito#readme",
|
|
7
|
+
"repository": { "type": "git", "url": "git+https://github.com/natanloterio/palito.git", "directory": "bindings/node" },
|
|
8
|
+
"main": "index.js",
|
|
9
|
+
"types": "index.d.ts",
|
|
10
|
+
"files": ["index.js", "index.d.ts", "README.md"],
|
|
11
|
+
"engines": { "node": ">=18" },
|
|
12
|
+
"scripts": { "test": "node --test test/*.test.js" },
|
|
13
|
+
"dependencies": { "koffi": "^3.3.8" }
|
|
14
|
+
}
|