class

Llama::Context

Inherits Reference / Object

Wrapper for the llama_context structure

Constructors

new(model : Model, n_ctx : UInt32 = 0, n_batch : UInt32 = 512, n_threads : Int32 = 0, n_threads_batch : Int32 = 0, embeddings : Bool = false, offload_kqv : Bool = false)

Creates a new Context instance for a model.

Parameters:

  • model: The Model to create a context for.
  • n_ctx: Text context (default: 0). The maximum context size. If 0, a minimum context size of 512 is used.
  • n_batch: Logical maximum batch size that can be submitted to llama_decode (default: 512).
  • n_threads: Number of threads to use for generation (default: 0). If 0, uses the number of hardware threads.
  • n_threads_batch: Number of threads to use for batch processing (default: 0). If 0, uses the number of hardware threads.
  • embeddings: Extract embeddings (together with logits) (default: false). If true, extract embeddings (together with logits).
  • offload_kqv: Whether to offload the KQV ops (including the KV cache) to GPU (default: false). Requires a GPU build of llama.cpp.

Raises:

  • Llama::Context::Error if the context cannot be created.
Source

Instance methods

apply_adapter_cvec(data : Slice(Float32), n_embd : Int32, il_start : Int32, il_end : Int32) : Int32

Applies a control vector to the LoRA adapter

Parameters:

  • data: The control vector data
  • n_embd: Embedding dimension per layer
  • il_start: Start layer index (inclusive, 1-based)
  • il_end: End layer index (inclusive, 1-based)

Returns:

  • 0 on success, non-zero on error

Raises:

  • Llama::Context::Error if the control vector cannot be applied
Source
apply_chat_template(messages : Array(ChatMessage), add_assistant : Bool = true, template : String | Nil = nil) : String

Applies the chat template to the given messages and returns the formatted prompt.

Parameters:

  • messages: Array of ChatMessage (user/assistant/system)
  • add_assistant: Whether to add assistant role (default: true)
  • template: Optional template string (default: model's template)

Returns:

  • The formatted prompt string.
Source
attach_adapter_lora(adapter : AdapterLora, scale : Float32 = 1.0) : Int32

Attaches a LoRA adapter to this context

Parameters:

  • adapter: The LoRA adapter to attach
  • scale: Scaling factor for the adapter (default: 1.0)

Returns:

  • 0 on success, non-zero on error

Raises:

  • Llama::Context::Error if the adapter cannot be attached
Source
chat(messages : Array(ChatMessage), max_tokens : Int32 = 128, temperature : Float32 = 0.8, template : String | Nil = nil) : String

Generates a response in a chat conversation

Parameters:

  • messages: Array of chat messages
  • max_tokens: Maximum number of tokens to generate
  • temperature: Sampling temperature
  • template: Optional chat template (nil to use model's default)

Returns:

  • The generated response text

Raises:

  • ArgumentError if parameters are invalid
  • Llama::Context::Error if text generation fails
  • Llama::TokenizationError if the prompt cannot be tokenized
Source
clear_adapters_lora

Clears all LoRA adapters from this context

Source
decode(batch : LibLlama::LlamaBatch | Batch) : Int32

Processes a batch of tokens with the decoder part of the model

Parameters:

  • batch: The batch to process (can be a LibLlama::LlamaBatch or a Batch instance)

Returns:

  • 0 on success
  • 1 if no KV slot was found for the batch
  • < 0 on error

Raises:

  • Llama::Batch::Error on error
Source
detach_adapter_lora(adapter : AdapterLora) : Int32

Detaches a LoRA adapter from this context

Parameters:

  • adapter: The LoRA adapter to detach

Returns:

  • 0 on success, non-zero on error

Raises:

  • Llama::Context::Error if the adapter cannot be detached
Source
embeddings

Gets embeddings for the latest output token.

Internally this uses the index-based embeddings API.

Returns:

  • An array of embeddings, or nil if embeddings are not available

Raises:

  • Llama::Context::Error if embeddings mode is not enabled
Source
embeddings=(enabled : Bool)

Sets whether the model is in embeddings mode or not If true, embeddings will be returned but logits will not

Parameters:

  • enabled: Whether to enable embeddings mode
Source
encode(batch : LibLlama::LlamaBatch | Batch) : Int32

Processes a batch of tokens with the encoder part of the model

This function is used for encoder-decoder models to encode the input before generating text with the decoder.

Parameters:

  • batch: The batch to process (can be a LibLlama::LlamaBatch or a Batch instance)

Returns:

  • 0 on success
  • < 0 on error

Raises:

  • Llama::Batch::Error on error
Source
finalize

Frees the resources associated with this context

Source
generate(prompt : String, max_tokens : Int32 = 128, temperature : Float32 = 0.8) : String

Generates text from a prompt

Parameters:

  • prompt: The input prompt
  • max_tokens: Maximum number of tokens to generate (must be positive)
  • temperature: Sampling temperature (0.0 = greedy, 1.0 = more random)

Returns:

  • The generated text

Raises:

  • ArgumentError if parameters are invalid
  • Llama::Context::Error if text generation fails
  • Llama::TokenizationError if the prompt cannot be tokenized
Source
generate_with_sampler(prompt : String, sampler : SamplerChain, max_tokens : Int32 = 128) : String

Generates text using a sampler chain

Parameters:

  • prompt: The input prompt
  • sampler: The sampler chain to use
  • max_tokens: Maximum number of tokens to generate (must be positive)

Returns:

  • The generated text

Raises:

  • ArgumentError if parameters are invalid
  • Llama::Context::Error if text generation fails
  • Llama::TokenizationError if the prompt cannot be tokenized
  • Llama::Sampler::Error if sampling fails
Source
get_embeddings_ith(i : Int32) : Array(Float32) | Nil

Gets the embeddings for a specific token

Parameters:

  • i: The token index (negative indices can be used to access in reverse order)

Returns:

  • An array of embedding values, or nil if not available

Raises:

  • Llama::Context::Error if embeddings mode is not enabled
Source
get_embeddings_seq(seq_id : Int32) : Array(Float32) | Nil

Gets the embeddings for a specific sequence

Parameters:

  • seq_id: The sequence ID

Returns:

  • An array of embedding values, or nil if not available

Raises:

  • Llama::Context::Error if embeddings mode is not enabled
Source
logits

Gets the logits for the latest output token.

Returns:

  • A pointer to the logits array
Source
logits_ith(i : Int32) : Pointer(Float32) | Nil

Gets the logits for a specific output index.

Parameters:

  • i: Output index (negative indices access from the end; -1 is latest)

Returns:

  • A pointer to the logits array for the specified output, or nil if unavailable
Source
memory

Returns the memory for this context (modern API)

The memory system provides unified access to various memory types:

  • Standard KV cache (llama_kv_cache_unified)
  • SWA (Sliding Window Attention) cache
  • Recurrent layer memory
  • Hybrid attention/recurrent models

Returns:

  • A Memory instance
Source
n_batch

Returns the logical batch size (n_batch)

Source
n_ctx

Returns the context window size (n_ctx)

Source
n_ctx_seq

Returns the sequence context window size (n_ctx_seq)

Source
n_seq_max

Returns the maximum number of sequence IDs per token (n_seq_max)

Source
n_threads

Returns the number of threads used for generation

Source
n_threads_batch

Returns the number of threads used for batch processing

Source
n_ubatch

Returns the micro-batch size (n_ubatch)

Source
pooling_type

Gets the pooling type used for embeddings

Returns:

  • The pooling type as a PoolingType enum
Source
process_embeddings(embeddings : Array(Array(Float32)), seq_ids : Array(Int32) | Nil = nil, n_seq_max : Int32 = 8) : Int32

Process embeddings

Parameters:

  • embeddings: Array of embedding vectors
  • seq_ids: Sequence IDs to use for all embeddings
  • n_seq_max: Maximum number of sequence IDs per token (default: 8)

Returns:

  • The result of the decode operation (0 on success)

Raises:

  • Llama::Batch::Error on error
Source
process_prompts(prompts : Array(String)) : Array(Int32)

Process multiple prompts in batch

Parameters:

  • prompts: Array of text prompts to process
  • compute_logits_for_last: Whether to compute logits only for the last token of each prompt

Returns:

  • Array of decode operation results (0 on success)

Raises:

  • Llama::Batch::Error on error
  • Llama::TokenizationError if a prompt cannot be tokenized
Source
process_tokens(tokens : Array(Int32), compute_logits_for_last : Bool = true, seq_ids : Array(Int32) | Nil = nil, n_seq_max : Int32 = 8) : Int32

Process a sequence of tokens

Parameters:

  • tokens: Array of token IDs to process
  • compute_logits_for_last: Whether to compute logits only for the last token
  • seq_ids: Sequence IDs to use for all tokens
  • n_seq_max: Maximum number of sequence IDs per token (default: 8)

Returns:

  • The result of the decode operation (0 on success)

Raises:

  • Llama::Batch::Error on error
Source
reset_perf

Reset performance counters for this context

This method resets all performance counters for the context.

Source
state

Returns the state manager for this context Lazily initializes the state if it doesn't exist yet

Source
to_unsafe

Returns the raw pointer to the underlying llama_context structure

Source

Nested types