Skip to content
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ Releases before 0.10.0 are in the
## Unreleased

- Widen native LiteRT-LM strict `responseFormat` to Gemma 4 (bundle template) and the macOS arm64 GPU, and to the JSON Schema subset that both llama.cpp's GBNF converter and LiteRT-LM's LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored patterns, `uuid`/`date` formats, bounds); other schemas, including `oneOf`, throw `LlamaUnsupportedException` naming the schema path before generation. Gemma 4 can think before its constrained reply; Qwen3 with thinking is refused. A reply cut off inside the JSON reports finish reason `length` ([#174](https://github.com/leehack/llamadart/issues/174)).
- Lift native LiteRT-LM strict `responseFormat` beyond macOS to iOS arm64 CPU and GPU and the Android arm64, Linux x64/arm64 and Windows x64 CPU, the hosts with passing real-model runs; other hosts, GPUs on Android, Linux and Windows, and NPU throw `LlamaUnsupportedException` ([#174](https://github.com/leehack/llamadart/issues/174)).

## 0.19.4

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ concrete engine; see [shared lifecycle ownership](https://llamadart.leehack.com/

LFM2 Python-style tool calls use declared argument types and preserve copied string backslashes; see [tool calling](https://llamadart.leehack.com/docs/guides/tool-calling). The automatic grammar preserves copied singleton string spellings and can use an existing Python arguments wrapper for unambiguous JSON-escaped string values. Foreign XML closing tags remain raw diagnostics with no executable calls.
Native llama.cpp applies schema-directed lazy grammar to LFM2 automatic Python tool calls. Web additionally requires bridge assets v0.1.82+ with a loaded-core prompt-penalty capability; older runtimes reject before inference.
Native LiteRT-LM enforces strict JSON Schema output for Qwen3 and Gemma 4 on macOS arm64 CPU and GPU, for the schemas llama.cpp's GBNF converter also enforces; see [structured output](https://llamadart.leehack.com/docs/guides/generation-and-streaming#structured-json-output) and the [support matrix](https://llamadart.leehack.com/docs/platforms/support-matrix).
Native LiteRT-LM enforces strict JSON Schema output for Qwen3 and Gemma 4 on the macOS and iOS arm64 CPU and GPU and the Android arm64, Linux and Windows CPU (per-host model evidence in the structured-output guide), for the schemas llama.cpp's GBNF converter also enforces; see [structured output](https://llamadart.leehack.com/docs/guides/generation-and-streaming#structured-json-output) and the [support matrix](https://llamadart.leehack.com/docs/platforms/support-matrix).
LFM2 replies cut off at a reported length limit expose raw `partialToolCalls` diagnostics separately from executable calls and history. LFM2 tool markers inside reasoning stay in reasoning and produce no executable calls. Explicit parallel-tool requests reach supported Dart tool grammars even when template probes do not recognize parallel history.

## Install
Expand Down
3 changes: 2 additions & 1 deletion doc/litert_lm_templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,8 @@ backend, not the registry:
real-model-tested rendered-prompt compatibility path, but its handler grammar
is still not applied by LiteRT-LM and must not be reported as grammar support.
- **Native JSON Schema uses its own provider.** Canonical Qwen3 text chat and
Gemma 4 chat with its bundle template, on macOS arm64 CPU and GPU, pass the
Gemma 4 chat with its bundle template, on macOS/iOS arm64 CPU and GPU and
the Android arm64, Linux x64/arm64 and Windows x64 CPU, pass the
schema directly to LLGuidance after constructing the model's provider. The
schema must sit in the subset both LLGuidance and the GBNF converter enforce.
Gemma 4 may think first; Qwen3 must disable thinking. Tools, media, custom
Expand Down
8 changes: 8 additions & 0 deletions doc/testing_matrix.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ Pick targeted rows based on the touched surface:
| Large WebGPU GGUF / wasm64 selection | `gemma4-webgpu-mem64` |
| LiteRT-LM web / Gemma 4 web bundle | `gemma4-litert-web` |
| Chat app model cache/download/projector | `chat-app-device-cache` |
| LiteRT-LM native JSON Schema on a device | `chat-app-litert-json-schema` |
| LiteRT-LM engine reload memory on a device | `chat-app-litert-reload-memory` |
| LiteRT-LM bundle in a read-only directory on a device | `chat-app-litert-read-only-bundle` |
| Android Vulkan prompt cap, Vulkan device facts or the Vulkan 1.2 load refusal on a device | `chat-app-micro-batch-sweep` |
Expand Down Expand Up @@ -1245,6 +1246,13 @@ recovery, thinking (Gemma 4 reasons and still returns the constrained reply;
Qwen3 is refused), system/history, before/after-content cancellation and a
`length` finish cut off inside a constrained string. Run it per model and
backend; `--list` and `--dry-run` first. Each host platform needs its own run.
`chat-app-litert-json-schema` runs the same checks in the chat app on an
Android or iOS device, simulator or emulator. `--model-path` is a path the app
can read (a host path works on the iOS simulator; the sandboxed macOS app
reads only its own container) or a plain `http(s)` URL the app downloads
into its support directory; for an Android emulator, serve the bundle on the
host and use `http://10.0.2.2:<port>/<bundle>`. URLs with credentials, a query
or a fragment are refused, since the URL is printed and compiled into the app.


### Complete image checkpoint containers
Expand Down
231 changes: 231 additions & 0 deletions example/chat_app/integration_test/litert_lm_json_schema_e2e_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,231 @@
@Tags(['local-only', 'e2e'])
@Timeout(Duration(minutes: 20))
/// Device qualification of native LiteRT-LM JSON Schema output.
///
/// Run through `run_local_e2e.dart --scenario chat-app-litert-json-schema`,
/// which passes the model path or URL and the backend as defines; serving a
/// URL is up to the caller.
library;

import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:llamadart/llamadart.dart';
import 'package:path_provider/path_provider.dart';

const _families = {
'c5f39b4191926786c3e6668b62af4d6eb15248dfc7a5348252a9b406f33f2108':
'qwen3-0.6b',
'181938105e0eefd105961417e8da75903eacda102c4fce9ce90f50b97139a63c':
'gemma-4-e2b',
};
const _prompt =
'Reply with exactly the word BANANA. Do not use JSON, quotes, punctuation, or explanation.';
const _params = GenerationParams(
maxTokens: 64,
temp: 0,
topK: 1,
topP: 1,
penalty: 1,
seed: 42,
);
const _messages = [
LlamaChatMessage.fromText(role: LlamaChatRole.user, text: _prompt),
];
const _sentinel = {
'type': 'object',
'properties': {
'verdict': {'type': 'string', 'const': 'CEDAR_174'},
},
'required': ['verdict'],
'additionalProperties': false,
};
const _wide = {
'type': 'object',
'properties': {
'code': {'type': 'string', 'pattern': r'^[A-Z]{3}-[0-9]{2}$'},
'count': {'type': 'integer', 'minimum': 3, 'maximum': 7},
'tags': {
'type': 'array',
'items': {r'$ref': r'#/$defs/tag'},
'minItems': 1,
'maxItems': 3,
},
'owner': {
'anyOf': [
{'type': 'null'},
{
'type': 'object',
'properties': {
'name': {'type': 'string', 'maxLength': 12},
},
'required': ['name'],
'additionalProperties': false,
},
],
},
},
'required': ['code', 'count', 'tags', 'owner'],
'additionalProperties': false,
r'$defs': {
'tag': {
'enum': ['red', 'green', 'blue'],
},
},
};
const _longString = {
'type': 'object',
'properties': {
'story': {'type': 'string', 'minLength': 400},
},
'required': ['story'],
'additionalProperties': false,
};

Map<String, dynamic> _format(Map<String, dynamic> schema) => {
'type': 'json_schema',
'json_schema': {'schema': schema},
};

Future<String> _resolveModel() async {
const path = String.fromEnvironment('LITERT_LM_MODEL');
if (path.isNotEmpty) return path;
const url = String.fromEnvironment('LITERT_LM_MODEL_URL');
final directory = await getApplicationSupportDirectory();
final target = File('${directory.path}/${Uri.parse(url).pathSegments.last}');
if (!target.existsSync()) await Dio().download(url, target.path);
return target.path;
}

void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
const configured =
String.fromEnvironment('LITERT_LM_MODEL') != '' ||
String.fromEnvironment('LITERT_LM_MODEL_URL') != '';
const backend = String.fromEnvironment(
'LITERT_LM_BACKEND',
defaultValue: 'cpu',
);

testWidgets('native JSON Schema enforcement, contract, thinking and cutoff', (
tester,
) async {
final model = await _resolveModel();
final digest = (await sha256.bind(File(model).openRead()).first).toString();
final family = _families[digest];
expect(family, isNotNull, reason: 'Use a qualified model artifact.');
final engine = LlamaEngine(LlamaBackend());
final records = <Map<String, Object?>>[];
Future<LlamaCompletion> run(
String name, {
Map<String, dynamic>? schema,
bool thinking = false,
GenerationParams params = _params,
}) async {
final completion = await engine
.create(
_messages,
params: params,
enableThinking: thinking,
responseFormat: schema == null ? null : _format(schema),
)
.collect();
records.add({
'case': name,
'text': completion.text,
'thinking_chars': completion.thinking.length,
'finish': completion.finishReason?.name,
});
return completion;
}

Map<String, dynamic> parse(LlamaCompletion reply, Map schema) =>
LlamaStructuredOutput<Map<String, dynamic>>.jsonSchema(
schema: Map<String, dynamic>.from(schema),
decoder: (json) => json,
).parse(reply.text);

try {
await engine.setModel(
LlamaModel(ModelSource.path(model)),
params: ModelParams(
device: backend == 'gpu' ? ComputeDevice.gpu : ComputeDevice.cpu,
contextSize: 2048,
numberOfThreads: backend == 'gpu' ? 0 : 2,
),
);
if (!(await engine.capabilities).supportsStructuredOutput) {
// The engine loads lazily, so the capability probe hides why admission
// failed; a strict request rethrows the admission error.
await engine
.create(
_messages,
params: _params,
responseFormat: _format(_sentinel),
)
.drain<void>();
fail('Native JSON Schema output is unsupported on this device.');
}
expect((await run('unconstrained')).text.trim(), isNot(startsWith('{')));
final sentinel = await run('sentinel', schema: _sentinel);
expect(jsonDecode(sentinel.text), {'verdict': 'CEDAR_174'});
expect(sentinel.finishReason, LlamaFinishReason.stop);
final wide = await run(
'wide_contract',
schema: _wide,
params: _params.copyWith(maxTokens: 192),
);
expect(wide.finishReason, LlamaFinishReason.stop);
parse(wide, _wide);
await expectLater(
engine
.create(
_messages,
params: _params,
enableThinking: false,
responseFormat: _format(const {
'type': 'object',
'properties': {
'v': {'type': 'string', 'format': 'time'},
},
}),
)
.drain<void>(),
throwsA(isA<LlamaUnsupportedException>()),
);
final thinking = run(
'thinking',
schema: _sentinel,
thinking: true,
params: _params.copyWith(maxTokens: 1024),
);
if (family == 'gemma-4-e2b') {
final reply = await thinking;
expect(jsonDecode(reply.text), {'verdict': 'CEDAR_174'});
expect(reply.thinking, isNotEmpty);
} else {
await expectLater(thinking, throwsA(isA<LlamaUnsupportedException>()));
}
final cutoff = await run(
'cut_inside_constrained_string',
schema: _longString,
params: _params.copyWith(maxTokens: 24),
);
expect(cutoff.finishReason, LlamaFinishReason.length);
expect(
() => parse(cutoff, _longString),
throwsA(isA<LlamaInferenceException>()),
);
} finally {
await engine.dispose();
// ignore: avoid_print
print(
'LITERT_JSON_SCHEMA_RESULT ${jsonEncode({'model_sha256': digest, 'family': family, 'backend': '${Platform.operatingSystem}-$backend', 'cases': records})}',
);
}
}, skip: !configured);
}
39 changes: 27 additions & 12 deletions lib/src/backends/litert_lm/litert_lm_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ const String _liteRtLmVideoUnsupportedMessage =
'LiteRT-LM video input is not supported through llamadart. '
'Extract and send image frames instead.';

// Hosts and accelerators where real-model JSON Schema runs passed; the others
// stay refused until a run on that host passes.
const _jsonSchemaQualifiedBackendsByAbi = <Abi, Set<String>>{
Abi.macosArm64: {'cpu', 'gpu'},
Abi.iosArm64: {'cpu', 'gpu'},
Abi.androidArm64: {'cpu'},
Abi.linuxX64: {'cpu'},
Abi.linuxArm64: {'cpu'},
Abi.windowsX64: {'cpu'},
};

/// Reads what the `.litertlm` bundle at a path declares, as
/// [LiteRtLmRuntimeClient.bundleCapabilities] does.
typedef LiteRtLmBundleCapabilitiesReader =
Expand Down Expand Up @@ -132,7 +143,7 @@ class LiteRtLmService {
LiteRtLmBundleChatTemplateReader? readBundleChatTemplate,
LiteRtLmBundleFirstChannelReader? readBundleFirstChannel,
String? finishReasonProbeLibraryPath,
bool Function()? jsonSchemaPlatformSupported,
Set<String> Function()? jsonSchemaQualifiedBackends,
LiteRtLmVulkanAdapters Function()? probeGpuAdapters,
}) : _probeGpuAdapters =
probeGpuAdapters ??
Expand All @@ -141,9 +152,9 @@ class LiteRtLmService {
runtimeClientFactory == null
? _systemVulkanAdaptersProbe
: null),
_jsonSchemaPlatformSupported =
jsonSchemaPlatformSupported ??
(() => Platform.isMacOS && Abi.current() == Abi.macosArm64),
_jsonSchemaQualifiedBackends =
jsonSchemaQualifiedBackends ??
(() => _jsonSchemaQualifiedBackendsByAbi[liteRtLmGateAbi()] ?? {}),
_clientFactory =
runtimeClientFactory ??
(() => clientFactory == null
Expand Down Expand Up @@ -219,7 +230,7 @@ class LiteRtLmService {

bool _jsonSchemaAdmitted = false;
bool _jsonSchemaThinking = false;
final bool Function() _jsonSchemaPlatformSupported;
final Set<String> Function() _jsonSchemaQualifiedBackends;
LiteRtLmEmbeddingRuntimeSession? _embedding;
LiteRtLmCacheLease? _cacheLease;
ModelParams? _modelParams;
Expand Down Expand Up @@ -658,13 +669,15 @@ class LiteRtLmService {
Future<void> prepareJsonSchemaChat() async {
if (_jsonSchemaAdmitted) return;
_requireConversationEngine();
const platformRefusal =
'Native JSON Schema chat is qualified only on macOS arm64 CPU and GPU; '
'NPU and other platforms are unsupported.';
if (!_jsonSchemaPlatformSupported() ||
_backendNameFor(_modelParams ?? const ModelParams()) == 'npu') {
throw LlamaUnsupportedException(platformRefusal);
}
final qualified = _jsonSchemaQualifiedBackends();
Never refuseBackend(String backend) => throw LlamaUnsupportedException(
'Native JSON Schema chat is not qualified for the LiteRT-LM $backend '
'backend on ${liteRtLmGateAbi()}'
'${qualified.isEmpty ? '' : '; load with ${qualified.map((b) => 'ComputeDevice.$b').join(' or ')}'}.',
);
// The loaded backend includes the deprecated preferredBackend override.
final loaded = _loadedBackend!;
if (!qualified.contains(loaded)) refuseBackend(loaded);
final routing = _templateRouting();
final family = routing.family;
final customTemplate = _modelParams?.chatTemplate;
Expand All @@ -686,6 +699,8 @@ class LiteRtLmService {
}
_cancelRequested = false;
final client = await _ensureClientForGeneration(const GenerationParams());
// An automatic GPU load can run on the CPU instead.
if (!qualified.contains(_activeBackend)) refuseBackend(_activeBackend!);
if (!client.supportsJsonSchemaConstraints) {
throw LlamaUnsupportedException(
'Native JSON Schema chat requires all constraint-provider and thinking-config symbols. '
Expand Down
6 changes: 4 additions & 2 deletions skills/llamadart-chat-streaming/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,10 @@ modalities and speculative strategies before offering them.
- For strict JSON, use `LlamaStructuredOutput` with
`engine.createStructuredJson`; it constrains decoding and validates the
final output. Native LiteRT-LM supports Qwen3 (canonical text template) and
Gemma 4 (bundle template) on macOS arm64 CPU and GPU after provider
admission, for schemas that both the GBNF converter and LiteRT-LM's
Gemma 4 (bundle template) on macOS/iOS arm64 CPU and GPU and the Android
arm64, Linux x64/arm64 and Windows x64 CPU after provider admission (other
hosts, accelerators and NPU throw; per-host model evidence is in the
structured-output guide), for schemas that both the GBNF converter and LiteRT-LM's
LLGuidance enforce (nested objects, arrays, `$ref`, `anyOf`, anchored
patterns, `uuid`/`date` formats, bounds); `oneOf`, other formats, open tuples
and the other differences listed in the structured-output guide throw
Expand Down
Loading
Loading