Using Models

Models requires JDK 25 or newer. The shortest path to a qualified model is the ModelJars facade plus one independently versioned marker JAR:

dependencies {
    implementation("org.modeljars:modeljars:0.1.78")
    implementation(
        "org.modeljars.huggingface:" +
            "ggml-org.qwen3-0.6b-gguf.q4_0:" +
            "3.0.0-q4_0.1"
    )
}

The marker contains its descriptor, checksum, production qualification, performance profiles, and generated Java reference. modeljars brings Models and both execution backends. Backend selection is tied to the exact model artifact rather than chosen from a file name.

Load and Generate

Instruction-tuned models require the control tokens and role boundaries defined by their chat template. openRuntime returns the template recorded for the exact qualified artifact, so application code does not guess from an architecture name.

import static org.modeljars.catalog.Qwen3_0_6b_Q4_0.MODEL;

import com.integrallis.models.api.ModelPrompt;
import com.integrallis.models.api.SamplingOptions;
import com.integrallis.models.runtime.chat.ChatMessage;
import java.util.List;
import org.modeljars.ModelJars;

try (var runtime = ModelJars.openRuntime(MODEL)) {
    var options = SamplingOptions.builder()
        .temperature(0.0f)
        .maxTokens(128)
        .build();

    ModelPrompt prompt = runtime.chatTemplate().render(List.of(
        ChatMessage.system("Classify the user's intent in one phrase."),
        ChatMessage.user("I want to cancel my order")));

    String answer = runtime.model().generate(prompt, options);
    System.out.println(answer);
    System.out.println(runtime.model().diagnostics().optimizations());
}

render preserves template-owned control tokens as trusted segments and keeps every message as ordinary text. User content that spells a token such as <|im_end|> therefore remains content instead of terminating its chat turn. Plain String prompts are also encoded as ordinary text. Use ModelPrompt.control(…​) only for a complete, trusted template supplied by the application.

For Needle 2, use ChatTemplate.NEEDLE2 with ordinary ToolSpec values. The renderer follows the CACT reference protocol: schemas are placed directly in the <tools> array rather than wrapped in an OpenAI function object, and parallel calls are emitted as one JSON array inside <tool_call>.

For Hammer 2.1 checkpoints, use ChatTemplate.HAMMER. It renders the checkpoint’s published tool-selection instructions and Python-style schema envelope. ToolCallScanner accepts the strict JSON requested by that prompt and the narrow Python-literal form emitted by the checkpoint; it never evaluates model output. Protocol support does not by itself qualify a specific artifact—the tool-calling qualification suite still gates catalog admission.

import static org.modeljars.catalog.Cactus_Compute_Needle2_Cact_Cq2_Mixed.MODEL;

var weather = new ToolSpec(
    "get_weather",
    "Get the current weather for a city.",
    "{\"type\":\"object\",\"properties\":{\"city\":{\"type\":\"string\"}},"
        + "\"required\":[\"city\"]}");

try (var runtime = ModelJars.openRuntime(MODEL)) {
    var tools = List.of(weather);
    var prompt = runtime.chatTemplate().render(
        List.of(ChatMessage.user("weather in Lagos")), tools);
    var constraint = ToolCallTokenConstraints.compile(
        runtime.tokenizer(), runtime.chatTemplate().toolSyntax(), tools,
        ignored -> List.of()).orElseThrow();
    var generated = runtime.pipeline().generate(prompt, options, constraint);
    var calls = ToolCallScanner.scan(
        generated, runtime.chatTemplate().toolSyntax()).toolCalls();
}

The Needle 2 artifact also carries contrastive retrieval and confidence heads. They are available from the same owning pipeline; no second model or service is loaded:

try (var runtime = ModelJars.openRuntime(MODEL)) {
    var pipeline = runtime.pipeline();
    if (pipeline.supportsContrastiveEncoding()) {
        var selector = new ToolSpecSelector(pipeline);
        List<ToolSpec> promptTools = selector.select(
            "weather in Lagos", List.of(weather));
    }

    if (pipeline.supportsConfidenceScoring()) {
        ModelPrompt sequence = ModelPrompt.text("complete prompt and generated output");
        float headScore = pipeline.scoreConfidence(sequence);
    }
}

ToolSpecSelector passes five or fewer declarations through unchanged. For a larger catalog, it embeds each schema once, retains a bounded in-memory index, and embeds only the current query on subsequent calls. LangChain4j and Spring AI perform this selection automatically when the wrapped model exposes the contrastive head. The selected five schemas are the only schemas rendered and the only schemas admitted by constrained decoding.

ModelJars.openRuntime resolves the marker already present on the classpath, downloads the pinned weights when they are absent, verifies size and SHA-256, selects the qualified backend, and applies a performance profile only when its artifact, backend, JVM, and hardware selectors match.

Run the JVM with the incubating Vector API enabled:

java --add-modules jdk.incubator.vector \
     --enable-native-access=ALL-UNNAMED ...

Stream Tokens

The plain Java streaming API delivers decoded token fragments serially and in generation order. Exactly one terminal callback follows: onComplete after a successful generation or onError with the original failure. Callbacks may run on an implementation-selected thread, so callback methods should return promptly and must not re-enter the same non-thread-safe model.

import com.integrallis.models.api.TokenStream;

try (var runtime = ModelJars.openRuntime(MODEL)) {
    var prompt = runtime.chatTemplate().render(
        List.of(ChatMessage.user("Explain local inference in one sentence.")));
    runtime.model().generate(prompt, options, new TokenStream() {
        @Override
        public void onToken(String token) {
            System.out.print(token);
        }

        @Override
        public void onComplete() {
            System.out.println();
        }

        @Override
        public void onError(Throwable failure) {
            failure.printStackTrace();
        }
    });
}

Inspect the Selected Plan

Backend diagnostics identify the runtime, execution plan, enabled optimizations, and reasons why another path was not selected:

try (var runtime = ModelJars.openRuntime(MODEL)) {
    System.out.println(runtime.model().diagnostics().backend());
    runtime.model().diagnostics().optimizations().forEach(System.out::println);
}

Bring Your Own Artifact

Applications that deliberately manage model files themselves can use the lower-level Models artifacts:

dependencies {
    implementation("com.integrallis:models:0.5.20")
    implementation("com.integrallis:backend-java:0.5.20")
}
Path artifact = Path.of("/opt/models/private-model.gguf");

try (InferencePipeline pipeline =
        new InferencePipeline(PureJavaBackend.load(artifact))) {
    ModelMetadata metadata = pipeline.metadata();
    Tokenizer tokenizer = pipeline.tokenizer();
    InferenceContextWindow context = pipeline.contextWindow();
    String answer = pipeline.generate(prompt, options);
}

This API intentionally accepts a filesystem path because Models cannot verify an unmanaged GGUF, supported Safetensors bundle, or CACT artifact against ModelJars metadata. Use backend-native and RustFfmBackend.load(artifact) for explicit native-kernel loading where that artifact and graph support native kernels. The pipeline owns and closes the supplied backend. See Inference Pipeline for structured tokenization, context capacity and position, prefill, forward-pass logits, checkpoint, and rewind.

See Model Support for the qualification boundary, Execution Planning for profile selection, and Concurrent Session Batching when one loaded model must serve several independent requests.