npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@joelrd01/llama-cpp-qwen2.5-0.5b

v1.0.3

Published

NPM package that automatically downloads and provides the Qwen2.5-0.5B-Instruct GGUF model from Hugging Face on install.

Downloads

390

Readme

🤖 @joelrd01/llama-cpp-qwen2.5-0.5b

Node.js Badge License Badge npm Badge Testin Badge Babel Badge Git Badge Jest Badge


📖 Descripción

Este paquete npm proporciona una integración sencilla y directa con el modelo Qwen2.5-0.5B-Instruct en formato GGUF, permitiendo ejecutar inferencias de inteligencia artificial directamente desde Node.js utilizando la librería node-llama-cpp.

✨ Características Principales

  • ⬇️ Descarga Automática: El modelo se descarga automáticamente al instalar el paquete
  • 🚀 Fácil de Usar: API minimalista y intuitiva
  • 💻 Multiplataforma: Soporta CPU y GPU (CUDA, Vulkan, Metal)
  • 📦 GGUF: Formato optimizado para eficiencia en memoria

🛠️ Instalación

Requisitos Previos

| Requisito | Versión Mínima | |-----------|----------------| | Node.js | 16.0.0+ | | npm | 7.0.0+ |

Instalación del Paquete

npm install @joelrd01/llama-cpp-qwen2.5-0.5b

Nota: El script postinstall se ejecutará automáticamente para descargar el modelo GGUF desde Hugging Face.


📚 Estructura del Proyecto

llama-cpp-qwen2.5:0.5b/
├── 📄 index.js              # Punto de entrada principal
├── 📂 scripts/
│   ├── 📥 postinstall.js   # Script de descarga del modelo
│   └── ✅ verify.js         # Script de verificación
├── 📂 node_modules/
│   └── @joelrd01/
│       └── llama-cpp-qwen2.5-0.5b/
│           └── model/
│               └── model.gguf  # Modelo descargado
└── 📦 package.json

🎯 Uso Rápido

Ejemplo Básico

import { initModelLocal, getModelPath, getModelInfo } from '@joelrd01/llama-cpp-qwen2.5-0.5b';

// Crear instancia del modelo
const model = new initModelLocal();

// Inicializar el modelo
await model.init();

// Ejecutar una consulta
const response = await model.runModel(
  'Eres un asistente útil.',
  '¿Cuál es la capital de Francia?'
);

console.log(response);
// Output: "La capital de Francia es París."

Ejemplo con Configuración Personalizada

import { initModelLocal } from '@joelrd01/llama-cpp-qwen2.5-0.5b';

// Crear instancia con configuración personalizada
const model = new initModelLocal({
  gpu: { vulkan: true },      // Habilitar Vulkan
  gpuLayers: 16,              // 16 capas en GPU
  contextSize: 8192,          // Contexto de 8192 tokens
  batchSize: 1024,            // Batch size aumentado
  ignoreMemorySafetyChecks: false
});

// Inicializar y ejecutar
await model.init();

const response = await model.runModel(
  'Eres un experto en programación.',
  'Explica qué es un closure en JavaScript.'
);

📖 Referencia de API

Clase initModelLocal

Constructor que crea una nueva instancia del modelo con configuración opcional.

new initModelLocal(options?)

Parámetros del Constructor

| Parámetro | Tipo | Valor por Defecto | Descripción | |-----------|------|-------------------|-------------| | gpu | Object | { vulkan: false, cuda: false, metal: false } | Configuración de GPU | | gpuLayers | number | 2 | Número de capas en GPU | | contextSize | number | 4096 | Tamaño del contexto en tokens | | batchSize | number | 512 | Tamaño del batch | | ignoreMemorySafetyChecks | boolean | false | Ignorar verificaciones de memoria |

Opciones de GPU

// Modo CPU únicamente (por defecto)
gpu: {}

// Solo Vulkan
gpu: { vulkan: true }

// Solo CUDA
gpu: { cuda: true }

// Metal (macOS)
gpu: { metal: true }

Método initModelLocal.init()

Inicializa el runtime de llama, carga el modelo y crea el contexto de inferencia.

Retorno

// Promise<void> - Resuelve cuando el modelo está listo
const model = new initModelLocal();
await model.init();

Método initModelLocal.runModel(systemPrompt?, userPrompt)

Ejecuta una inferencia contra el modelo cargado.

Parámetros

| Parámetro | Tipo | Requerido | Descripción | |-----------|------|-----------|-------------| | systemPrompt | string | No | Prompt de sistema para definir el comportamiento del modelo | | userPrompt | string | | Mensaje del usuario a enviar al modelo |

Retorno

// Promise<string> - Respuesta del modelo (sin espacios en blanco al inicio/final)
const respuesta = await model.runModel('Eres un asistente.', 'Hola, ¿cómo estás?');

Ejemplo Completo

import { initModelLocal } from '@joelrd01/llama-cpp-qwen2.5-0.5b';

const model = new initModelLocal();
await model.init();

// Consulta simple
const r1 = await model.runModel('', '¿Cuánto es 2 + 2?');
console.log(r1);

// Consulta con contexto
const r2 = await model.runModel(
  'Responde siempre en español y de forma concisa.',
  'Explícame qué es una API REST.'
);
console.log(r2);

Función getModelPath()

Retorna la ruta absoluta al directorio del modelo.

Retorno

// string - Ruta absoluta al directorio del modelo
const ruta = getModelPath();
// => /home/usuario/proyecto/node_modules/@joelrd01/llama-cpp-qwen2.5-0.5b/model

4. getModelInfo()

Retorna metadatos sobre los archivos del modelo descargado.

Retorno

// Object - Metadatos del modelo
{
  path: string,           // Ruta absoluta del directorio
  files: string[],        // Nombres de archivos GGUF
  fileCount: number,      // Cantidad de archivos
  totalSizeBytes: number, // Tamaño total en bytes
  totalSizeMB: string,    // Tamaño en MB (2 decimales)
  totalSizeGB: string     // Tamaño en GB (2 decimales)
}

Ejemplo

import { getModelInfo } from '@joelrd01/llama-cpp-qwen2.5-0.5b';

const info = getModelInfo();
console.log(`
📦 Modelo: Qwen2.5-0.5B-Instruct GGUF
📁 Archivos: ${info.fileCount}
💾 Tamaño: ${info.totalSizeMB} MB
📂 Ubicación: ${info.path}
`);

🔧 Configuración Avanzada

Configuración de Memoria

// Para sistemas con memoria limitada
const model = new initModelLocal({
  gpuLayers: 0,                         // Solo CPU
  contextSize: 2048,                     // Contexto reducido
  batchSize: 256,                       // Batch pequeño
  ignoreMemorySafetyChecks: false       // Mantener verificaciones
});
await model.init();

Optimización para GPU

// Configuración para GPU dedicada
const model = new initModelLocal({
  gpu: { cuda: true },      // NVIDIA GPU
  gpuLayers: 32,            // Todas las capas en GPU
  contextSize: 8192,        // Contexto amplio
  batchSize: 2048,          // Batch grande
});
await model.init();

🎨 Múltiples Instancias

Cada instancia de initModelLocal mantiene su propio estado:

// Crear múltiples instancias independientes
const model1 = new initModelLocal({ gpuLayers: 4 });
const model2 = new initModelLocal({ gpuLayers: 0 }); // CPU-only

await model1.init();
await model2.init();

// Cada modelo puede tener diferente configuración
const r1 = await model1.runModel('', 'Pregunta 1');
const r2 = await model2.runModel('', 'Pregunta 2');

⚠️ Manejo de Errores

Modelo No Encontrado

// Error: Model directory not found
// Solución: Ejecutar npm run postinstall
npm run postinstall

Memoria Insuficiente

// Reducir uso de memoria
const model = new initModelLocal({
  gpuLayers: 0,
  contextSize: 2048,
  batchSize: 256
});
await model.init();

📊 Benchmark Rápido

| Configuración | Velocidad Aproximada | |--------------|---------------------| | CPU (1 hilo) | ~30 tokens/segundo | | CPU (4 hilos) | ~80 tokens/segundo | | GPU (CUDA) | ~200 tokens/segundo | | GPU (Vulkan) | ~150 tokens/segundo |

Valores aproximados, varían según hardware


📝 Scripts Disponibles

| Script | Descripción | |--------|-------------| | npm run postinstall | Descarga el modelo GGUF | | npm run test | Verifica la instalación del modelo |


🔗 Recursos Externos

| Recurso | Enlace | |---------|--------| | Repositorio GitHub | HuggingFace | | Modelo en HuggingFace | Qwen2.5-0.5B-Instruct-GGUF | | Librería node-llama-cpp | npm |


📄 Licencia

MIT License - Ver archivo LICENSE


👨‍💻 Autor

joelrd01