palito 0.7.0__tar.gz
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.
- palito-0.7.0/PKG-INFO +35 -0
- palito-0.7.0/README.md +24 -0
- palito-0.7.0/palito/__init__.py +324 -0
- palito-0.7.0/palito.egg-info/PKG-INFO +35 -0
- palito-0.7.0/palito.egg-info/SOURCES.txt +8 -0
- palito-0.7.0/palito.egg-info/dependency_links.txt +1 -0
- palito-0.7.0/palito.egg-info/top_level.txt +1 -0
- palito-0.7.0/pyproject.toml +20 -0
- palito-0.7.0/setup.cfg +4 -0
- palito-0.7.0/tests/test_palito.py +70 -0
palito-0.7.0/PKG-INFO
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: palito
|
|
3
|
+
Version: 0.7.0
|
|
4
|
+
Summary: Python binding for Palito, fast local LLM inference for GGUF models
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/natanloterio/palito
|
|
7
|
+
Project-URL: Source, https://github.com/natanloterio/palito/tree/master/bindings/python
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# palito (Python)
|
|
13
|
+
|
|
14
|
+
Python binding for [Palito](../../README.md). It uses only the standard library (ctypes).
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
pip install ./bindings/python
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import palito
|
|
22
|
+
|
|
23
|
+
with palito.Palito("model.gguf") as llm:
|
|
24
|
+
reply = llm.chat([{"role": "user", "content": "Hello!"}],
|
|
25
|
+
on_text=lambda text: print(text, end="", flush=True))
|
|
26
|
+
print(reply.finish_reason, reply.tokens_per_second)
|
|
27
|
+
|
|
28
|
+
for text in llm.stream_chat([{"role": "user", "content": "A haiku about tea"}],
|
|
29
|
+
temperature=0.7, top_p=0.9, stop=["\n\n"]):
|
|
30
|
+
print(text, end="", flush=True)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
- **Generation keywords:** `max_tokens`, `thinking`, `temperature` (0: greedy), `top_p`, `top_k`, `seed`, `stop` and `json_schema` (a dict or JSON string; the reply is JSON matching it, with reasoning off; `{"type": "object"}` for any object).
|
|
34
|
+
- **Results:** a `Completion` dataclass.
|
|
35
|
+
- **Errors:** raise `palito.PalitoError`.
|
palito-0.7.0/README.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# palito (Python)
|
|
2
|
+
|
|
3
|
+
Python binding for [Palito](../../README.md). It uses only the standard library (ctypes).
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install ./bindings/python
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
import palito
|
|
11
|
+
|
|
12
|
+
with palito.Palito("model.gguf") as llm:
|
|
13
|
+
reply = llm.chat([{"role": "user", "content": "Hello!"}],
|
|
14
|
+
on_text=lambda text: print(text, end="", flush=True))
|
|
15
|
+
print(reply.finish_reason, reply.tokens_per_second)
|
|
16
|
+
|
|
17
|
+
for text in llm.stream_chat([{"role": "user", "content": "A haiku about tea"}],
|
|
18
|
+
temperature=0.7, top_p=0.9, stop=["\n\n"]):
|
|
19
|
+
print(text, end="", flush=True)
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
- **Generation keywords:** `max_tokens`, `thinking`, `temperature` (0: greedy), `top_p`, `top_k`, `seed`, `stop` and `json_schema` (a dict or JSON string; the reply is JSON matching it, with reasoning off; `{"type": "object"}` for any object).
|
|
23
|
+
- **Results:** a `Completion` dataclass.
|
|
24
|
+
- **Errors:** raise `palito.PalitoError`.
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""Python binding for Palito: fast local LLM inference for GGUF models.
|
|
2
|
+
|
|
3
|
+
Standard library only (ctypes) on top of the C API in libpalito.so.
|
|
4
|
+
|
|
5
|
+
import palito
|
|
6
|
+
|
|
7
|
+
with palito.Palito("model.gguf") as llm:
|
|
8
|
+
reply = llm.chat([{"role": "user", "content": "Hello!"}],
|
|
9
|
+
on_text=lambda text: print(text, end="", flush=True))
|
|
10
|
+
print(reply.finish_reason, reply.tokens_per_second)
|
|
11
|
+
|
|
12
|
+
for text in llm.stream_chat([{"role": "user", "content": "Tell a joke"}],
|
|
13
|
+
temperature=0.7):
|
|
14
|
+
print(text, end="", flush=True)
|
|
15
|
+
|
|
16
|
+
person = llm.chat([{"role": "user", "content": "Invent a person."}],
|
|
17
|
+
json_schema={"type": "object",
|
|
18
|
+
"properties": {"name": {"type": "string"}},
|
|
19
|
+
"required": ["name"]})
|
|
20
|
+
print(json.loads(person.text)["name"])
|
|
21
|
+
|
|
22
|
+
The library is found via $PALITO_LIBRARY, then the installed `palito` command
|
|
23
|
+
(<bundle>/lib/libpalito.so), then the system loader.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
import ctypes
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import queue
|
|
30
|
+
import shutil
|
|
31
|
+
import sys
|
|
32
|
+
import threading
|
|
33
|
+
from ctypes import (CFUNCTYPE, POINTER, Structure, c_char_p, c_double, c_float,
|
|
34
|
+
c_int, c_int64, c_size_t, c_uint32, c_uint64, c_void_p)
|
|
35
|
+
from dataclasses import dataclass
|
|
36
|
+
|
|
37
|
+
__all__ = ["Palito", "PalitoError", "Completion", "DEVICE_DEFAULT", "DEVICE_CPU",
|
|
38
|
+
"DEVICE_CUDA", "version", "library_path"]
|
|
39
|
+
|
|
40
|
+
DEVICE_DEFAULT, DEVICE_CPU, DEVICE_CUDA = 0, 1, 2
|
|
41
|
+
_FINISH_REASONS = {0: "stop", 1: "length", 2: "context_full", 3: "cancelled"}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class PalitoError(RuntimeError):
|
|
45
|
+
"""An error reported by the Palito library."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class Completion:
|
|
50
|
+
text: str
|
|
51
|
+
finish_reason: str # "stop", "length", "context_full" or "cancelled"
|
|
52
|
+
prompt_tokens: int
|
|
53
|
+
generated_tokens: int
|
|
54
|
+
ttft_ms: float
|
|
55
|
+
tokens_per_second: float
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _Options(Structure):
|
|
59
|
+
_fields_ = [("device", c_int), ("context_tokens", c_uint32), ("threads", c_uint32),
|
|
60
|
+
("gpu_device", c_uint32), ("gpu_memory_limit_bytes", c_uint64),
|
|
61
|
+
("kernel_cache_dir", c_char_p)]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class _Message(Structure):
|
|
65
|
+
_fields_ = [("role", c_char_p), ("content", c_char_p)]
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class _Generation(Structure):
|
|
69
|
+
_fields_ = [("max_tokens", c_uint32), ("enable_thinking", c_int),
|
|
70
|
+
("temperature", c_float), ("top_p", c_float), ("top_k", c_uint32),
|
|
71
|
+
("seed", c_int64), ("stop", POINTER(c_char_p)), ("stop_count", c_size_t)]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class _Result(Structure):
|
|
75
|
+
_fields_ = [("text", c_void_p), ("finish_reason", c_int), ("prompt_tokens", c_uint32),
|
|
76
|
+
("generated_tokens", c_uint32), ("ttft_ms", c_double),
|
|
77
|
+
("tokens_per_second", c_double)]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
_Callback = CFUNCTYPE(c_int, c_void_p, c_size_t, c_void_p)
|
|
81
|
+
|
|
82
|
+
_LIBRARY_NAME = {"darwin": "libpalito.dylib", "win32": "palito.dll"}.get(sys.platform,
|
|
83
|
+
"libpalito.so")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def library_path():
|
|
87
|
+
"""Where libpalito is loaded from (see the module docstring)."""
|
|
88
|
+
explicit = os.environ.get("PALITO_LIBRARY")
|
|
89
|
+
if explicit:
|
|
90
|
+
return explicit
|
|
91
|
+
command = shutil.which("palito")
|
|
92
|
+
if command:
|
|
93
|
+
bundled = os.path.join(os.path.dirname(os.path.realpath(command)), "lib", _LIBRARY_NAME)
|
|
94
|
+
if os.path.isfile(bundled):
|
|
95
|
+
return bundled
|
|
96
|
+
return _LIBRARY_NAME
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
_lib = None
|
|
100
|
+
_lib_lock = threading.Lock()
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _load():
|
|
104
|
+
global _lib
|
|
105
|
+
with _lib_lock:
|
|
106
|
+
if _lib is not None:
|
|
107
|
+
return _lib
|
|
108
|
+
path = library_path()
|
|
109
|
+
try:
|
|
110
|
+
lib = ctypes.CDLL(path)
|
|
111
|
+
except OSError as error:
|
|
112
|
+
raise PalitoError(f"cannot load {path}: {error}. Install Palito or set "
|
|
113
|
+
"PALITO_LIBRARY to libpalito.so") from error
|
|
114
|
+
lib.palito_version.restype = c_char_p
|
|
115
|
+
lib.palito_options_init.argtypes = [POINTER(_Options)]
|
|
116
|
+
lib.palito_generation_init.argtypes = [POINTER(_Generation)]
|
|
117
|
+
lib.palito_open.argtypes = [c_char_p, POINTER(_Options), POINTER(c_void_p)]
|
|
118
|
+
lib.palito_open.restype = c_void_p
|
|
119
|
+
lib.palito_close.argtypes = [c_void_p]
|
|
120
|
+
lib.palito_context_tokens.argtypes = [c_void_p]
|
|
121
|
+
lib.palito_context_tokens.restype = c_uint32
|
|
122
|
+
lib.palito_profile.argtypes = [c_void_p]
|
|
123
|
+
lib.palito_profile.restype = c_char_p
|
|
124
|
+
common = [POINTER(_Generation), _Callback, c_void_p, POINTER(_Result),
|
|
125
|
+
POINTER(c_void_p)]
|
|
126
|
+
lib.palito_chat.argtypes = [c_void_p, POINTER(_Message), c_size_t] + common
|
|
127
|
+
lib.palito_complete.argtypes = [c_void_p, c_char_p] + common
|
|
128
|
+
if hasattr(lib, "palito_chat_json"): # newer than 0.5.0
|
|
129
|
+
lib.palito_chat_json.argtypes = ([c_void_p, POINTER(_Message), c_size_t]
|
|
130
|
+
+ common[:1] + [c_char_p] + common[1:])
|
|
131
|
+
lib.palito_complete_json.argtypes = ([c_void_p, c_char_p] + common[:1]
|
|
132
|
+
+ [c_char_p] + common[1:])
|
|
133
|
+
lib.palito_result_free.argtypes = [POINTER(_Result)]
|
|
134
|
+
lib.palito_string_free.argtypes = [c_void_p]
|
|
135
|
+
_lib = lib
|
|
136
|
+
return lib
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def version():
|
|
140
|
+
return _load().palito_version().decode()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _take_error(lib, error):
|
|
144
|
+
message = ctypes.string_at(error.value).decode() if error.value else "unknown error"
|
|
145
|
+
lib.palito_string_free(error)
|
|
146
|
+
return message
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def _schema_bytes(json_schema):
|
|
150
|
+
if json_schema is None:
|
|
151
|
+
return None
|
|
152
|
+
if isinstance(json_schema, (bytes, str)):
|
|
153
|
+
return json_schema.encode() if isinstance(json_schema, str) else json_schema
|
|
154
|
+
return json.dumps(json_schema).encode()
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class Palito:
|
|
158
|
+
"""A model opened once; chat() and complete() can be called many times.
|
|
159
|
+
|
|
160
|
+
One request runs at a time per engine (calls from several threads wait).
|
|
161
|
+
"""
|
|
162
|
+
|
|
163
|
+
def __init__(self, model_path, device=DEVICE_DEFAULT, context_tokens=0, threads=0,
|
|
164
|
+
gpu_device=0, gpu_memory_limit_bytes=0, kernel_cache_dir=None):
|
|
165
|
+
self._lib = _load()
|
|
166
|
+
self._lock = threading.Lock()
|
|
167
|
+
options = _Options()
|
|
168
|
+
self._lib.palito_options_init(ctypes.byref(options))
|
|
169
|
+
options.device = device
|
|
170
|
+
options.context_tokens = context_tokens
|
|
171
|
+
options.threads = threads
|
|
172
|
+
options.gpu_device = gpu_device
|
|
173
|
+
options.gpu_memory_limit_bytes = gpu_memory_limit_bytes
|
|
174
|
+
if kernel_cache_dir is not None:
|
|
175
|
+
options.kernel_cache_dir = os.fsencode(kernel_cache_dir)
|
|
176
|
+
error = c_void_p()
|
|
177
|
+
self._engine = self._lib.palito_open(os.fsencode(model_path), ctypes.byref(options),
|
|
178
|
+
ctypes.byref(error))
|
|
179
|
+
if not self._engine:
|
|
180
|
+
raise PalitoError(_take_error(self._lib, error))
|
|
181
|
+
|
|
182
|
+
@property
|
|
183
|
+
def context_tokens(self):
|
|
184
|
+
return self._lib.palito_context_tokens(self._handle())
|
|
185
|
+
|
|
186
|
+
@property
|
|
187
|
+
def profile(self):
|
|
188
|
+
""""cpu", "int8-fast", "f32-tiled" or "f32"."""
|
|
189
|
+
return self._lib.palito_profile(self._handle()).decode()
|
|
190
|
+
|
|
191
|
+
def chat(self, messages, on_text=None, **generation):
|
|
192
|
+
"""Replies to messages ([{"role": ..., "content": ...}]) with the model's chat template.
|
|
193
|
+
|
|
194
|
+
on_text(str) receives the reply as it is generated; returning False stops it.
|
|
195
|
+
Generation keywords: max_tokens=0 (no cap), thinking=True, temperature=0.0
|
|
196
|
+
(greedy), top_p=1.0, top_k=0, seed=None, stop=() (strings), json_schema=None
|
|
197
|
+
(a JSON Schema dict or string: the reply is JSON matching it, reasoning off;
|
|
198
|
+
{"type": "object"} for any object).
|
|
199
|
+
"""
|
|
200
|
+
array = (_Message * len(messages))(
|
|
201
|
+
*[_Message(m["role"].encode(), m["content"].encode()) for m in messages])
|
|
202
|
+
return self._run(lambda gen, schema, cb, res, err: (
|
|
203
|
+
self._lib.palito_chat(self._handle(), array, len(messages), gen, cb, None, res, err)
|
|
204
|
+
if schema is None else
|
|
205
|
+
self._lib.palito_chat_json(self._handle(), array, len(messages), gen, schema, cb,
|
|
206
|
+
None, res, err)),
|
|
207
|
+
on_text, **generation)
|
|
208
|
+
|
|
209
|
+
def complete(self, prompt, on_text=None, **generation):
|
|
210
|
+
"""Continues prompt without a chat template; keywords as in chat()."""
|
|
211
|
+
return self._run(lambda gen, schema, cb, res, err: (
|
|
212
|
+
self._lib.palito_complete(self._handle(), prompt.encode(), gen, cb, None, res, err)
|
|
213
|
+
if schema is None else
|
|
214
|
+
self._lib.palito_complete_json(self._handle(), prompt.encode(), gen, schema, cb,
|
|
215
|
+
None, res, err)),
|
|
216
|
+
on_text, **generation)
|
|
217
|
+
|
|
218
|
+
def stream_chat(self, messages, **generation):
|
|
219
|
+
"""Yields the reply text as it is generated. Closing the generator stops it."""
|
|
220
|
+
return self._stream(lambda on_text: self.chat(messages, on_text, **generation))
|
|
221
|
+
|
|
222
|
+
def stream_complete(self, prompt, **generation):
|
|
223
|
+
return self._stream(lambda on_text: self.complete(prompt, on_text, **generation))
|
|
224
|
+
|
|
225
|
+
def _stream(self, run):
|
|
226
|
+
pieces = queue.Queue()
|
|
227
|
+
stop = threading.Event()
|
|
228
|
+
done = object()
|
|
229
|
+
|
|
230
|
+
def on_text(text):
|
|
231
|
+
pieces.put(text)
|
|
232
|
+
return not stop.is_set()
|
|
233
|
+
|
|
234
|
+
def worker():
|
|
235
|
+
try:
|
|
236
|
+
run(on_text)
|
|
237
|
+
pieces.put(done)
|
|
238
|
+
except BaseException as error: # re-raised in the consumer
|
|
239
|
+
pieces.put(error)
|
|
240
|
+
|
|
241
|
+
thread = threading.Thread(target=worker, daemon=True)
|
|
242
|
+
thread.start()
|
|
243
|
+
try:
|
|
244
|
+
while True:
|
|
245
|
+
item = pieces.get()
|
|
246
|
+
if item is done:
|
|
247
|
+
return
|
|
248
|
+
if isinstance(item, BaseException):
|
|
249
|
+
raise item
|
|
250
|
+
yield item
|
|
251
|
+
finally:
|
|
252
|
+
stop.set()
|
|
253
|
+
thread.join()
|
|
254
|
+
|
|
255
|
+
def _run(self, call, on_text, max_tokens=0, thinking=True, temperature=0.0,
|
|
256
|
+
top_p=1.0, top_k=0, seed=None, stop=(), json_schema=None):
|
|
257
|
+
schema = _schema_bytes(json_schema)
|
|
258
|
+
if schema is not None and not hasattr(self._lib, "palito_chat_json"):
|
|
259
|
+
raise PalitoError("json_schema needs a libpalito newer than 0.5.0")
|
|
260
|
+
generation = _Generation()
|
|
261
|
+
self._lib.palito_generation_init(ctypes.byref(generation))
|
|
262
|
+
generation.max_tokens = max_tokens
|
|
263
|
+
generation.enable_thinking = 1 if thinking else 0
|
|
264
|
+
generation.temperature = temperature
|
|
265
|
+
generation.top_p = top_p
|
|
266
|
+
generation.top_k = top_k
|
|
267
|
+
generation.seed = -1 if seed is None else seed
|
|
268
|
+
stops = (c_char_p * len(stop))(*[s.encode() for s in stop])
|
|
269
|
+
generation.stop = stops
|
|
270
|
+
generation.stop_count = len(stop)
|
|
271
|
+
failure = []
|
|
272
|
+
|
|
273
|
+
def forward(text, length, _user):
|
|
274
|
+
if on_text is None:
|
|
275
|
+
return 0
|
|
276
|
+
try:
|
|
277
|
+
return 0 if on_text(ctypes.string_at(text, length).decode()) is not False else 1
|
|
278
|
+
except BaseException as error: # stop generation, re-raise after the call
|
|
279
|
+
failure.append(error)
|
|
280
|
+
return 1
|
|
281
|
+
|
|
282
|
+
callback = _Callback(forward)
|
|
283
|
+
result = _Result()
|
|
284
|
+
error = c_void_p()
|
|
285
|
+
with self._lock:
|
|
286
|
+
status = call(ctypes.byref(generation), schema, callback, ctypes.byref(result),
|
|
287
|
+
ctypes.byref(error))
|
|
288
|
+
if status:
|
|
289
|
+
raise PalitoError(_take_error(self._lib, error))
|
|
290
|
+
try:
|
|
291
|
+
completion = Completion(
|
|
292
|
+
text=ctypes.string_at(result.text).decode(),
|
|
293
|
+
finish_reason=_FINISH_REASONS[result.finish_reason],
|
|
294
|
+
prompt_tokens=result.prompt_tokens,
|
|
295
|
+
generated_tokens=result.generated_tokens,
|
|
296
|
+
ttft_ms=result.ttft_ms,
|
|
297
|
+
tokens_per_second=result.tokens_per_second,
|
|
298
|
+
)
|
|
299
|
+
finally:
|
|
300
|
+
self._lib.palito_result_free(ctypes.byref(result))
|
|
301
|
+
if failure:
|
|
302
|
+
raise failure[0]
|
|
303
|
+
return completion
|
|
304
|
+
|
|
305
|
+
def _handle(self):
|
|
306
|
+
if not self._engine:
|
|
307
|
+
raise PalitoError("engine is closed")
|
|
308
|
+
return self._engine
|
|
309
|
+
|
|
310
|
+
def close(self):
|
|
311
|
+
with self._lock:
|
|
312
|
+
if self._engine:
|
|
313
|
+
self._lib.palito_close(self._engine)
|
|
314
|
+
self._engine = None
|
|
315
|
+
|
|
316
|
+
def __enter__(self):
|
|
317
|
+
return self
|
|
318
|
+
|
|
319
|
+
def __exit__(self, *_):
|
|
320
|
+
self.close()
|
|
321
|
+
|
|
322
|
+
def __del__(self):
|
|
323
|
+
if getattr(self, "_engine", None):
|
|
324
|
+
self.close()
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: palito
|
|
3
|
+
Version: 0.7.0
|
|
4
|
+
Summary: Python binding for Palito, fast local LLM inference for GGUF models
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/natanloterio/palito
|
|
7
|
+
Project-URL: Source, https://github.com/natanloterio/palito/tree/master/bindings/python
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# palito (Python)
|
|
13
|
+
|
|
14
|
+
Python binding for [Palito](../../README.md). It uses only the standard library (ctypes).
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
pip install ./bindings/python
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
import palito
|
|
22
|
+
|
|
23
|
+
with palito.Palito("model.gguf") as llm:
|
|
24
|
+
reply = llm.chat([{"role": "user", "content": "Hello!"}],
|
|
25
|
+
on_text=lambda text: print(text, end="", flush=True))
|
|
26
|
+
print(reply.finish_reason, reply.tokens_per_second)
|
|
27
|
+
|
|
28
|
+
for text in llm.stream_chat([{"role": "user", "content": "A haiku about tea"}],
|
|
29
|
+
temperature=0.7, top_p=0.9, stop=["\n\n"]):
|
|
30
|
+
print(text, end="", flush=True)
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
- **Generation keywords:** `max_tokens`, `thinking`, `temperature` (0: greedy), `top_p`, `top_k`, `seed`, `stop` and `json_schema` (a dict or JSON string; the reply is JSON matching it, with reasoning off; `{"type": "object"}` for any object).
|
|
34
|
+
- **Results:** a `Completion` dataclass.
|
|
35
|
+
- **Errors:** raise `palito.PalitoError`.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
palito
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "palito"
|
|
7
|
+
version = "0.7.0"
|
|
8
|
+
description = "Python binding for Palito, fast local LLM inference for GGUF models"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
classifiers = ["Programming Language :: Python :: 3"]
|
|
13
|
+
dependencies = []
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Homepage = "https://github.com/natanloterio/palito"
|
|
17
|
+
Source = "https://github.com/natanloterio/palito/tree/master/bindings/python"
|
|
18
|
+
|
|
19
|
+
[tool.setuptools]
|
|
20
|
+
packages = ["palito"]
|
palito-0.7.0/setup.cfg
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Run: PALITO_TEST_MODEL=/path/to/SmolLM2-135M-Instruct-Q4_K_M.gguf python3 tests/test_palito.py"""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
import unittest
|
|
6
|
+
|
|
7
|
+
sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
|
|
8
|
+
|
|
9
|
+
import palito
|
|
10
|
+
|
|
11
|
+
MODEL = os.environ.get("PALITO_TEST_MODEL")
|
|
12
|
+
HELLO = [{"role": "user", "content": "Say hello."}]
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@unittest.skipUnless(MODEL, "set PALITO_TEST_MODEL to a small GGUF model")
|
|
16
|
+
class PalitoTest(unittest.TestCase):
|
|
17
|
+
@classmethod
|
|
18
|
+
def setUpClass(cls):
|
|
19
|
+
cls.llm = palito.Palito(MODEL, device=palito.DEVICE_CPU, context_tokens=512)
|
|
20
|
+
|
|
21
|
+
@classmethod
|
|
22
|
+
def tearDownClass(cls):
|
|
23
|
+
cls.llm.close()
|
|
24
|
+
|
|
25
|
+
def test_streamed_text_equals_the_reply(self):
|
|
26
|
+
pieces = []
|
|
27
|
+
reply = self.llm.chat(HELLO, max_tokens=24, on_text=pieces.append)
|
|
28
|
+
self.assertEqual("".join(pieces), reply.text)
|
|
29
|
+
self.assertTrue(0 < reply.generated_tokens <= 24)
|
|
30
|
+
self.assertEqual("".join(self.llm.stream_chat(HELLO, max_tokens=24)), reply.text)
|
|
31
|
+
|
|
32
|
+
def test_stop_sampling_and_cancel(self):
|
|
33
|
+
cut = self.llm.complete("1, 2, 3, 4,", max_tokens=24, stop=[" 7"])
|
|
34
|
+
self.assertEqual(cut.finish_reason, "stop")
|
|
35
|
+
self.assertNotIn(" 7", cut.text)
|
|
36
|
+
a = self.llm.chat(HELLO, max_tokens=16, temperature=0.9, seed=4)
|
|
37
|
+
b = self.llm.chat(HELLO, max_tokens=16, temperature=0.9, seed=4)
|
|
38
|
+
self.assertEqual(a.text, b.text)
|
|
39
|
+
cancelled = self.llm.complete("Once upon a time", on_text=lambda _: False)
|
|
40
|
+
self.assertEqual(cancelled.finish_reason, "cancelled")
|
|
41
|
+
stream = self.llm.stream_complete("Once upon a time", max_tokens=200)
|
|
42
|
+
next(stream)
|
|
43
|
+
stream.close() # stops generation; the engine is usable again
|
|
44
|
+
self.assertEqual(self.llm.complete("Hi", max_tokens=2).generated_tokens, 2)
|
|
45
|
+
|
|
46
|
+
def test_json_schema(self):
|
|
47
|
+
schema = {"type": "object", "properties": {"ok": {"type": "boolean"}},
|
|
48
|
+
"required": ["ok"], "additionalProperties": False}
|
|
49
|
+
for temperature in (0.0, 0.9):
|
|
50
|
+
reply = self.llm.chat([{"role": "user", "content": "Is water wet?"}],
|
|
51
|
+
max_tokens=64, temperature=temperature, seed=1,
|
|
52
|
+
json_schema=schema)
|
|
53
|
+
self.assertIsInstance(json.loads(reply.text)["ok"], bool)
|
|
54
|
+
streamed = "".join(self.llm.stream_chat(HELLO, max_tokens=64,
|
|
55
|
+
json_schema='{"enum": ["hi", "hello"]}'))
|
|
56
|
+
self.assertIn(json.loads(streamed), ("hi", "hello"))
|
|
57
|
+
with self.assertRaisesRegex(palito.PalitoError, "uniqueItems"):
|
|
58
|
+
self.llm.chat(HELLO, json_schema={"type": "array", "uniqueItems": True})
|
|
59
|
+
|
|
60
|
+
def test_errors(self):
|
|
61
|
+
with self.assertRaises(palito.PalitoError):
|
|
62
|
+
palito.Palito("/nonexistent.gguf")
|
|
63
|
+
with self.assertRaises(palito.PalitoError):
|
|
64
|
+
self.llm.chat(HELLO, temperature=-1)
|
|
65
|
+
with self.assertRaises(ZeroDivisionError):
|
|
66
|
+
self.llm.complete("Hi", on_text=lambda _: 1 / 0)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
if __name__ == "__main__":
|
|
70
|
+
unittest.main()
|