llama

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 7 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-llama-pure

Go bindings for llama.cpp without cgo, using purego to dynamically load the llama.cpp shared library at runtime.

Features

  • No cgo required - Pure Go code that loads llama.cpp as a shared library
  • Cross-compilation friendly - Build for any platform without a C toolchain
  • Modern API - Wraps the latest llama.cpp C API (sampler chains, batch processing)
  • High-level interface - Simple Generate() and Embedding() methods
  • Streaming support - Token-by-token callbacks during generation
  • Full sampling control - Temperature, top-k, top-p, min-p, repetition penalties

Requirements

You need a pre-built llama.cpp shared library:

  • Linux: libllama.so
  • macOS: libllama.dylib
  • Windows: llama.dll
Building llama.cpp as a shared library
git clone https://github.com/ggml-org/llama.cpp
cd llama.cpp
mkdir build && cd build

# CPU only
cmake .. -DBUILD_SHARED_LIBS=ON
make -j

# With CUDA support
cmake .. -DBUILD_SHARED_LIBS=ON -DGGML_CUDA=ON
make -j

# With Metal support (macOS)
cmake .. -DBUILD_SHARED_LIBS=ON -DGGML_METAL=ON
make -j

The shared library will be in build/src/libllama.so (or .dylib/.dll).

Installation

go get github.com/develerltd/go-llama-pure

Usage

Basic text generation
package main

import (
    "fmt"
    llama "github.com/develerltd/go-llama-pure"
)

func main() {
    // Initialize (optionally specify library path)
    if err := llama.Init(""); err != nil {
        panic(err)
    }
    defer llama.Shutdown()

    // Load model
    model, err := llama.LoadModel("model.gguf", llama.ModelOptions{
        NGPULayers: 35, // Offload layers to GPU
        UseMmap:    true,
    })
    if err != nil {
        panic(err)
    }
    defer model.Close()

    // Create context
    ctx, err := model.NewContext(llama.ContextOptions{
        ContextSize: 4096,
        Threads:     8,
    })
    if err != nil {
        panic(err)
    }
    defer ctx.Close()

    // Generate with streaming
    response, err := ctx.Generate("Once upon a time", llama.GenerateOptions{
        MaxTokens: 256,
        Sampling: llama.SamplingParams{
            Temperature:   0.8,
            TopK:          40,
            TopP:          0.95,
            RepeatPenalty: 1.1,
        },
        Callback: func(token llama.LlamaToken, text string) bool {
            fmt.Print(text)
            return true // continue
        },
    })
    if err != nil {
        panic(err)
    }
}
Embeddings
// Create context with embeddings enabled
ctx, err := model.NewContext(llama.ContextOptions{
    Embeddings: true,
})

// Get embeddings
embedding, err := ctx.Embedding("Hello, world!")
// embedding is []float32 with dimension model.EmbeddingSize()
Tokenization
// Tokenize text
tokens, err := model.Tokenize("Hello, world!", true, false)

// Detokenize
text := model.Detokenize(tokens)

// Single token to text
piece := model.TokenToPiece(tokens[0])
Low-level API
// Manual batch processing
tokens, _ := model.Tokenize(prompt, true, false)
ctx.Decode(tokens, 0)

// Get logits
logits := ctx.GetLogits()

// Create custom sampler
sampler := llama.NewSampler(llama.SamplingParams{
    Temperature: 0.7,
    TopK:        50,
})
defer sampler.Close()

token := sampler.Sample(ctx, -1)
sampler.Accept(token)

Library Path

The library searches for llama.cpp in this order:

  1. Path passed to Init(path)
  2. libllama.so / libllama.dylib / llama.dll in system library paths
  3. Current directory

You can also set LD_LIBRARY_PATH (Linux), DYLD_LIBRARY_PATH (macOS), or PATH (Windows).

Platform Support

Platform Architecture Status
Linux amd64, arm64 ✅
macOS amd64, arm64 ✅
Windows amd64, arm64 ✅

Comparison with go-skynet/go-llama.cpp

Feature This library go-skynet/go-llama.cpp
Cgo required ❌ No ✅ Yes
Cross-compile ✅ Easy ❌ Requires C toolchain
llama.cpp version Latest Outdated
API style Modern sampler chains Legacy
Build time Fast Slow (compiles C++)

License

MIT License - see LICENSE file.

Acknowledgments

Documentation

Overview

Package llama provides Go bindings for llama.cpp without requiring cgo. It uses purego to dynamically load the llama.cpp shared library at runtime.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrModelLoad      = errors.New("failed to load model")
	ErrContextInit    = errors.New("failed to initialize context")
	ErrTokenize       = errors.New("tokenization failed")
	ErrDecode         = errors.New("decode failed")
	ErrNotInitialized = errors.New("llama library not initialized - call Init() first")
)

Functions

func Init

func Init(libraryPath string) error

Init initializes the llama.cpp library.

func Shutdown

func Shutdown()

Shutdown cleans up the llama.cpp library

Types

type BatchData

type BatchData struct {
	Batch     LlamaBatch
	Tokens    []LlamaToken
	Pos       []LlamaPos
	NSeqID    []int32
	SeqIDData []LlamaSeqID
	SeqIDPtrs []uintptr
	Logits    []int8
}

BatchData holds the underlying data for a batch to prevent GC collection

func BatchGetOne

func BatchGetOne(tokens []LlamaToken, pos0 LlamaPos, seqID LlamaSeqID) *BatchData

BatchGetOne creates a batch for a single sequence of tokens. Returns BatchData which must be kept alive during the C call. Panics if tokens is empty.

type Context

type Context struct {
	// contains filtered or unexported fields
}

Context represents an inference context

func (*Context) ClearKVCache

func (c *Context) ClearKVCache()

ClearKVCache clears the KV cache (memory) for this context.

func (*Context) Close

func (c *Context) Close()

Close frees the context resources

func (*Context) ContextSize

func (c *Context) ContextSize() uint32

ContextSize returns the context window size

func (*Context) Decode

func (c *Context) Decode(tokens []LlamaToken, pos int32) error

Decode processes a batch of tokens through the model

func (*Context) Embedding

func (c *Context) Embedding(text string) ([]float32, error)

Embedding generates embeddings for the given text

func (*Context) Generate

func (c *Context) Generate(prompt string, opts GenerateOptions) (string, error)

Generate generates text from a prompt

func (*Context) GetEmbeddings

func (c *Context) GetEmbeddings() []float32

GetEmbeddings returns a copy of the embeddings (requires embeddings mode). The returned slice is Go-owned and safe to retain across Decode calls.

func (*Context) GetLogits

func (c *Context) GetLogits() []float32

GetLogits returns a copy of the logits for the last token. The returned slice is Go-owned and safe to retain across Decode calls.

func (*Context) GetLogitsIth

func (c *Context) GetLogitsIth(i int32) []float32

GetLogitsIth returns a copy of the logits for token at index i. The returned slice is Go-owned and safe to retain across Decode calls.

func (*Context) Model

func (c *Context) Model() *Model

Model returns the associated model

func (*Context) PrintTimings

func (c *Context) PrintTimings()

PrintTimings prints timing information

func (*Context) RemoveKVCache

func (c *Context) RemoveKVCache(seqID int32, p0, p1 int32) bool

RemoveKVCache removes KV cache entries for a sequence in position range [p0, p1) NOTE: This is a no-op in current llama.cpp versions where KV cache is managed internally

func (*Context) ResetTimings

func (c *Context) ResetTimings()

ResetTimings resets timing counters

func (*Context) Synchronize

func (c *Context) Synchronize()

Synchronize waits for all computations to complete

type ContextOptions

type ContextOptions struct {
	ContextSize    uint32 // Context window size (0 = model default)
	BatchSize      uint32 // Batch size for prompt processing
	Threads        int32  // Number of threads (0 = auto)
	ThreadsBatch   int32  // Number of threads for batch processing (0 = same as Threads)
	Embeddings     bool   // Enable embeddings mode
	FlashAttention bool   // Enable flash attention (if available)
}

ContextOptions contains options for creating a context

func DefaultContextOptions

func DefaultContextOptions() ContextOptions

DefaultContextOptions returns default context options

type GGMLType

type GGMLType int32
const (
	GGMLTypeF32  GGMLType = 0
	GGMLTypeF16  GGMLType = 1
	GGMLTypeQ4_0 GGMLType = 2
	GGMLTypeQ4_1 GGMLType = 3
	GGMLTypeQ5_0 GGMLType = 6
	GGMLTypeQ5_1 GGMLType = 7
	GGMLTypeQ8_0 GGMLType = 8
	GGMLTypeQ8_1 GGMLType = 9
)

type GenerateOptions

type GenerateOptions struct {
	// MaxTokens is the maximum number of tokens to generate
	MaxTokens int

	// Sampling parameters
	Sampling SamplingParams

	// StopTokens are tokens that stop generation
	StopTokens []LlamaToken

	// Callback is called for each generated token. Return false to stop.
	Callback func(token LlamaToken, text string) bool
}

GenerateOptions contains options for text generation

func DefaultGenerateOptions

func DefaultGenerateOptions() GenerateOptions

DefaultGenerateOptions returns default generation options

type LlamaAttentionType

type LlamaAttentionType int32
const (
	LlamaAttentionTypeUnspecified LlamaAttentionType = -1
	LlamaAttentionTypeCausal      LlamaAttentionType = 0
	LlamaAttentionTypeNonCausal   LlamaAttentionType = 1
)

type LlamaBatch

type LlamaBatch struct {
	NTokens int32 // offset 0, 4 bytes

	Token  uintptr // offset 8, 8 bytes - llama_token *
	Embd   uintptr // offset 16, 8 bytes - float *
	Pos    uintptr // offset 24, 8 bytes - llama_pos *
	NSeqID uintptr // offset 32, 8 bytes - int32_t *
	SeqID  uintptr // offset 40, 8 bytes - llama_seq_id **
	Logits uintptr // offset 48, 8 bytes - int8_t *
	// contains filtered or unexported fields
}

LlamaBatch represents a batch of tokens for processing Must match C struct llama_batch layout exactly (56 bytes total)

type LlamaChatMessage

type LlamaChatMessage struct {
	Role    uintptr // const char *
	Content uintptr // const char *
}

LlamaChatMessage represents a chat message. Role and Content are uintptr (not *byte) so the GC does not follow them into C-allocated memory, which would cause heap corruption.

type LlamaContext

type LlamaContext uintptr

Opaque pointer types matching llama.cpp

type LlamaContextParams

type LlamaContextParams struct {
	NCtx              uint32
	NBatch            uint32
	NUBatch           uint32
	NSeqMax           uint32
	NThreads          int32
	NThreadsBatch     int32
	RopeScalingType   LlamaRopeScalingType
	PoolingType       LlamaPoolingType
	AttentionType     LlamaAttentionType
	FlashAttnType     int32 // enum llama_flash_attn_type
	RopeFreqBase      float32
	RopeFreqScale     float32
	YarnExtFactor     float32
	YarnAttnFactor    float32
	YarnBetaFast      float32
	YarnBetaSlow      float32
	YarnOrigCtx       uint32
	DefragThold       float32
	CbEval            uintptr // ggml_backend_sched_eval_callback
	CbEvalUserData    uintptr // void *
	TypeK             GGMLType
	TypeV             GGMLType
	AbortCallback     uintptr // ggml_abort_callback
	AbortCallbackData uintptr // void *
	Embeddings        bool
	OffloadKQV        bool
	NoPerf            bool
	OpOffload         bool
	SwaFull           bool
	KvUnified         bool
	Samplers          uintptr // struct llama_sampler_seq_config *
	NSamplers         uint64  // size_t
}

LlamaContextParams contains parameters for context creation

func DefaultContextParams

func DefaultContextParams() LlamaContextParams

DefaultContextParams returns default context parameters matching llama_context_default_params()

type LlamaModel

type LlamaModel uintptr

Opaque pointer types matching llama.cpp

type LlamaModelParams

type LlamaModelParams struct {
	Devices                  uintptr // ggml_backend_dev_t *
	TensorBuftOverrides      uintptr // const struct llama_model_tensor_buft_override *
	NGPULayers               int32
	SplitMode                LlamaSplitMode
	MainGPU                  int32
	TensorSplit              uintptr // const float *
	ProgressCallback         uintptr // llama_progress_callback
	ProgressCallbackUserData uintptr // void *
	KVOverrides              uintptr // const struct llama_model_kv_override *
	VocabOnly                bool
	UseMmap                  bool
	UseDirectIO              bool
	UseMlock                 bool
	CheckTensors             bool
	UseExtraBufts            bool
	NoHost                   bool
	NoAlloc                  bool
}

LlamaModelParams contains parameters for model loading This struct must match the C struct layout exactly

func DefaultModelParams

func DefaultModelParams() LlamaModelParams

DefaultModelParams returns default model parameters matching llama_model_default_params()

type LlamaPoolingType

type LlamaPoolingType int32
const (
	LlamaPoolingTypeUnspecified LlamaPoolingType = -1
	LlamaPoolingTypeNone        LlamaPoolingType = 0
	LlamaPoolingTypeMean        LlamaPoolingType = 1
	LlamaPoolingTypeCLS         LlamaPoolingType = 2
	LlamaPoolingTypeLast        LlamaPoolingType = 3
)

type LlamaPos

type LlamaPos int32

LlamaPos represents a position in the context

type LlamaRopeScalingType

type LlamaRopeScalingType int32
const (
	LlamaRopeScalingTypeUnspecified LlamaRopeScalingType = -1
	LlamaRopeScalingTypeNone        LlamaRopeScalingType = 0
	LlamaRopeScalingTypeLinear      LlamaRopeScalingType = 1
	LlamaRopeScalingTypeYarn        LlamaRopeScalingType = 2
)

type LlamaSampler

type LlamaSampler uintptr

Opaque pointer types matching llama.cpp

type LlamaSamplerChainParams

type LlamaSamplerChainParams struct {
	NoPerf bool
}

LlamaSamplerChainParams contains parameters for sampler chain

func DefaultSamplerChainParams

func DefaultSamplerChainParams() LlamaSamplerChainParams

DefaultSamplerChainParams returns default sampler chain parameters

type LlamaSeqID

type LlamaSeqID int32

LlamaSeqID represents a sequence ID

type LlamaSplitMode

type LlamaSplitMode int32

Enum types

const (
	LlamaSplitModeNone  LlamaSplitMode = 0 // single GPU
	LlamaSplitModeLayer LlamaSplitMode = 1 // split layers and KV across GPUs
	LlamaSplitModeRow   LlamaSplitMode = 2 // split rows across GPUs
)

type LlamaToken

type LlamaToken int32

LlamaToken represents a token ID

type LlamaTokenData

type LlamaTokenData struct {
	ID    LlamaToken
	Logit float32
	P     float32
}

LlamaTokenData represents token data for sampling

type LlamaTokenDataArray

type LlamaTokenDataArray struct {
	Data     uintptr // llama_token_data *
	Size     uint64  // size_t
	Selected int64
	Sorted   bool
}

LlamaTokenDataArray represents an array of token data for sampling

type LlamaVocab

type LlamaVocab uintptr

Opaque pointer types matching llama.cpp

type Model

type Model struct {
	// contains filtered or unexported fields
}

Model represents a loaded llama model

func LoadModel

func LoadModel(path string, opts ModelOptions) (*Model, error)

LoadModel loads a model from a file

func (*Model) BOS

func (m *Model) BOS() LlamaToken

BOS returns the beginning-of-sequence token

func (*Model) Close

func (m *Model) Close()

Close frees the model resources

func (*Model) Detokenize

func (m *Model) Detokenize(tokens []LlamaToken) string

Detokenize converts tokens back to text

func (*Model) EOS

func (m *Model) EOS() LlamaToken

EOS returns the end-of-sequence token

func (*Model) EmbeddingSize

func (m *Model) EmbeddingSize() int32

EmbeddingSize returns the embedding dimension

func (*Model) NewContext

func (m *Model) NewContext(opts ContextOptions) (*Context, error)

NewContext creates a new inference context from a model

func (*Model) TokenToPiece

func (m *Model) TokenToPiece(token LlamaToken) string

TokenToPiece converts a single token to its text representation

func (*Model) Tokenize

func (m *Model) Tokenize(text string, addBOS bool, special bool) ([]LlamaToken, error)

Tokenize converts text to tokens

func (*Model) VocabSize

func (m *Model) VocabSize() int32

VocabSize returns the vocabulary size

type ModelOptions

type ModelOptions struct {
	NGPULayers int32 // Number of layers to offload to GPU (0 = CPU only)
	UseMmap    bool  // Use memory mapping for model loading
	UseMlock   bool  // Lock model in memory
	VocabOnly  bool  // Only load vocabulary
	MainGPU    int32 // Main GPU to use
}

ModelOptions contains options for loading a model

func DefaultModelOptions

func DefaultModelOptions() ModelOptions

DefaultModelOptions returns default model loading options

type Sampler

type Sampler struct {
	// contains filtered or unexported fields
}

Sampler wraps llama.cpp's sampler chain

func NewSampler

func NewSampler(params SamplingParams) *Sampler

NewSampler creates a new sampler with the given parameters

func (*Sampler) Accept

func (s *Sampler) Accept(token LlamaToken)

Accept tells the sampler that a token was accepted (for penalties)

func (*Sampler) Close

func (s *Sampler) Close()

Close frees the sampler resources

func (*Sampler) Reset

func (s *Sampler) Reset()

Reset resets the sampler state

func (*Sampler) Sample

func (s *Sampler) Sample(ctx *Context, idx int32) LlamaToken

Sample samples a token from the context at the given index

type SamplingParams

type SamplingParams struct {
	// Temperature for sampling (1.0 = neutral, <1.0 = more deterministic, >1.0 = more random)
	Temperature float32

	// TopK limits sampling to the K most likely tokens (0 = disabled)
	TopK int32

	// TopP (nucleus sampling) limits to tokens with cumulative probability >= p
	TopP float32

	// MinP filters out tokens with probability < p * max_prob
	MinP float32

	// TypicalP for locally typical sampling
	TypicalP float32

	// RepeatPenalty penalizes repeated tokens
	RepeatPenalty float32

	// FrequencyPenalty penalizes based on frequency
	FrequencyPenalty float32

	// PresencePenalty penalizes based on presence
	PresencePenalty float32

	// PenaltyLastN number of tokens to consider for repetition penalty
	PenaltyLastN int32

	// Seed for random sampling (0 = random seed)
	Seed uint32

	// Greedy uses greedy sampling (ignores temperature and other params)
	Greedy bool
}

SamplingParams contains parameters for text generation sampling

func DefaultSamplingParams

func DefaultSamplingParams() SamplingParams

DefaultSamplingParams returns sensible default sampling parameters

Directories

Path Synopsis
examples
cpu command
Example: CPU-only inference (no GPU)
Example: CPU-only inference (no GPU)
cuda command
Example: NVIDIA CUDA GPU acceleration
Example: NVIDIA CUDA GPU acceleration
embeddings command
Example demonstrating embeddings generation with go-llama-pure
Example demonstrating embeddings generation with go-llama-pure
metal command
Example: Apple Silicon with Metal GPU acceleration
Example: Apple Silicon with Metal GPU acceleration
simple command
Example demonstrating basic usage of go-llama-pure
Example demonstrating basic usage of go-llama-pure

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址