Metadata-Version: 2.5
Name: sinapsis-llama-cpp
Version: 1.0.0
Summary: Sinapsis templates for llama.cpp text generation.
Project-URL: Homepage, https://sinapsis.tech
Project-URL: Documentation, https://docs.sinapsis.tech/docs/latest
Project-URL: Tutorials, https://docs.sinapsis.tech/docs/latest/tutorials
Project-URL: Repository, https://github.com/SinapsisHub/sinapsis-hub
Project-URL: Issues, https://github.com/SinapsisHub/sinapsis-hub/issues
Project-URL: Discord, https://discord.gg/uuBqQqu2vS
Author-email: Ariel Ruiz-Garcia <ariel@sinapsis.tech>
Maintainer-email: sinapsis <dev@sinapsis.tech>
License-Expression: MIT OR Apache-2.0
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
Requires-Python: >=3.13
Requires-Dist: huggingface-hub>=0.32.4
Requires-Dist: llama-cpp-python>=0.3.36
Requires-Dist: sinapsis-chatbots-base<2,>=1.0.2
Requires-Dist: sinapsis<2,>=1
Provides-Extra: infra
Requires-Dist: sinapsis-infra>=0.1.0; extra == 'infra'
Description-Content-Type: text/markdown

<h1 align="center">
<br>
<a href="https://sinapsis.tech/">
  <img
    src="https://github.com/SinapsisHub/brand-resources/blob/main/public/logo/sinapsis-logo-horizontal-dark-brand.png?raw=true"
    alt="Sinapsis"
    width="300">
</a>
<br>
Sinapsis Llama-Cpp
<br>
</h1>

<h3 align="center">Run LLMs with llama.cpp inside the Sinapsis Template contract.</h3>

<p align="center">
  <a href="#overview">Overview</a> &bull;
  <a href="#installation">Installation</a> &bull;
  <a href="#hardware-acceleration-optional">Hardware Acceleration</a> &bull;
  <a href="#features">Features</a> &bull;
  <a href="#example-agent">Example Agent</a> &bull;
  <a href="#troubleshooting">Troubleshooting</a> &bull;
  <a href="#documentation">Documentation</a> &bull;
  <a href="#license">License</a>
</p>

## Overview

**`sinapsis-llama-cpp`** — Sinapsis templates for llama.cpp text generation.

llama.cpp is useful for locally hosted, quantized models where inference stays on your infrastructure. The Sinapsis wrapper places generation and streaming in the same Agent graph as prompts, parsers and downstream processing.

### Where it fits

Choose this route when the llama.cpp runtime and its supported model formats fit your hardware. Unlike managed APIs, model files and compute are your responsibility. The templates use the `llama-cpp-python` Python bindings directly for local inference.

## Installation

Requires **Python 3.13 or later**. We recommend using a dedicated virtual environment:

```bash
uv venv --python 3.13
source .venv/bin/activate
uv pip install sinapsis-llama-cpp
# or, in the same activated environment:
# python -m pip install sinapsis-llama-cpp
```

On Windows PowerShell, activate the environment with `.venv\Scripts\Activate.ps1` instead.

The base installation includes `llama-cpp-python`, the Python bindings used directly by the templates. GPU acceleration is not guaranteed by a standard installation.

### Hardware acceleration (optional)

For platform-specific wheels, supported GPU backends and source-build requirements, see the official [llama-cpp-python installation guide](https://github.com/abetlen/llama-cpp-python#installation).

Alternatively, install this package with its optional `infra` extra to access **Sinapsis Infra**, the hardware-aware runtime installer:

```bash
uv pip install "sinapsis-llama-cpp[infra]"
sinx-infra install llama-cpp-python --dry-run
sinx-infra install llama-cpp-python --allow-source-build
```

If you already have the templates installed, you can install Sinapsis Infra directly instead:

```bash
uv pip install sinapsis-infra
sinx-infra install llama-cpp-python --allow-source-build
```

Use a release of Sinapsis Infra that includes the `install llama-cpp-python` command. Both installation approaches must target the **same virtual environment** as the templates; do not use a separate `uv tool install` environment for this workflow. The `infra` extra installs the utility, not a GPU-specific build of the bindings; run the installer command to select that build.

The installer detects your hardware and selects compatible bindings for NVIDIA CUDA, Apple Silicon Metal or CPU. AMD ROCm and Vulkan are experimental source-build options. The supported CUDA wheel families are curated by Sinapsis Infra; GPU drivers, compilers and SDKs must be installed separately. Source compilation is opt-in; on hosts with a detected GPU, automatic CPU fallback is also opt-in.

```bash
# Require GPU acceleration (no CPU fallback)
sinx-infra install llama-cpp-python --require-gpu --allow-source-build

# See all installer options
sinx-infra install llama-cpp-python --help
```

Equivalent module invocation:

```bash
python -m sinapsis_infra install llama-cpp-python --allow-source-build
```

<details>
<summary><strong>Advanced installation options</strong></summary>

| Option | Purpose |
|---|---|
| `--acceleration cuda` | Explicit NVIDIA CUDA selection |
| `--acceleration metal` | Apple Silicon Metal |
| `--acceleration cpu` | CPU-only bindings |
| `--acceleration rocm` / `vulkan` | Experimental source build; add `--allow-source-build` |
| `--cuda-version 13.0` | Select a supported CUDA family |
| `--bindings-version 0.3.37` | Request an exact compatible bindings version |
| `--from-source` | Skip prebuilt wheels and compile locally |
| `--allow-cpu-fallback` | Permit CPU fallback in auto mode |
| `--verbose` | Show diagnostic output |

See the installer help and the [llama-cpp-python repository](https://github.com/abetlen/llama-cpp-python) for details. A compatible NVIDIA driver is required for CUDA wheels; source builds additionally require a supported CUDA Toolkit (`nvcc`) and C/C++ compiler.

</details>

### If the initial package installation fails

If the initial install fails while building `llama-cpp-python`, install the infrastructure utility first and prepare the bindings before retrying the template package:

```bash
uv pip install sinapsis-infra
sinx-infra install llama-cpp-python --allow-source-build
uv pip install sinapsis-llama-cpp
```

Alternatively, install the bindings using the upstream installation guide and retry the package installation. This bootstrap path does not require `sinapsis-llama-cpp` to be installed first. If the `infra` extra fails while installing the bindings, use this standalone bootstrap route rather than retrying the extra.

> [!NOTE]
> Sinapsis Infra reinstalls the bindings in place in an unmanaged virtual environment. A failed installation may leave the last attempted build installed; use a fresh environment if necessary. Subsequent `uv sync` or an automatic sync during `uv run` may replace the selected wheel with the version from the lockfile. Use `uv pip install` for this workflow, and run from the activated environment or use `uv run --no-sync`.

### Verify GPU support

```bash
python -c "import llama_cpp; print(llama_cpp.__version__); print('GPU offload supported:', llama_cpp.llama_supports_gpu_offload())"
```

`True` indicates GPU offloading capability, not proof of actual GPU inference. Check model-loading logs and GPU memory usage. Set `n_gpu_layers: -1` to request full model offloading, `0` for CPU-only inference, or a positive number for partial offloading.

### Development installation

From a repository checkout, in the activated environment:

```bash
uv pip install -e .
# or include the optional infrastructure utilities:
uv pip install -e ".[infra]"
```

Use the same optional Sinapsis Infra workflow above to configure hardware acceleration. If the editable installation fails on the bindings, install the bindings first and then retry `uv pip install -e .`. The `dev` dependency group contains Ruff and pre-commit and is not a runtime extra.

<h2 id="features">🚀 Features</h2>

<h3>Templates Supported</h3>

- **LLaMACPPTextCompletion**: Standard llama.cpp chat completion using `LLMConversationPacket`.
- **LLaMACPPStreamingTextCompletion**: Async streaming variant that yields partial packets during generation.
- **LLaMACPPTextCompletionWithMCP**: llama.cpp chat completion with packet-native MCP tool state.

<details>
<summary><strong><span style="font-size: 1.25em;">🧩 Common Attributes</span></strong></summary>

- `init_args` (`LLaMACPPInitArgs`, required): llama.cpp runtime arguments.
  - `llm_model_name` (`str`, required): Hugging Face repo id or local directory containing the GGUF file.
  - `llm_model_file` (`str`, required): GGUF file name to load.
  - Additional runtime controls include `n_ctx`, `n_threads`, `n_gpu_layers`, `flash_attn_type`, `tensor_split`, `use_mmap`, `use_mlock`, `seed`, and `chat_format`.
- `completion_args` (`LLaMACPPCompletionArgs`, required): Request-time generation parameters such as `max_tokens`, `temperature`, `top_p`, `top_k`, `min_p`, penalties, stop sequences, and structured-output settings.
- `reasoning_start_tag` / `reasoning_end_tag` (`str | None`, optional): Tags used to extract reasoning into `LLMConversationPacket.reasoning` before the final response is cleaned.

</details>

## Example Agent

The following is adapted from the package's shipped [`streaming.yaml`](src/sinapsis_llama_cpp/configs/streaming.yaml) configuration. Save it as `my_llama_cpp_agent.yaml`. The example may require model checkpoints, input files, additional Template packages, or provider credentials as described in its configuration.

The example requests full GPU offload. For CPU-only inference, change `n_gpu_layers` to `0`. If GPU memory is limited, reduce the number of offloaded layers or context size.

```yaml
agent:
  name: my_llama_cpp_agent
  description: Single-shot llama-cpp text completion for Q&A and text generation.

templates:
  - template_name: InputTemplate
    class_name: InputTemplate
    attributes: {}

  - template_name: LLMConversationInput
    class_name: LLMConversationInput
    template_input: InputTemplate
    attributes:
      prompt: Give three short tips for staying organized during a busy week.
      system_prompt: You are a helpful assistant.

  - template_name: LLaMACPPStreamingTextCompletion
    class_name: LLaMACPPStreamingTextCompletion
    template_input: LLMConversationInput
    attributes:
      init_args:
        llm_model_name: unsloth/Qwen3.5-9B-GGUF
        llm_model_file: Qwen3.5-9B-Q4_K_M.gguf
        n_ctx: 8192
        n_threads: 8
        n_gpu_layers: -1
        flash_attn_type: -1
        seed: 10
      completion_args:
        max_tokens: 4096
        temperature: 0.2
        seed: 10
```

Run the Agent from your activated environment:

```bash
sinx jobs run my_llama_cpp_agent.yaml
```

For a project already synced with your selected backend, you can also use `uv run --no-sync sinx jobs run my_llama_cpp_agent.yaml` to preserve the installed native build.

More configurations: [`streaming.yaml`](src/sinapsis_llama_cpp/configs/streaming.yaml), [`text_completion.yaml`](src/sinapsis_llama_cpp/configs/text_completion.yaml), [`structured_outputs.yaml`](src/sinapsis_llama_cpp/configs/structured_outputs.yaml).

## Troubleshooting

### Model loading and inference

| Issue | What to check |
|---|---|
| `llama_cpp` cannot be imported or a shared library fails to load | Check that the Agent is running in the virtual environment where `sinapsis-llama-cpp` and its bindings are installed. See the installation and hardware acceleration sections above if the bindings need to be reinstalled. |
| GGUF model cannot be found or loaded | Check that `init_args.llm_model_name` points to the correct Hugging Face repository or local directory and that `init_args.llm_model_file` matches the exact GGUF filename. Check model access permissions, download completeness and available disk space. Ensure your bindings support the model architecture. |
| GPU acceleration is not being used | Run the GPU support check above, set `init_args.n_gpu_layers` to `-1` or a positive value, and inspect llama.cpp model-loading logs to confirm that layers are actually offloaded. |
| Out-of-memory errors during model loading or generation | Use a smaller or more heavily quantized GGUF model, reduce `init_args.n_ctx`, or reduce `init_args.n_gpu_layers` to fit available GPU memory. For CPU-only inference, set `n_gpu_layers: 0` and ensure sufficient system RAM. |
| Slow text generation | Check whether inference is running on the expected device. Adjust `n_threads` for CPU inference, choose a smaller model if needed, and tune `n_gpu_layers` according to available GPU memory. |
| Context length exceeded or truncated responses | Reduce the prompt or conversation history, or adjust `init_args.n_ctx` and `completion_args.max_tokens`. Leave enough context capacity for both the formatted input and generated tokens. |
| Unexpected responses or formatting | Check the model's expected chat template, the configured `chat_format`, system prompt, stop sequences and generation parameters. If reasoning extraction is enabled, ensure the configured reasoning tags match the model's output. |

### Sinapsis Agent and template configuration

- **Template not found or configuration validation fails:** Ensure `sinapsis-llama-cpp` is installed in the environment running `sinx`, check the exact template class name and validate the required `init_args` and `completion_args` fields against the shipped examples.
- **Missing conversation input:** Check that `template_input` references the correct upstream template and that the input is an `LLMConversationPacket`, as in the [example Agent](#example-agent).
- **Streaming output is not appearing as expected:** Use `LLaMACPPStreamingTextCompletion` and ensure the downstream processing path consumes the partial packets emitted during generation.
- **Structured output is invalid:** Start with the shipped [`structured_outputs.yaml`](src/sinapsis_llama_cpp/configs/structured_outputs.yaml), check the requested schema and ensure the generation budget is sufficient for a complete response.
- **MCP tool calls are not working:** Check that the selected model and chat format support tool calling, that the packet carries the expected MCP tool state, and that `LLaMACPPTextCompletionWithMCP` is used.

### Reporting issues

Include the Sinapsis and `llama-cpp-python` versions, operating system, Python version, model repository and GGUF filename, relevant Agent configuration and the full error traceback or runtime logs. For GPU-related issues, also include the GPU model, selected backend and GPU offload settings. Remove credentials, private prompts and other sensitive information before sharing.

## Documentation

- [Sinapsis documentation](https://docs.sinapsis.tech/)
- [Tutorials and examples](https://docs.sinapsis.tech/docs/latest/tutorials)
- [Sinapsis website](https://sinapsis.tech/)
- [llama-cpp-python installation guide](https://github.com/abetlen/llama-cpp-python#installation)
- [llama-cpp-python releases and prebuilt wheels](https://github.com/abetlen/llama-cpp-python/releases)
- [NVIDIA CUDA compatibility](https://docs.nvidia.com/deploy/cuda-compatibility/)
- [uv documentation](https://docs.astral.sh/uv/)

## License

Sinapsis open-source components are available under your choice of the [MIT License](LICENSE-MIT) or the [Apache License 2.0](LICENSE-APACHE), unless otherwise noted.