Skip to content

About

In-process local GGUF inference, SSE token streaming, and cooperative native cancellation in Spring Boot 3.4 + LangChain4j — powered by libargus (Panama FFM & JNI).

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Project Argus — Local AI Workbench

Local AI Workbench — libargus + LangChain4j + Spring Boot

CI Maven Central Spring Boot 3.5 LangChain4j 1.23.0 JDK 25 / 22+ Panama FFM | 17+ JNI MIT License

A tiny, production-grade Spring Boot 3.5 + LangChain4j 1.23.0 reference application demonstrating in-process local GGUF inference, incremental Server-Sent Events (SSE) token & separated <think> reasoning streaming, StreamingHandle.cancel() + cooperative C++ ArgusAbortFlag cancellation, opt-in Multimodal Vision (mmproj / ImageContent), opt-in Whisper ASR & Speech-LLM TTS, and exact BPE / vision-patch token budgeting—with zero Python sidecars, zero external daemons, and zero cloud API keys.

Tip

Powered by libargus — an open-source, unmanaged C++17 native AI execution runtime engineered for zero-allocation steady-state inference across LLM text generation, bidirectional RAG embeddings, Whisper speech-to-text (ASR), text-to-speech (TTS), and Vision/Audio/Video multimodal pipelines.

Explore and star ProjectArgus-cc/libargus.cc for full documentation, EmbeddingModel / RAG cookbooks, Android/JNI guides, and low-level Java FFI references. See CHANGELOG.md for version-pinned release notes.

Local AI Workbench 2.4.0 — Live In-Process Whisper ASR, Multimodal Vision, <think> Reasoning, Streaming & Speech-LLM TTS Demo

View High-Resolution Workbench Screenshot (2.4.0)

Local AI Workbench 2.4.0 — High-Resolution UI Screenshot

Capabilities at a Glance (2.4.0)

Modality / Feature HTTP / SSE Surface LangChain4j 1.23.0 Adapter Activation
Chat & Incremental SSE Streaming POST /api/chat, POST /api/chat/stream LibArgusChatModel, LibArgusStreamingChatModel, LibArgusTokenCountEstimator ARGUS_CHAT_MODEL_PATH (required)
Separated <think> Reasoning event: thinking SSE + thinking / thinkingDurationMs JSON .returnThinking(true) (PartialThinking + collapsible UI drawer) Enabled by default (ARGUS_RETURN_THINKING=true)
Dual Cooperative Cancellation POST /api/chat/stop + SSE disconnect StreamingHandle.cancel() ↔ ArgusAbortFlag.abort() Always active
Multimodal Vision (mmproj) Inline Base64 images on /api/chat* (PNG/JPEG/WEBP/GIF/BMP) .mmprojPath(...) + Zero-Trust allowLocalFileMedia(false) (ImageContent) ARGUS_VISION_MMPROJ_PATH (opt-in)
Local Whisper ASR & Speech-LLM TTS POST /api/audio/transcribe, POST /api/audio/speech LibArgusAudioTranscriptionModel, LibArgusTextToSpeechModel ARGUS_ASR_MODEL_PATH, ARGUS_TTS_MODEL_PATH + ARGUS_TTS_VOCODER_PATH (opt-in)

1. Copy-Paste Into Your Own Spring Boot Project

Want to embed in-process local GGUF, <think>, Vision, Whisper ASR, and TTS directly inside an existing Spring Boot 3.5 + LangChain4j 1.23.0 service? Here is the complete pattern:

Minimal pom.xml Dependencies

<properties>
    <!-- Align Jackson with LangChain4j 1.23.0 (prevents Spring Boot 3.5 BOM downgrade to Jackson 2.19.x) -->
    <jackson-bom.version>2.22.4</jackson-bom.version>
</properties>

<dependencies>
    <!-- In-process LangChain4j ChatModel, StreamingChatModel, AudioTranscriptionModel, TextToSpeechModel & TokenCountEstimator -->
    <dependency>
        <groupId>cc.projectargus</groupId>
        <artifactId>libargus-langchain4j</artifactId>
        <version>2.4.0</version>
    </dependency>

    <!-- Choose libargus-core (JDK 22+/25 Panama FFM) OR libargus-jni (JDK 17+ / Android — 100% API parity) -->
    <dependency>
        <groupId>cc.projectargus</groupId>
        <artifactId>libargus-jni</artifactId>
        <version>2.4.0</version>
    </dependency>

    <!-- Precompiled native SPI provider (auto-extracts libargus at runtime; swap for cuda/metal/rocm/vulkan) -->
    <dependency>
        <groupId>cc.projectargus</groupId>
        <artifactId>libargus-native-linux-cpu</artifactId>
        <version>2.4.0</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

Important

Spring Boot 3.5 + LangChain4j 1.23.0 Jackson BOM Note: LangChain4j 1.23.0 compiles against Jackson 2.22.4 (jackson-annotations:2.22), whereas spring-boot-starter-parent:3.5.x manages Jackson 2.19.x by default. Setting <jackson-bom.version>2.22.4</jackson-bom.version> in <properties> keeps Maven dependency convergence clean with zero runtime NoSuchMethodError conflicts.

Minimal @Configuration Wiring Shared Model Weights, <think> & Optional Vision

@Configuration(proxyBeanMethods = false)
public class LocalAiConfig {

    @Bean(destroyMethod = "close")
    public ArgusModel argusModel(@Value("${argus.chat.model-path}") Path modelPath) {
        ArgusBackend.init();
        return ArgusModel.load(modelPath, /* gpuLayers */ 99, /* useMlock */ false);
    }

    @Bean(destroyMethod = "close")
    public LibArgusStreamingChatModel streamingChatModel(
        ArgusModel sharedModel,
        @Value("${argus.vision.mmproj-path:}") String mmprojPath
    ) {
        LibArgusStreamingChatModel.Builder builder = LibArgusStreamingChatModel.builder()
            .model(sharedModel)                         // Shares weights; owns its KV cache context
            .chatFormatter(LibArgusChatFormatter.autoDetect())
            .returnThinking(true)                       // Separates <think>...</think> into PartialThinking
            .contextLength(4096)
            .maxOutputTokens(512);

        if (!mmprojPath.isBlank()) {
            builder
                .mmprojPath(Path.of(mmprojPath))        // Opt-in multimodal vision projection
                .allowLocalFileMedia(false)             // Zero-Trust: block file:// & http(s):// SSRF
                .allowedMediaRoot(null)
                .maxMediaBytes(4_194_304L);
        }
        return builder.build();
    }
}
Optional @Bean Snippet: Local Whisper ASR & Speech-LLM TTS
@Bean(destroyMethod = "close")
public LibArgusAudioTranscriptionModel whisperModel(@Value("${argus.audio.asr-model-path}") Path asrPath) {
    return LibArgusAudioTranscriptionModel.builder()
        .modelPath(asrPath)
        .trimOutput(true)
        .padShortAudioToOneSecond(true)
        .build();
}

@Bean(destroyMethod = "close")
public LibArgusTextToSpeechModel ttsModel(
    @Value("${argus.audio.tts-model-path}") Path ttsPath,
    @Value("${argus.audio.tts-vocoder-path}") Path vocoderPath
) {
    return LibArgusTextToSpeechModel.builder()
        .modelPath(ttsPath)
        .vocoderPath(vocoderPath)
        .defaultVoice("42")
        .build();
}

Because LibArgusChatModel, LibArgusStreamingChatModel, LibArgusAudioTranscriptionModel, and LibArgusTextToSpeechModel implement standard LangChain4j 1.23.0 interfaces, they plug directly into LangChain4j AiServices, @SystemMessage, ChatMemory, ChatModelListener observability, Tools, and Flow.Publisher reactive streams—while this repository exposes constructor-injectable @Bean delegates in ArgusLangChain4jConfig backed by ArgusRuntimeManager for per-request cancellation and live model recovery.


2. Architecture & Why In-Process Matters

flowchart LR
    UI["Obsidian Workbench / curl\n(Chat, <think>, Paste/Drop Image, Mic WAV, Audio Playback)"]
    FILT["WebSecurityHeadersFilter (Strict CSP)\n+ JsonRequestBodySizeFilter (64 KiB | 8 MiB Vision | 10 MiB Audio)"]
    SVC["ChatService & AudioService\n(Magic-Byte Preflight + BPE & Vision-Patch Eviction + LIFO Concurrency Gate)"]
    MGR["ArgusRuntimeManager\n(Read/Write Lifecycle Lease + Platform GPU Workers)"]
    NAT["In-Process libargus 2.4.0 (Panama FFM JDK 22+/25 | JNI JDK 17+)\n(Shared ArgusModel + mmproj Vision + Whisper ASR + Speech-LLM TTS + ArgusAbortFlag)"]

    UI --> FILT --> SVC --> MGR --> NAT
Loading
Engineering Dimension Loopback Sidecar Stack (Ollama + Whisper + TTS Containers) In-Process libargus + Spring Boot
Process Topology 3–4 separate OS daemons/containers + JVM service Single JVM process (java -jar app.jar)
Multimodal & Audio Pipeline Separate HTTP/Base64/multipart hops across LLM, VLM, ASR, and TTS services Process-global backend singularity sharing ArgusModel weights across Chat, Vision mmproj, Whisper ASR, and Speech-LLM TTS
Per-Token Streaming Path C++ → Sidecar HTTP/JSON → Loopback TCP → JVM Direct FFI memory read (Panama FFM or JNI)
Mid-Prefill Cancellation Socket disconnect often waits until prefill completes Immediate C++ abort via StreamingHandle.cancel() + ArgusAbortFlag.abort()
Token Window Budgeting Approximate char heuristics or duplicate Java tokenizer Exact lock-free native BPE count (LibArgusTokenCountEstimator) + tokensPerImage vision patch reserve
GPU Thread Affinity Unmanaged external worker pools Dedicated daemon platform threads (argus-inference-worker-* / argus-model-async-*) avoiding virtual-thread carrier hopping across thread-local cublasHandle_t pools

Production Patterns Demonstrated in This Repo

  1. First-Class Dual FFI (JNI Baseline + Automatic Panama FFM Shift): Builds on portable libargus-jni (--release 17) for JDK 17–21 and automatically shifts to Project Panama FFM (libargus-core, --release 22) whenever Maven detects JDK 22+ / JDK 25 LTS—with Enable-Native-Access: ALL-UNNAMED stamped into MANIFEST.MF so java -jar needs zero extra CLI flags.
  2. Deterministic Native Lifecycle & Reverse-Order Teardown: ArgusRuntimeManager initializes native handles in strict forward order, unwinds partial allocations on startup failure, coordinates with server.shutdown: graceful + ChatService.destroy() / AudioService.destroy(), and closes every handle in exact reverse order under a ReentrantReadWriteLock lifecycle lease.
  3. Separated <think> Reasoning Without History Pollution: Streams model chain-of-thought over dedicated event: thinking SSE frames into a live collapsible <details class="thinking-trace"> drawer that opens while reasoning, auto-collapses when visible answer tokens arrive, stays open if stopped mid-thought, and never leaks <think> tokens back into multi-turn prompt history.
  4. Dual Cooperative Cancellation (StreamingHandle.cancel() + ArgusAbortFlag): Client disconnect or POST /api/chat/stop immediately aborts the native C++ prefill/decode loop and releases concurrency permits in strict LIFO order (semaphore.release() before activeCount.decrementAndGet()).
  5. Zero-Trust Multimodal Vision & Vision-Patch KV Budgeting: Initializes adapters with allowLocalFileMedia(false) and allowedMediaRoot(null), validates exact Base64 lengths before decoding, sniffs binary magic headers (PNG, JPEG, WEBP, GIF, BMP), reserves tokensPerImage KV tokens during sliding-turn eviction, and automatically sheds oldest historical images in the browser above 85% of the body ceiling.
  6. In-Process Voice (Whisper ASR + Speech-LLM TTS) Under Shared Admission: Transcribes raw RIFF/WAVE / 16 kHz PCM or multipart uploads and synthesizes audio/wav under the same bounded InferenceConcurrencyGate as chat.
  7. Discoverable Local-First Obsidian UI: Zero-build static HTML/CSS/JS served at http://127.0.0.1:8080 with strict CSP, XSS-safe textContent rendering, pure-JS 16 kHz WAV resampling, revocable blob: cleanup on New Chat, and disabled-with-tooltip ATTACH IMAGE, MIC DICTATE, UPLOAD WAV, and SPEAK controls whenever optional models are unconfigured.

3. Quick Start (60 Seconds)

Prerequisites

  • Java: JDK 17 or newer (JDK 17/21 runs via JNI; JDK 22 / JDK 25 LTS automatically shifts to Project Panama FFM).
  • Local GGUF Model: Any instruct/chat .gguf model on disk (e.g., Qwen3.8-27B-UD-Q4_K_XL.gguf, Qwen2.5-1.5B-Instruct-Q4_K_M.gguf, Llama-3.2-3B-Instruct-Q4_K_M.gguf, or gemma-2-2b-it-Q4_K_M.gguf). This app never auto-downloads weights at startup.

Step 1 — Run Tests & Package (No Model File Needed)

./mvnw clean test package

Step 2 — Launch With a Single Chat Model

ARGUS_CHAT_MODEL_PATH="/absolute/path/to/Qwen2.5-1.5B-Instruct-Q4_K_M.gguf" \
  java -jar target/libargus-spring-boot-example-2.4.0.jar

(Or run directly via Maven: ARGUS_CHAT_MODEL_PATH="/absolute/path/to/model.gguf" ./mvnw spring-boot:run.)

Step 2b — Full Multimodal Launch (Chat + <think> + Vision + Whisper ASR + Speech-LLM TTS)

ARGUS_CHAT_MODEL_PATH="/absolute/path/to/Qwen3.8-27B-UD-Q4_K_XL.gguf" \
ARGUS_VISION_MMPROJ_PATH="/absolute/path/to/Qwen3.8-27B-mmproj-F16.gguf" \
ARGUS_ASR_MODEL_PATH="/absolute/path/to/whisper-base.gguf" \
ARGUS_TTS_MODEL_PATH="/absolute/path/to/OuteTTS-0.2-500M-Q4_K_M.gguf" \
ARGUS_TTS_VOCODER_PATH="/absolute/path/to/wavtokenizer-large-Q4_K_M.gguf" \
ARGUS_CHAT_MODE="stream" \
ARGUS_GPU_LAYERS="99" \
ARGUS_VISION_USE_GPU="true" \
  java -jar target/libargus-spring-boot-example-2.4.0.jar

Open http://127.0.0.1:8080 in your browser—verify the top-right status badge (READY (PANAMA-FFM) on JDK 22+/25 or READY (JNI) on JDK 17–21) and telemetry bar (VISION: ON, VOICE: ASR + TTS). When optional Vision/ASR/TTS models are omitted, ATTACH IMAGE, MIC DICTATE, UPLOAD WAV, and SPEAK remain visible and disabled with hover tooltips explaining which ARGUS_* env var activates them.


4. FFI Binding & Hardware Accelerator Profiles

Automatic FFI Selection (Panama FFM vs. JNI)

Environment / Flag Active Binding Artifact Bytecode Target Notes
JDK 17 – 21 (Default) cc.projectargus:libargus-jni:2.4.0 --release 17 Zero JVM flags; broad enterprise & Android parity
JDK 22 / 25 LTS (Auto-Activated) cc.projectargus:libargus-core:2.4.0 --release 22 Project Panama FFM (MemorySegment / Linker); MANIFEST.MF sets Enable-Native-Access: ALL-UNNAMED
JDK 22 / 25 with -Pjni cc.projectargus:libargus-jni:2.4.0 --release 17 Explicit override to cross-compile & verify a portable JDK 17 JAR from a JDK 22/25 machine (tested in CI)

OS & GPU Accelerator Profiles

By default, pom.xml bundles libargus-native-linux-cpu. Activate any platform/GPU classifier profile (which composes cleanly with auto-activated panama or -Pjni):

Target Platform / Accelerator Maven Profile Native SPI Artifact (2.4.0)
Linux x86_64 CPU (Default) -Plinux-cpu cc.projectargus:libargus-native-linux-cpu:2.4.0
Linux x86_64 NVIDIA CUDA -Plinux-cuda cc.projectargus:libargus-native-linux-cuda:2.4.0
Linux x86_64 AMD ROCm -Plinux-rocm cc.projectargus:libargus-native-linux-rocm:2.4.0
Linux x86_64 Vulkan -Plinux-vulkan cc.projectargus:libargus-native-linux-vulkan:2.4.0
macOS Apple Silicon Metal -Pmacos-metal cc.projectargus:libargus-native-macos-metal:2.4.0
Windows x86_64 CPU -Pwindows-cpu cc.projectargus:libargus-native-windows-cpu:2.4.0
Windows x86_64 NVIDIA CUDA -Pwindows-cuda cc.projectargus:libargus-native-windows-cuda:2.4.0
Windows x86_64 Vulkan -Pwindows-vulkan cc.projectargus:libargus-native-windows-vulkan:2.4.0
# macOS Apple Silicon (Metal GPU offload)
ARGUS_CHAT_MODEL_PATH="/path/to/model.gguf" ARGUS_GPU_LAYERS=99 \
  ./mvnw spring-boot:run -Pmacos-metal

# Linux NVIDIA CUDA GPU offload
ARGUS_CHAT_MODEL_PATH="/path/to/model.gguf" ARGUS_GPU_LAYERS=99 \
  ./mvnw spring-boot:run -Plinux-cuda

5. Configuration Reference

All settings in src/main/resources/application.yml bind to validated @ConfigurationProperties classes: ArgusWorkbenchProperties (argus.chat.*), ArgusVisionProperties (argus.vision.*), and ArgusAudioProperties (argus.audio.*).

Core Chat & Runtime (argus.chat.*)

Environment Variable Property Default Description
ARGUS_CHAT_MODEL_PATH argus.chat.model-path (unset) Required. Path to a local .gguf chat/instruct model file.
ARGUS_CHAT_FORMATTER argus.chat.chat-formatter auto Prompt template (auto, chatml, llama3, gemma, mistral, fallback).
ARGUS_CHAT_MODE argus.chat.chat-mode both Active adapter mode: both (sync + SSE streaming), stream, or sync.
ARGUS_RETURN_THINKING argus.chat.return-thinking true Separate <think>...</think> reasoning traces (event: thinking + thinking).
ARGUS_CONTEXT_LENGTH argus.chat.context-length 4096 KV cache context window in tokens (128–131072).
ARGUS_MAX_OUTPUT_TOKENS argus.chat.max-output-tokens 512 Maximum generated tokens per response (1–32768, < contextLength).
ARGUS_GPU_LAYERS argus.chat.gpu-layers 0 Model layers offloaded to GPU (0 = CPU-only, 99 = full offload).
ARGUS_CPU_THREADS argus.chat.cpu-threads 0 CPU threads for evaluation (0 = auto-detect physical cores).
ARGUS_TEMPERATURE argus.chat.temperature 0.7 Default sampling temperature (0.0 = greedy argmax, up to 2.0).
ARGUS_MAX_CONCURRENT_INFERENCE argus.chat.max-concurrent-inference 1 Max simultaneous inference jobs before returning HTTP 429.
ARGUS_MAX_PROMPT_CHARS argus.chat.max-prompt-chars 12000 Max characters per message and per conversation payload.
ARGUS_MAX_HISTORY_MESSAGES argus.chat.max-history-messages 20 Max conversation messages accepted per request.
ARGUS_MAX_REQUEST_BODY_BYTES argus.chat.max-request-body-bytes 65536 Max raw JSON body bytes (64 KiB default) before returning HTTP 413.
ARGUS_INFERENCE_TIMEOUT_SECONDS argus.chat.inference-timeout-seconds 180 Per-request generation timeout in seconds.
ARGUS_FAIL_FAST_STARTUP argus.chat.fail-fast-startup true Fail immediately if model is missing (false boots UI in degraded state and live-recovers once the file arrives).
ARGUS_SYSTEM_PROMPT argus.chat.system-prompt (concise assistant) Trusted server-owned system instruction prepended to every request.

Multimodal Vision Projection (argus.vision.*)

Environment Variable Property Default Description
ARGUS_VISION_MMPROJ_PATH argus.vision.mmproj-path (unset) Optional local multimodal projector .mmproj GGUF file enabling inline images on /api/chat*.
ARGUS_VISION_USE_GPU argus.vision.use-gpu false Offload vision projector layers to GPU when available.
ARGUS_VISION_MAX_IMAGE_BYTES argus.vision.max-image-bytes 4194304 Max decoded byte size per attached image (4 MiB default, 4 KiB–32 MiB).
ARGUS_VISION_MAX_IMAGES_PER_MESSAGE argus.vision.max-images-per-message 4 Max inline image attachments per user message (1–8).
ARGUS_VISION_TOKENS_PER_IMAGE argus.vision.tokens-per-image 512 Reserved KV cache token budget per image during sliding-turn eviction (4–8192).
ARGUS_VISION_MAX_REQUEST_BODY_BYTES argus.vision.max-request-body-bytes 8388608 Raised raw JSON body cap on /api/chat* when mmprojPath is configured (8 MiB default).

Local Voice: Whisper ASR & Speech-LLM TTS (argus.audio.*)

Environment Variable Property Default Description
ARGUS_ASR_MODEL_PATH argus.audio.asr-model-path (unset) Optional local Whisper .bin (GGML) or .gguf model enabling POST /api/audio/transcribe.
ARGUS_ASR_GPU_LAYERS argus.audio.asr-gpu-layers 0 GPU layers offloaded for Whisper ASR (0 = CPU-only).
ARGUS_AUDIO_MAX_UPLOAD_BYTES argus.audio.max-upload-bytes 10485760 Max audio payload bytes on /api/audio/transcribe (10 MiB default).
ARGUS_AUDIO_MAX_TRANSCRIPT_CHARS argus.audio.max-transcript-chars 32768 Max decoded transcript length returned by Whisper ASR.
ARGUS_TTS_MODEL_PATH argus.audio.tts-model-path (unset) Optional Speech-LLM base .gguf model (requires ARGUS_TTS_VOCODER_PATH).
ARGUS_TTS_VOCODER_PATH argus.audio.tts-vocoder-path (unset) Optional WavTokenizer vocoder .gguf model for POST /api/audio/speech.
ARGUS_TTS_GPU_LAYERS argus.audio.tts-gpu-layers 0 GPU layers offloaded for Speech-LLM & vocoder (0 = CPU-only).
ARGUS_TTS_VOICE argus.audio.tts-voice 42 Default voice seed or named voice ID for TTS synthesis.
ARGUS_TTS_MAX_CHARS argus.audio.tts-max-chars 2000 Max input text length accepted by POST /api/audio/speech.
ARGUS_TTS_MAX_DURATION_SECONDS argus.audio.tts-max-duration-seconds 30 Maximum synthesized speech duration in seconds (1–120).

Server & HTTP

Environment Variable Property Default Description
SERVER_ADDRESS server.address 127.0.0.1 Bind address (loopback-only by default).
SERVER_PORT server.port 8080 HTTP listen port.

Note

VRAM / RAM Tip on ARGUS_CHAT_MODE: LibArgusChatModel and LibArgusStreamingChatModel share a single ArgusModel weight allocation in memory, while each adapter maintains its own ArgusContext KV cache (and its own ArgusMultimodalContext projector when ARGUS_VISION_MMPROJ_PATH is set). On memory-constrained GPUs or with large models/context windows, set ARGUS_CHAT_MODE=stream (or sync) to allocate only one KV cache and one .mmproj projector context.


6. HTTP & SSE API (curl Examples)

GET /api/status — Runtime Readiness & Active FFI Telemetry

curl -s http://127.0.0.1:8080/api/status
{
  "status": "ready",
  "chatEnabled": true,
  "returnThinking": true,
  "asrEnabled": true,
  "asrModelName": "whisper-base.gguf",
  "maxAudioUploadBytes": 10485760,
  "ttsEnabled": true,
  "ttsModelName": "OuteTTS-0.2-500M-Q4_K_M.gguf",
  "ttsMaxChars": 2000,
  "visionEnabled": true,
  "visionProjectorName": "Qwen3.8-27B-mmproj-F16.gguf",
  "maxImageBytes": 4194304,
  "maxImagesPerMessage": 4,
  "maxVisionRequestBodyBytes": 8388608,
  "capabilities": ["streaming", "thinking", "vision", "asr", "tts"],
  "binding": "panama-ffm",
  "runtimeVersion": "2.4.0",
  "availableBackends": ["CUDA0", "CPU"],
  "modelName": "Qwen3.8-27B-UD-Q4_K_XL.gguf",
  "chatFormatter": "auto",
  "contextLength": 4096,
  "maxOutputTokens": 512,
  "gpuLayers": 99,
  "maxConcurrentInference": 1,
  "activeInferenceCount": 0,
  "maxPromptChars": 12000,
  "maxHistoryMessages": 20
}

(Fields with null values—such as asrModelName, ttsModelName, visionProjectorName, errorCode, and errorMessage when disabled/healthy—are omitted via spring.jackson.default-property-inclusion: non_null. Local filesystem paths are never exposed.)

POST /api/chat/stream — Incremental SSE Token & <think> Reasoning Streaming

curl -N -X POST http://127.0.0.1:8080/api/chat/stream \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "requestId": "demo-stream-1",
    "prompt": "Write a haiku about CPU cache lines.",
    "temperature": 0.0,
    "maxOutputTokens": 64
  }'
event:start
data:{"requestId":"demo-stream-1","promptTokens":28,"evictedMessages":0}

event:thinking
data:{"text":"Let me count syllables carefully..."}

event:token
data:{"text":"Sixty-four "}

event:token
data:{"text":"bytes aligned,\n"}

event:complete
data:{"requestId":"demo-stream-1","text":"Sixty-four bytes aligned,\n...","thinking":"Let me count syllables carefully...","thinkingDurationMs":412,"finishReason":"STOP","cancelled":false,"usage":{"inputTokens":28,"outputTokens":17,"totalTokens":45},"evictedMessages":0,"durationMs":730}

POST /api/chat — Synchronous JSON Chat

curl -s -X POST http://127.0.0.1:8080/api/chat \
  -H "Content-Type: application/json" \
  -d '{
    "requestId": "demo-sync-1",
    "messages": [
      { "role": "user", "content": "Give one reason to run GGUF models in-process on the JVM." }
    ],
    "temperature": 0.2,
    "maxOutputTokens": 128
  }'
{
  "requestId": "demo-sync-1",
  "reply": "In-process FFI eliminates loopback HTTP serialization and lets Java abort native prefill immediately.",
  "thinking": "Focus on the highest-signal systems benefit: zero loopback serialization and direct cancellation.",
  "finishReason": "STOP",
  "usage": { "inputTokens": 34, "outputTokens": 19, "totalTokens": 53 },
  "evictedMessages": 0,
  "durationMs": 418
}

POST /api/chat/stream — Multimodal Vision (When ARGUS_VISION_MMPROJ_PATH Is Set)

Supports inline Base64 (or data:image/*;base64,... URI) attachments in PNG, JPEG, WEBP, GIF, and BMP formats on "user" messages—including image-only turns (prompt omitted or blank):

IMG_B64=$(base64 -w0 sample.png)
curl -N -X POST http://127.0.0.1:8080/api/chat/stream \
  -H "Content-Type: application/json" \
  -d "{\"prompt\":\"Describe what is shown in this image.\",\"images\":[{\"mimeType\":\"image/png\",\"data\":\"${IMG_B64}\"}]}"

POST /api/chat/stop — Cooperative Native Cancellation

curl -s -X POST http://127.0.0.1:8080/api/chat/stop \
  -H "Content-Type: application/json" \
  -d '{"requestId": "demo-stream-1"}'

POST /api/audio/transcribe — Local Whisper Speech-to-Text (When ARGUS_ASR_MODEL_PATH Is Set)

# Raw RIFF/WAVE upload (also accepts audio/L16, audio/pcm, audio/f32le)
curl -s -X POST http://127.0.0.1:8080/api/audio/transcribe \
  -H "Content-Type: audio/wav" \
  --data-binary @sample.wav

# Or multipart/form-data upload
curl -s -X POST http://127.0.0.1:8080/api/audio/transcribe \
  -F "file=@sample.wav"

POST /api/audio/speech — Local Speech-LLM TTS (When ARGUS_TTS_MODEL_PATH & ARGUS_TTS_VOCODER_PATH Are Set)

curl -s -X POST http://127.0.0.1:8080/api/audio/speech \
  -H "Content-Type: application/json" \
  -d '{"text":"Hello from Project Argus running in-process on the JVM.","voice":"42"}' \
  --output reply.wav

HTTP Error Contract Summary

HTTP Status Error Codes Trigger
400 Bad Request forbidden_message_role, images_only_allowed_on_user_messages, unsupported_image_format, invalid_image_base64, image_too_large, too_many_images, context_length_exceeded, invalid_audio_format Schema, MIME/magic-byte, attachment count, decoded size, or token-window violation
413 Payload Too Large payload_too_large Raw request body exceeded dynamic ceiling (64 KiB JSON / 8 MiB Vision / 10 MiB Audio) before deserialization
429 Too Many Requests inference_busy, duplicate_request_id All ARGUS_MAX_CONCURRENT_INFERENCE permits busy (Retry-After: 2) or duplicate active requestId
503 Service Unavailable model_not_ready, vision_not_enabled, asr_not_enabled, tts_not_enabled Runtime degraded or opt-in modality requested without its configured local model

7. Automated & Opt-In Real Native Test Suite

All 43 model-free tests (unit validation, dynamic filter bounds, concurrency gate, lifecycle startup checks, Spring MVC integration, and Node VM frontend regression covering <think>, voice, vision staging, and multi-turn image shedding) execute in seconds without model weights (./mvnw test, skipping the 5 opt-in native tests cleanly).

To run the complete 48 / 48 suite including NativeModelIntegrationTest end-to-end against real GGUF/GGML models across Panama FFM (JDK 22+/25) and Portable JNI (-Pjni, --release 17):

# Full Panama FFM native multimodal gate (JDK 22 / 25 LTS)
ARGUS_CHAT_MODEL_PATH="/absolute/path/to/qwen2-vl-2b-it-Q4_K_M.gguf" \
ARGUS_VISION_MMPROJ_PATH="/absolute/path/to/qwen2-vl-2b-it-mmproj.gguf" \
ARGUS_ASR_MODEL_PATH="/absolute/path/to/whisper-base.gguf" \
ARGUS_TTS_MODEL_PATH="/absolute/path/to/OuteTTS-0.2-500M-Q4_K_M.gguf" \
ARGUS_TTS_VOCODER_PATH="/absolute/path/to/wavtokenizer-large-Q4_K_M.gguf" \
  ./mvnw test package

# Full portable JNI native multimodal gate (--release 17)
ARGUS_CHAT_MODEL_PATH="/absolute/path/to/qwen2-vl-2b-it-Q4_K_M.gguf" \
ARGUS_VISION_MMPROJ_PATH="/absolute/path/to/qwen2-vl-2b-it-mmproj.gguf" \
ARGUS_ASR_MODEL_PATH="/absolute/path/to/whisper-base.gguf" \
ARGUS_TTS_MODEL_PATH="/absolute/path/to/OuteTTS-0.2-500M-Q4_K_M.gguf" \
ARGUS_TTS_VOCODER_PATH="/absolute/path/to/wavtokenizer-large-Q4_K_M.gguf" \
  ./mvnw test package -Pjni

8. Security, Operational Boundaries & Troubleshooting

  • Loopback-Only & Strict CSP by Default: Binds strictly to 127.0.0.1:8080 with Content-Security-Policy (default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:), X-Frame-Options: DENY, and X-Content-Type-Options: nosniff enforced by WebSecurityHeadersFilter.
  • Zero-Trust Media Sandbox & Binary Magic-Byte Preflight: ArgusRuntimeManager forces .allowLocalFileMedia(false) and .allowedMediaRoot(null), blocking http:///https:// SSRF and file:// path reads unconditionally. ChatService validates padding-exact Base64 sizes before decoding and verifies PNG, JPEG, GIF87a/GIF89a, WEBP, and BMP binary signatures (400 unsupported_image_format), while AudioService validates RIFF/WAVE headers and PCM frame alignment.
  • Trusted System Prompt Ownership: Client payloads may only submit "user" and "assistant" messages; "system" and "tool" roles are rejected with 400 forbidden_message_role, and image attachments are restricted strictly to "user" turns.
  • Dynamic Route-Aware Payload Ceilings & Bounded Admission: JsonRequestBodySizeFilter enforces 64 KiB on JSON routes by default, expanding only /api/chat and /api/chat/stream to 8 MiB when ARGUS_VISION_MMPROJ_PATH is configured (and /api/audio/transcribe to 10 MiB), while InferenceConcurrencyGate rejects excess load immediately with 429 Too Many Requests (Retry-After: 2).
  • Sanitized Diagnostics: Startup validation errors ([model_not_configured], [model_file_not_found], [invalid_gguf_header], [mmproj_file_not_found], [invalid_mmproj_gguf_header], [invalid_whisper_header], [incomplete_tts_configuration], [native_runtime_unavailable]) render actionable Spring Boot FailureAnalyzer guidance on the console while never leaking host filesystem paths or stack traces over HTTP.
  • Looking for EmbeddingModel / RAG? This workbench intentionally focuses on stateless Layer-0 conversational modalities (Chat, <think>, Vision, ASR, TTS) without bundling a vector database or retrieval pipeline. For in-process bidirectional embeddings (EmbeddingGemma 2, jina-embeddings-v3, Matryoshka truncation, and EmbeddingInputType), see the upstream libargus LangChain4j Developer Cookbook.

Upstream Ecosystem & License

Released under the MIT License. Built to showcase libargus—the open-source Layer-0 native AI inference engine from ProjectArgus.cc.

About

In-process local GGUF inference, SSE token streaming, and cooperative native cancellation in Spring Boot 3.4 + LangChain4j — powered by libargus (Panama FFM & JNI).

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages