LlamaEngine

llama.cpp text-generation engine: streaming generation, KV-cache sessions, grammar / JSON-schema constrained decoding and embeddings.

Create instances with the LlamaEngine factory function. Engines are ordinary objects — never singletons — and any number of them (with the same or different models and backends) can coexist and run concurrently: each owns its native model, KV-cache context and a dedicated single-threaded dispatcher (SerialExecutor) that serializes loading, every inference call and the native release in close.

Session. The engine keeps one conversation in its KV cache: the tokens of the last prompt and of everything generated after it. A new generate reuses the longest common token prefix with that session (GenerationOptions.reusePromptCache), so continuing a conversation only evaluates the new text. saveSession / restoreSession serialize that KV cache to a ByteArray and back, on this or another engine with the same model.

Images. With a projector (LlamaEngineOptions.projectorPath) prompts may carry in-memory LlamaImages (vision-language models such as LLaVA, Gemma 3, Qwen-VL or SmolVLM): see generate with images.

Cancellation is cooperative and prompt: cancelling the collector of generate sets the native abort flag that llama.cpp polls inside every ggml graph computation (llama_set_abort_callback), so a running decode stops within one graph step. The engine stays usable afterwards.

Types

Link copied to clipboard
object Companion

Constants and factory functions of LlamaEngine.

Properties

Link copied to clipboard
open override val activeBackend: ComputeBackend

The backend llama.cpp actually runs on (never ComputeBackend.AUTO).

Link copied to clipboard
open override val activeDeviceName: String?

The GPU llama.cpp offloads to, or null on the CPU (see InferenceEngine.activeDeviceName).

Link copied to clipboard
open override val backendConfig: BackendConfig

The backend configuration this engine was loaded with.

Link copied to clipboard
open override val backendFallbackReason: String?

Why activeBackend is not the requested backend, or null (see InferenceEngine.backendFallbackReason).

Link copied to clipboard

The KV-cache configuration this engine was created with.

Link copied to clipboard

Effective context window in tokens (llama.cpp may round LlamaContextConfig.contextLength up).

Link copied to clipboard
open override val isClosed: Boolean

true once close has been called.

Link copied to clipboard

true while a generation or embedding is executing native code on this engine.

Link copied to clipboard

Static properties of the loaded model.

Link copied to clipboard

Path of the loaded GGUF model.

Link copied to clipboard

LLM-specific construction options.

Link copied to clipboard

Number of tokens (KV-cache positions, including image embeddings) currently held in the session.

Link copied to clipboard

true if a projector (LlamaEngineOptions.projectorPath) with vision input is loaded: images are accepted.

Link copied to clipboard

true if at least one GPU device was handed to llama.cpp; always false for ComputeBackend.CPU_ONLY.

Functions

Link copied to clipboard

Requests the native abort of the generation or embedding currently executing, if any; a generate flow then ends with a terminal TokenEvent.Error (InferenceCancelledException). Safe from any thread. Queued calls are not affected.

Link copied to clipboard
suspend fun clearSession()

Empties the session (KV cache and token history).

Link copied to clipboard
open override fun close()

Closes the engine: aborts a running generation, rejects queued and future calls with IllegalStateException, frees the sampler, contexts and model on the engine thread, and stops that thread. Idempotent and safe from any thread.

Link copied to clipboard
open suspend override fun closeAndAwait()

closes the engine and suspends until its native memory has been freed on the engine thread (after a running call has been aborted and left native code). Idempotent; cancelling the caller stops the wait, not the release. See InferenceEngine.closeAndAwait.

Link copied to clipboard
suspend fun detokenize(tokens: IntArray, renderSpecial: Boolean = false): String

Concatenates the pieces of tokens and decodes them as UTF-8.

Link copied to clipboard
suspend fun embed(text: String, normalize: Boolean = true): FloatArray

Computes the embedding of text on a dedicated embedding context (created on first use, separate from the generation session, so embeddings never disturb it). The vector is pooled with LlamaContextConfig.embeddingPooling (for causal LMs usually the last token's hidden state).

Link copied to clipboard
fun generate(prompt: String, options: GenerationOptions = GenerationOptions.DEFAULT): Flow<TokenEvent>

Streams the continuation of prompt as a cold Flow of TokenEvents. Each collection runs one generation on the engine thread (collections and other calls on the same engine are serialized).

fun generate(prompt: String, images: List<LlamaImage>, options: GenerationOptions = GenerationOptions.DEFAULT): Flow<TokenEvent>

Streams the continuation of a multimodal prompt with in-memory images, like generate without images. Requires a projector (LlamaEngineOptions.projectorPath, supportsVision); without one the flow reports InvalidInputException.

Link copied to clipboard
suspend fun generateText(prompt: String, options: GenerationOptions = GenerationOptions.DEFAULT): GenerationResult

Runs generate to completion and returns the generated text.

suspend fun generateText(prompt: String, images: List<LlamaImage>, options: GenerationOptions = GenerationOptions.DEFAULT): GenerationResult

Runs the multimodal generate (with images) to completion and returns the generated text.

Link copied to clipboard
suspend fun restoreSession(session: ByteArray)

Replaces the session with one saved by saveSession. A following generate whose prompt starts with the restored tokens only evaluates the remainder.

Link copied to clipboard
suspend fun saveSession(): ByteArray

Serializes the session (token history + KV cache of the conversation) after all queued work.

Link copied to clipboard
suspend fun tokenize(text: String, addSpecial: Boolean = false, parseSpecial: Boolean = false): IntArray

Tokenizes UTF-8 text with the model's vocabulary.