litertlmgo

package module
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2026 License: Apache-2.0 Imports: 0 Imported by: 0

README ΒΆ

litertlm-go

Go Reference

A high-performance, cgo-free, purego-backed Go binding for Google's LiteRT-LM runtime, designed for local on-device LLM inference.

[!NOTE] Inspired by Hybridgroup's Yzma.

πŸ“– Full documentation: vladimirvivien.github.io/litertlm-go


πŸ”₯ Features

  • πŸ’¬ Stateful Chat & Conversations β€” Multi-turn chat orchestration with system prompts, message history, and token tracking.
  • πŸ–ΌοΈ Multimodal Inputs β€” Process text, images, and audio inputs in any order using a unified Go interface.
  • πŸ› οΈ Automated Tool Calling β€” Register standard Go functions as tools that the model can call automatically and in parallel.
  • 🎯 Structured JSON Output β€” Extract model outputs directly into Go structs with type-safe generic helpers.
  • ⚑ High Performance & GPU Acceleration β€” Run on CPU or GPU (WebGPU/Direct3D 12) with built-in memory safety.
  • πŸ” Low-Level Control β€” Access the full LiteRT-LM C-API when you need custom inference loops, scoring, or custom memory management.

βš™οΈ Install

go get github.com/vladimirvivien/litertlm-go@latest

πŸš€ Quickstart

package main

import (
	"context"
	"fmt"
	"os"

	"github.com/vladimirvivien/litertlm-go/pkg/litertlm"
)

func main() {
	ctx := context.Background()
	
	// Initialize client using compiled libraries and model
	client, err := litertlm.New(ctx,
		litertlm.WithLib(os.Getenv("LITERTLM_LIB")),
		litertlm.WithModel(os.Getenv("LITERTLM_MODEL")),
	)
	if err != nil {
		fmt.Printf("Initialization failed: %v\n", err)
		os.Exit(1)
	}
	defer client.Close()

	// Generate text
	text, err := client.Generate(ctx, "Write a haiku about the sea.")
	if err != nil {
		fmt.Printf("Generation failed: %v\n", err)
		os.Exit(1)
	}
	fmt.Println(text)
}

Run with your compiled libraries and model paths:

LITERTLM_LIB=/abs/path/to/dist/lib \
LITERTLM_MODEL=/abs/path/to/gemma-4-E2B-it.litertlm \
    go run main.go

[!TIP] To run on the GPU backend, configure your initialization with litertlm.WithBackend("gpu") (defaults to "cpu").


πŸ—οΈ Building the C Library

LiteRT-LM does not ship prebuilt C-API shared libraries. Build the staging libraries (litertlm_c.dll / litertlm_c_cpu.dll) for your platform using the guides below:

[!IMPORTANT] Minimum supported upstream: LiteRT-LM v0.13.1. Stateful token tracking via Chat.TokenCount() binds to litert_lm_conversation_get_token_count, which was introduced in v0.13.1.


πŸ€– Examples

The repository includes a variety of examples showcasing advanced features. For example, ./examples/bot demonstrates the OCR capabilities of the Gemma 4 family, extracting structured information from an image of a form:

OCR example

See examples/README.md for a full list of available examples.


πŸ“– Documentation


πŸ“„ License

Apache-2.0, same as LiteRT-LM itself.

Documentation ΒΆ

Overview ΒΆ

Package litertlmgo is the module root for litertlm-go.

Consumers import the actual Go API from the subpackages:

import "github.com/vladimirvivien/litertlm-go/pkg/litertlm"
import "github.com/vladimirvivien/litertlm-go/pkg/loader"

See README.md for the full usage guide and LITERTLM-BUILD.md for the native-library build recipe.

Directories ΒΆ

Path Synopsis
examples
activation-dtype command
activation-dtype contrasts the default activation precision with a caller-selected WithActivationDataType.
activation-dtype contrasts the default activation precision with a caller-selected WithActivationDataType.
audio command
audio transcribes or answers a question about a short audio clip using a multimodal model.
audio transcribes or answers a question about a short audio clip using a multimodal model.
autotool command
autotool demonstrates typed tool registration and auto-dispatch.
autotool demonstrates typed tool registration and auto-dispatch.
benchmarks command
benchmarks contrasts two per-generation benchmark surfaces on the same Client and Engine:
benchmarks contrasts two per-generation benchmark surfaces on the same Client and Engine:
bot command
bot is a tiny CLI chat assistant.
bot is a tiny CLI chat assistant.
cache-warmup command
cache-warmup contrasts a cold and warm WithCacheDir load by running litertlm.New + a one-shot Generate twice against the same cache directory and reporting the wall-clock delta.
cache-warmup contrasts a cold and warm WithCacheDir load by running litertlm.New + a one-shot Generate twice against the same cache directory and reporting the wall-clock delta.
cancel command
cancel demonstrates aborting an in-flight streaming generation using the high-level Client.GenerateStream API and context cancellation.
cancel demonstrates aborting an in-flight streaming generation using the high-level Client.GenerateStream API and context cancellation.
chat command
chat demonstrates multi-turn conversation using the high-level Client.NewChat / Chat.Send API.
chat demonstrates multi-turn conversation using the high-level Client.NewChat / Chat.Send API.
chat-history command
chat-history resumes a prior conversation by seeding Chat with a transcript of {role, content} messages via WithInitialMessages.
chat-history resumes a prior conversation by seeding Chat with a transcript of {role, content} messages via WithInitialMessages.
clone command
clone demonstrates Chat.Clone: open a Chat, prefill some shared context with one turn, branch the conversation into two independent clones, and send a different follow-up to each.
clone demonstrates Chat.Clone: open a Chat, prefill some shared context with one turn, branch the conversation into two independent clones, and send a different follow-up to each.
conversation command
conversation showcases the full tool-using flow on the high-level Chat API: declare a tool, send a user prompt, dispatch the structured tool_call the model returns, send the result back, read the final natural-language answer.
conversation showcases the full tool-using flow on the high-level Chat API: declare a tool, send a user prompt, dispatch the structured tool_call the model returns, send the result back, read the final natural-language answer.
conversation-lowlevel command
conversation-lowlevel runs a two-turn chat directly against the low-level Conversation API: it constructs a SessionConfig, ConversationConfig and Conversation by hand β€” the same path Client.NewChat / Chat.Send build internally.
conversation-lowlevel runs a two-turn chat directly against the low-level Conversation API: it constructs a SessionConfig, ConversationConfig and Conversation by hand β€” the same path Client.NewChat / Chat.Send build internally.
extract command
extract uses litertlm.GenerateDataMulti[T] to pull a typed Scene struct out of an image, prints the JSON, then asks the model to briefly assess how well the extracted JSON aligns with a reference description loaded from disk.
extract uses litertlm.GenerateDataMulti[T] to pull a typed Scene struct out of an image, prints the JSON, then asks the model to briefly assess how well the extracted JSON aligns with a reference description loaded from disk.
fd-loader command
fd-loader demonstrates how to initialize the LiteRT-LM engine from an open file descriptor instead of a filesystem path string.
fd-loader demonstrates how to initialize the LiteRT-LM engine from an open file descriptor instead of a filesystem path string.
gpu command
gpu demonstrates GPU-accelerated local inference: load the GPU-capable LiteRT-LM build, configure an engine for the GPU backend, and stream tokens from a single prompt.
gpu demonstrates GPU-accelerated local inference: load the GPU-capable LiteRT-LM build, configure an engine for the GPU backend, and stream tokens from a single prompt.
hello command
hello demonstrates a minimal synchronous inference using the high-level Client API.
hello demonstrates a minimal synchronous inference using the high-level Client API.
logging command
logging demonstrates the LiteRT-LM log severity floor.
logging demonstrates the LiteRT-LM log severity floor.
lora-tuner command
lora-tuner demonstrates how to configure LoRA ranks and parameters on EngineSettings at engine initialization.
lora-tuner demonstrates how to configure LoRA ranks and parameters on EngineSettings at engine initialization.
parallel-load command
parallel-load measures litertlm.New wall-clock under the engine's default parallel section loading vs the serial path forced by WithParallelSectionLoading(false).
parallel-load measures litertlm.New wall-clock under the engine's default parallel section loading vs the serial path forced by WithParallelSectionLoading(false).
per-call-sampler command
per-call-sampler runs the same prompt three times against one Client, each Generate call overriding the sampler shape via WithSampler.
per-call-sampler runs the same prompt three times against one Client, each Generate call overriding the sampler shape via WithSampler.
prefill-chunk command
prefill-chunk contrasts the engine's default prefill chunking with a caller-selected WithPrefillChunkSize.
prefill-chunk contrasts the engine's default prefill chunking with a caller-selected WithPrefillChunkSize.
prefill-decode command
prefill-decode demonstrates the explicit two-phase generation flow: RunPrefill seeds the session with the prompt context, RunDecode then produces the response.
prefill-decode demonstrates the explicit two-phase generation flow: RunPrefill seeds the session with the prompt context, RunDecode then produces the response.
raw-multi command
raw-multi runs the same image + caption-text input through each of Client.GenerateMulti, Client.GenerateMultiStream, and Client.GenerateMultiResponse to surface the call-shape and return-type differences between the three *Multi siblings.
raw-multi runs the same image + caption-text input through each of Client.GenerateMulti, Client.GenerateMultiStream, and Client.GenerateMultiResponse to surface the call-shape and return-type differences between the three *Multi siblings.
score command
score demonstrates per-target text scoring: prefill the prompt, then score one candidate completion and inspect its log-probability score and tokenized length.
score demonstrates per-target text scoring: prefill the prompt, then score one candidate completion and inspect its log-probability score and tokenized length.
speculative command
speculative compares decode throughput with and without WithSpeculativeDecodingEnabled.
speculative compares decode throughput with and without WithSpeculativeDecodingEnabled.
stream command
stream demonstrates token-by-token streaming on the high-level Chat.SendStream API.
stream demonstrates token-by-token streaming on the high-level Chat.SendStream API.
structured command
structured demonstrates type-safe structured-output extraction with litertlm.GenerateData[T].
structured demonstrates type-safe structured-output extraction with litertlm.GenerateData[T].
template-inspector command
template-inspector demonstrates how to inspect the exact prompt template preface generated by the C-API template renderer before running generation.
template-inspector demonstrates how to inspect the exact prompt template preface generated by the C-API template renderer before running generation.
thread-tuner command
thread-tuner runs a quick benchmark prompt across different CPU thread counts to demonstrate how allocating thread resources affects generation speed.
thread-tuner runs a quick benchmark prompt across different CPU thread counts to demonstrate how allocating thread resources affects generation speed.
token-count command
token-count demonstrates Chat.TokenCount: the running number of tokens held in the conversation's KV cache, read after each turn to project a chat against the engine's max-token budget.
token-count demonstrates Chat.TokenCount: the running number of tokens held in the conversation's KV cache, read after each turn to project a chat against the engine's max-token budget.
token-limiter command
token-limiter demonstrates how to dynamically restrict token generation length on a per-call basis using the WithMaxOutputTokens runtime option.
token-limiter demonstrates how to dynamically restrict token generation length on a per-call basis using the WithMaxOutputTokens runtime option.
token-scores command
token-scores scores one or more candidate continuations against the same prefilled prompt and prints the per-token scores alongside the detokenized text.
token-scores scores one or more candidate continuations against the same prefilled prompt and prints the per-token scores alongside the detokenized text.
tokenize command
tokenize shows the high-level Client.Tokenize / Client.TokenLength helpers paired with the underlying Engine accessors (Detokenize, StartTokenIDs, StopTokenIDs) reached via Client.Engine().
tokenize shows the high-level Client.Tokenize / Client.TokenLength helpers paired with the underlying Engine accessors (Detokenize, StartTokenIDs, StopTokenIDs) reached via Client.Engine().
tool-policy command
tool-policy contrasts the two values of WithToolPolicy by running a tool whose handler errors for inputs not in its lookup table.
tool-policy contrasts the two values of WithToolPolicy by running a tool whose handler errors for inputs not in its lookup table.
vision command
vision asks the model to describe an image, then asks the model to briefly assess how well its description aligns with a reference description loaded from disk.
vision asks the model to describe an image, then asks the model to briefly assess how well its description aligns with a reference description loaded from disk.
pkg
litertlm
Package litertlm is a purego-backed, cgo-free Go wrapper around Google's LiteRT-LM C API (see c/engine.h in the LiteRT-LM repository).
Package litertlm is a purego-backed, cgo-free Go wrapper around Google's LiteRT-LM C API (see c/engine.h in the LiteRT-LM repository).
loader
Package loader resolves and loads the LiteRT-LM native shared library.
Package loader resolves and loads the LiteRT-LM native shared library.
utils
Package utils provides platform-abstracted helpers for marshalling strings across the Go/C FFI boundary.
Package utils provides platform-abstracted helpers for marshalling strings across the Go/C FFI boundary.

Jump to

Keyboard shortcuts

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