Serve Engine
Inference on your machines
SMILE Serve Engine is the inference runtime all you need. A commercial license covers production use without the AGPL network source offer.
Overview
SMILE Serve Engine is a production-ready inference server built on Quarkus that brings together three complementary inference capabilities on the JVM. A React-based web UI is bundled and served from the same process.
| Capability | API prefix | Description |
|---|---|---|
| Classic ML | /api/v1/smile | Serialized SMILE models (.sml) — classification, regression, clustering, vector quantization, and anomaly detection |
| ONNX Runtime | /api/v1/onnx | Any model in the ONNX open format (.onnx) |
| LLM Chat | /api/v1/chat | OpenAI-compatible chat completions |
| Models | /api/v1/models | OpenAI-compatible list and retrieve for every loaded model — chat, ONNX, and SMILE |
| Metrics | /q/metrics | Prometheus scrape for classic, ONNX, and LLM models |
Quick Start with Docker
The fastest way to run SMILE Serve Engine is via the pre-built Docker image. Mount a local directory containing your model files and map the port:
docker run -it \
-v /path/to/model/folder:/model \
-p 8888:8080 \
ghcr.io/haifengl/smile-serve:latest
The service starts on port 8080 inside the container (mapped to 8888 on the host). Place your .sml and .onnx model files in /path/to/model/folder; they are discovered automatically at startup.
Image Flavors
The release workflow publishes four variants of the image to the GitHub Container Registry, ghcr.io/haifengl/smile-serve. Pick one with the tag suffix: latest or 7.3.0 for the JVM image, and e.g. latest-micro or 7.3.0-native for the others.
| Tag | Image | Chat | User accounts, conversations (database) | Size |
|---|---|---|---|---|
latest | JVM (OpenJDK 25), CPU | CPU: ONNX Runtime GenAI packages | yes | 0.6 GB |
latest-gpu | JVM, NVIDIA CUDA | GPU: LibTorch (Llama, Qwen, MiniMax, DeepSeek) and ONNX Runtime GenAI | yes | 16 GB |
latest-native | GraalVM native executable, CPU | CPU: ONNX Runtime GenAI packages | yes | 0.4 GB |
latest-micro | GraalVM native executable, CPU, inference only | none | none | 0.2 GB |
All four serve SMILE (.sml) and ONNX models, the web UI, health probes (/q/health), and Prometheus metrics (/q/metrics). The published images use the local profile: users and conversation history are kept in an embedded H2 database file, /model/smile_serve, so mount /model read-write if you want them to survive restarts.
The CPU images (latest, latest-native, latest-micro) are published as multi-arch manifests for linux/amd64 and linux/arm64; the GPU image is linux/amd64 only. The native CPU baseline is x86-64-v3 (AVX2) on amd64 and armv8-a on arm64.
| Metric / Requirement | latest-micro | latest-native | latest (JVM) | latest-gpu |
|---|---|---|---|---|
| Startup (no chat model) | 0.4 s | 0.5 s | 3.4 s | 3.3 s |
| Idle memory | ~80 MiB | ~115 MiB | ~600 MiB | — |
| With a chat model loaded | n/a | 8 s, 3 GiB (Phi-4-mini, 4.6 GB package) | 11 s, 3.5 GiB (same) | 15 s, ~34 GiB GPU RAM (Llama-3.1-8B BF16, 1 GPU) |
| Cloud blob storage plugin (S3, GCS, Azure) | no | no | no | yes |
| Server-side Kirin assistant agent (OAuth-gated) | no | no | no | yes |
| Needs | x86-64-v3 or armv8-a CPU | x86-64-v3 or armv8-a CPU | any x86-64 or arm64 CPU | NVIDIA GPU, CUDA 13.4 driver, NVIDIA Container Toolkit |
Under sustained 100,000-request load across 18 tree ensembles (50–500 trees, 20–200 features) and an XGBoost ONNX model, latest-micro holds 140–178 MiB RSS with 0.34–0.65 ms p50 / 0.55–1.57 ms p99 single-row scoring and 1.26–3.97 ms p99 local GBM TreeSHAP explanations (see the full benchmark tables on Edge AI Benchmarks).
GPU Build & Run
Build the JVM+GPU image from source and run it with CUDA graph decode enabled. The image builds the Quarkus app inside Docker with the local profile by default (--build-arg QUARKUS_PROFILE=local, embedded H2 database in /model/smile_serve); pass --build-arg QUARKUS_PROFILE=prod for PostgreSQL. Mount /smile to persist per-user Kirin assistant agent workspaces (/smile/users/) and isolated local attachment blobs (/smile/blobs/) across container restarts. Google and Microsoft OAuth work out of the box on localhost using built-in sealed credentials, or you can supply custom OAuth client credentials via -Dsmile.auth.google.* / -Dsmile.auth.microsoft.* (see Authentication); keep secrets out of shell history / docker inspect by sourcing them from environment variables rather than inlining literals.
sudo docker build -f serve/src/main/docker/Dockerfile.gpu -t quarkus/smile-serve-gpu .
sudo docker run -i --rm --gpus all -p 8888:8080 \
-e JAVA_OPTS_APPEND="-Dsmile.chat.model=Qwen/Qwen3.8-27B" \
-u root -v "/llm/model":/model -v "/data/smile":/smile quarkus/smile-serve-gpu
Debug variant (adds CUDA_LAUNCH_BLOCKING=1 for synchronous CUDA error reporting; slower, use only when diagnosing a CUDA graph issue):
sudo docker run -i --rm --gpus all -p 8888:8080 \
-e CUDA_LAUNCH_BLOCKING=1 \
-e JAVA_OPTS_APPEND="-Dsmile.chat.model=Qwen/Qwen3.8-27B" \
-u root -v "/llm/model":/model quarkus/smile-serve-gpu
LLM Decode Benchmarks
Steady-state continuous-batching decode on NVIDIA A100 with FlashInfer, smile.chat.max-batch-size=48, max_tokens: 512, greedy sampling (temperature: 0), and a uniform decode cohort (smile.chat.admit-coalesce-ms=50 for parallel load tests). Step is engine decode-step throughput (batch / step_ms); aggregate is AggregateTokenThroughput over a ~3 s window (includes streaming / logging overhead).
MiniMax-M3.1-Flash
MiniMaxAI/MiniMax-M3.1-Flash (~250 GB, 428B total / 23B active MoE with MXFP8 attention + dense/shared FFNs and NVFP4 routed experts on Marlin) ships a 2.3 GB draft model (dspark/, 5 dense decoder layers, sliding window 4096) that proposes 7 tokens per round; the target verifies them in one CUDA-graph forward and keeps the longest matching prefix, so the output distribution is unchanged. It is on by default when the checkpoint has the dspark/ folder (smile.chat.speculative=false or SMILE_MINIMAX_DSPARK=0 turns it off), and works with prefix reuse, sampling, chunked prefill, and multimodal image/video requests.
Setup: 8× A100 40 GB, tensor-parallel non-expert weights, greedy, 8 chat prompts, 128 new tokens, warm graphs:
| Concurrency | Plain decode | DSpark (7 drafts) |
|---|---|---|
| One request | 25.4 ms/token (39 tok/s) | 11.7 ms/token (85 tok/s, 2.2x) |
| Drafts per round 3 / 4 / 5 / 6 | n/a | 71 / 77 / 79 / 80 tok/s |
| 2 concurrent requests (aggregate) | 64 tok/s | 126 tok/s |
| 4 concurrent requests (aggregate) | 123 tok/s | 160 tok/s |
| 8 concurrent requests (aggregate) | 210 tok/s | 214 tok/s |
The gain shrinks with concurrency (batched plain decode gets more efficient too) and is gone at 8 concurrent requests, so the service lets at most 4 requests speculate at once unless smile.chat.speculative-max-concurrency says otherwise (the rest use batched plain decode). Through the HTTP API (4 reasoning-heavy prompts, 160 tokens each, one request at a time, prefill and request overhead included), Flash answers at 67.8 tok/s with DSpark against 37.9 tok/s without (1.8x). The draft model is loaded only when smile.chat.speculative=true and costs ~3 GB on GPU 0 (adjust smile.chat.mem-fraction-static accordingly or set SMILE_MINIMAX_VISION=0).
Qwen3.8 27B
Full-batch BF16 decode (TP=4). Hybrid Qwen3.5/3.8 stack (Gated DeltaNet + full attention) at full concurrency (48 active requests) and locked positions (e.g. positions=[466..466]) across four A100 40 GB GPUs; per-request generation stays ~17 tok/s with the batch saturated:
| Checkpoint | Setup | Step | Aggregate | Step time | Forward / sample |
|---|---|---|---|---|---|
| Qwen/Qwen3.8-27B | BF16, TP=4 | 906 tok/s | ~896 tok/s | 53 ms | 51 / 1 ms |
Block-FP8 on a single 40 GB A100. Qwen/Qwen3.8-27B-FP8 (block FP8, 29 GB) runs on a single A100-40GB through the weight-only FP8 Marlin kernel (smile.chat.devices=0, mem-fraction-static=0.93, FlashInfer attention, decode CUDA graphs, no tensor parallelism) alongside fused DeltaNet decode/verify kernels (register-resident recurrent kernel at 10 µs per layer call, fused conv + split + gates + recurrent, fused residual-add + Gemma RMSNorm, and strided QK norm + RoPE). Greedy, batch 1, 11 different prompts × 256 new tokens:
| Setup (1× A100 40 GB, FP8 Marlin) | Throughput | Draft accept rate |
|---|---|---|
| Plain decode | 36.3 tok/s | n/a |
| MTP, 3 draft tokens (default) | 77.8 tok/s (2.1x) | 66 % |
| MTP, 4 draft tokens | 80.1 tok/s (2.2x) | 58 % |
An MTP round on the single-GPU FP8 setup takes ~37 ms (8.2 ms draft, 28.1 ms verify, 0.6 ms state replay). With 2 / 4 concurrent requests (200 tokens each), aggregate throughput is 70 / 129 tok/s with MTP versus 35 / 74 tok/s without.
MTP speculative decoding & concurrency scaling (BF16, TP=4). Qwen3.5/3.8 checkpoints ship a native multi-token-prediction (MTP) head. With smile.chat.speculative=true, the engine drafts speculative-tokens tokens with that head and verifies them in one target forward pass; accepted tokens are byte-for-byte what greedy decoding would have produced (lossless up to rare bf16 near-tie flips). Below is single-request progression (BF16, TP=4 on A100 40 GB, greedy, speculative-tokens=2, 512 new tokens, warm run including prefill):
| Single request (BF16, TP=4) | Throughput | Verify forward / round | Draft accept rate |
|---|---|---|---|
| Plain decode | 18.7 tok/s | n/a | n/a |
| MTP + persistent draft context (+ checkpoint replay) | 23 tok/s | 91 ms | ~73 % |
| + fused DeltaNet window + FlashInfer verify attention | 38 tok/s | 49 ms | ~75 % |
| + verify CUDA graph (default) | 52.8 tok/s (2.8x plain) | ~32 ms | ~77 % |
A round (draft + one verify + bookkeeping) takes ~48 ms and commits 2.5 tokens on average (mean accepted draft depth 1.5 of 2). Throughput gains hold at long context (6.6k-token prompt, 256 new tokens: 16.7 s with the verify graph vs 26.5 s plain). Speculating requests are drafted and verified together as one batched round, each with its own persistent draft context, so the gain holds across concurrent batches (tok/s, 512 new tokens, identical prompts, decode CUDA graph on, max-batch-size=48, admit-coalesce-ms=50, BF16 TP=4 on A100 40 GB, default mem-fraction-static=0.85):
| Active requests | Plain decode | speculative=true | Speedup |
|---|---|---|---|
| 1 | 25 | 53 | 2.1x |
| 2 | 48 | 62 | 1.3x |
| 4 | 94 | 121 | 1.3x |
| 8 | 187 | 216-236 | 1.2x |
| 16 | 335 | 408-441 | 1.2-1.3x |
| 32 | 484 | 694 | 1.4x |
| 48 | 688-702 | 811 | 1.15x |
Memory & Controls. Each speculating Qwen request reserves DeltaNet checkpoint buffers (~0.11 GB per GPU at default depth 3 for a 27B hybrid model) at load for min(max-batch-size, speculative-max-concurrency) rows before the KV pool is sized. To keep more KV slots, lower smile.chat.speculative-max-concurrency or set smile.chat.speculative=false. Controls (all default to the benchmarked values):
| Setting | Default | Meaning |
|---|---|---|
smile.chat.speculative | true | MTP speculation for Qwen3.5/3.8 checkpoints with MTP weights, DSpark speculation for MiniMax-M3.1-Flash checkpoints with a dspark/ folder (ignored for other models). Set false to disable. |
smile.chat.speculative-tokens | 0 (model default; 3 for Qwen3.8-27B, 7 for MiniMax DSpark) | Draft depth. Measured Qwen aggregate tok/s at 1 / 8 / 16 requests: depth 1: 47 / 203 / 387; depth 2: 53 / 216-236 / 408-441; depth 3 (default): 55 / 232 / 446; depth 4: 54 / 241 / 439. |
smile.chat.speculative-max-concurrency | 0 (= max-batch-size; 4 for MiniMax) | Requests that may speculate at once. A request keeps its speculation slot for its whole life; requests beyond the limit use batched plain decode. |
SMILE_DECODE_CUDA_GRAPH | on | Capture plain decode steps as CUDA graphs (needs FlashInfer attention, the default backend). 0 disables. |
SMILE_VERIFY_CUDA_GRAPH | on | Capture the verify forward as one CUDA graph (one capture per session). 0 disables. |
SMILE_MTP_HISTORY | on | Draft head keeps a persistent per-request KV of the whole prefix (prompt and accepted tokens). 0 restores the context-free legacy head. |
SMILE_MTP_VERIFY_CHECKPOINT_REPLAY | on | On a partial accept, restore the DeltaNet state saved during the verify pass instead of running a second forward. 0 disables. |
SMILE_VERIFY_CUDA_GRAPH_RAGGED | on | Also graph cohorts of 2+ requests at different positions. 0 limits the graph to a lone request (or equal positions). |
SMILE_VERIFY_CUDA_GRAPH_MAX_BATCH | 16 | Largest cohort that uses a verify graph. |
SMILE_VERIFY_FLASHINFER_EAGER | on | Use FlashInfer's paged prefill kernel for verify windows when the graph is not replaying. 0 disables. |
Llama 3.1 8B Instruct
| Checkpoint | Weight path | Step | Aggregate | Step time | Forward / sample |
|---|---|---|---|---|---|
| meta-llama/Llama-3.1-8B-Instruct | BF16 dense | 2087 tok/s | ~2036 tok/s | 23 ms | 22 / 1 ms |
| hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4 | AWQ INT4 (Marlin) | 2667 tok/s | ~2543 tok/s | 18 ms | 17 / 0 ms |
Both runs used a full batch of 48 active requests at locked positions (e.g. positions=[417..417]). AWQ is ~28% faster at the same concurrency; lighter weights also leave more free KV slots for longer context.
Building and Running
All commands use the Gradle wrapper from the project root.
Dev Mode
Live-reload development mode — changes to Java sources are reflected without restarting. The Quarkus Dev UI is available at http://localhost:8888/q/dev/.
./gradlew :serve:quarkusDev \
--jvm-args="--add-opens java.base/java.lang=ALL-UNNAMED"
The --add-opens flags are required by ONNX Runtime's Foreign Function Interface. The dev-mode HTTP port defaults to 8888 (configured via %dev.quarkus.http.port).
Packaging as a JAR
./gradlew :serve:build
This produces a Quarkus layered application in build/quarkus-app/. The entry point is build/quarkus-app/quarkus-run.jar; the dependencies live in build/quarkus-app/lib/ and must be distributed together.
Run it with:
java \
--add-opens java.base/java.lang=ALL-UNNAMED \
--add-opens java.base/java.nio=ALL-UNNAMED \
--enable-native-access ALL-UNNAMED \
-jar build/quarkus-app/quarkus-run.jar
To run on a custom port:
java \
--add-opens java.base/java.lang=ALL-UNNAMED \
--add-opens java.base/java.nio=ALL-UNNAMED \
--enable-native-access ALL-UNNAMED \
-Dquarkus.http.port=3801 \
-jar build/quarkus-app/quarkus-run.jar
Uber-JAR
A single self-contained JAR (slower to start, simpler to deploy):
./gradlew :serve:build -Dquarkus.package.jar.type=uber-jar
java \
--add-opens java.base/java.lang=ALL-UNNAMED \
--add-opens java.base/java.nio=ALL-UNNAMED \
--enable-native-access ALL-UNNAMED \
-jar build/smile-serve-runner.jar
Native Executable
Compile to a native binary with GraalVM (sub-millisecond startup, lower memory):
./gradlew :serve:build -Dquarkus.native.enabled=true
./build/smile-serve-*-runner
Without a local GraalVM installation, use a Docker-based build:
./gradlew :serve:build \
-Dquarkus.native.enabled=true \
-Dquarkus.native.container-build=true
See the Quarkus native build guide for details.
Native Image Variants & Plugins
Both native Dockerfiles build in-container from the repository root and need no host-side build:
| Dockerfile | Contents | Size |
|---|---|---|
Dockerfile.native | Full CPU image: SMILE, ONNX, CPU chat (ONNX Runtime GenAI packages), auth, and embedded H2 database. No LibTorch. | ~375 MB |
Dockerfile.micro | Inference only (-Dquarkus.profile=micro): SMILE and ONNX models plus the web UI's inference pages. No chat, auth/users, database, LibTorch, or GenAI. | ~205 MB |
Optional plugins (such as commercial/enterprise storage backends implementing smile.chat.blob.BlobStoreProvider and Prometheus telemetry implementing smile.serve.ModelMetricsBinder / smile.chat.LlmMetrics) can be placed in serve/plugins/*.jar before building so ArC indexes them into the Quarkus application.
Configuration Reference
Configuration is managed in src/main/resources/application.properties. Quarkus profile prefixes (%dev., %test.) override the base values in the corresponding profiles.
| Property | Default | Description |
|---|---|---|
quarkus.http.port | 8080 | HTTP listen port (%dev default: 8888) |
quarkus.rest.path | /api/v1 | Global REST path prefix |
smile.serve.model | ../model | Path to a .sml file or directory of .sml files |
smile.onnx.model | ../model | Path to a .onnx file or directory of .onnx files |
smile.chat.model | ../model/Llama3.1-8B-Instruct | Local HF-layout checkpoint directory, or Hugging Face repo id (owner/name). Tokenizer is resolved next to the checkpoint (original/tokenizer.model, tokenizer.model, or HF tokenizer.json for AWQ/GPTQ cards) |
smile.chat.max-seq-len | 0 (auto) | Max context (prompt+output), like vLLM --max-model-len / SGLang --context-length. <=0 uses max_position_embeddings from the model config; set explicitly (e.g. 8192) to cap large-window models such as Qwen3.5 |
smile.chat.max-batch-size | 1 | Max in-flight chat generations (InferenceEngine Fluid Injection cap). Values >1 enable continuous batching. A waiting request is admitted only when free KV can reserve its full prompt + max_tokens window (capped by max-seq-len); otherwise it stays queued. |
smile.chat.max-decode-batch | 0 (same as max-batch-size) | Cap on requests per GPU decodeStep; 0 means use max-batch-size |
smile.chat.prefill-token-budget | 2048 | Max prompt tokens prefilled per scheduler tick (chunked prefill so long prompts do not stall decode) |
smile.chat.admission-timeout-ms | 120000 | Max ms a job may wait for KV admission before failing (0 = wait until Instant Eviction frees capacity) |
smile.chat.admit-coalesce-ms | 0 | When idle, delay first admission up to this many ms so a parallel burst can fill the queue; stops early once queued >= max-batch-size. 0 disables (default). Use e.g. 50 for curl --parallel load tests |
smile.chat.mem-fraction-static | 0.85 | SGLang --mem-fraction-static: fraction y of total GPU memory for the static region (weights + DeltaNet + KV). Leaves ~(1−y)×total free for activations (plus a small soft margin). Idle use near y×total is expected. Short-prompt OOM usually means activation peak/leak during forward — try 0.75 and/or a lower max-seq-len on 40GB TP=2 Qwen desktops. Pool is static (no per-request growth); when free KV is exhausted, generation stops early with partial output (finish_reason=length) |
smile.chat.model-loader-threads | 0 (auto) | Concurrent safetensors shard readers. Each worker loads one shard to CPU then fans out to TP ranks. Peak host RAM ≈ threads × shard size. 0 = min(8, CPUs), capped by number of shard files. Use 1–2 on RAM-tight desktops |
smile.chat.devices | 0 | CUDA device index, or comma-separated TP list (0,7). %dev default: 7 |
smile.chat.tensor-parallel-size | 1 | TP world size; with a single devices entry expands to consecutive GPUs |
smile.chat.pipeline-parallel-size | 1 | Must stay 1 until multi-node PP |
smile.chat.kv-cache.dtype | (unset) | KV-cache element dtype (bfloat16, float16, float32, fp8_e4m3, fp8_e5m2, …). When unset, uses torch_dtype from the model config.json. Set fp8_e4m3 for ~2× KV capacity (longer context); attention dequants to BF16/FP16. Independent of weight quant. |
smile.chat.quantization | auto | Weight GEMM: auto / dense / fp8 / nvfp4 / marlin. auto selects FP8/NVFP4 on Hopper/Blackwell for native checkpoints, Marlin on Ampere/Ada for GPTQ/AWQ. GPTQ/AWQ on Hopper+ fails fast (no silent Marlin). Qwen hybrid: native FP8 (e.g. Qwen3.8-FP8) on H100+ (sm_90+) uses block-128 weight_scale_inv via LibTorch _scaled_mm_v2 (Fp8BlockLinear); rebuild libsmile_torch after pulling. Vision tower and lm_head stay BF16. A100 still fails fast on native FP8 Qwen. GPTQ/AWQ/Marlin for Qwen remain unsupported. Marlin AWQ/GPTQ install batch-reads each safetensors shard once and packs linears in parallel (direct int4→Marlin, no FP16 round-trip); expect on the order of tens of seconds for 8B AWQ on A100 rather than multi-minute phase-1 loads. GPTQ act-order (g_idx) is rejected. |
smile.chat.kv-cache.page-size | 16 | Tokens per radix / KV pool page (prefix match and insert are page-aligned) |
smile.chat.kv-cache.prefix-reuse | true | Match/insert prompts in the radix KV tree (SGLang-style). Hybrid Qwen also needs hybrid-prefix-replay |
smile.chat.kv-cache.hybrid-prefix-replay | true | On a hybrid Qwen prefix hit, replay the matched prefix to restore DeltaNet state while sharing KV pages. Set false to force-disable hybrid prefix reuse |
smile.chat.oga.enabled | true | When Torch path is not selected, try ORT GenAI for GenAI-ready models (incl. nested HF packages / Olive cache) |
smile.chat.oga.precision | (auto) | Cache-key / offline Olive optimize --precision; empty/auto uses cascade default (int4 — optimize does not accept fp8) |
smile.chat.oga.cache-dir | {SMILE_CACHE}/olive | Olive output cache root (never writes into HF_HOME hub trees); serve opens hits at startup |
smile.chat.oga.olive-command | olive | Olive CLI executable for offline conversion only (not run at startup) |
smile.chat.oga.device / provider | (cascade) | Optional Olive overrides for offline convert / cache key; default from GenAI.resolveOliveTarget() |
quarkus.datasource.db-kind | postgresql | Database backend for chat history |
quarkus.datasource.jdbc.url | jdbc:postgresql://localhost:5432/smile | JDBC connection URL |
quarkus.hibernate-orm.active | false | Enable ORM (set true when database is available) |
smile.home.users | /smile/users | Base directory for per-user Kirin agent homes (SMILE_USERS_DIR env overrides) |
smile.auth.local-me.enabled | true | Auto-sign in as local me on localhost (raw LLM chat only; does not activate Kirin) |
smile.auth.google.client-id / client-secret / redirect-uri | (built-in vault) | Custom Google OAuth 2.0 app credentials (latest-gpu falls back to built-in OAuthClientVault on localhost) |
smile.auth.microsoft.client-id / client-secret / tenant-id / redirect-uri | (built-in vault, common) | Custom Microsoft Entra ID / Outlook.com OAuth 2.0 app credentials (latest-gpu falls back to built-in OAuthClientVault) |
smile.auth.session-secret | (dev default) | HMAC signing secret for session cookies; always override in production |
Override at runtime with -D system properties, for example:
java ... -Dsmile.serve.model=/data/models/rf_classifier.sml -jar quarkus-run.jar
Classic ML Inference API
Model Format
Classic ML models are serialized Java objects saved in .sml files by the SMILE smile.model.Model framework. Supported model types are:
ClassificationModel— supervised classifiers (random-forest,gradient-boost,ada-boost,cart,logistic,fisher,lda,qda,rda,mlp,svm,rbf)RegressionModel— supervised regressors (random-forest,gradient-boost,cart,ols,lasso,ridge,elastic-net,gaussian-process,mlp,svm,rbf)ClusteringModel— centroid-based clustering (kmeans,xmeans,gmeans,deterministic-annealing)VectorQuantizerModel— online vector quantizers and competitive learning models (som,neural-gas,growing-neural-gas,neural-map,birch)AnomalyModel— anomaly and novelty detectors (isolation-forest,lof,ocsvm)
Each .sml file carries the trained algorithm (and optional feature Transform), input feature schema, training/validation metrics, and optional metadata tags (id, version, user-defined properties). Models that support incremental updates (VectorQuantizerModel and online classifiers/regressors) expose "online": true in GET /api/v1/smile/{id} and can be updated in place via POST /api/v1/smile/{id}/update and POST /api/v1/smile/{id}/update/stream (restricted to localhost).
At startup, InferenceService scans the path specified by the property smile.serve.model. If the path is a regular .sml file only that model is loaded; if it is a directory every .sml file in the directory is loaded.
Get Model Metadata
Returns the algorithm name, input schema, and tags for a model. Use GET /api/v1/models to discover loaded model IDs.
GET /api/v1/smile/{id}
Example:
curl http://localhost:8080/api/v1/smile/iris_random_forest-1
{
"id": "iris_random_forest-1",
"algorithm": "random-forest",
"schema": {
"petallength": { "type": "float", "nullable": false },
"petalwidth": { "type": "float", "nullable": false },
"sepallength": { "type": "float", "nullable": false },
"sepalwidth": { "type": "float", "nullable": false }
},
"tags": {
"smile.random_forest.trees": "200"
}
}
The schema object lists every input feature in alphabetical order — this is the column order used by the CSV streaming endpoint.
Single Inference (JSON)
POST /api/v1/smile/{id}
Content-Type: application/json
The request body is a flat JSON object whose keys are the feature names defined in the model schema. All non-nullable fields are required.
Classification example (iris):
curl -X POST http://localhost:8080/api/v1/smile/iris_random_forest-1 \
-H "Content-Type: application/json" \
-d '{
"sepallength": 5.1,
"sepalwidth": 3.5,
"petallength": 1.4,
"petalwidth": 0.2
}'
{
"prediction": 0,
"probabilities": [0.960, 0.021, 0.019]
}
prediction— the predicted class label (integer) or regression value (float).probabilities— posterior class probabilities for soft classifiers (e.g. random forest, logistic regression). Absent for hard classifiers and regressors.explanations— optional model explanation object (present when requested).
Explanations (TreeSHAP & KernelSHAP)
Explanations can be requested by passing "enableExplanations": true in the JSON body, or appending ?explain=true to the URL.
curl -X POST "http://localhost:8080/api/v1/smile/iris_random_forest-1?explain=true" \
-H "Content-Type: application/json" \
-d '{
"sepallength": 5.1,
"sepalwidth": 3.5,
"petallength": 1.4,
"petalwidth": 0.2
}'
{
"prediction": 0,
"probabilities": [0.960, 0.021, 0.019],
"explanations": {
"shap": [
[0.012, -0.045, 0.123, -0.002],
[-0.034, 0.056, -0.210, 0.015],
[0.022, -0.011, 0.087, -0.013]
]
}
}
- For classification models (tree models via TreeSHAP, and non-tree classifiers via KernelSHAP),
shapis a 2D array of floats with dimension[classes][features], formatted to 3 decimal places. - For regression models (tree models via TreeSHAP, linear models, and non-tree regressors via KernelSHAP),
shapis a 1D array of floats with dimension[features]. - For custom models that do not support SHAP,
shapreturns"Not supported".
For models using KernelSHAP, optional per-request parameters can be passed as query parameters (?samples=N&ridge=R) or in the JSON request body (shapSamples, shapRidge, or "shap": {"samples": N, "ridge": R}):
| Query param | JSON field | Type | Default | Description |
|---|---|---|---|---|
samples | shapSamples / shap.samples | int | 0 (auto: 2 * M + 2048) | Maximum number of feature coalitions to evaluate per instance (>= 0). |
ridge | shapRidge / shap.ridge | double | 1e-8 | L2 regularization penalty for weighted least squares (>= 0, finite). |
curl -X POST "http://localhost:8080/api/v1/smile/iris_lda-1?explain=true&samples=256&ridge=1e-6" \
-H "Content-Type: application/json" \
-d '{
"sepallength": 5.1,
"sepalwidth": 3.5,
"petallength": 1.4,
"petalwidth": 0.2
}'
Error responses:
| HTTP | Cause |
|---|---|
400 Bad Request | Missing required field, malformed JSON, or invalid SHAP parameters (samples < 0 or ridge < 0 / non-finite) |
404 Not Found | Unknown model ID |
Streaming Inference (CSV / JSON-lines)
Process many samples in a single request. The server returns results as a Server-Sent Events stream emitting structured JSON objects — one data: line per input sample. Append ?explain=true to include explanations in each streaming event.
POST /api/v1/smile/{id}/stream
Content-Type: text/plain ← CSV mode
Content-Type: application/json ← JSON-lines mode
CSV mode (text/plain)
Each non-blank line is a comma-separated row of feature values in the same column order as the model schema (alphabetical by field name, as shown by GET /api/v1/smile/{id}).
cat iris.csv | curl -X POST \
-H "Content-Type: text/plain" \
--data-binary @- \
http://localhost:8080/api/v1/smile/iris_random_forest-1/stream
Where iris.csv might contain:
5.1,3.5,1.4,0.2
6.7,3.0,5.2,2.3
5.8,2.7,4.1,1.0
The response stream (SSE format emitting JSON payloads):
data: {"prediction":0,"probabilities":[0.960,0.021,0.019]}
data: {"prediction":2,"probabilities":[0.012,0.051,0.937]}
data: {"prediction":1,"probabilities":[0.031,0.752,0.217]}
JSON-lines mode (application/json)
Each non-blank line must be a complete JSON object (one per line). This is more verbose but supports named fields in any order. Each sample can also independently include "enableExplanations": true.
cat iris.jsonl | curl -X POST \
-H "Content-Type: application/json" \
--data-binary @- \
http://localhost:8080/api/v1/smile/iris_random_forest-1/stream
Where iris.jsonl contains:
{"sepallength":5.1,"sepalwidth":3.5,"petallength":1.4,"petalwidth":0.2}
{"sepallength":6.7,"sepalwidth":3.0,"petallength":5.2,"petalwidth":2.3,"enableExplanations":true}
Model IDs
A model's ID is constructed as <name>-<version> from the model's embedded metadata tags (smile.model.Model.ID and smile.model.Model.VERSION). If those tags are absent, the file name stem is used as the name and "1" as the version. For example, a file named iris_random_forest.sml with no ID tag gets the ID iris_random_forest-1.
ONNX Inference API
The ONNX endpoint exposes any model in the ONNX open format through SMILE's native ONNX Runtime binding (smile.onnx). This covers models exported from PyTorch, TensorFlow, scikit-learn (via sklearn-onnx), and many other frameworks. Classical ONNX inference is documented on ONNX.
Model Format
At startup, OnnxService scans the folder specified by the property smile.onnx.model. Every .onnx file found is loaded into an InferenceSession. The model ID is the file name without the .onnx extension (e.g., resnet50.onnx → ID resnet50).
Native library: the ONNX Runtime shared library (libonnxruntime.so / libonnxruntime.dylib / onnxruntime.dll) must be on the OS library search path, and the JVM must include --enable-native-access=ALL-UNNAMED. If the library is missing, startup continues without ONNX models (endpoints return 404) rather than aborting the whole serve process. Download pre-built binaries from the ORT releases page.
Get ONNX Model Info
Returns graph metadata and the typed, shaped input/output node descriptors. Use GET /api/v1/models to discover loaded model IDs.
GET /api/v1/onnx/{id}
curl http://localhost:8080/api/v1/onnx/resnet50
{
"id": "resnet50",
"graphName": "ResNet50",
"description": "Image classification model",
"version": 1,
"inputs": [
{
"name": "input",
"onnxType": "TENSOR",
"elementType": "FLOAT",
"shape": [1, 3, 224, 224]
}
],
"outputs": [
{
"name": "output",
"onnxType": "TENSOR",
"elementType": "FLOAT",
"shape": [1, 1000]
}
],
"customMeta": {}
}
A shape value of -1 means that dimension is dynamic (determined at inference time from the input data).
Single Inference (JSON)
POST /api/v1/onnx/{id}
Content-Type: application/json
The request body is a JSON object mapping each input name to a flat JSON array of numbers or strings. The server constructs the required ORT tensor from the declared element type and shape.
Example — image classification (resnet50, 1×3×224×224 = 150528 floats):
curl -X POST http://localhost:8080/api/v1/onnx/resnet50 \
-H "Content-Type: application/json" \
-d '{"input": [0.485, 0.456, 0.406, ...]}'
The Infer UI image path resizes to the model's H×W, scales to [0, 1], then applies ImageNet channel normalization (x - mean) / std with mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225] (NCHW or NHWC as declared). When posting tensors yourself, use the same layout and normalization the model was trained with.
Response — a JSON object mapping each output name to a flat array of raw logits (not probabilities) or strings. ImageNet classifiers from the ONNX Model Zoo typically omit a Softmax node; apply MathEx.softmax before interpreting scores as class probabilities (same as InferenceSessionTest in core).
{
"output": [0.001, 0.002, 0.872, 0.003, ...]
}
Multi-input model example:
curl -X POST http://localhost:8080/api/v1/onnx/bert_classifier \
-H "Content-Type: application/json" \
-d '{
"input_ids": [101, 2054, 2003, 1996, 3007, 1997, 2605, 1029, 102],
"attention_mask": [1, 1, 1, 1, 1, 1, 1, 1, 1 ],
"token_type_ids": [0, 0, 0, 0, 0, 0, 0, 0, 0 ]
}'
String input model example (e.g. scikit-learn pipeline with categorical string features or text inputs):
curl -X POST http://localhost:8080/api/v1/onnx/pipeline_classifier \
-H "Content-Type: application/json" \
-d '{
"category": ["electronics", "apparel"],
"rating": [4.5, 3.0]
}'
Supported input element types:
| ONNX type | JSON values | ORT type |
|---|---|---|
FLOAT | numbers | float[] |
DOUBLE | numbers | double[] |
INT32 | integers | int[] |
INT64 | integers | long[] |
INT8 / UINT8 / BOOL | integers (0/1 for bool) | byte[] |
STRING | strings | String[] |
Error responses:
| HTTP | Cause |
|---|---|
400 Bad Request | Missing input, wrong element count, type mismatch |
404 Not Found | Unknown model ID |
Streaming Inference
Identical in structure to the classic ML streaming endpoint but returns JSON objects:
POST /api/v1/onnx/{id}/stream
Content-Type: text/plain ← CSV floats for single-input models
Content-Type: application/json ← JSON-lines for multi-input models
CSV (single-input models only):
cat features.csv | curl -X POST \
-H "Content-Type: text/plain" \
--data-binary @- \
http://localhost:8080/api/v1/onnx/my_classifier/stream
Each response line is a compact JSON object:
data: {"output":[0.02,0.95,0.03]}
data: {"output":[0.88,0.07,0.05]}
JSON-lines (any number of inputs):
cat samples.jsonl | curl -X POST \
-H "Content-Type: application/json" \
--data-binary @- \
http://localhost:8080/api/v1/onnx/bert_classifier/stream
Tensor Types and Shape Resolution
The server automatically resolves the ORT tensor shape from the model's declared input shape and the actual array length:
- Fully static shape (no
-1dimensions) — the array length must exactly match the product of all dimensions. A mismatch returns HTTP 400. - Single dynamic dimension — the unknown dimension is inferred as
arrayLength / product(staticDimensions). For example, a declared shape[-1, 3, 224, 224]with 150528 elements resolves to[1, 3, 224, 224]. - Multiple dynamic dimensions — the shape is set to
[1, arrayLength]. - No shape info — the shape is set to
[1, arrayLength].
LLM Chat API
SMILE Serve Engine includes a Java implementation of Large Language Models for on-premise LLM inference. The chat API is designed to be compatible with the OpenAI Chat Completions interface.
The LLM is optional: if the path specified by the property smile.chat.model does not exist on the file system (and cannot be resolved via Hugging Face / OGA), ChatService starts in an unavailable state and every request to the chat endpoints returns HTTP 503 Service Unavailable.
Backend selection: with CUDA and a builtin Llama/Qwen/MiniMax/DeepSeek checkpoint, serve uses the Torch path + continuous batching. Otherwise it falls back to ONNX Runtime GenAI (GenAiChatModel) when the model is already GenAI-ready (genai_config.json at the repo root or under provider folders such as cuda/cuda-int4-…/, or a prior Olive cache under {SMILE_CACHE}/olive). Serve does not run Olive at startup — convert offline with smile.chat.Olive (see smile.chat.oga.*). Tools input / structured tool_calls output work on the serial GenAI path; multimodal GenAI materializes media to temp files. See ONNX GenAI.
There are therefore two ways to run a chat model — the native (LibTorch) path for the built-in Llama-3.1, Qwen3.5/3.8, MiniMax-M3 / M3.1-Flash, and DeepSeek-V4.1 implementations, and the ONNX Runtime GenAI path for every other family packaged as a GenAI-ready directory.
Supported Models
The native path covers Llama-3.1, Qwen3.5/3.8, MiniMax-M3 / M3.1-Flash, and DeepSeek-V4.1 checkpoints. Every other family is served through ONNX Runtime GenAI and needs only a GenAI-ready package — published on the Hugging Face Hub, converted offline with Olive (smile.chat.Olive, see ONNX GenAI), or built with the ONNX Runtime GenAI model builder. Pass any repo id below (or a local directory) to smile.chat.model:
./gradlew :serve:quarkusDev "-Dsmile.chat.model=microsoft/Phi-4-mini-instruct-onnx"
Language models (decoder-only). The runtime dispatches on the architecture recorded in genai_config.json; the checkpoint listed for each family is a known-good, GenAI-ready Hub repository.
Vision-language models. GenAiChatModel accepts local image/audio paths through MultiModalProcessor; serve materializes data-URL / HTTP media to temp files first.
| Family | GenAI architecture | Example GenAI-ready checkpoint |
|---|---|---|
| Phi-3 Vision / Phi-4 multimodal | phi3v | microsoft/Phi-3.5-vision-instruct-onnx, microsoft/Phi-4-multimodal-instruct-onnx |
| Qwen-VL / Qwen2.5-VL / Qwen3-VL | qwen2_vl | build with the model builder from the Qwen VL checkpoints |
Audio models. Whisper speech recognition is supported by the runtime; select it outside the chat API (the chat endpoint is text-only).
| Family | GenAI architecture | Example GenAI-ready checkpoint |
|---|---|---|
| Whisper | whisper | tonythethompson/Whisper-Tiny-GenAI-ONNX, tonythethompson/whisper-large-v3-genai |
The architecture list mirrors the upstream ONNX Runtime GenAI supported models and model-builder support matrix; the checkpoint ids are Hub repositories that ship genai_config.json. File layouts and provider folders vary per repo — GenAiModelPaths auto-detects the nested package (CUDA / DirectML / CPU) that matches your execution provider.
List models
GET /api/v1/models
OpenAI-compatible catalog of all loaded models — chat LLMs, ONNX graphs, and SMILE .sml models. Inference still uses type-specific paths: /api/v1/chat/completions, /api/v1/onnx/{id}, /api/v1/smile/{id}.
curl http://localhost:8080/api/v1/models
{
"object": "list",
"data": [
{
"id": "meta-llama/Llama-3.1-8B-Instruct",
"object": "model",
"created": 1741900000,
"owned_by": "meta-llama",
"shutdown_date": null,
"kind": "LLM"
},
{
"id": "iris_random_forest-1",
"object": "model",
"created": 1710000000,
"owned_by": "Unknown",
"shutdown_date": null,
"kind": "random-forest"
},
{
"id": "resnet50",
"object": "model",
"created": 1710000000,
"owned_by": "Unknown",
"shutdown_date": null,
"kind": "ONNX"
}
]
}
kind values:
LLM— chat / completion modelsONNX— ONNX Runtime graphs- SMILE algorithm name — e.g.
random-forest,cart,logistic(from the.smlmodel)
owned_by rules:
- Chat (HF): first segment of the repo id (
meta-llama/...→meta-llama) - Chat (local): first segment of
Llama.family()(meta/llama3→meta) - SMILE
.sml: tagauthor, elseowner; otherwiseUnknown - ONNX: custom metadata
author/ownerwhen present; otherwiseUnknown
Retrieve model
GET /api/v1/models/{id}
OpenAI-compatible retrieve model. Returns the same base ModelObject fields as list entries, plus an optional type-specific detail block. Does not run inference — use /chat/completions, /onnx/{id}, or /smile/{id} for that. Ids may contain slashes (e.g. Hugging Face repo ids).
kind | Extra field | Contents |
|---|---|---|
| SMILE algorithm | smile | formula, schema, tags, train / validation / test metrics (finite values only) |
ONNX | onnx | producer, domain, graph info, I/O shapes, custom metadata from the .onnx file |
LLM | llm | family, source (local/huggingface), architecture from config.json / params.json |
List responses omit smile / onnx / llm so the catalog stays lean.
curl http://localhost:8080/api/v1/models/iris_random_forest-1
{
"id": "iris_random_forest-1",
"object": "model",
"created": 1710000000,
"owned_by": "Unknown",
"shutdown_date": null,
"kind": "random-forest",
"smile": {
"formula": "class ~ .",
"schema": {
"petallength": { "type": "float", "nullable": false }
},
"tags": {},
"train": {
"accuracy": 0.97,
"size": 150
},
"validation": null,
"test": null
}
}
Chat Completions
POST /api/v1/chat/completions
Content-Type: application/json
Tokens are streamed back as Server-Sent Events when stream is true, or returned as a single OpenAI chat.completion JSON object when stream is false or omitted (OpenAI default). The conversation (user message + assistant reply) is automatically persisted to the configured database after generation finishes.
Serve runs an InferenceEngine continuous-batching loop (Fluid Injection admission, chunked prefill, batched decode, Instant Eviction on abort). Offline library callers may still use LanguageModel.generate; HTTP chat always goes through the engine. Client disconnect on an SSE stream aborts the GenerationHandle, which Instant-Evicts that request's KV pages without stopping peer in-flight generations.
Request body fields (snake_case):
| Field | Type | Default | Description |
|---|---|---|---|
model | string | loaded model | Must match the loaded model id when set (HF repo id or local directory name); omit/empty to use the loaded model |
messages | Message[] | required | Ordered dialog turns |
conversation | string | null | Existing conversation id (conv_<n>) to append to |
max_tokens | int | remaining context | Max new tokens (legacy OpenAI name). Default: max-model-len − prompt_len |
max_completion_tokens | int | — | Alias for max_tokens; takes precedence when set |
temperature | double | 0.6 | Sampling temperature (higher = more random) |
top_p | double | 0.9 | Nucleus-sampling threshold |
logprobs | boolean | false | Include log-probabilities |
seed | long | 0 | Random seed (0 = non-deterministic) |
stream | boolean | false | true → SSE chunks; false/omitted → single chat.completion JSON |
tools | array | — | OpenAI tool definitions (type: function) for Qwen3 / Qwen3.5 / Qwen3.8 |
tool_choice | string|object | auto | auto / none / required / {"type":"function","function":{"name":"…"}} |
parallel_tool_calls | boolean | true | Allow multiple tool calls in one assistant turn |
Each Message has a role (system, user, assistant, or tool) and content. Assistant turns may include tool_calls; tool-result turns use role: "tool" and tool_call_id. Legacy "ipython" is accepted as an alias for "tool".
Tool calling (Qwen3 / Qwen3.5 / Qwen3.8)
OpenAI-compatible tool calling is supported for latest Qwen checkpoints (XML <tool_call> format). Clients run tools locally and continue the dialog:
curl -X POST http://localhost:8080/api/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "What is the weather in SF?"}],
"tools": [{
"type": "function",
"function": {
"name": "get_current_temperature",
"description": "Get temperature for a location",
"parameters": {
"type": "object",
"properties": {"location": {"type": "string"}},
"required": ["location"]
}
}
}],
"tool_choice": "auto"
}'
A successful tool-call response uses finish_reason: "tool_calls" and message.tool_calls[]. Append tool results as {"role":"tool","tool_call_id":"…","content":"…"} and call again for the final answer. Streaming (v1) buffers the completion and replays delta.tool_calls at the end (not token-true XML streaming).
Smoke test with the OpenAI Python SDK:
python serve/scripts/test_tool_calling.py --base-url http://localhost:8888/api/v1
Streaming example (stream: true):
curl -X POST http://localhost:8080/api/v1/chat/completions \
-H "Content-Type: application/json" \
-N \
-d '{
"stream": true,
"messages": [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"}
],
"max_tokens": 256,
"temperature": 0.7
}'
The response is an SSE stream of OpenAI-shaped chat.completion.chunk JSON events, terminated by data: [DONE].
Non-streaming example (stream omitted or false):
curl -X POST http://localhost:8080/api/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [
{"role": "user", "content": "What is the capital of France?"}
],
"max_completion_tokens": 256
}'
{
"id": "chatcmpl-...",
"object": "chat.completion",
"created": 1741900000,
"model": "meta-llama/Llama-3.1-8B-Instruct",
"choices": [
{
"index": 0,
"message": { "role": "assistant", "content": "Paris." },
"logprobs": null,
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 20,
"completion_tokens": 3,
"total_tokens": 23
}
}
Example — continue a previous conversation:
curl -X POST http://localhost:8080/api/v1/chat/completions \
-H "Content-Type: application/json" \
-N \
-d '{
"conversation": 42,
"messages": [
{"role": "user", "content": "What about Germany?"}
]
}'
Conversation History API
Chat history is stored in a relational database (PostgreSQL in production, H2 in dev mode). The API base path is /api/v1/conversations.
Conversations are scoped to authenticated users. Guests (no session) may still create conversations and chat, but those rows are tied to client IP and do not appear in the sidebar list until the user signs in (recent guest threads from the same IP within 24 hours are merged on login).
On localhost or 127.0.0.1 (any port), the server auto-logs you in as the local me account so dev workflows work without OAuth.
Authentication
The authentication endpoints manage user identity for conversation history, personal settings, and (on latest-gpu) server-side Kirin Agent Mode. Both Google and Microsoft OAuth 2.0 flows use Authorization Code + S256 PKCE and request unified identity, Mail, and Calendar scopes so a single sign-in powers both web chat history and each user's isolated Email/Calendar tools. Note that this is a session-cookie identity mechanism intended for personal and small-office use, not an enterprise API gateway: ML/ONNX inference endpoints remain unauthenticated at the engine level.
| Endpoint | Description |
|---|---|
GET /api/v1/auth/me | Current user (logged_in, user profile, agent_mode, enabled OAuth providers) or guest |
GET /api/v1/auth/login/google | Redirect to Google OAuth 2.0 + S256 PKCE |
GET /api/v1/auth/callback/google | Google OAuth callback (sets session cookie and provisions /smile/users/<user-key>/.smile/ for Kirin on GPU builds) |
GET /api/v1/auth/login/microsoft | Redirect to Microsoft Entra ID / Outlook.com OAuth 2.0 + S256 PKCE |
GET /api/v1/auth/callback/microsoft | Microsoft OAuth callback (sets session cookie and provisions /smile/users/<user-key>/.smile/ for Kirin on GPU builds) |
POST /api/v1/auth/logout | Clear session |
GET /api/v1/users/me | Profile (authenticated) |
PATCH /api/v1/users/me | Update display name, avatar URL, personal instructions |
In latest-gpu (where ioa-agent is bundled), Google and Microsoft OAuth work out of the box on localhost using Studio's built-in OAuthClientVault. For custom LAN/WAN domains or non-GPU images, configure your own OAuth app credentials in application.properties (or via environment variables / -D system properties):
# Google OAuth 2.0 (optional override on latest-gpu)
smile.auth.google.client-id=${GOOGLE_CLIENT_ID}
smile.auth.google.client-secret=${GOOGLE_CLIENT_SECRET}
# Optional; default is {origin}/api/v1/auth/callback/google
# smile.auth.google.redirect-uri=https://your-host/api/v1/auth/callback/google
# Microsoft Entra ID / Outlook.com OAuth 2.0 (optional override on latest-gpu)
smile.auth.microsoft.client-id=${MICROSOFT_CLIENT_ID}
# smile.auth.microsoft.client-secret=${MICROSOFT_CLIENT_SECRET}
# smile.auth.microsoft.tenant-id=common
# Optional; default is {origin}/api/v1/auth/callback/microsoft
# smile.auth.microsoft.redirect-uri=https://your-host/api/v1/auth/callback/microsoft
# Persistent per-user Kirin homes (default: /smile/users; SMILE_USERS_DIR env overrides)
smile.home.users=/smile/users
smile.auth.session-secret=${SMILE_SESSION_SECRET}
Register the callback redirect URI in Google Cloud Console or Microsoft Entra ID when using custom OAuth credentials. Personal instructions from the user profile are injected as the chat system prompt (and synced to SMILE.local.md in the user's Kirin workspace).
Server-Side Kirin Assistant Agent (latest-gpu)
In the GPU container flavor (ghcr.io/haifengl/smile-serve:latest-gpu), SMILE Serve Engine embeds Kirin, a server-side personal and small-office assistant built on the ioa agent runtime. Browser and mobile users connecting to /chat get multi-step tool execution directly against your local GPU LLM without installing the desktop IDE.
- Strict OAuth Activation Gate: Kirin Agent Mode activates only for users signed in via Login with Google or Login with Microsoft. Unauthenticated guests and the localhost auto-login
meaccount always bypass Kirin and run standard raw LLM completions againstChatService. - Host-Safe 6-Tool Allowlist: Kirin is strictly restricted to
WebFetch,WebSearch,Email,Calendar,Skill, andTodoWrite. Host shell and filesystem mutation tools (Bash,PowerShell,Write,Edit,ApplyPatch,KillShell,NotebookEdit,Computer) are never exposed in web chat—even if a user editsAGENT.mdon the mounted volume. - Per-User Isolated Workspaces (
/smile/users/<user-key>/.smile/): On first OAuth login, SMILE Serve Engine provisions a deterministic, collision-resistant home directory under/smile/users/containingagents/kirin/AGENT.md,agents/kirin/skills/,conf/email.json,conf/calendar.json, and an isolatedcredentials/SecretStore. Each user'sEmailandCalendartools are bound strictly to their own workspace context with zero cross-user token leakage. - Custom Skills on the Mounted Volume: Drop custom
SKILL.mddirectories into/smile/users/<user-key>/.smile/agents/kirin/skills/(or customizeAGENT.md) on the mounted/smilevolume and Kirin discovers and invokes them via theSkilltool. - In-Process Local LLM Loopback: Multi-turn tool-calling loops execute against SMILE Serve Engine's own loaded GPU model over local loopback and stream tokens back to
/chatvia SSE.
Create, retrieve, update, and delete follow the OpenAI Conversations shapes. Conversation ids are strings of the form conv_<n>. List, PATCH (title/pin), and GET .../items are SMILE extensions.
List conversations (SMILE extension, requires login)
GET /api/v1/conversations?pageIndex=0&pageSize=25&q=search&pinned=true
Returns the signed-in user's conversations (title, pinned, updated_at). Search matches title and message content.
curl "http://localhost:8080/api/v1/conversations?pageSize=10"
Create a conversation
POST /api/v1/conversations
Content-Type: application/json
Optional body fields: metadata (≤16 string pairs) and items (≤20 message items with role + text content).
curl http://localhost:8080/api/v1/conversations \
-H "Content-Type: application/json" \
-d '{"metadata":{"topic":"demo"},"items":[{"type":"message","role":"user","content":"Hello!"}]}'
{
"id": "conv_1",
"object": "conversation",
"created_at": 1741900000,
"metadata": {"topic": "demo"}
}
Retrieve a conversation
GET /api/v1/conversations/{conversation_id}
Update a conversation
POST /api/v1/conversations/{conversation_id}
Content-Type: application/json
curl http://localhost:8080/api/v1/conversations/conv_1 \
-H "Content-Type: application/json" \
-d '{"metadata":{"topic":"project-x"}}'
Patch sidebar fields (SMILE extension, requires ownership)
PATCH /api/v1/conversations/{conversation_id}
Content-Type: application/json
{"title": "My chat", "pinned": true}
Delete a conversation
DELETE /api/v1/conversations/{conversation_id}
{
"id": "conv_1",
"object": "conversation.deleted",
"deleted": true
}
Get conversation messages (SMILE extension)
GET /api/v1/conversations/{conversation_id}/items?pageIndex=0&pageSize=25
Returns the individual message turns (role + content + createdAt) in chronological order.
curl http://localhost:8080/api/v1/conversations/conv_42/items
[
{ "id": 1, "conversationId": 42, "role": "user", "content": "What is the capital of France?", "createdAt": "2026-04-15T10:00:00Z" },
{ "id": 2, "conversationId": 42, "role": "assistant", "content": "The capital of France is Paris.", "createdAt": "2026-04-15T10:00:02Z" }
]
Web UI
A React-based web interface is bundled via Quarkus Quinoa. It is served from the root URL and provides:
- Inference UI (
/infer) — unified model shell: collapsible sidebar lists chat, SMILE (.sml), and ONNX (.onnx) models. Selecting a chat model embeds the chat module with a collapsible right nav (history, login, settings). SMILE models get a schema-driven form with an Explain (SHAP) toggle (displaying the activeTreeSHAP,LinearSHAP, orKernelSHAPmethod plus inlineSamplesandRidgecontrols for KernelSHAP) and an inline bottom SHAP explanation pane rendering interactive Waterfall, Force, and Decision plots for any selected prediction row. ONNX models get a numeric form from tensor shapes, or an image upload when a 4-D vision-like input is detected (overrideable). - Chat UI (
/chat) — standalone chat with the same right nav panel (New Chat always available; history, settings, and Login with Google / Login with Microsoft buttons). Streaming tokens, Markdown/math. On localhost, you are auto-signed-in asme(raw LLM chat) with quick OAuth buttons to switch into Kirin Agent Mode onlatest-gpu—indicated by the Kirin badge beside your display name.
Database
Chat conversation history requires a relational database (not required for the ML or ONNX inference endpoints, or for the micro profile):
| Profile | Backend | URL |
|---|---|---|
local (Docker default) | H2 (embedded file) | jdbc:h2:file:/model/smile_serve |
prod | PostgreSQL | jdbc:postgresql://localhost:5432/smile |
micro | None | Disabled (inference-only native image) |
dev / test | H2 (file / in-memory) | jdbc:h2:file:./build/smile_serve / jdbc:h2:mem:test;DB_CLOSE_DELAY=-1 |
To enable the database in production set:
quarkus.hibernate-orm.active=true
quarkus.datasource.username=<user>
quarkus.datasource.password=<password>
Hibernate ORM uses drop-and-create by default. Change the strategy in production to update or validate:
quarkus.hibernate-orm.schema-management.strategy=update
The database is not required for the ML or ONNX inference endpoints — only for chat conversation persistence.
Testing
./gradlew :serve:test
The test profile (%test.*) configures the service with:
- An in-memory H2 database (no external database required).
- A pre-trained iris random forest model from
serve/src/test/resources/model/iris_random_forest.sml. - The ONNX model path also pointed at the test resources directory (no
.onnxfiles present by default, soOnnxServicestarts empty). - The chat model path set to a non-existent path so
ChatServicestarts gracefully unavailable without attempting to load a GPU model.
The test class InferenceResourceTest covers:
| Test | Endpoint | Scenario |
|---|---|---|
testGetModelMetadata | GET /smile/{id} | Returns algorithm, schema, and nullability |
testGetUnknownModelReturns404 | GET /smile/{id} | 404 for unknown ID |
testPredictJsonReturnsPredictionAndProbabilities | POST /smile/{id} | Correct label + probabilities |
testPredictJsonWithZeroFeaturesReturnsValidPrediction | POST /smile/{id} | Edge case: all-zero features |
testPredictJsonMissingFieldReturns400 | POST /smile/{id} | 400 for missing field |
testPredictUnknownModelReturns404 | POST /smile/{id} | 404 for unknown model |
testStreamCsvReturnsPredictions | POST /smile/{id}/stream | 3 CSV rows → 3 SSE data lines |
testStreamJsonLinesReturnsPredictions | POST /smile/{id}/stream | 2 JSON-lines → 2 SSE data lines |
testStreamCsvTooFewColumnsEmitsNoPredictions | POST /smile/{id}/stream | Bad CSV closes stream |
testStreamUnknownModelReturns404 | POST /smile/{id}/stream | 404 before stream starts |
API Quick Reference
Classic ML — /api/v1/smile
| Method | Path | Description |
|---|---|---|
GET | /smile/{id} | Get model metadata and schema |
POST | /smile/{id} | Single JSON inference |
POST | /smile/{id}/stream | Streaming CSV or JSON-lines inference |
ONNX — /api/v1/onnx
| Method | Path | Description |
|---|---|---|
GET | /onnx/{id} | Get graph info, input/output shapes |
POST | /onnx/{id} | Single JSON inference |
POST | /onnx/{id}/stream | Streaming CSV or JSON-lines inference |
Chat — /api/v1/models, /api/v1/chat, /api/v1/conversations
| Method | Path | Description |
|---|---|---|
GET | /models | List all loaded models — chat, ONNX, SMILE (OpenAI-compatible) |
GET | /models/{id} | Retrieve a model by id (OpenAI-compatible) |
POST | /chat/completions | Chat completion — SSE when stream: true, JSON when stream: false |
GET | /conversations | List conversations (paginated; SMILE extension) |
GET | /conversations/{conversation_id} | Retrieve conversation (OpenAI-compatible) |
POST | /conversations | Create conversation (OpenAI-compatible) |
POST | /conversations/{conversation_id} | Update conversation metadata (OpenAI-compatible) |
DELETE | /conversations/{conversation_id} | Delete conversation (OpenAI-compatible) |
GET | /conversations/{conversation_id}/items | List message turns (paginated; SMILE extension) |
GET | /auth/me | Current user, agent_mode status, and enabled OAuth providers |
GET | /auth/login/{google|microsoft} | Start Google or Microsoft OAuth 2.0 + S256 PKCE login |
GET | /auth/callback/{google|microsoft} | OAuth callback (establishes session and provisions Kirin workspace on latest-gpu) |
POST | /auth/logout | Clear session cookie |
See Also
- Large Language Models —
LanguageModelAPI and LibTorch path - ONNX — classical
InferenceSession/ execution providers - ONNX GenAI — ORT GenAI bindings and OGA fallback
- Deep Learning — neural network training and inference
For the absolute latest details, see the SMILE Serve Engine user guide in the repository.