ggufly 0.2.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.
- ggufly-0.2.0/LICENSE +21 -0
- ggufly-0.2.0/PKG-INFO +218 -0
- ggufly-0.2.0/README.md +187 -0
- ggufly-0.2.0/ggufly/__init__.py +67 -0
- ggufly-0.2.0/ggufly/api.py +181 -0
- ggufly-0.2.0/ggufly/cli.py +153 -0
- ggufly-0.2.0/ggufly/client.py +251 -0
- ggufly-0.2.0/ggufly/config.py +43 -0
- ggufly-0.2.0/ggufly/engine.py +376 -0
- ggufly-0.2.0/ggufly/py.typed +1 -0
- ggufly-0.2.0/ggufly/resolve.py +65 -0
- ggufly-0.2.0/ggufly/server.py +230 -0
- ggufly-0.2.0/ggufly/utils.py +115 -0
- ggufly-0.2.0/ggufly.egg-info/PKG-INFO +218 -0
- ggufly-0.2.0/ggufly.egg-info/SOURCES.txt +19 -0
- ggufly-0.2.0/ggufly.egg-info/dependency_links.txt +1 -0
- ggufly-0.2.0/ggufly.egg-info/entry_points.txt +2 -0
- ggufly-0.2.0/ggufly.egg-info/requires.txt +6 -0
- ggufly-0.2.0/ggufly.egg-info/top_level.txt +1 -0
- ggufly-0.2.0/pyproject.toml +50 -0
- ggufly-0.2.0/setup.cfg +4 -0
ggufly-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ggufly
|
|
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.
|
ggufly-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ggufly
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Modelos GGUF locales con llama.cpp precompilado: un solo modelo en memoria para todas tus respuestas simultaneas.
|
|
5
|
+
Author: ggufly
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/ggufly/ggufly
|
|
8
|
+
Project-URL: Issues, https://github.com/ggufly/ggufly/issues
|
|
9
|
+
Keywords: gguf,llama.cpp,llm,local-ai,batching,concurrent,vision,mmproj
|
|
10
|
+
Classifier: Development Status :: 4 - Beta
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
13
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
14
|
+
Classifier: Operating System :: MacOS
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
22
|
+
Requires-Python: >=3.9
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Requires-Dist: httpx>=0.27
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
28
|
+
Requires-Dist: build>=1; extra == "dev"
|
|
29
|
+
Requires-Dist: twine>=5; extra == "dev"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# ggufly 🦙
|
|
33
|
+
|
|
34
|
+
**Respuestas simultáneas con un solo modelo en memoria.** ggufly gestiona un **único `llama-server` de llama.cpp** (binarios oficiales precompilados que se instalan solos — **nunca compilas nada**) y te da una API de Python sencilla para chatear con modelos GGUF.
|
|
35
|
+
|
|
36
|
+
> ⚠️ **ggufly NO descarga modelos.** Obtén tus archivos `.gguf` por tu cuenta (p. ej. con `huggingface-cli download <repo>`) y pasa la **ruta local** a la librería.
|
|
37
|
+
|
|
38
|
+
**La idea clave:** si el modelo ya está en memoria/VRAM respondiendo a un usuario, los demás usuarios **reutilizan ese mismo modelo** — nunca se cargan copias extra:
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
Usuario 1 ──┐
|
|
42
|
+
Usuario 2 ──┤ ┌──────────────────────────────┐
|
|
43
|
+
Usuario 3 ──┼────▶│ 1 solo proceso llama-server │
|
|
44
|
+
Usuario 4 ──┤ │ modelo cargado UNA vez │
|
|
45
|
+
Usuario 5 ──┘ └──────────────────────────────┘
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Con 5 usuarios consumes `1 × modelo` en vez de `5 × modelo` (~80% de ahorro; con 20 usuarios, ~93%).
|
|
49
|
+
|
|
50
|
+
---
|
|
51
|
+
|
|
52
|
+
## 📦 Instalación
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
pip install ggufly
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
O desde el código fuente:
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
cd ggufly
|
|
62
|
+
pip install -e .
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
El **motor llama.cpp** se descarga automáticamente la primera vez que lo uses (binarios oficiales: CUDA si detecta GPU NVIDIA, Vulkan en Windows si no, CPU como último recurso). Se guarda en `%LOCALAPPDATA%\ggufly\engine` y se reutiliza para siempre. Configurable con las variables de entorno `GGUFLY_HOME` y `GGUFLY_ENGINE`.
|
|
66
|
+
|
|
67
|
+
## 🚀 Uso básico
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import ggufly
|
|
71
|
+
|
|
72
|
+
# Tu modelo GGUF local (texto y/o carpeta que lo contenga)
|
|
73
|
+
m = ggufly.load(r"C:\modelos\mi-modelo-q4_k_m.gguf", n_ctx=8192, n_parallel=4)
|
|
74
|
+
|
|
75
|
+
# Respuesta completa
|
|
76
|
+
r = m.chat("¿Qué es un GGUF?", max_tokens=200)
|
|
77
|
+
print(r["choices"][0]["message"]["content"])
|
|
78
|
+
|
|
79
|
+
# Streaming token a token
|
|
80
|
+
for chunk in m.chat("Cuéntame un cuento", stream=True, max_tokens=300):
|
|
81
|
+
print(chunk, end="", flush=True)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
- `n_ctx`: contexto **total** (se reparte entre los slots; más usuarios = menos contexto por usuario).
|
|
85
|
+
- `n_parallel`: número de respuestas simultáneas (slots de batching).
|
|
86
|
+
- `n_gpu_layers=-1`: todas las capas en GPU (pon un nº para descargar capas a CPU si falta VRAM).
|
|
87
|
+
|
|
88
|
+
Puedes pasarle una **carpeta** en vez de un archivo: elegirá el `.gguf` principal solo.
|
|
89
|
+
|
|
90
|
+
## 👥 Respuestas simultáneas (lo importante)
|
|
91
|
+
|
|
92
|
+
Varios usuarios a la vez, **compartiendo el mismo modelo en memoria**:
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
import concurrent.futures as cf
|
|
96
|
+
import ggufly
|
|
97
|
+
|
|
98
|
+
m = ggufly.load(r"C:\modelos\mi-modelo.gguf", n_ctx=8192, n_parallel=4)
|
|
99
|
+
|
|
100
|
+
preguntas = ["hola", "¿qué es la IA?", "cuéntame un chiste", "adiós"]
|
|
101
|
+
with cf.ThreadPoolExecutor(max_workers=4) as ex:
|
|
102
|
+
respuestas = list(ex.map(lambda q: m.chat(q), preguntas))
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Con **asyncio**:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
import asyncio, ggufly
|
|
109
|
+
|
|
110
|
+
async def main():
|
|
111
|
+
m = ggufly.load(r"C:\modelos\mi-modelo.gguf", n_parallel=8)
|
|
112
|
+
outs = await ggufly.arun_many(m, preguntas, max_tokens=200) # 8 a la vez
|
|
113
|
+
for o in outs:
|
|
114
|
+
print(o["choices"][0]["message"]["content"])
|
|
115
|
+
|
|
116
|
+
asyncio.run(main())
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
**Streaming en paralelo** (cada usuario ve su stream íntegro):
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
def usuario(i, pregunta):
|
|
123
|
+
for chunk in m.chat(pregunta, stream=True, max_tokens=100):
|
|
124
|
+
print(f"[usuario {i}] {chunk}", end="", flush=True)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
💡 Si en otro módulo de tu app vuelves a hacer `ggufly.load()` con el mismo modelo+config, **no** se crea un segundo servidor: se reutiliza el mismo (cero memoria duplicada).
|
|
128
|
+
|
|
129
|
+
## 🖼️ Visión con mmproj
|
|
130
|
+
|
|
131
|
+
1. Coloca el `mmproj*.gguf` del modelo **en la misma carpeta** que el modelo (lo sacas del mismo repo donde descargaste el GGUF).
|
|
132
|
+
2. ggufly lo detecta y carga solo:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
m = ggufly.load(r"C:\modelos\mi-modelo-vision") # carpeta con modelo.gguf + mmproj.gguf
|
|
136
|
+
|
|
137
|
+
r = m.chat("¿Qué hay en la imagen?", images=["foto.jpg"], max_tokens=300)
|
|
138
|
+
# images acepta: rutas locales, URLs http(s) o bytes
|
|
139
|
+
print(r["choices"][0]["message"]["content"])
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
## 🧩 API completa
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
m.chat(prompt_o_historial, *, images=None, stream=False, **params_gen)
|
|
146
|
+
m.generate(prompt, *, stream=False, **params_gen) # /completion crudo (sin plantilla de chat)
|
|
147
|
+
m.embed(["texto 1", "texto 2"]) # embeddings (modelo de embeddings GGUF)
|
|
148
|
+
m.slots() # estado de los slots de batching
|
|
149
|
+
m.wait_stream(iterador) # consume un stream -> texto completo
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
- Historial de chat formato OpenAI:
|
|
153
|
+
|
|
154
|
+
```python
|
|
155
|
+
m.chat([
|
|
156
|
+
{"role": "system", "content": "Eres un asistente conciso."},
|
|
157
|
+
{"role": "user", "content": "¿Quién eres?"},
|
|
158
|
+
])
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
- Async: `await m.achat(...)`, `await m.agenerate(...)`, `await m.aembed(...)`.
|
|
162
|
+
- Parámetros de generación habituales: `max_tokens`, `temperature`, `top_p`, `repeat_penalty`, `stop`, `seed`...
|
|
163
|
+
|
|
164
|
+
### Servir a otras apps (endpoint OpenAI-compatible)
|
|
165
|
+
|
|
166
|
+
```python
|
|
167
|
+
srv = ggufly.serve(r"C:\modelos\mi-modelo.gguf", port=8080, n_parallel=8)
|
|
168
|
+
print(srv.base_url) # -> http://127.0.0.1:8080 (endpoints /v1/chat/completions, /v1/embeddings...)
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
Cualquier cliente OpenAI puede apuntar a esa URL. `ggufly.serve()` no bloquea; usa `srv.stop()` para parar.
|
|
172
|
+
|
|
173
|
+
### Argumentos avanzados de llama.cpp
|
|
174
|
+
|
|
175
|
+
Se pasan tal cual al motor:
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
m = ggufly.load("modelo.gguf", extra_args=[
|
|
179
|
+
"--cache-type-k", "q8_0", # KV-cache cuantizado: menos memoria por usuario
|
|
180
|
+
"--cache-type-v", "q8_0",
|
|
181
|
+
"--no-mmap",
|
|
182
|
+
])
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## 🖥️ CLI
|
|
186
|
+
|
|
187
|
+
```bash
|
|
188
|
+
# Instalar/verificar el motor llama.cpp
|
|
189
|
+
ggufly engines status
|
|
190
|
+
ggufly engines install [--backend cuda|vulkan|cpu]
|
|
191
|
+
|
|
192
|
+
# Servir el modelo (API OpenAI-compatible en la terminal)
|
|
193
|
+
ggufly serve "C:\modelos\mi-modelo.gguf" --parallel 8 --ctx 8192 --port 8080
|
|
194
|
+
|
|
195
|
+
# Chat interactivo en la terminal (/image <ruta> adjunta imagen, /exit sale)
|
|
196
|
+
ggufly chat "C:\modelos\mi-modelo.gguf"
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## 🛠️ Solución de problemas
|
|
200
|
+
|
|
201
|
+
| Problema | Solución |
|
|
202
|
+
|---|---|
|
|
203
|
+
| `No existe: ...` | ggufly no descarga modelos: descarga tu `.gguf` (p. ej. `huggingface-cli download <repo>`) y pasa la ruta. |
|
|
204
|
+
| Falta VRAM | Baja `n_gpu_layers` (p. ej. `30` de 32 capas), usa `extra_args=["--cache-type-k","q8_0"]` o un GGUF más pequeño. |
|
|
205
|
+
| Respuestas se cortan | Sube `n_ctx` (recuerda: se reparte entre slots). |
|
|
206
|
+
| El servidor no arranca | Revisa el log en `%LOCALAPPDATA%\ggufly\logs\`. Si tu ruta tiene espacios, ggufly reubica el motor solo a `C:\Users\Public\ggufly\engine`. |
|
|
207
|
+
| Silenciar los logs INFO | `logging.getLogger("ggufly").setLevel(logging.WARNING)` |
|
|
208
|
+
|
|
209
|
+
## 🧠 Cómo funciona por dentro
|
|
210
|
+
|
|
211
|
+
- **`engine.py`**: descarga e instala los binarios oficiales de llama.cpp (GitHub releases), detecta tu mejor backend y verifica que arranca.
|
|
212
|
+
- **`server.py`**: lanza y vigila el proceso `llama-server` con `--parallel N` (batching continuo). Registro interno: mismo modelo+config = mismo proceso compartido.
|
|
213
|
+
- **`client.py`**: cliente HTTP OpenAI-compatible con streaming SSE (sync + async).
|
|
214
|
+
- **`resolve.py`**: localiza tu `.gguf` y el `mmproj` en rutas locales.
|
|
215
|
+
|
|
216
|
+
## 📄 Licencia
|
|
217
|
+
|
|
218
|
+
MIT — el motor llama.cpp tiene su propia licencia MIT.
|
ggufly-0.2.0/README.md
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# ggufly 🦙
|
|
2
|
+
|
|
3
|
+
**Respuestas simultáneas con un solo modelo en memoria.** ggufly gestiona un **único `llama-server` de llama.cpp** (binarios oficiales precompilados que se instalan solos — **nunca compilas nada**) y te da una API de Python sencilla para chatear con modelos GGUF.
|
|
4
|
+
|
|
5
|
+
> ⚠️ **ggufly NO descarga modelos.** Obtén tus archivos `.gguf` por tu cuenta (p. ej. con `huggingface-cli download <repo>`) y pasa la **ruta local** a la librería.
|
|
6
|
+
|
|
7
|
+
**La idea clave:** si el modelo ya está en memoria/VRAM respondiendo a un usuario, los demás usuarios **reutilizan ese mismo modelo** — nunca se cargan copias extra:
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
Usuario 1 ──┐
|
|
11
|
+
Usuario 2 ──┤ ┌──────────────────────────────┐
|
|
12
|
+
Usuario 3 ──┼────▶│ 1 solo proceso llama-server │
|
|
13
|
+
Usuario 4 ──┤ │ modelo cargado UNA vez │
|
|
14
|
+
Usuario 5 ──┘ └──────────────────────────────┘
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Con 5 usuarios consumes `1 × modelo` en vez de `5 × modelo` (~80% de ahorro; con 20 usuarios, ~93%).
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## 📦 Instalación
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install ggufly
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
O desde el código fuente:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
cd ggufly
|
|
31
|
+
pip install -e .
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
El **motor llama.cpp** se descarga automáticamente la primera vez que lo uses (binarios oficiales: CUDA si detecta GPU NVIDIA, Vulkan en Windows si no, CPU como último recurso). Se guarda en `%LOCALAPPDATA%\ggufly\engine` y se reutiliza para siempre. Configurable con las variables de entorno `GGUFLY_HOME` y `GGUFLY_ENGINE`.
|
|
35
|
+
|
|
36
|
+
## 🚀 Uso básico
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
import ggufly
|
|
40
|
+
|
|
41
|
+
# Tu modelo GGUF local (texto y/o carpeta que lo contenga)
|
|
42
|
+
m = ggufly.load(r"C:\modelos\mi-modelo-q4_k_m.gguf", n_ctx=8192, n_parallel=4)
|
|
43
|
+
|
|
44
|
+
# Respuesta completa
|
|
45
|
+
r = m.chat("¿Qué es un GGUF?", max_tokens=200)
|
|
46
|
+
print(r["choices"][0]["message"]["content"])
|
|
47
|
+
|
|
48
|
+
# Streaming token a token
|
|
49
|
+
for chunk in m.chat("Cuéntame un cuento", stream=True, max_tokens=300):
|
|
50
|
+
print(chunk, end="", flush=True)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
- `n_ctx`: contexto **total** (se reparte entre los slots; más usuarios = menos contexto por usuario).
|
|
54
|
+
- `n_parallel`: número de respuestas simultáneas (slots de batching).
|
|
55
|
+
- `n_gpu_layers=-1`: todas las capas en GPU (pon un nº para descargar capas a CPU si falta VRAM).
|
|
56
|
+
|
|
57
|
+
Puedes pasarle una **carpeta** en vez de un archivo: elegirá el `.gguf` principal solo.
|
|
58
|
+
|
|
59
|
+
## 👥 Respuestas simultáneas (lo importante)
|
|
60
|
+
|
|
61
|
+
Varios usuarios a la vez, **compartiendo el mismo modelo en memoria**:
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import concurrent.futures as cf
|
|
65
|
+
import ggufly
|
|
66
|
+
|
|
67
|
+
m = ggufly.load(r"C:\modelos\mi-modelo.gguf", n_ctx=8192, n_parallel=4)
|
|
68
|
+
|
|
69
|
+
preguntas = ["hola", "¿qué es la IA?", "cuéntame un chiste", "adiós"]
|
|
70
|
+
with cf.ThreadPoolExecutor(max_workers=4) as ex:
|
|
71
|
+
respuestas = list(ex.map(lambda q: m.chat(q), preguntas))
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Con **asyncio**:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
import asyncio, ggufly
|
|
78
|
+
|
|
79
|
+
async def main():
|
|
80
|
+
m = ggufly.load(r"C:\modelos\mi-modelo.gguf", n_parallel=8)
|
|
81
|
+
outs = await ggufly.arun_many(m, preguntas, max_tokens=200) # 8 a la vez
|
|
82
|
+
for o in outs:
|
|
83
|
+
print(o["choices"][0]["message"]["content"])
|
|
84
|
+
|
|
85
|
+
asyncio.run(main())
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
**Streaming en paralelo** (cada usuario ve su stream íntegro):
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
def usuario(i, pregunta):
|
|
92
|
+
for chunk in m.chat(pregunta, stream=True, max_tokens=100):
|
|
93
|
+
print(f"[usuario {i}] {chunk}", end="", flush=True)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
💡 Si en otro módulo de tu app vuelves a hacer `ggufly.load()` con el mismo modelo+config, **no** se crea un segundo servidor: se reutiliza el mismo (cero memoria duplicada).
|
|
97
|
+
|
|
98
|
+
## 🖼️ Visión con mmproj
|
|
99
|
+
|
|
100
|
+
1. Coloca el `mmproj*.gguf` del modelo **en la misma carpeta** que el modelo (lo sacas del mismo repo donde descargaste el GGUF).
|
|
101
|
+
2. ggufly lo detecta y carga solo:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
m = ggufly.load(r"C:\modelos\mi-modelo-vision") # carpeta con modelo.gguf + mmproj.gguf
|
|
105
|
+
|
|
106
|
+
r = m.chat("¿Qué hay en la imagen?", images=["foto.jpg"], max_tokens=300)
|
|
107
|
+
# images acepta: rutas locales, URLs http(s) o bytes
|
|
108
|
+
print(r["choices"][0]["message"]["content"])
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## 🧩 API completa
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
m.chat(prompt_o_historial, *, images=None, stream=False, **params_gen)
|
|
115
|
+
m.generate(prompt, *, stream=False, **params_gen) # /completion crudo (sin plantilla de chat)
|
|
116
|
+
m.embed(["texto 1", "texto 2"]) # embeddings (modelo de embeddings GGUF)
|
|
117
|
+
m.slots() # estado de los slots de batching
|
|
118
|
+
m.wait_stream(iterador) # consume un stream -> texto completo
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
- Historial de chat formato OpenAI:
|
|
122
|
+
|
|
123
|
+
```python
|
|
124
|
+
m.chat([
|
|
125
|
+
{"role": "system", "content": "Eres un asistente conciso."},
|
|
126
|
+
{"role": "user", "content": "¿Quién eres?"},
|
|
127
|
+
])
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
- Async: `await m.achat(...)`, `await m.agenerate(...)`, `await m.aembed(...)`.
|
|
131
|
+
- Parámetros de generación habituales: `max_tokens`, `temperature`, `top_p`, `repeat_penalty`, `stop`, `seed`...
|
|
132
|
+
|
|
133
|
+
### Servir a otras apps (endpoint OpenAI-compatible)
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
srv = ggufly.serve(r"C:\modelos\mi-modelo.gguf", port=8080, n_parallel=8)
|
|
137
|
+
print(srv.base_url) # -> http://127.0.0.1:8080 (endpoints /v1/chat/completions, /v1/embeddings...)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
Cualquier cliente OpenAI puede apuntar a esa URL. `ggufly.serve()` no bloquea; usa `srv.stop()` para parar.
|
|
141
|
+
|
|
142
|
+
### Argumentos avanzados de llama.cpp
|
|
143
|
+
|
|
144
|
+
Se pasan tal cual al motor:
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
m = ggufly.load("modelo.gguf", extra_args=[
|
|
148
|
+
"--cache-type-k", "q8_0", # KV-cache cuantizado: menos memoria por usuario
|
|
149
|
+
"--cache-type-v", "q8_0",
|
|
150
|
+
"--no-mmap",
|
|
151
|
+
])
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
## 🖥️ CLI
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
# Instalar/verificar el motor llama.cpp
|
|
158
|
+
ggufly engines status
|
|
159
|
+
ggufly engines install [--backend cuda|vulkan|cpu]
|
|
160
|
+
|
|
161
|
+
# Servir el modelo (API OpenAI-compatible en la terminal)
|
|
162
|
+
ggufly serve "C:\modelos\mi-modelo.gguf" --parallel 8 --ctx 8192 --port 8080
|
|
163
|
+
|
|
164
|
+
# Chat interactivo en la terminal (/image <ruta> adjunta imagen, /exit sale)
|
|
165
|
+
ggufly chat "C:\modelos\mi-modelo.gguf"
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
## 🛠️ Solución de problemas
|
|
169
|
+
|
|
170
|
+
| Problema | Solución |
|
|
171
|
+
|---|---|
|
|
172
|
+
| `No existe: ...` | ggufly no descarga modelos: descarga tu `.gguf` (p. ej. `huggingface-cli download <repo>`) y pasa la ruta. |
|
|
173
|
+
| Falta VRAM | Baja `n_gpu_layers` (p. ej. `30` de 32 capas), usa `extra_args=["--cache-type-k","q8_0"]` o un GGUF más pequeño. |
|
|
174
|
+
| Respuestas se cortan | Sube `n_ctx` (recuerda: se reparte entre slots). |
|
|
175
|
+
| El servidor no arranca | Revisa el log en `%LOCALAPPDATA%\ggufly\logs\`. Si tu ruta tiene espacios, ggufly reubica el motor solo a `C:\Users\Public\ggufly\engine`. |
|
|
176
|
+
| Silenciar los logs INFO | `logging.getLogger("ggufly").setLevel(logging.WARNING)` |
|
|
177
|
+
|
|
178
|
+
## 🧠 Cómo funciona por dentro
|
|
179
|
+
|
|
180
|
+
- **`engine.py`**: descarga e instala los binarios oficiales de llama.cpp (GitHub releases), detecta tu mejor backend y verifica que arranca.
|
|
181
|
+
- **`server.py`**: lanza y vigila el proceso `llama-server` con `--parallel N` (batching continuo). Registro interno: mismo modelo+config = mismo proceso compartido.
|
|
182
|
+
- **`client.py`**: cliente HTTP OpenAI-compatible con streaming SSE (sync + async).
|
|
183
|
+
- **`resolve.py`**: localiza tu `.gguf` y el `mmproj` en rutas locales.
|
|
184
|
+
|
|
185
|
+
## 📄 Licencia
|
|
186
|
+
|
|
187
|
+
MIT — el motor llama.cpp tiene su propia licencia MIT.
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
r"""ggufly: modelos GGUF locales con llama.cpp precompilado y
|
|
2
|
+
respuestas simultaneas compartiendo memoria (un solo modelo cargado).
|
|
3
|
+
|
|
4
|
+
NOTA: ggufly NO descarga modelos. El usuario obtiene sus .gguf por su cuenta
|
|
5
|
+
(p.ej. `huggingface-cli download <repo>`) y pasa la ruta local.
|
|
6
|
+
|
|
7
|
+
Ejemplo:
|
|
8
|
+
import ggufly
|
|
9
|
+
m = ggufly.load(r"C:\modelos\qwen2.5-0.5b-instruct-q4_k_m.gguf")
|
|
10
|
+
print(m.chat("Hola!")["choices"][0]["message"]["content"])
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Optional
|
|
15
|
+
|
|
16
|
+
__version__ = "0.2.0"
|
|
17
|
+
__all__ = [
|
|
18
|
+
"Model",
|
|
19
|
+
"load",
|
|
20
|
+
"run_many",
|
|
21
|
+
"arun_many",
|
|
22
|
+
"ensure_engine",
|
|
23
|
+
"installed_engine",
|
|
24
|
+
"serve",
|
|
25
|
+
"start_server",
|
|
26
|
+
"shutdown_all",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
from .api import Model, load, run_many, arun_many
|
|
30
|
+
from .engine import ensure_engine, installed_engine
|
|
31
|
+
from .server import Server, ServerConfig, get_or_start, shutdown_all
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def start_server(
|
|
35
|
+
model: str,
|
|
36
|
+
*,
|
|
37
|
+
mmproj: Optional[str] = None,
|
|
38
|
+
port: Optional[int] = None,
|
|
39
|
+
n_ctx: int = 8192,
|
|
40
|
+
n_parallel: int = 4,
|
|
41
|
+
n_gpu_layers: int = -1,
|
|
42
|
+
backend: Optional[str] = None,
|
|
43
|
+
extra_args: Optional[list] = None,
|
|
44
|
+
host: str = "127.0.0.1",
|
|
45
|
+
) -> Server:
|
|
46
|
+
"""Levanta un llama-server gestionado y devuelve el objeto Server.
|
|
47
|
+
|
|
48
|
+
Util si quieres exponer la API OpenAI-compatible de llama.cpp a otras
|
|
49
|
+
apps (el endpoint esta en Server.base_url).
|
|
50
|
+
"""
|
|
51
|
+
cfg = ServerConfig(
|
|
52
|
+
model=model,
|
|
53
|
+
mmproj=mmproj,
|
|
54
|
+
port=port,
|
|
55
|
+
n_ctx=n_ctx,
|
|
56
|
+
n_parallel=n_parallel,
|
|
57
|
+
n_gpu_layers=n_gpu_layers,
|
|
58
|
+
backend=backend,
|
|
59
|
+
extra_args=tuple(extra_args or ()),
|
|
60
|
+
host=host,
|
|
61
|
+
)
|
|
62
|
+
return get_or_start(cfg)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def serve(model: str, **kwargs) -> Server:
|
|
66
|
+
"""Alias de start_server."""
|
|
67
|
+
return start_server(model, **kwargs)
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""API de alto nivel: un objeto `Model` que enciende/reutiliza un solo
|
|
2
|
+
llama-server compartido y expone chat, streaming, vision y embeddings.
|
|
3
|
+
|
|
4
|
+
Uso basico:
|
|
5
|
+
import ggufly
|
|
6
|
+
m = ggufly.load("Qwen/Qwen2.5-VL-7B-Instruct-GGUF") # auto-descarga
|
|
7
|
+
r = m.chat("Hola, ¿quien eres?")
|
|
8
|
+
print(r["choices"][0]["message"]["content"])
|
|
9
|
+
|
|
10
|
+
Vision:
|
|
11
|
+
r = m.chat("¿Que hay en la imagen?", images=["foto.jpg"])
|
|
12
|
+
|
|
13
|
+
Concurrencia (comparte el mismo modelo en VRAM):
|
|
14
|
+
import concurrent.futures as cf
|
|
15
|
+
with cf.ThreadPoolExecutor(8) as ex:
|
|
16
|
+
outs = list(ex.map(lambda q: m.chat(q, max_tokens=200), preguntas))
|
|
17
|
+
"""
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import asyncio
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any, AsyncIterator, Dict, Iterator, List, Optional, Union
|
|
23
|
+
|
|
24
|
+
from .client import AsyncChatClient, ChatClient
|
|
25
|
+
from .resolve import resolve
|
|
26
|
+
from .server import ServerConfig, get_or_start
|
|
27
|
+
|
|
28
|
+
Message = Dict[str, Any]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _as_messages(prompt_or_messages: Union[str, List[Message]]) -> List[Message]:
|
|
32
|
+
if isinstance(prompt_or_messages, str):
|
|
33
|
+
return [{"role": "user", "content": prompt_or_messages}]
|
|
34
|
+
return prompt_or_messages
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class Model:
|
|
38
|
+
"""Modelo GGUF cargado (texto y/o vision) con respuestas simultaneas."""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
source: str,
|
|
43
|
+
*,
|
|
44
|
+
mmproj: Optional[str] = None,
|
|
45
|
+
backend: Optional[str] = None,
|
|
46
|
+
n_ctx: int = 8192,
|
|
47
|
+
n_parallel: int = 4,
|
|
48
|
+
n_gpu_layers: int = -1,
|
|
49
|
+
flash_attn: bool = True,
|
|
50
|
+
threads: Optional[int] = None,
|
|
51
|
+
port: Optional[int] = None,
|
|
52
|
+
extra_args: Optional[List[str]] = None,
|
|
53
|
+
):
|
|
54
|
+
model_path, mmproj_path = resolve(source, mmproj=mmproj)
|
|
55
|
+
self.model_path: Path = model_path
|
|
56
|
+
self.mmproj_path: Optional[Path] = mmproj_path
|
|
57
|
+
self.config = ServerConfig(
|
|
58
|
+
model=str(model_path),
|
|
59
|
+
mmproj=str(mmproj_path) if mmproj_path else None,
|
|
60
|
+
backend=backend,
|
|
61
|
+
n_ctx=n_ctx,
|
|
62
|
+
n_parallel=n_parallel,
|
|
63
|
+
n_gpu_layers=n_gpu_layers,
|
|
64
|
+
flash_attn=flash_attn,
|
|
65
|
+
threads=threads,
|
|
66
|
+
port=port,
|
|
67
|
+
extra_args=tuple(extra_args or ()),
|
|
68
|
+
)
|
|
69
|
+
self.server = get_or_start(self.config)
|
|
70
|
+
self.base_url = self.server.base_url
|
|
71
|
+
self._sync = ChatClient(self.base_url)
|
|
72
|
+
self._async = AsyncChatClient(self.base_url)
|
|
73
|
+
|
|
74
|
+
# ------------------------------------------------------------ propiedades
|
|
75
|
+
@property
|
|
76
|
+
def has_vision(self) -> bool:
|
|
77
|
+
return self.mmproj_path is not None
|
|
78
|
+
|
|
79
|
+
def slots(self) -> dict:
|
|
80
|
+
"""Estado de los slots de batching (activos, tamaños de ctx, etc)."""
|
|
81
|
+
return self._sync.slots()
|
|
82
|
+
|
|
83
|
+
def __repr__(self) -> str:
|
|
84
|
+
return (
|
|
85
|
+
f"<Model {self.model_path.name} vision={self.has_vision} "
|
|
86
|
+
f"slots={self.config.n_parallel} at {self.base_url}>"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
# ----------------------------------------------------------------- sync
|
|
90
|
+
def chat(
|
|
91
|
+
self,
|
|
92
|
+
prompt_or_messages: Union[str, List[Message]],
|
|
93
|
+
*,
|
|
94
|
+
images: Optional[List[Any]] = None,
|
|
95
|
+
stream: bool = False,
|
|
96
|
+
**gen: Any,
|
|
97
|
+
) -> Union[Dict[str, Any], Iterator[str]]:
|
|
98
|
+
"""Chat con el modelo. Con stream=True devuelve un iterador de chunks.
|
|
99
|
+
|
|
100
|
+
Args de generacion habituales: max_tokens, temperature, top_p,
|
|
101
|
+
repeat_penalty, stop, seed...
|
|
102
|
+
"""
|
|
103
|
+
msgs = _as_messages(prompt_or_messages)
|
|
104
|
+
return self._sync.chat(msgs, images=images, stream=stream, **gen)
|
|
105
|
+
|
|
106
|
+
def generate(self, prompt: str, *, stream: bool = False, **gen: Any) -> Union[dict, Iterator[str]]:
|
|
107
|
+
"""Completado crudo (/completion) sin plantilla de chat."""
|
|
108
|
+
return self._sync.completion(prompt, stream=stream, **gen)
|
|
109
|
+
|
|
110
|
+
def embed(self, texts: Union[str, List[str]]) -> List[List[float]]:
|
|
111
|
+
"""Embeddings (requiere un modelo de embeddings GGUF)."""
|
|
112
|
+
return self._sync.embeddings(texts)
|
|
113
|
+
|
|
114
|
+
# ---------------------------------------------------------------- async
|
|
115
|
+
async def achat(
|
|
116
|
+
self,
|
|
117
|
+
prompt_or_messages: Union[str, List[Message]],
|
|
118
|
+
*,
|
|
119
|
+
images: Optional[List[Any]] = None,
|
|
120
|
+
stream: bool = False,
|
|
121
|
+
**gen: Any,
|
|
122
|
+
) -> Union[Dict[str, Any], AsyncIterator[str]]:
|
|
123
|
+
msgs = _as_messages(prompt_or_messages)
|
|
124
|
+
return await self._async.chat(msgs, images=images, stream=stream, **gen)
|
|
125
|
+
|
|
126
|
+
async def agenerate(self, prompt: str, *, stream: bool = False, **gen: Any) -> Union[dict, AsyncIterator[str]]:
|
|
127
|
+
return await self._async.completion(prompt, stream=stream, **gen)
|
|
128
|
+
|
|
129
|
+
async def aembed(self, texts: Union[str, List[str]]) -> List[List[float]]:
|
|
130
|
+
return await self._async.embeddings(texts)
|
|
131
|
+
|
|
132
|
+
# ----------------------------------------------------------- utilidades
|
|
133
|
+
def wait_stream(self, stream_iter) -> str:
|
|
134
|
+
"""Consume un stream y devuelve el texto completo."""
|
|
135
|
+
return "".join(stream_iter)
|
|
136
|
+
|
|
137
|
+
async def await_stream(self, async_iter) -> str:
|
|
138
|
+
parts = []
|
|
139
|
+
async for chunk in async_iter:
|
|
140
|
+
parts.append(chunk)
|
|
141
|
+
return "".join(parts)
|
|
142
|
+
|
|
143
|
+
def close(self) -> None:
|
|
144
|
+
"""Para el servidor solo si este objeto fue quien lo creo (no recomendado
|
|
145
|
+
si compartes el modelo entre varios `Model`). Usa ggufly.shutdown_all()."""
|
|
146
|
+
from .server import shutdown_all
|
|
147
|
+
|
|
148
|
+
shutdown_all()
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def load(source: str, **kwargs: Any) -> Model:
|
|
152
|
+
"""Atajo para Model(...)."""
|
|
153
|
+
return Model(source, **kwargs)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def run_many(model: "Model", prompts: List[str], *, workers: int = 4, **gen: Any) -> List[Dict[str, Any]]:
|
|
157
|
+
"""Ejecuta varios prompts en paralelo reutilizando el mismo modelo en VRAM."""
|
|
158
|
+
import concurrent.futures as cf
|
|
159
|
+
|
|
160
|
+
with cf.ThreadPoolExecutor(max_workers=workers) as ex:
|
|
161
|
+
futures = [ex.submit(lambda p=p: model.chat(p, **gen)) for p in prompts]
|
|
162
|
+
return [f.result() for f in futures]
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
async def arun_many(
|
|
166
|
+
model: "Model",
|
|
167
|
+
prompts: List[str],
|
|
168
|
+
*,
|
|
169
|
+
concurrency: Optional[int] = None,
|
|
170
|
+
**gen: Any,
|
|
171
|
+
) -> List[Dict[str, Any]]:
|
|
172
|
+
"""Igual que run_many pero async (semáforo opcional)."""
|
|
173
|
+
sem = asyncio.Semaphore(concurrency) if concurrency else None
|
|
174
|
+
|
|
175
|
+
async def one(p: str):
|
|
176
|
+
if sem:
|
|
177
|
+
async with sem:
|
|
178
|
+
return await model.achat(p, **gen)
|
|
179
|
+
return await model.achat(p, **gen)
|
|
180
|
+
|
|
181
|
+
return await asyncio.gather(*[one(p) for p in prompts])
|