From 0d67b1944a75106be0ed66a58f6b901cba85dfc9 Mon Sep 17 00:00:00 2001 From: alay2shah Date: Wed, 18 Nov 2026 18:48:10 -0600 Subject: [PATCH 1/5] Exclude repository maintenance files from docs publishing --- .github/workflows/check-docs.yaml | 4 ++ .mintignore | 6 +++ scripts/checkPublishedContent.mjs | 55 ++++++++++++++++++++++++++ scripts/checkPublishedContent.test.mjs | 41 +++++++++++++++++++ 4 files changed, 106 insertions(+) create mode 100644 scripts/checkPublishedContent.mjs create mode 100644 scripts/checkPublishedContent.test.mjs diff --git a/.github/workflows/check-docs.yaml b/.github/workflows/check-docs.yaml index a0b6489..6bf168c 100644 --- a/.github/workflows/check-docs.yaml +++ b/.github/workflows/check-docs.yaml @@ -21,6 +21,10 @@ jobs: node-version: '22' - name: Install Mintlify CLI run: npm install --global mint@4.3.51 + - name: Check publication exclusions + run: | + node --test scripts/checkPublishedContent.test.mjs + node scripts/checkPublishedContent.mjs - name: Validate all MDX pages and navigation run: mint validate - name: Check internal documentation links diff --git a/.mintignore b/.mintignore index 27ad499..c42be2c 100644 --- a/.mintignore +++ b/.mintignore @@ -1,3 +1,9 @@ +# Repository maintenance and validation files, not model/tool documentation. +/scripts/ +/util/ +/bin/ +**/AGENTS.md + MODEL-MATRIX.md DESIGN.md CLAUDE.md diff --git a/scripts/checkPublishedContent.mjs b/scripts/checkPublishedContent.mjs new file mode 100644 index 0000000..7a98bd2 --- /dev/null +++ b/scripts/checkPublishedContent.mjs @@ -0,0 +1,55 @@ +import { execFileSync, spawnSync } from 'node:child_process'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const publicDirectories = new Set([ + 'api', 'deployment', 'examples', 'guides', 'leap', 'lfm', 'snippets', +]); +const defaultIgnores = [ + '.git/', '.github/', '.claude/', '.agents/', '.idea/', '.vscode/', + '.cursor/', '.mintlify/', 'node_modules/', + 'README.md', 'LICENSE.md', 'CHANGELOG.md', 'CONTRIBUTING.md', +]; + +export function unexpectedPages(paths, mintignore) { + const markdown = paths.filter((path) => /\.mdx?$/i.test(path)); + if (!markdown.length) return []; + + // Use Git's pattern parser so directory rules and negations match .mintignore. + const directory = mkdtempSync(resolve(tmpdir(), 'docs-publication-')); + try { + execFileSync('git', ['init', '--quiet', directory]); + writeFileSync(resolve(directory, '.gitignore'), + `${defaultIgnores.join('\n')}\n${mintignore}\n`); + const result = spawnSync('git', [ + '-C', directory, 'check-ignore', '--no-index', '-z', '--stdin', + ], { input: `${markdown.join('\0')}\0`, encoding: 'utf8' }); + if (result.error) throw result.error; + if (![0, 1].includes(result.status)) { + throw new Error(result.stderr || 'Unable to evaluate publication exclusions'); + } + const excluded = new Set(result.stdout.split('\0').filter(Boolean)); + return markdown.filter((path) => + !excluded.has(path) && !publicDirectories.has(path.split('/')[0])); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); + const paths = execFileSync('git', ['ls-files', '-z'], { + cwd: root, encoding: 'utf8', + }).split('\0').filter(Boolean); + const unexpected = unexpectedPages(paths, readFileSync(resolve(root, '.mintignore'), 'utf8')); + if (unexpected.length) { + console.error('Markdown outside the public documentation directories would be published:'); + for (const path of unexpected) console.error(` ${path}`); + console.error('Exclude internal files in .mintignore, or put model/tool docs in a public directory.'); + process.exitCode = 1; + } else { + console.log('Publication check passed: no unexpected Markdown pages.'); + } +} diff --git a/scripts/checkPublishedContent.test.mjs b/scripts/checkPublishedContent.test.mjs new file mode 100644 index 0000000..6ba82c3 --- /dev/null +++ b/scripts/checkPublishedContent.test.mjs @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; +import { unexpectedPages } from './checkPublishedContent.mjs'; + +test('the previous exclusions expose the validation report', () => { + assert.deepEqual(unexpectedPages([ + 'scripts/validation/lfm3-modernization.md', + ], 'MODEL-MATRIX.md\nDESIGN.md\nCLAUDE.md\nINTERACTIVE_QUICKSTART_WIDGET.md'), [ + 'scripts/validation/lfm3-modernization.md', + ]); +}); + +test('current exclusions cover repository maintenance files without excluding model docs', () => { + const patterns = readFileSync(new URL('../.mintignore', import.meta.url), 'utf8'); + assert.deepEqual(unexpectedPages([ + 'scripts/validation/lfm3-modernization.md', + 'scripts/validation/future-report.mdx', + 'util/testing-notes.md', + 'bin/migration-notes.md', + 'MODEL-MATRIX.md', + 'AGENTS.md', + 'README.md', + 'notebooks/README.md', + 'lfm/models/lfm2-1.2b.mdx', + 'deployment/tools/model-bundling/reference.mdx', + 'snippets/quickstart/text-llamacpp.mdx', + ], patterns), []); +}); + +test('a new planning directory fails instead of silently publishing', () => { + assert.deepEqual(unexpectedPages(['planning/next-release.md'], ''), [ + 'planning/next-release.md', + ]); +}); + +test('negating an exclusion exposes the internal page again', () => { + assert.deepEqual(unexpectedPages(['notes/review.md'], 'notes/*.md\n!notes/review.md'), [ + 'notes/review.md', + ]); +}); From 26d3604a40414dba3bbde012efff28d2770943ec Mon Sep 17 00:00:00 2001 From: alay2shah Date: Wed, 18 Nov 2026 18:48:13 -0600 Subject: [PATCH 2/5] Lead speculative decoding with verified community LFM3 support --- deployment/gpu-inference/baseten.mdx | 2 +- deployment/gpu-inference/fal.mdx | 2 +- deployment/gpu-inference/modal.mdx | 2 +- deployment/on-device/llama-cpp.mdx | 22 +++++---- .../on-device/llama-cpp/function-calling.mdx | 2 +- .../llama-cpp/migrating-from-leap-sdk.mdx | 4 +- lfm/help/contributing.mdx | 4 +- lfm/key-concepts/speculative-decoding.mdx | 49 ++++++++++++++----- lfm/models/complete-library.mdx | 2 +- lfm/models/lfm3-1.7b.mdx | 4 ++ 10 files changed, 61 insertions(+), 32 deletions(-) diff --git a/deployment/gpu-inference/baseten.mdx b/deployment/gpu-inference/baseten.mdx index fe14469..29592cf 100644 --- a/deployment/gpu-inference/baseten.mdx +++ b/deployment/gpu-inference/baseten.mdx @@ -4,7 +4,7 @@ description: "Deploy Liquid AI LFM models on Baseten with optimized inference, a --- -This integration retains its original LFM2 deployment project and runtime pins. For new LFM3 GPU serving, start with the current [vLLM](/deployment/gpu-inference/vllm) or [SGLang](/deployment/gpu-inference/sglang) guide. Updating a provider script requires testing its image, model architecture, and launch flags together; changing only `MODEL_NAME` is insufficient. +For new **LFM3** GPU serving, start with the current [vLLM](/deployment/gpu-inference/vllm) or [SGLang](/deployment/gpu-inference/sglang) runtime guide. The provider project below retains its original **LFM2** checkpoint and runtime pins. It is an older integration, not an LFM3 deployment recipe; changing only `MODEL_NAME` is insufficient. diff --git a/deployment/gpu-inference/fal.mdx b/deployment/gpu-inference/fal.mdx index 51d85b7..3aa003a 100644 --- a/deployment/gpu-inference/fal.mdx +++ b/deployment/gpu-inference/fal.mdx @@ -4,7 +4,7 @@ description: "Deploy Liquid AI LFM models on Fal for serverless inference with f --- -This integration retains its original LFM2 deployment project and runtime pins. For new LFM3 GPU serving, start with the current [vLLM](/deployment/gpu-inference/vllm) or [SGLang](/deployment/gpu-inference/sglang) guide. Updating a provider script requires testing its image, model architecture, and launch flags together; changing only `MODEL_NAME` is insufficient. +For new **LFM3** GPU serving, start with the current [vLLM](/deployment/gpu-inference/vllm) or [SGLang](/deployment/gpu-inference/sglang) runtime guide. The provider project below retains its original **LFM2** checkpoint and runtime pins. It is an older integration, not an LFM3 deployment recipe; changing only `MODEL_NAME` is insufficient. diff --git a/deployment/gpu-inference/modal.mdx b/deployment/gpu-inference/modal.mdx index beb06d0..a8fce46 100644 --- a/deployment/gpu-inference/modal.mdx +++ b/deployment/gpu-inference/modal.mdx @@ -4,7 +4,7 @@ description: "Deploy Liquid AI LFM models on Modal with serverless GPU inference --- -This integration retains its original LFM2 deployment project and runtime pins. For new LFM3 GPU serving, start with the current [vLLM](/deployment/gpu-inference/vllm) or [SGLang](/deployment/gpu-inference/sglang) guide. Updating a provider script requires testing its image, model architecture, and launch flags together; changing only `MODEL_NAME` is insufficient. +For new **LFM3** GPU serving, start with the current [vLLM](/deployment/gpu-inference/vllm) or [SGLang](/deployment/gpu-inference/sglang) runtime guide. The provider project below retains its original **LFM2** checkpoint and runtime pins. It is an older integration, not an LFM3 deployment recipe; changing only `MODEL_NAME` is insufficient. diff --git a/deployment/on-device/llama-cpp.mdx b/deployment/on-device/llama-cpp.mdx index 69f08e2..b74eb84 100644 --- a/deployment/on-device/llama-cpp.mdx +++ b/deployment/on-device/llama-cpp.mdx @@ -350,16 +350,17 @@ llama-tts -m LFM3-Audio-2B-Q4_K_M.gguf -mm mmproj-LFM3-Audio-2B-Q8_0.gguf \ ## Speculative Decoding -Some LFM2.5 models have DSpark draft models that make generation faster without changing the output. In llama.cpp, the drafter is a GGUF sidecar that you load next to the target with `-hfd` (or `-md` for a local file): +[LFM3-1.7B](/lfm/models/lfm3-1.7b) has a community-maintained [DSpark drafter](https://huggingface.co/rasyosef/LFM3-1.7B-DSpark-GGUF). It is a GGUF sidecar that you load next to the matching target with `-hfd` (or `-md` for a local file). This is a community checkpoint, not an official LiquidAI release: ```bash -llama serve -hf LiquidAI/LFM2.5-1.2B-Instruct-GGUF:F16 \ - -hfd LiquidAI/LFM2.5-1.2B-Instruct-DSpark-GGUF:F16 \ - --spec-type draft-dspark --spec-draft-n-max 10 --spec-draft-n-min 0 \ - -ngl 99 -ngld 99 -fa on +llama serve -hf LiquidAI/LFM3-1.7B-GGUF:Q4_K_M \ + -hfd rasyosef/LFM3-1.7B-DSpark-GGUF:F16 \ + --spec-type draft-dspark --spec-draft-n-max 8 --spec-draft-n-min 0 \ + -c 4096 -ngl 99 -ngld 99 -fa on \ + --temp 0.1 --top-k 50 --repeat-penalty 1.1 ``` -The sidecar cannot run on its own. Speedups are largest with a 16-bit target. Each response's `timings` report `draft_n` and `draft_n_accepted`. See [Speculative Decoding](/lfm/key-concepts/speculative-decoding) for which models have drafters. +This pair was checked with b12359 on Apple silicon and accepted drafted tokens. The sidecar cannot run on its own. Each response's `timings` report `draft_n` and `draft_n_accepted`; measure speed and output behavior on your own workload. See [Speculative Decoding](/lfm/key-concepts/speculative-decoding) for the LFM3 path, official LFM2.5 drafters, and output-equivalence limits. ## Converting Custom Models @@ -367,14 +368,15 @@ If you have a finetuned model or need to create a GGUF from a Hugging Face model ```bash # Clone llama.cpp if you haven't already -git clone https://github.com/ggerganov/llama.cpp +git clone https://github.com/ggml-org/llama.cpp cd llama.cpp -# Convert model with quantization -python convert_hf_to_gguf.py /path/to/your/model --outfile model.gguf --outtype q4_k_m +# Export a floating-point GGUF, then quantize it +python convert_hf_to_gguf.py /path/to/your/model --outfile model-f16.gguf --outtype f16 +llama-quantize model-f16.gguf model-q4_k_m.gguf Q4_K_M ``` -Use `--outtype` to specify the quantization level (e.g., `q4_0`, `q4_k_m`, `q5_k_m`, `q6_k`, `q8_0`, `f16`). +Install the converter's Python dependencies from the llama.cpp repository and use a build of `llama-quantize` from the same revision. The converter's `--outtype` selects an export format such as `f16`, `bf16`, or `q8_0`; it does not accept `q4_k_m`. Use `llama-quantize` for K-quants such as `Q4_K_M`, `Q5_K_M`, and `Q6_K`. ## Building Applications diff --git a/deployment/on-device/llama-cpp/function-calling.mdx b/deployment/on-device/llama-cpp/function-calling.mdx index ec433c8..465d84f 100644 --- a/deployment/on-device/llama-cpp/function-calling.mdx +++ b/deployment/on-device/llama-cpp/function-calling.mdx @@ -92,7 +92,7 @@ def run_agent(user_text: str, max_steps: int = 5) -> str: if not message.tool_calls: return message.content # final answer - for call in message.tool_calls: # LFM2.5 may request several calls at once + for call in message.tool_calls: # A response may request several calls at once args = json.loads(call.function.arguments) result = TOOL_IMPLS[call.function.name](**args) messages.append({ diff --git a/deployment/on-device/llama-cpp/migrating-from-leap-sdk.mdx b/deployment/on-device/llama-cpp/migrating-from-leap-sdk.mdx index d6e409d..fae7063 100644 --- a/deployment/on-device/llama-cpp/migrating-from-leap-sdk.mdx +++ b/deployment/on-device/llama-cpp/migrating-from-leap-sdk.mdx @@ -4,7 +4,7 @@ description: "The LEAP SDK is deprecated. This page maps each LEAP SDK concept t --- -The **LEAP SDK is deprecated** and no longer receives new releases. It was a Kotlin Multiplatform wrapper around llama.cpp; everything it did is available directly from llama.cpp, which supports LFM2 / LFM2.5 models, LFM2-VL projectors, and LFM2 tool-call parsing upstream. Existing LEAP SDK artifacts remain on Maven Central and GitHub, and the archived reference is at [LEAP SDK (archived)](/deployment/on-device/sdk/overview). +The **LEAP SDK is deprecated** and no longer receives new releases. For new applications, use [llama.cpp with LFM3](/deployment/on-device/llama-cpp). llama.cpp also supports the older LFM2.5 and LFM2 checkpoints used by existing SDK applications, with their matching projectors, sampling settings, and tool-call formats. Existing LEAP SDK artifacts remain on Maven Central and GitHub, and the archived reference is at [LEAP SDK (archived)](/deployment/on-device/sdk/overview). ## Concept mapping @@ -49,4 +49,4 @@ Fine-tuned models continue to work: convert them with `convert_hf_to_gguf.py` as ## Archived reference -The LEAP SDK pages remain online for teams still shipping the SDK but are no longer maintained: [Overview](/deployment/on-device/sdk/overview), [Quick Start](/deployment/on-device/sdk/quick-start), [Changelog](/deployment/on-device/leap-sdk-changelog). The Android example apps under [Examples](/examples/index#android) were built with the LEAP SDK and are kept as architectural references. +The LEAP SDK pages remain online for teams still shipping the SDK but are no longer maintained: [Overview](/deployment/on-device/sdk/overview), [Quick Start](/deployment/on-device/sdk/quick-start), [Changelog](/deployment/on-device/leap-sdk-changelog). The current [Android examples](/examples/index#android) use llama.cpp directly; follow each project's pinned build and model requirements. diff --git a/lfm/help/contributing.mdx b/lfm/help/contributing.mdx index a7a0757..6c4c9b4 100644 --- a/lfm/help/contributing.mdx +++ b/lfm/help/contributing.mdx @@ -53,7 +53,7 @@ Always specify the language for syntax highlighting: ````markdown ```python from transformers import AutoModelForCausalLM -model = AutoModelForCausalLM.from_pretrained("LiquidAI/LFM2.5-1.2B-Instruct") +model = AutoModelForCausalLM.from_pretrained("LiquidAI/LFM3-1.7B", trust_remote_code=True) ``` ```` @@ -61,7 +61,7 @@ For bash commands: ````markdown ```bash -pip install transformers torch +uv pip install "transformers==5.23.0" torch accelerate ``` ```` diff --git a/lfm/key-concepts/speculative-decoding.mdx b/lfm/key-concepts/speculative-decoding.mdx index e019a6c..e5eedfb 100644 --- a/lfm/key-concepts/speculative-decoding.mdx +++ b/lfm/key-concepts/speculative-decoding.mdx @@ -1,6 +1,6 @@ --- title: "Speculative Decoding" -description: "Speed up LFM2.5 text and vision models with DSpark draft models in SGLang, llama.cpp, and MLX-VLM, with no change to output." +description: "Speculative decoding for LFM3 and older models: compatible DSpark drafters, runtime requirements, and examples." keywords: ["speculative decoding", "DSpark", "draft model", "drafter", "MTP", "faster inference"] --- @@ -8,22 +8,43 @@ import { DsparkSglang } from "/snippets/quickstart/dspark-sglang.mdx"; import { DsparkLlamacpp } from "/snippets/quickstart/dspark-llamacpp.mdx"; import { DsparkMlxVlm } from "/snippets/quickstart/dspark-mlx-vlm.mdx"; -Speculative decoding makes generation faster without changing what the model outputs. A small **draft model** proposes several tokens ahead, and the **target model** checks all of them in a single forward pass. The target keeps every token it agrees with and corrects the first one it does not. +Start with [LFM3-1.7B](/lfm/models/lfm3-1.7b) for new text applications. Speculative decoding can speed up generation: a small **draft model** proposes several tokens ahead, and the **target model** verifies them together. A drafter must match the target model and be supported by the inference engine; an LFM2.5 drafter cannot be reused with LFM3. + +## LFM3 speculative decoding + +LFM3-1.7B has a community-maintained [DSpark drafter](https://huggingface.co/rasyosef/LFM3-1.7B-DSpark) and [GGUF sidecar](https://huggingface.co/rasyosef/LFM3-1.7B-DSpark-GGUF). These are community checkpoints, not official LiquidAI releases. LiquidAI's official DSpark releases currently cover the LFM2.5 targets listed below. + +With a recent llama.cpp build, run the LFM3 target with its matching drafter: + +```bash +llama serve -hf LiquidAI/LFM3-1.7B-GGUF:Q4_K_M \ + -hfd rasyosef/LFM3-1.7B-DSpark-GGUF:F16 \ + --spec-type draft-dspark --spec-draft-n-max 8 --spec-draft-n-min 0 \ + -c 4096 -ngl 99 -ngld 99 -fa on \ + --temp 0.1 --top-k 50 --repeat-penalty 1.1 +``` + +This target/drafter pair was checked with llama.cpp b12359 on Apple silicon and accepted drafted tokens. Check that `llama serve --help` lists `draft-dspark`. The drafter's [model card](https://huggingface.co/rasyosef/LFM3-1.7B-DSpark#usage) also documents a vLLM integration with additional requirements; the SGLang and MLX-VLM recipes below are for LFM2.5, not this LFM3 drafter. + +Measure speed and output behavior with your own prompts. A compatible drafter does not guarantee a speedup, and numerical differences can change generated text; see the [output FAQ](#faq). ## Available draft models -| Target model | DSpark Drafter (HF) | DSpark Drafter (GGUF) | -| ----- | ----- | ----- | -| **Text Models** | | | -| [LFM2.5-1.2B-Instruct](/lfm/models/lfm25-1.2b-instruct) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-DSpark-GGUF) | -| [LFM2.5-2.6B](/lfm/models/lfm25-2.6b) | [✓](https://huggingface.co/LiquidAI/LFM2.5-2.6B-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-2.6B-DSpark-GGUF) | -| [LFM2.5-8B-A1B](/lfm/models/lfm25-8b-a1b) | [✓](https://huggingface.co/LiquidAI/LFM2.5-8B-A1B-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-8B-A1B-DSpark-GGUF) | -| [LFM2.5-24B-A2B](/lfm/models/lfm25-24b-a2b) | [✓](https://huggingface.co/LiquidAI/LFM2.5-24B-A2B-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-24B-A2B-DSpark-GGUF) | -| **Vision Language Models** | | | -| [LFM2.5-VL-3B](/lfm/models/lfm25-vl-3b) | [✓](https://huggingface.co/LiquidAI/LFM2.5-VL-3B-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-VL-3B-DSpark-GGUF) | +| Target model | Publisher | DSpark Drafter (HF) | DSpark Drafter (GGUF) | +| ----- | ----- | ----- | ----- | +| **Text Models** | | | | +| [LFM3-1.7B](/lfm/models/lfm3-1.7b) | Community (`rasyosef`) | [✓](https://huggingface.co/rasyosef/LFM3-1.7B-DSpark) | [✓](https://huggingface.co/rasyosef/LFM3-1.7B-DSpark-GGUF) | +| [LFM2.5-1.2B-Instruct](/lfm/models/lfm25-1.2b-instruct) | LiquidAI | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-DSpark-GGUF) | +| [LFM2.5-2.6B](/lfm/models/lfm25-2.6b) (deprecated) | LiquidAI | [✓](https://huggingface.co/LiquidAI/LFM2.5-2.6B-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-2.6B-DSpark-GGUF) | +| [LFM2.5-8B-A1B](/lfm/models/lfm25-8b-a1b) | LiquidAI | [✓](https://huggingface.co/LiquidAI/LFM2.5-8B-A1B-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-8B-A1B-DSpark-GGUF) | +| [LFM2.5-24B-A2B](/lfm/models/lfm25-24b-a2b) | LiquidAI | [✓](https://huggingface.co/LiquidAI/LFM2.5-24B-A2B-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-24B-A2B-DSpark-GGUF) | +| **Vision Language Models** | | | | +| [LFM2.5-VL-3B](/lfm/models/lfm25-vl-3b) | LiquidAI | [✓](https://huggingface.co/LiquidAI/LFM2.5-VL-3B-DSpark) | [✓](https://huggingface.co/LiquidAI/LFM2.5-VL-3B-DSpark-GGUF) | ## Supported inference engines +The table below covers the official **LFM2.5** drafters. For the community LFM3 drafter, use the llama.cpp example above or the integration documented by its author; these LFM2.5 commands are not interchangeable with LFM3. + | Engine | Text drafters | Vision drafters | |---|---|---| | [SGLang](/deployment/gpu-inference/sglang) | ✓ | ✓ | @@ -32,6 +53,8 @@ Speculative decoding makes generation faster without changing what the model out ## Run with text models +These examples retain the **deprecated LFM2.5-2.6B** target for existing deployments. Use the [LFM3 example](#lfm3-speculative-decoding) above for a new text application. + @@ -60,11 +83,11 @@ Speculative decoding makes generation faster without changing what the model out - No. The target model checks every drafted token and keeps only the ones it would have generated itself. With greedy decoding (`temperature=0`), the output is identical to running the target model alone. With sampling, the output follows the same distribution as the target model, as long as you use the same sampling settings. + The target verifies the proposed tokens. An exact speculative sampler is designed to preserve the target's sampling distribution, but implementation details and floating-point differences can change a particular generated sequence, including with greedy decoding. In our quantized LFM3 llama.cpp smoke test, two of three greedy responses matched the baseline exactly and one diverged. Validate output behavior as well as latency with your target, drafter, quantization, and runtime. - Only DSpark. Liquid AI publishes DSpark draft models for the models listed in [Available draft models](#available-draft-models). Other methods, such as DFlash, DFlash2, EAGLE, and multi-token prediction (MTP), are not supported. LFM models do not include MTP heads, so engine options such as vLLM's `--speculative-config` with `"method": "mtp"` do not work with them. + This page documents DSpark: the community LFM3 drafter and LiquidAI's official LFM2.5 drafters in [Available draft models](#available-draft-models). Other methods require their own compatible checkpoints and runtime support; selecting an engine flag alone does not add support. These LFM checkpoints do not include MTP heads, so vLLM's `--speculative-config` with `"method": "mtp"` does not work with them. diff --git a/lfm/models/complete-library.mdx b/lfm/models/complete-library.mdx index a5c33b9..8824ec9 100644 --- a/lfm/models/complete-library.mdx +++ b/lfm/models/complete-library.mdx @@ -101,7 +101,7 @@ Quantization reduces model size and speeds up inference with minimal quality los | Model | HF | GGUF | MLX | ONNX | Drafter | Trainable? | | ----- | ----- | ----- | ----- | ----- | ----- | ----- | | **Text-to-text Models** | | | | | | | -| [LFM3-1.7B](/lfm/models/lfm3-1.7b) | [✓](https://huggingface.co/LiquidAI/LFM3-1.7B) | [✓](https://huggingface.co/LiquidAI/LFM3-1.7B-GGUF) | [✓](https://huggingface.co/LiquidAI/LFM3-1.7B-MLX-4bit) | [✓](https://huggingface.co/LiquidAI/LFM3-1.7B-ONNX) | ✗ | Yes (TRL) | +| [LFM3-1.7B](/lfm/models/lfm3-1.7b) | [✓](https://huggingface.co/LiquidAI/LFM3-1.7B) | [✓](https://huggingface.co/LiquidAI/LFM3-1.7B-GGUF) | [✓](https://huggingface.co/LiquidAI/LFM3-1.7B-MLX-4bit) | [✓](https://huggingface.co/LiquidAI/LFM3-1.7B-ONNX) | [Community](/lfm/key-concepts/speculative-decoding#lfm3-speculative-decoding) | Yes (TRL) | | [LFM2.5-1.2B-Instruct](/lfm/models/lfm25-1.2b-instruct) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-GGUF) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-MLX-8bit) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Instruct-ONNX) | [✓](/lfm/key-concepts/speculative-decoding#available-draft-models) | Yes (TRL) | | [LFM2.5-1.2B-Thinking](/lfm/models/lfm25-1.2b-thinking) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Thinking) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Thinking-GGUF) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Thinking-MLX-8bit) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Thinking-ONNX) | ✗ | Yes (TRL) | | [LFM2.5-1.2B-JP-202606](/lfm/models/lfm25-1.2b-jp-202606) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-JP-202606) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-JP-202606-GGUF) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-JP-202606-MLX-8bit) | [✓](https://huggingface.co/LiquidAI/LFM2.5-1.2B-JP-202606-ONNX) | ✗ | Yes (TRL) | diff --git a/lfm/models/lfm3-1.7b.mdx b/lfm/models/lfm3-1.7b.mdx index 4b4815a..5964a51 100644 --- a/lfm/models/lfm3-1.7b.mdx +++ b/lfm/models/lfm3-1.7b.mdx @@ -172,6 +172,10 @@ On Apple Silicon, use [MLX-VLM 0.8.0](/deployment/on-device/mlx#lfm3-and-d1-mode For local agent setup, see the [Agent Harnesses guide](/examples/agent-harnesses). +## Speculative Decoding + +A community-maintained DSpark drafter is available for LFM3-1.7B. See [Speculative Decoding](/lfm/key-concepts/speculative-decoding#lfm3-speculative-decoding) for the llama.cpp example, checkpoint links, and output-equivalence limits. This drafter is not an official LiquidAI release. + ## Reasoning Reasoning is enabled by default. You can set `enable_thinking=False` for direct answers, but the model may still emit reasoning or give inconsistent answers, particularly for reasoning-heavy tasks. We recommend leaving thinking on. Leave room for the reasoning in your token limit. See [Thinking](/lfm/key-concepts/thinking) for guidance on how to use it, and [Chat Template](/lfm/key-concepts/chat-template) and [Tool Use](/lfm/key-concepts/tool-use) for the message format. From 21dbe56227153e39922ff6baf57052be7647d257 Mon Sep 17 00:00:00 2001 From: alay2shah Date: Wed, 18 Nov 2026 18:51:08 -0600 Subject: [PATCH 3/5] Clarify the model scope of MLX speculative decoding --- deployment/on-device/mlx.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/deployment/on-device/mlx.mdx b/deployment/on-device/mlx.mdx index 1b73d67..3de7784 100644 --- a/deployment/on-device/mlx.mdx +++ b/deployment/on-device/mlx.mdx @@ -99,7 +99,7 @@ For an existing LFM2 deployment, keep its own model repository and sampling sett ## Speculative Decoding -Some LFM2.5 vision models have DSpark draft models that make generation faster without changing the output. Pass the drafter to MLX-VLM (v0.7.2 or newer) with `--draft-model`: +For LFM3, the [community DSpark example](/lfm/key-concepts/speculative-decoding#lfm3-speculative-decoding) uses llama.cpp. The MLX-VLM example below is specifically for **LFM2.5-VL-3B** and its official drafter; it does not establish support for the LFM3 drafter. DSpark can accelerate generation by verifying proposed tokens together. Pass the drafter to MLX-VLM (v0.7.2 or newer) with `--draft-model`: ```bash python -m mlx_vlm.generate \ From 0ce97160bc11e674304bed7efa238db2f4c5429b Mon Sep 17 00:00:00 2001 From: alay2shah Date: Thu, 19 Nov 2026 10:08:30 -0600 Subject: [PATCH 4/5] Fix remaining documentation audit findings and Markdown quickstarts --- .github/workflows/check-link-snapshot.yaml | 4 + README.md | 15 +- api/guides/batch.mdx | 2 +- api/guides/decisions.mdx | 2 +- api/guides/your-data.mdx | 12 +- api/models.mdx | 16 +- api/openapi.json | 2501 +++++++++++++++-- .../on-device/llama-cpp/structured-output.mdx | 8 +- .../on-device/sdk/advanced-features.mdx | 40 +- .../on-device/sdk/ai-agent-usage-guide.mdx | 23 +- .../on-device/sdk/cloud-ai-comparison.mdx | 15 +- .../on-device/sdk/conversation-generation.mdx | 24 +- .../on-device/sdk/desktop-platforms.mdx | 37 +- deployment/on-device/sdk/function-calling.mdx | 3 + deployment/on-device/sdk/messages-content.mdx | 16 +- deployment/on-device/sdk/model-loading.mdx | 33 +- deployment/on-device/sdk/openai-client.mdx | 164 +- deployment/on-device/sdk/overview.mdx | 2 + deployment/on-device/sdk/quick-start.mdx | 69 +- deployment/on-device/sdk/utilities.mdx | 4 +- deployment/on-device/sdk/voice-assistant.mdx | 37 +- .../tools/model-bundling/authentication.mdx | 2 + .../tools/model-bundling/bundle-creation.mdx | 2 + .../model-bundling/bundle-management.mdx | 2 + deployment/tools/model-bundling/changelog.mdx | 2 + .../tools/model-bundling/configuration.mdx | 2 + .../tools/model-bundling/data-privacy.mdx | 2 + deployment/tools/model-bundling/download.mdx | 2 + .../tools/model-bundling/quick-start.mdx | 2 + deployment/tools/model-bundling/reference.mdx | 2 + docs.json | 19 + examples/agent-harnesses.mdx | 5 +- examples/customize-models/home-assistant.mdx | 44 +- examples/customize-models/satellite-vlm.mdx | 43 +- .../customize-models/wildfire-prevention.mdx | 5 +- examples/laptop-examples/browser-control.mdx | 26 +- .../build-a-game-with-decision-models.mdx | 2 +- ...voice-extractor-tool-with-liquid-nanos.mdx | 7 +- .../lfm2-english-to-korean.mdx | 12 +- .../laptop-examples/meeting-summarization.mdx | 13 +- examples/web/hand-voice-racer.mdx | 2 + lfm/fine-tuning/liquid-finetune.mdx | 5 +- lfm/fine-tuning/unsloth.mdx | 75 +- lfm/help/model-license.mdx | 2 +- lfm/help/troubleshooting.mdx | 11 +- lfm/key-concepts/thinking.mdx | 18 +- lfm/key-concepts/tool-use.mdx | 7 + lfm/models/complete-library.mdx | 4 +- lfm/models/d1-omni-2b.mdx | 41 +- lfm/models/decision-models.mdx | 4 +- lfm/models/lfm2-1.2b.mdx | 115 +- lfm/models/lfm2-2.6b-exp.mdx | 115 +- lfm/models/lfm2-2.6b.mdx | 115 +- lfm/models/lfm2-24b-a2b.mdx | 83 +- lfm/models/lfm2-350m.mdx | 115 +- lfm/models/lfm2-700m.mdx | 115 +- lfm/models/lfm2-8b-a1b.mdx | 115 +- lfm/models/lfm2-vl-1.6b.mdx | 161 +- lfm/models/lfm2-vl-3b.mdx | 161 +- lfm/models/lfm2-vl-450m.mdx | 161 +- lfm/models/lfm25-1.2b-base.mdx | 33 + lfm/models/lfm25-1.2b-instruct.mdx | 191 +- lfm/models/lfm25-1.2b-jp-202606.mdx | 115 +- lfm/models/lfm25-1.2b-jp.mdx | 114 +- lfm/models/lfm25-1.2b-thinking.mdx | 116 +- lfm/models/lfm25-2.6b.mdx | 192 +- lfm/models/lfm25-230m.mdx | 117 +- lfm/models/lfm25-24b-a2b.mdx | 158 +- lfm/models/lfm25-350m.mdx | 115 +- lfm/models/lfm25-8b-a1b.mdx | 157 +- lfm/models/lfm25-audio-1.5b-jp.mdx | 41 +- lfm/models/lfm25-vl-1.6b.mdx | 161 +- lfm/models/lfm25-vl-3b.mdx | 272 +- lfm/models/lfm25-vl-450m.mdx | 161 +- lfm/models/lfm3-1.7b.mdx | 23 +- lfm/models/lfm3-audio-2b.mdx | 37 +- lfm/models/lfm3-omni-2b.mdx | 54 +- lfm/models/lfm3-vl-2b.mdx | 34 +- link-snapshot.yaml | 19 + scripts/generate_snippets.py | 4 +- scripts/materializeQuickstarts.mjs | 94 + scripts/materializeQuickstarts.test.mjs | 28 + scripts/supplementOpenApi.mjs | 173 ++ scripts/supplementOpenApi.test.mjs | 37 + scripts/validation/claude-audit-followup.md | 38 + snippets/quickstart/text-transformers.mdx | 4 +- 86 files changed, 6304 insertions(+), 830 deletions(-) create mode 100644 lfm/models/lfm25-1.2b-base.mdx create mode 100644 scripts/materializeQuickstarts.mjs create mode 100644 scripts/materializeQuickstarts.test.mjs create mode 100644 scripts/supplementOpenApi.mjs create mode 100644 scripts/supplementOpenApi.test.mjs create mode 100644 scripts/validation/claude-audit-followup.md diff --git a/.github/workflows/check-link-snapshot.yaml b/.github/workflows/check-link-snapshot.yaml index d9f6984..b28d7cd 100644 --- a/.github/workflows/check-link-snapshot.yaml +++ b/.github/workflows/check-link-snapshot.yaml @@ -19,5 +19,9 @@ jobs: node-version: "22" cache: "npm" - run: npm ci + - name: Verify model quickstarts and API schema supplements + run: | + node --test scripts/materializeQuickstarts.test.mjs scripts/supplementOpenApi.test.mjs + node scripts/materializeQuickstarts.mjs --check - name: Verify snapshot contract run: npm run snapshot:check diff --git a/README.md b/README.md index 67fe64d..9e4d5d3 100644 --- a/README.md +++ b/README.md @@ -170,12 +170,25 @@ The documentation will be available at `http://localhost:3000` (or `http://local For more details on Mintlify setup and configuration, visit the [official Mintlify documentation](https://mintlify.com/docs/quickstart). +### Model quickstarts + +Shared quickstarts are rendered into literal Markdown code blocks on model pages. This keeps code copyable in both the website and `.md`/LLM exports. Edit the shared template or notebook, then regenerate: + +```bash +uv run scripts/generate_snippets.py +node scripts/materializeQuickstarts.mjs +``` + +The `quickstart` comments in model pages retain the component name and parameters. Edit those parameters to change a model's example, then run the materializer again. CI checks both generated snippets and model-page output. + ### Liquid API Reference -The **Hosted API** tab documents the hosted Liquid API served by Liquid Console. The endpoint pages under **API reference** are generated by Mintlify from [`api/openapi.json`](./api/openapi.json). Don't edit that file by hand: it is exported from the endpoint registry in the console repository (`apps/web/lib/api/docs.ts`). After an API change lands there, regenerate it from the console's `apps/web` directory and open a pull request here with the result: +The **Hosted API** tab documents the hosted Liquid API served by Liquid Console. The endpoint pages under **API reference** are generated by Mintlify from [`api/openapi.json`](./api/openapi.json). Export the baseline from the endpoint registry in the console repository (`apps/web/lib/api/docs.ts`), then apply the maintained schema supplements in this repository. The supplements describe runtime-validated fields that are not yet represented completely in the registry; keep them aligned with the endpoint validators when the API changes. After an API change lands there, regenerate it from the console's `apps/web` directory and open a pull request here with the result: ```bash bun run openapi:export /api/openapi.json +# From this docs repository: +node scripts/supplementOpenApi.mjs ``` The overview, quickstart, models page, and guides under `api/` are written by hand. diff --git a/api/guides/batch.mdx b/api/guides/batch.mdx index 2b00628..4f7606f 100644 --- a/api/guides/batch.mdx +++ b/api/guides/batch.mdx @@ -73,7 +73,7 @@ The Batch API runs a file of requests asynchronously, for work that doesn't need A completed batch has an `output_file_id`, and an `error_file_id` if any requests failed. Download each with [`GET /openai/v1/files/{id}/content`](/api/reference/files/retrieve-file-content). Each line of the output is one result, with the `custom_id` of its request, so match results to requests by `custom_id`. ```bash - curl https://api.liquid.ai/openai/v1/files/$OUTPUT_FILE_ID/content \ + curl -L "https://api.liquid.ai/openai/v1/files/$OUTPUT_FILE_ID/content" \ -H "Authorization: Bearer $LIQUID_API_KEY" > batch_output.jsonl ``` diff --git a/api/guides/decisions.mdx b/api/guides/decisions.mdx index 8cf3c2a..02cf879 100644 --- a/api/guides/decisions.mdx +++ b/api/guides/decisions.mdx @@ -87,7 +87,7 @@ curl https://api.liquid.ai/decisions/v1/systemone \ | ---- | ------- | ---------- | | Noul | One probability that the answer is yes. | Yes/no gates, moderation, flags. | | Choice | The most likely option, its confidence, and the full distribution over options. | Classification and routing. | -| Score | The most likely level, its confidence, and the full distribution over ordered levels. | Rating and prioritization. | +| Score | A probability-weighted value across ordered levels, its confidence, and the full distribution. | Rating and prioritization. | | Choice with `multiple` | Every option that applies, each with its own probability. | Tagging and multi-label classification. | | Text, Number, Date | A value read from the state, with the characters it came from, or "not found". | Extraction from documents, forms, and messages. | | Number with `range` | An estimate with a likely range. | Counts and quantities. | diff --git a/api/guides/your-data.mdx b/api/guides/your-data.mdx index 61a8069..7b6e0f6 100644 --- a/api/guides/your-data.mdx +++ b/api/guides/your-data.mdx @@ -5,13 +5,17 @@ description: "How the Liquid API uses and retains your prompts, outputs, and usa How we handle your data depends on the endpoint you use. -## Standard endpoints +## Direct online inference -Liquid may save prompts and outputs and use them to improve our models and services. +The direct API endpoints `POST /openai/v1/chat/completions` and `POST /decisions/v1/systemone` use zero data retention (ZDR). -## ZDR endpoints +For these endpoints, we use request content, including prompts, system instructions, files, and responses, only to process and return the requested response. Other than temporary in-memory processing required to complete the request, we don't log, store, cache, or otherwise retain request content. Any temporary processing data is deleted when the request is complete. We don't use request content to train, fine-tune, evaluate, benchmark, or improve our models or services. -For endpoints identified as zero data retention (ZDR), we use request content, including prompts, system instructions, files, and responses, only to process and return the requested response. Other than temporary in-memory processing required to complete the request, we don't log, store, cache, or otherwise retain request content. Any temporary processing data is deleted when the request is complete. We don't use request content to train, fine-tune, evaluate, benchmark, or improve our models or services. +## Batch files and other surfaces + +The Files and Batch APIs store uploaded inputs and generated outputs so asynchronous jobs can read them and you can download results. They are not covered by the online inference ZDR statement above. Do not treat a presigned file upload as temporary in-memory inference. + +Console playgrounds and third-party platforms can have different data handling. Check the terms and data settings of the surface you use. ## Usage information diff --git a/api/models.mdx b/api/models.mdx index 440fec1..d49fcff 100644 --- a/api/models.mdx +++ b/api/models.mdx @@ -9,13 +9,15 @@ Pass a model's id as `model` in your request. Your organization's models, with t Call these through [chat completions](/api/guides/text-generation). -| Model | Input | Output | Context window | Best for | -| ----- | ----- | ------ | -------------- | -------- | -| `lfm3-1.7b` | Text | Text | 128,000 | Fast agents, tool use, and everyday chat. | -| `lfm3-vl-2b` | Text, images | Text | 128,000 | [Vision](/api/guides/vision): describing, reading, and reasoning about images. | -| `lfm3-audio-2b` | Text, audio | Text, speech | 128,000 | [Audio](/api/guides/audio): transcription, translation, and spoken replies. | -| `lfm3-omni-2b` | Text, audio, images | Text, speech | 128,000 | [Audio](/api/guides/audio) and images in one conversation. | -| `lfm2.5-24b-a2b` | Text | Text | 128,000 | Our largest model: a reasoning mixture of experts (24B, 2B active) for harder tasks. | +| Model | Input | Output | Best for | +| ----- | ----- | ------ | -------- | +| `lfm3-1.7b` | Text | Text | Fast agents, tool use, and everyday chat. | +| `lfm3-vl-2b` | Text, images | Text | [Vision](/api/guides/vision): describing, reading, and reasoning about images. | +| `lfm3-audio-2b` | Text, audio | Text, speech | [Audio](/api/guides/audio): transcription, translation, and spoken replies. | +| `lfm3-omni-2b` | Text, audio, images | Text, speech | [Audio](/api/guides/audio) and images in one conversation. | +| `lfm2.5-24b-a2b` | Text | Text | Our largest model: a reasoning mixture of experts (24B, 2B active) for harder tasks. | + +Hosted input limits can differ from a checkpoint's native context length. Check the selected model in [Liquid Console](https://console.liquid.ai/dashboard/models) before sizing requests; the open-weight model card alone does not establish the hosted limit. ## Decision models diff --git a/api/openapi.json b/api/openapi.json index 95f8af7..3938698 100644 --- a/api/openapi.json +++ b/api/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "Liquid inference API", "version": "1.0.0", - "description": "OpenAI-compatible inference API plus native endpoints.\n\n**Authentication** — Every request needs an API key, sent as a bearer token: `Authorization: Bearer $LIQUID_API_KEY`. Create a key on the [API keys](https://console.liquid.ai/dashboard/api-keys) page of Liquid Console; it is shown once.\n\n**Batch uploads** — Batch input files are uploaded through a presigned URL from `POST /v1/files`; see the [Batch guide](https://docs.liquid.ai/api/guides/batch).\n\n**Decision models** — `POST /decisions/v1/systemone` implements TypeSafe's System One API for typed Choice, Score, and Noul decisions from decision models such as `d1.1` and `d1-ultra`." + "description": "OpenAI-compatible inference API plus native endpoints.\n\n**Authentication** — Every request needs an API key, sent as a bearer token: `Authorization: Bearer $LIQUID_API_KEY`. Create a key on the [API keys](https://console.liquid.ai/dashboard/api-keys) page of Liquid Console; it is shown once.\n\n**Batch uploads** — Batch input files are uploaded through a presigned URL from `POST /v1/files`; see the [Batch guide](https://docs.liquid.ai/api/guides/batch).\n\n**Decision models** — `POST /decisions/v1/systemone` answers typed questions using models such as `d1.2` and `d1.2-ultra`." }, "servers": [ { @@ -42,6 +42,1620 @@ "scheme": "bearer", "description": "A Liquid API key from the [API keys](https://console.liquid.ai/dashboard/api-keys) page of Liquid Console, sent as `Authorization: Bearer $LIQUID_API_KEY`." } + }, + "schemas": { + "FunctionToolCall": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "type": { + "const": "function", + "type": "string" + }, + "function": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "arguments": { + "type": "string", + "description": "JSON-encoded function arguments." + } + }, + "required": [ + "name", + "arguments" + ] + } + }, + "required": [ + "id", + "type", + "function" + ] + }, + "FunctionTool": { + "type": "object", + "properties": { + "type": { + "const": "function", + "type": "string" + }, + "function": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "parameters": { + "type": "object", + "additionalProperties": true, + "description": "JSON Schema for function arguments." + }, + "strict": { + "type": "boolean" + } + }, + "required": [ + "name" + ] + } + }, + "required": [ + "type", + "function" + ] + }, + "ChatMessage": { + "oneOf": [ + { + "type": "object", + "properties": { + "role": { + "type": "string", + "enum": [ + "system", + "developer" + ] + }, + "content": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "const": "text" + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "text" + ] + } + } + ] + }, + "name": { + "type": "string" + } + }, + "required": [ + "role", + "content" + ] + }, + { + "type": "object", + "properties": { + "role": { + "const": "user", + "type": "string" + }, + "content": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "const": "text" + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "text" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "image_url" + }, + "image_url": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "Public HTTP(S) image URL or base64 image data URL." + }, + "detail": { + "type": "string", + "enum": [ + "auto", + "low", + "high" + ] + } + }, + "required": [ + "url" + ] + } + }, + "required": [ + "type", + "image_url" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "input_audio" + }, + "input_audio": { + "type": "object", + "properties": { + "data": { + "type": "string", + "description": "Base64 WAV bytes, without a data URL prefix." + }, + "format": { + "const": "wav", + "type": "string" + } + }, + "required": [ + "data", + "format" + ] + } + }, + "required": [ + "type", + "input_audio" + ] + } + ] + } + } + ] + }, + "name": { + "type": "string" + } + }, + "required": [ + "role", + "content" + ] + }, + { + "type": "object", + "properties": { + "role": { + "const": "assistant", + "type": "string" + }, + "content": { + "anyOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "object", + "properties": { + "type": { + "const": "text" + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "text" + ] + } + } + ] + }, + { + "type": "null" + } + ] + }, + "reasoning": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "reasoning_content": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "tool_calls": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FunctionToolCall" + } + }, + "name": { + "type": "string" + } + }, + "required": [ + "role" + ], + "anyOf": [ + { + "required": [ + "content" + ] + }, + { + "required": [ + "tool_calls" + ] + } + ] + }, + { + "type": "object", + "properties": { + "role": { + "const": "tool", + "type": "string" + }, + "content": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "const": "text" + }, + "text": { + "type": "string" + } + }, + "required": [ + "type", + "text" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "image_url" + }, + "image_url": { + "type": "object", + "properties": { + "url": { + "type": "string", + "description": "Public HTTP(S) image URL or base64 image data URL." + }, + "detail": { + "type": "string", + "enum": [ + "auto", + "low", + "high" + ] + } + }, + "required": [ + "url" + ] + } + }, + "required": [ + "type", + "image_url" + ] + } + ] + } + } + ] + }, + "tool_call_id": { + "type": "string" + } + }, + "required": [ + "role", + "content", + "tool_call_id" + ] + } + ], + "description": "Role-specific OpenAI-compatible messages. Tool results must use the corresponding tool_call_id. Preserve returned reasoning with an assistant tool-call turn when the model requires it. Earlier spoken replies must be sent as their transcript in content; audio.id alone is not supported." + }, + "ReplyAudio": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "data": { + "type": "string", + "description": "Base64 audio bytes." + }, + "transcript": { + "type": "string" + }, + "expires_at": { + "type": "integer" + } + } + }, + "DecisionQuestion": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "const": "noul", + "type": "string" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + }, + "criteria": { + "anyOf": [ + { + "type": "object", + "properties": { + "true": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + }, + "false": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + } + } + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "type", + "instructions" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "choice", + "type": "string" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + }, + "multiple": { + "type": "boolean", + "default": false + }, + "criteria": { + "type": "object", + "additionalProperties": { + "anyOf": [ + { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + }, + { + "type": "null" + } + ] + }, + "minProperties": 2, + "maxProperties": 255 + } + }, + "required": [ + "type", + "instructions", + "criteria" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "score", + "type": "string" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + }, + "criteria": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + }, + "minItems": 2, + "maxItems": 10 + } + }, + "required": [ + "type", + "instructions", + "criteria" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "text", + "type": "string" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + } + }, + "required": [ + "type", + "instructions" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "date", + "type": "string" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + } + }, + "required": [ + "type", + "instructions" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "number", + "type": "string" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + }, + "unit": { + "type": "string" + }, + "range": { + "type": "array", + "items": { + "type": "number" + }, + "minItems": 2, + "maxItems": 2, + "description": "Ascending [low, high] interval for estimation. Without range, read a number from the state." + }, + "step": { + "type": "number", + "exclusiveMinimum": 0, + "description": "Requires range and must divide it into equal parts." + } + }, + "required": [ + "type", + "instructions" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "box", + "type": "string" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + } + }, + "required": [ + "type", + "instructions" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "boxes", + "type": "string" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + }, + "max": { + "type": "integer", + "minimum": 1, + "maximum": 64 + } + }, + "required": [ + "type", + "instructions" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "spans", + "type": "string" + }, + "instructions": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "additionalProperties": true + }, + { + "type": "array", + "items": {} + } + ] + }, + "max": { + "type": "integer", + "minimum": 1, + "maximum": 64 + } + }, + "required": [ + "type", + "instructions" + ] + } + ], + "description": "Named typed question. box and boxes require exactly one image. Instructions are written text or JSON; send audio clips in the request audio array, not as spoken instructions." + }, + "DecisionAnswer": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "const": "noul", + "type": "string" + }, + "noul": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "type", + "noul" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "choice", + "type": "string" + }, + "choice": { + "type": "string" + }, + "probabilities": { + "type": "object", + "additionalProperties": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "type", + "choice", + "probabilities", + "confidence" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "choice", + "type": "string" + }, + "choices": { + "type": "array", + "items": { + "type": "string" + } + }, + "probabilities": { + "type": "object", + "additionalProperties": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + } + }, + "required": [ + "type", + "choices", + "probabilities" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "score", + "type": "string" + }, + "score": { + "type": "number" + }, + "legend": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "probabilities": { + "type": "object", + "additionalProperties": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "type", + "score", + "legend", + "probabilities", + "confidence" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "text", + "type": "string" + }, + "text": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "span": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "minItems": 2, + "maxItems": 2 + }, + { + "type": "null" + } + ] + }, + "found": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "path": { + "type": "string", + "description": "JSON Pointer for a span in a JSON state, when provided." + } + }, + "required": [ + "type", + "text", + "span", + "found" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "date", + "type": "string" + }, + "date": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "text": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "span": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "minItems": 2, + "maxItems": 2 + }, + { + "type": "null" + } + ] + }, + "found": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "path": { + "type": "string", + "description": "JSON Pointer for a span in a JSON state, when provided." + } + }, + "required": [ + "type", + "date", + "text", + "span", + "found" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "number", + "type": "string" + }, + "number": { + "anyOf": [ + { + "type": "number" + }, + { + "type": "null" + } + ] + }, + "unit": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "text": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "span": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "minItems": 2, + "maxItems": 2 + }, + { + "type": "null" + } + ] + }, + "found": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "path": { + "type": "string", + "description": "JSON Pointer for a span in a JSON state, when provided." + } + }, + "required": [ + "type", + "number", + "unit", + "text", + "span", + "found" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "number", + "type": "string" + }, + "number": { + "type": "number" + }, + "interval": { + "type": "array", + "items": { + "type": "number" + }, + "minItems": 2, + "maxItems": 2 + }, + "unit": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "type", + "number", + "interval", + "unit" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "box", + "type": "string" + }, + "box": { + "anyOf": [ + { + "type": "object", + "properties": { + "top": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "bottom": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "left": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "right": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "top", + "bottom", + "left", + "right" + ] + }, + { + "type": "null" + } + ] + }, + "found": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "type", + "box", + "found", + "confidence" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "boxes", + "type": "string" + }, + "boxes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "box": { + "type": "object", + "properties": { + "top": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "bottom": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "left": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "right": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "top", + "bottom", + "left", + "right" + ] + }, + "found": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "confidence": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + }, + "required": [ + "box", + "found", + "confidence" + ] + } + }, + "count": { + "type": "integer", + "minimum": 0 + }, + "at_least": { + "type": "boolean" + }, + "presence": { + "type": "array", + "items": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + } + }, + "required": [ + "type", + "boxes", + "count", + "at_least", + "presence" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "spans", + "type": "string" + }, + "spans": { + "type": "array", + "items": { + "type": "object", + "properties": { + "text": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "span": { + "anyOf": [ + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "minItems": 2, + "maxItems": 2 + }, + { + "type": "null" + } + ] + }, + "found": { + "type": "number", + "minimum": 0, + "maximum": 1 + }, + "path": { + "type": "string", + "description": "JSON Pointer for a span in a JSON state, when provided." + } + }, + "required": [ + "text", + "span", + "found" + ] + } + }, + "count": { + "type": "integer", + "minimum": 0 + }, + "at_least": { + "type": "boolean" + }, + "presence": { + "type": "array", + "items": { + "type": "number", + "minimum": 0, + "maximum": 1 + } + } + }, + "required": [ + "type", + "spans", + "count", + "at_least", + "presence" + ] + } + ], + "description": "An answer for the question under the same key. Read values are null when found < 0.5. Spans are [start, end) Unicode code-point offsets into the state (JSON states use two-space indentation). Box edges are fractions of the image. Estimate interval is [p10, p90]." + }, + "ApiError": { + "type": "object", + "properties": { + "error": { + "type": "object", + "properties": { + "message": { + "type": "string" + }, + "type": { + "type": "string" + }, + "param": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "code": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "message", + "type", + "param", + "code" + ] + } + }, + "required": [ + "error" + ] + }, + "Model": { + "type": "object", + "properties": { + "id": { + "type": "string" + }, + "object": { + "const": "model" + }, + "created": { + "type": "integer" + }, + "owned_by": { + "type": "string" + } + }, + "required": [ + "id", + "object", + "created", + "owned_by" + ] + }, + "DecisionModel": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Model id to pass in the request." + }, + "description": { + "type": "string" + }, + "release_date": { + "type": "string", + "format": "date" + }, + "input_modalities": { + "type": "array", + "items": { + "type": "string", + "enum": [ + "text", + "image", + "audio" + ] + } + } + }, + "required": [ + "name", + "description", + "release_date", + "input_modalities" + ] + }, + "File": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The file id, referenced when creating a batch." + }, + "object": { + "type": "string", + "description": "Always \"file\"." + }, + "bytes": { + "type": "integer", + "description": "Size of the file in bytes." + }, + "created_at": { + "type": "integer", + "description": "Unix timestamp (seconds) of creation." + }, + "filename": { + "type": "string", + "description": "The name the file was uploaded with." + }, + "purpose": { + "type": "string", + "description": "Either \"batch\" (an input) or \"batch_output\" (a generated result/error file)." + }, + "status": { + "type": "string", + "description": "Always \"processed\"; stored files are ready." + }, + "expires_at": { + "type": "integer", + "description": "Unix expiry timestamp, when an expiry is set." + } + } + }, + "Batch": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The batch id." + }, + "object": { + "type": "string", + "description": "Always \"batch\"." + }, + "endpoint": { + "type": "string", + "description": "The endpoint each request targets." + }, + "input_file_id": { + "type": "string", + "description": "The uploaded input file id." + }, + "output_file_id": { + "type": "string", + "description": "Result file id, once completed." + }, + "error_file_id": { + "type": "string", + "description": "Error file id, if any requests failed." + }, + "status": { + "type": "string", + "description": "One of validating, in_progress, finalizing, completed, failed, expired, cancelling, cancelled." + }, + "completion_window": { + "type": "string", + "description": "The requested completion window." + }, + "request_counts": { + "type": "object", + "properties": { + "total": { + "type": "integer" + }, + "completed": { + "type": "integer" + }, + "failed": { + "type": "integer" + } + }, + "required": [ + "total", + "completed", + "failed" + ] + }, + "created_at": { + "type": "integer", + "description": "Unix timestamp in seconds; optional until the corresponding event occurs." + }, + "errors": { + "type": "object", + "properties": { + "object": { + "const": "list" + }, + "data": { + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "message": { + "type": "string" + }, + "param": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "line": { + "type": "integer" + } + } + } + } + } + }, + "metadata": { + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "in_progress_at": { + "type": "integer", + "description": "Unix timestamp in seconds; optional until the corresponding event occurs." + }, + "finalizing_at": { + "type": "integer", + "description": "Unix timestamp in seconds; optional until the corresponding event occurs." + }, + "completed_at": { + "type": "integer", + "description": "Unix timestamp in seconds; optional until the corresponding event occurs." + }, + "failed_at": { + "type": "integer", + "description": "Unix timestamp in seconds; optional until the corresponding event occurs." + }, + "expires_at": { + "type": "integer", + "description": "Unix timestamp in seconds; optional until the corresponding event occurs." + }, + "cancelled_at": { + "type": "integer", + "description": "Unix timestamp in seconds; optional until the corresponding event occurs." + } + } + } } }, "paths": { @@ -62,7 +1676,7 @@ "object": "list", "data": [ { - "id": "$MODEL_ID", + "id": "lfm3-1.7b", "object": "model", "created": 1730419200, "owned_by": "liquid" @@ -79,25 +1693,7 @@ "data": { "type": "array", "items": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The model id to pass as `model`." - }, - "object": { - "type": "string", - "description": "Always \"model\"." - }, - "created": { - "type": "integer", - "description": "Unix timestamp (seconds)." - }, - "owned_by": { - "type": "string", - "description": "Always \"liquid\"." - } - } + "$ref": "#/components/schemas/Model" }, "description": "The list of model objects." } @@ -130,31 +1726,13 @@ "content": { "application/json": { "example": { - "id": "$MODEL_ID", + "id": "lfm3-1.7b", "object": "model", "created": 1730419200, "owned_by": "liquid" }, "schema": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The model id to pass as `model`." - }, - "object": { - "type": "string", - "description": "Always \"model\"." - }, - "created": { - "type": "integer", - "description": "Unix timestamp (seconds)." - }, - "owned_by": { - "type": "string", - "description": "Always \"liquid\"." - } - } + "$ref": "#/components/schemas/Model" } } } @@ -164,7 +1742,7 @@ { "lang": "curl", "label": "cURL", - "source": "curl https://api.liquid.ai/openai/v1/models/$MODEL_ID \\\n -H \"Authorization: Bearer $LIQUID_API_KEY\"" + "source": "curl https://api.liquid.ai/openai/v1/models/lfm3-1.7b \\\n -H \"Authorization: Bearer $LIQUID_API_KEY\"" } ], "parameters": [ @@ -175,7 +1753,7 @@ "description": "The model id.", "schema": { "type": "string", - "example": "$MODEL_ID" + "example": "lfm3-1.7b" } } ] @@ -185,7 +1763,7 @@ "post": { "operationId": "chat-completions", "summary": "Chat completions", - "description": "Generate a model response for a chat conversation. See [Text generation](https://docs.liquid.ai/api/guides/text-generation).", + "description": "Generate a model response for a chat conversation. See [Text generation](https://docs.liquid.ai/api/guides/text-generation). Sampling, tool calling, reasoning, and structured output support depend on the selected model. With stream=true the response is text/event-stream, rather than a JSON completion.", "tags": [ "Chat" ], @@ -198,7 +1776,7 @@ "id": "chatcmpl-abc123", "object": "chat.completion", "created": 1730419200, - "model": "$MODEL_ID", + "model": "lfm3-1.7b", "choices": [ { "index": 0, @@ -236,7 +1814,81 @@ }, "choices": { "type": "array", - "items": {}, + "items": { + "type": "object", + "properties": { + "index": { + "type": "integer" + }, + "message": { + "type": "object", + "properties": { + "role": { + "const": "assistant" + }, + "content": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + }, + "reasoning": { + "anyOf": [ + { + "type": "string", + "description": "Reasoning text when returned by the model/parser." + }, + { + "type": "null" + } + ] + }, + "reasoning_content": { + "anyOf": [ + { + "type": "string", + "description": "Provider-compatible reasoning field, when returned." + }, + { + "type": "null" + } + ] + }, + "tool_calls": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FunctionToolCall" + } + }, + "audio": { + "$ref": "#/components/schemas/ReplyAudio" + } + }, + "required": [ + "role" + ] + }, + "finish_reason": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ] + } + }, + "required": [ + "index", + "message", + "finish_reason" + ] + }, "description": "The generated choices." }, "usage": { @@ -246,6 +1898,83 @@ } } } + }, + "text/event-stream": { + "schema": { + "type": "string", + "description": "Server-sent events when stream=true. Each data event is a chat.completion.chunk with choices[].delta (content, reasoning, tool_calls, or audio) and finish_reason. A usage chunk may have an empty choices array. The stream ends with data: [DONE]." + }, + "example": "data: {\"object\":\"chat.completion.chunk\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hello\"},\"finish_reason\":null}]}\n\ndata: [DONE]\n\n" + } + } + }, + "400": { + "description": "Invalid request or unsupported modality.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Missing or invalid API key.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "402": { + "description": "Insufficient credit.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Access denied.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Unknown or unavailable model id.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "413": { + "description": "Request body exceeds the endpoint limit.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "422": { + "description": "Request validation failed or the model input limit was exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } } } }, @@ -306,11 +2035,44 @@ "application/json": { "example": { "error": { - "message": "Rate limit exceeded for model `$MODEL_ID`. To request a higher limit, contact us at https://www.liquid.ai/connect.", + "message": "Rate limit exceeded for model `lfm3-1.7b`. To request a higher limit, contact us at https://www.liquid.ai/connect.", "type": "rate_limit_error", "param": null, "code": "rate_limit_exceeded" } + }, + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "502": { + "description": "Inference backend failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "503": { + "description": "Model temporarily unavailable.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "504": { + "description": "Inference deadline exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" } } } @@ -320,7 +2082,7 @@ { "lang": "curl", "label": "cURL", - "source": "curl https://api.liquid.ai/openai/v1/chat/completions \\\n -H \"Authorization: Bearer $LIQUID_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"$MODEL_ID\",\n \"messages\": [\n {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"user\", \"content\": \"Hello!\"}\n ]\n }'" + "source": "curl https://api.liquid.ai/openai/v1/chat/completions \\\n -H \"Authorization: Bearer $LIQUID_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"lfm3-1.7b\",\n \"messages\": [\n {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"user\", \"content\": \"Hello!\"}\n ]\n }'" } ], "requestBody": { @@ -333,12 +2095,15 @@ "model": { "type": "string", "description": "The model id to use.", - "example": "$MODEL_ID" + "example": "lfm3-1.7b" }, "messages": { "type": "array", - "items": {}, - "description": "The conversation so far. Messages follow OpenAI role-specific content requirements. User messages may include `image_url` parts for models that take images, each a base64 `data:` URL or an http(s) URL, and `input_audio` parts (base64 WAV, `format: \"wav\"`) for models that take audio; other models return 400. Liquid downloads linked images itself before the request reaches the model, from public addresses only, and returns 400 when one cannot be downloaded or is not a PNG, JPEG, WebP, or GIF image; a request may link up to 8 images, of at most 10 MB each and 20 MB together." + "items": { + "$ref": "#/components/schemas/ChatMessage" + }, + "description": "The conversation so far. Messages follow OpenAI role-specific content requirements. User messages may include `image_url` parts for models that take images, each a base64 `data:` URL or an http(s) URL, and `input_audio` parts (base64 WAV, `format: \"wav\"`) for models that take audio; other models return 400. Liquid downloads linked images itself before the request reaches the model, from public addresses only, and returns 400 when one cannot be downloaded or is not a PNG, JPEG, WebP, or GIF image; a request may link up to 8 images, of at most 10 MB each and 20 MB together.", + "minItems": 1 }, "stream": { "type": "boolean", @@ -346,13 +2111,199 @@ }, "modalities": { "type": "array", - "items": {}, + "items": { + "type": "string", + "enum": [ + "text", + "audio" + ] + }, "description": "Output types. [\"text\", \"audio\"] asks a model with speech output for a spoken reply, returned in `message.audio` (or streamed in `delta.audio`) beside the text. Defaults to [\"text\"]; models without speech output return 400." }, - "audio": { + "audio": { + "type": "object", + "additionalProperties": true, + "description": "Spoken reply options when `modalities` includes \"audio\", as in OpenAI: `{ \"voice\", \"format\" }`. `format` is `pcm16` (headerless 16-bit PCM, 24 kHz mono), or `wav` (each streamed chunk a complete WAV file); other formats return 400. The reply arrives in `message.audio` or streamed `delta.audio`, with its words in `transcript`. `voice` is accepted but does not change the voice.", + "properties": { + "format": { + "type": "string", + "enum": [ + "pcm16", + "wav" + ] + }, + "voice": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "object", + "properties": { + "id": { + "type": "string" + } + }, + "required": [ + "id" + ] + } + ], + "description": "Accepted for compatibility; does not change the voice." + } + } + }, + "temperature": { + "type": "number", + "description": "Sampling temperature; supported values depend on the model." + }, + "top_p": { + "type": "number", + "description": "Nucleus sampling probability." + }, + "top_k": { + "type": "integer", + "description": "Top-k sampling, when supported by the model." + }, + "repetition_penalty": { + "type": "number" + }, + "max_tokens": { + "type": "integer", + "minimum": 1, + "description": "Maximum generated tokens, including reasoning. Leave enough room for a final answer." + }, + "max_completion_tokens": { + "type": "integer", + "minimum": 1, + "description": "OpenAI-compatible output budget; model support may vary. Use one output-budget field per request." + }, + "stop": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ] + }, + "tools": { + "type": "array", + "items": { + "$ref": "#/components/schemas/FunctionTool" + } + }, + "tool_choice": { + "anyOf": [ + { + "type": "string", + "enum": [ + "none", + "auto", + "required" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "function" + }, + "function": { + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "required": [ + "name" + ] + } + }, + "required": [ + "type", + "function" + ] + } + ] + }, + "response_format": { + "oneOf": [ + { + "type": "object", + "properties": { + "type": { + "const": "text" + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "json_object" + } + }, + "required": [ + "type" + ] + }, + { + "type": "object", + "properties": { + "type": { + "const": "json_schema" + }, + "json_schema": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "description": { + "type": "string" + }, + "schema": { + "type": "object", + "additionalProperties": true + }, + "strict": { + "type": "boolean" + } + }, + "required": [ + "name", + "schema" + ] + } + }, + "required": [ + "type", + "json_schema" + ] + } + ], + "description": "Structured output format, where supported by the selected model." + }, + "stream_options": { "type": "object", - "additionalProperties": true, - "description": "Spoken reply options when `modalities` includes \"audio\", as in OpenAI: `{ \"voice\", \"format\" }`. `format` is `pcm16` (headerless 16-bit PCM, 24 kHz mono), or `wav` (each streamed chunk a complete WAV file); other formats return 400. The reply arrives in `message.audio` or streamed `delta.audio`, with its words in `transcript`. `voice` is accepted but does not change the voice." + "properties": { + "include_usage": { + "type": "boolean" + } + } + }, + "user": { + "type": "string", + "description": "Optional caller identifier." } }, "required": [ @@ -361,7 +2312,7 @@ ] }, "example": { - "model": "$MODEL_ID", + "model": "lfm3-1.7b", "messages": [ { "role": "system", @@ -382,7 +2333,7 @@ "post": { "operationId": "decisions", "summary": "Make decisions", - "description": "Answer typed questions about a state with calibrated probabilities, using TypeSafe's System One API. See [Decisions](https://docs.liquid.ai/api/guides/decisions).", + "description": "Answer named typed questions about text, JSON, images, or audio. Supports noul, choice (including multiple=true), score, text, date, number, box, boxes, and spans. See [Decisions](https://docs.liquid.ai/api/guides/decisions) for examples. The hosted endpoint does not accept video or spoken question instructions; open-weight model APIs have different input shapes.", "tags": [ "Decision models" ], @@ -392,7 +2343,7 @@ "content": { "application/json": { "example": { - "model": "$DECISION_MODEL_ID", + "model": "d1.2", "answers": { "department": { "type": "choice", @@ -438,8 +2389,10 @@ }, "answers": { "type": "object", - "additionalProperties": true, - "description": "One answer per question id. Choice: `choice`, `probabilities` per option, `confidence`. Score: `score` (probability-weighted, may fall between levels), `legend`, `probabilities` per level, `confidence`. Noul: `noul`, the probability of yes. Confidence runs from 0 (probability spread evenly) to 1 (all on one answer); for a Score it also counts how far the probability sits from the most likely level, so a split between the two ends of the scale is 0." + "additionalProperties": { + "$ref": "#/components/schemas/DecisionAnswer" + }, + "description": "One typed answer per question id, under the same keys." }, "usage": { "type": "object", @@ -451,6 +2404,76 @@ } } }, + "400": { + "description": "Invalid request or unsupported modality.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "401": { + "description": "Missing or invalid API key.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "402": { + "description": "Insufficient credit.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "403": { + "description": "Access denied.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "404": { + "description": "Unknown or unavailable model id.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "413": { + "description": "Request body exceeds the endpoint limit.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "422": { + "description": "Request validation failed or the model input limit was exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, "429": { "description": "The organization's request or token limit for the model was exceeded.", "headers": { @@ -508,11 +2531,44 @@ "application/json": { "example": { "error": { - "message": "Rate limit exceeded for model `$MODEL_ID`. To request a higher limit, contact us at https://www.liquid.ai/connect.", + "message": "Rate limit exceeded for model `lfm3-1.7b`. To request a higher limit, contact us at https://www.liquid.ai/connect.", "type": "rate_limit_error", "param": null, "code": "rate_limit_exceeded" } + }, + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "502": { + "description": "Inference backend failed.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "503": { + "description": "Model temporarily unavailable.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" + } + } + } + }, + "504": { + "description": "Inference deadline exceeded.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ApiError" } } } @@ -522,7 +2578,7 @@ { "lang": "curl", "label": "cURL", - "source": "curl https://api.liquid.ai/decisions/v1/systemone \\\n -H \"Authorization: Bearer $LIQUID_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"$DECISION_MODEL_ID\",\n \"state\": \"Help! My payouts have been failing for 3 days.\",\n \"questions\": {\n \"department\": {\n \"type\": \"choice\",\n \"instructions\": \"Which team should handle this?\",\n \"criteria\": {\n \"billing\": \"Payments, invoicing, refunds\",\n \"technical\": \"Bugs, outages, integrations\",\n \"sales\": \"Pricing, upgrades, new accounts\"\n }\n },\n \"is_urgent\": { \"type\": \"noul\", \"instructions\": \"Does this convey urgency?\" },\n \"frustration\": {\n \"type\": \"score\",\n \"instructions\": \"How frustrated is the customer?\",\n \"criteria\": [\"Calm\", \"Frustrated\", \"Very angry\"]\n }\n }\n }'" + "source": "curl https://api.liquid.ai/decisions/v1/systemone \\\n -H \"Authorization: Bearer $LIQUID_API_KEY\" \\\n -H \"Content-Type: application/json\" \\\n -d '{\n \"model\": \"d1.2\",\n \"state\": \"Help! My payouts have been failing for 3 days.\",\n \"questions\": {\n \"department\": {\n \"type\": \"choice\",\n \"instructions\": \"Which team should handle this?\",\n \"criteria\": {\n \"billing\": \"Payments, invoicing, refunds\",\n \"technical\": \"Bugs, outages, integrations\",\n \"sales\": \"Pricing, upgrades, new accounts\"\n }\n },\n \"is_urgent\": { \"type\": \"noul\", \"instructions\": \"Does this convey urgency?\" },\n \"frustration\": {\n \"type\": \"score\",\n \"instructions\": \"How frustrated is the customer?\",\n \"criteria\": [\"Calm\", \"Frustrated\", \"Very angry\"]\n }\n }\n }'" } ], "requestBody": { @@ -534,21 +2590,89 @@ "properties": { "model": { "type": "string", - "description": "The decision model id to use. `d1:latest` and `d1-ultra:latest` always point to the newest model of their family; pin an exact id such as `d1-ultra` to keep the same model.", - "example": "$DECISION_MODEL_ID" + "description": "A decision model id from GET /decisions/v1/models, such as d1.2 or d1.2-ultra. Use the exact id returned for your organization.", + "example": "d1.2" }, "state": { "description": "The content the questions are about: plain text, or structured JSON such as a chat log or record. Omit or send null when the questions stand alone. As in Perplexity's Decisions API, an array state may also hold images as OpenAI-style `{ \"type\": \"image_url\", \"image_url\": { \"url\": \"data:…\" } }` parts: they are taken out of the state and checked under the same rules as `images`, which the request must then leave out (sending both returns 422), and a single string left beside them becomes the text state." }, "images": { "type": "array", - "items": {}, - "description": "Up to 8 images the questions are about, for decision models that accept images: those listing `image` in `input_modalities` from GET /decisions/v1/models, such as `d1`. Other models return 422. Each is a base64 `data:image/…;base64,` URL or a `{ \"content_type\", \"base64\" }` object: JPEG, PNG, or WebP, 5 MB each, within the 4.5 MB request body limit. Remote image URLs are not accepted. Images come before the state in the prompt, in the order sent, and every question sees all of them. On `d1` and `d1-ultra`, an image costs 1.5 input tokens per 32×32-pixel patch that covers it (`ceil(width / 32) × ceil(height / 32)` patches), rounded up per image, and a request is billed its images once, however many questions it asks. The images of a request may cover at most 10,000 patches in all, and no image may be more than 100 times as long as it is wide; either returns 422. This is an extension to the System One API; omit it to stay TypeSafe-compatible." + "items": { + "oneOf": [ + { + "type": "string", + "description": "Base64 data URL with a matching media content type." + }, + { + "type": "object", + "properties": { + "content_type": { + "type": "string", + "enum": [ + "image/jpeg", + "image/png", + "image/webp" + ] + }, + "base64": { + "type": "string", + "description": "Base64-encoded file bytes." + } + }, + "required": [ + "content_type", + "base64" + ] + } + ] + }, + "description": "Up to 8 JPEG, PNG, or WebP images as base64 data URLs or {content_type, base64} objects. Remote URLs are not accepted. Each image is at most 5 MiB, subject to the smaller 4.5 MiB whole-request limit. box and boxes require exactly one image. Check input_modalities in GET /decisions/v1/models for model support.", + "maxItems": 8 }, "questions": { "type": "object", - "additionalProperties": true, - "description": "Up to 128 named questions; answers come back under the same keys. Each has a `type` (\"choice\", \"score\", or \"noul\") and `instructions` (a string or JSON). A Choice takes `criteria` mapping 2–255 option names to a description or null; a Score takes `criteria` as an ordered list of 2–10 level descriptions; a Noul takes optional `criteria` of `{ \"true\": …, \"false\": … }`, used only when both are given and say more than a bare yes and no. A request is billed its state and images once plus each question's own tokens, so asking a state several questions in one request costs far less than asking them in separate requests. Every question still reads the whole state, so the input limits apply to the state, images, and one question together: `d1` and `d1.1` allow 65,536 tokens and `d1-ultra` 32,768, and all three 250 KB of text, and they return 422 over either." + "additionalProperties": { + "$ref": "#/components/schemas/DecisionQuestion" + }, + "minProperties": 1, + "maxProperties": 128, + "description": "Up to 128 named questions. Each question reads the state and media. d1.2 and d1.2-ultra allow 65,536 input tokens per question and 250,000 bytes of text; the entire request must fit the 4.5 MiB body limit." + }, + "audio": { + "type": "array", + "items": { + "oneOf": [ + { + "type": "string", + "description": "Base64 data URL with a matching media content type." + }, + { + "type": "object", + "properties": { + "content_type": { + "type": "string", + "enum": [ + "audio/wav", + "audio/mpeg", + "audio/flac", + "audio/ogg" + ] + }, + "base64": { + "type": "string", + "description": "Base64-encoded file bytes." + } + }, + "required": [ + "content_type", + "base64" + ] + } + ] + }, + "maxItems": 8, + "description": "Up to 8 WAV, MP3, FLAC, or OGG clips, at most 300 seconds combined, subject to the whole-request body limit. The declared content type must match the bytes. Check input_modalities for model support. Video is not accepted." } }, "required": [ @@ -557,7 +2681,7 @@ ] }, "example": { - "model": "$DECISION_MODEL_ID", + "model": "d1.2", "state": "Help! My payouts have been failing for 3 days.", "questions": { "department": { @@ -605,11 +2729,13 @@ "example": { "models": [ { - "name": "$DECISION_MODEL_ID", - "description": "Fast, calibrated Choice, Score, and Noul decisions.", + "name": "d1.2", + "description": "Typed decisions over text, images, and audio.", "release_date": "2026-09-22", "input_modalities": [ - "text" + "text", + "image", + "audio" ] } ] @@ -619,8 +2745,10 @@ "properties": { "models": { "type": "array", - "items": {}, - "description": "One entry per model: { name, description, release_date, input_modalities }. `input_modalities` is [\"text\"], or [\"text\", \"image\"] for a model that accepts `images`." + "items": { + "$ref": "#/components/schemas/DecisionModel" + }, + "description": "Decision models available to your organization, including accepted input modalities. Current d1.2 models accept text, images, and audio." } } } @@ -641,7 +2769,7 @@ "get": { "operationId": "list-files", "summary": "List files", - "description": "List the files your organization has uploaded.", + "description": "List all files for the organization in descending creation order. Pagination parameters are not supported.", "tags": [ "Files" ], @@ -673,7 +2801,9 @@ }, "data": { "type": "array", - "items": {}, + "items": { + "$ref": "#/components/schemas/File" + }, "description": "The list of file objects." } } @@ -714,41 +2844,7 @@ "status": "processed" }, "schema": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The file id, referenced when creating a batch." - }, - "object": { - "type": "string", - "description": "Always \"file\"." - }, - "bytes": { - "type": "integer", - "description": "Size of the file in bytes." - }, - "created_at": { - "type": "integer", - "description": "Unix timestamp (seconds) of creation." - }, - "filename": { - "type": "string", - "description": "The name the file was uploaded with." - }, - "purpose": { - "type": "string", - "description": "Either \"batch\" (an input) or \"batch_output\" (a generated result/error file)." - }, - "status": { - "type": "string", - "description": "Always \"processed\"; stored files are ready." - }, - "expires_at": { - "type": "integer", - "description": "Unix timestamp (seconds) when the file expires, if set." - } - } + "$ref": "#/components/schemas/File" } } } @@ -784,14 +2880,16 @@ "Files" ], "responses": { - "200": { - "description": "Successful response.", - "content": { - "application/jsonl": { + "302": { + "description": "Redirect to a short-lived presigned download URL. Use curl -L to retrieve the file bytes.", + "headers": { + "Location": { + "required": true, "schema": { - "type": "string" + "type": "string", + "format": "uri" }, - "example": "{\"id\": \"batch_req_abc\", \"custom_id\": \"task-1\", \"response\": {\"status_code\": 200, \"body\": {\"id\": \"chatcmpl-1\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Hi!\"}, \"finish_reason\": \"stop\"}]}}, \"error\": null}\n{\"id\": \"batch_req_def\", \"custom_id\": \"task-2\", \"response\": {\"status_code\": 200, \"body\": {\"id\": \"chatcmpl-2\", \"choices\": [{\"index\": 0, \"message\": {\"role\": \"assistant\", \"content\": \"Hello!\"}, \"finish_reason\": \"stop\"}]}}, \"error\": null}" + "description": "Presigned file download URL." } } } @@ -846,60 +2944,7 @@ } }, "schema": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The batch id." - }, - "object": { - "type": "string", - "description": "Always \"batch\"." - }, - "endpoint": { - "type": "string", - "description": "The endpoint each request targets." - }, - "input_file_id": { - "type": "string", - "description": "The uploaded input file id." - }, - "output_file_id": { - "type": "string", - "description": "Result file id, once completed." - }, - "error_file_id": { - "type": "string", - "description": "Error file id, if any requests failed." - }, - "status": { - "type": "string", - "description": "One of validating, in_progress, finalizing, completed, failed, expired, cancelling, cancelled." - }, - "completion_window": { - "type": "string", - "description": "The requested completion window." - }, - "request_counts": { - "type": "object", - "additionalProperties": true, - "description": "Live counts: { total, completed, failed }." - }, - "created_at": { - "type": "integer", - "description": "Unix timestamp (seconds) of creation." - }, - "errors": { - "type": "object", - "additionalProperties": true, - "description": "Present when the input failed validation: { object: \"list\", data: [...] }." - }, - "metadata": { - "type": "object", - "additionalProperties": true, - "description": "Any metadata supplied at creation." - } - } + "$ref": "#/components/schemas/Batch" } } } @@ -992,7 +3037,9 @@ }, "data": { "type": "array", - "items": {}, + "items": { + "$ref": "#/components/schemas/Batch" + }, "description": "The list of batch objects." } } @@ -1042,60 +3089,7 @@ } }, "schema": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The batch id." - }, - "object": { - "type": "string", - "description": "Always \"batch\"." - }, - "endpoint": { - "type": "string", - "description": "The endpoint each request targets." - }, - "input_file_id": { - "type": "string", - "description": "The uploaded input file id." - }, - "output_file_id": { - "type": "string", - "description": "Result file id, once completed." - }, - "error_file_id": { - "type": "string", - "description": "Error file id, if any requests failed." - }, - "status": { - "type": "string", - "description": "One of validating, in_progress, finalizing, completed, failed, expired, cancelling, cancelled." - }, - "completion_window": { - "type": "string", - "description": "The requested completion window." - }, - "request_counts": { - "type": "object", - "additionalProperties": true, - "description": "Live counts: { total, completed, failed }." - }, - "created_at": { - "type": "integer", - "description": "Unix timestamp (seconds) of creation." - }, - "errors": { - "type": "object", - "additionalProperties": true, - "description": "Present when the input failed validation: { object: \"list\", data: [...] }." - }, - "metadata": { - "type": "object", - "additionalProperties": true, - "description": "Any metadata supplied at creation." - } - } + "$ref": "#/components/schemas/Batch" } } } @@ -1151,60 +3145,7 @@ } }, "schema": { - "type": "object", - "properties": { - "id": { - "type": "string", - "description": "The batch id." - }, - "object": { - "type": "string", - "description": "Always \"batch\"." - }, - "endpoint": { - "type": "string", - "description": "The endpoint each request targets." - }, - "input_file_id": { - "type": "string", - "description": "The uploaded input file id." - }, - "output_file_id": { - "type": "string", - "description": "Result file id, once completed." - }, - "error_file_id": { - "type": "string", - "description": "Error file id, if any requests failed." - }, - "status": { - "type": "string", - "description": "One of validating, in_progress, finalizing, completed, failed, expired, cancelling, cancelled." - }, - "completion_window": { - "type": "string", - "description": "The requested completion window." - }, - "request_counts": { - "type": "object", - "additionalProperties": true, - "description": "Live counts: { total, completed, failed }." - }, - "created_at": { - "type": "integer", - "description": "Unix timestamp (seconds) of creation." - }, - "errors": { - "type": "object", - "additionalProperties": true, - "description": "Present when the input failed validation: { object: \"list\", data: [...] }." - }, - "metadata": { - "type": "object", - "additionalProperties": true, - "description": "Any metadata supplied at creation." - } - } + "$ref": "#/components/schemas/Batch" } } } diff --git a/deployment/on-device/llama-cpp/structured-output.mdx b/deployment/on-device/llama-cpp/structured-output.mdx index 7a8a249..3426d1c 100644 --- a/deployment/on-device/llama-cpp/structured-output.mdx +++ b/deployment/on-device/llama-cpp/structured-output.mdx @@ -83,11 +83,7 @@ curl http://localhost:8080/v1/chat/completions \ }' ``` -To see the grammar llama.cpp generates for a schema, or to ship a pre-converted grammar with your app: - -```bash -python llama.cpp/examples/json_schema_to_grammar.py schema.json > schema.gbnf -``` +The former `examples/json_schema_to_grammar.py` helper is no longer in current llama.cpp. Send `response_format` to `llama-server` to have it convert the schema, or call `json_schema_to_grammar()` from llama.cpp's [common library](https://github.com/ggml-org/llama.cpp/blob/master/common/json-schema-to-grammar.h) in an application that links it. ## In-process bindings @@ -95,7 +91,7 @@ These examples retain LFM2.5 because each binding bundles its own llama.cpp buil - Add a grammar sampler to the chain before the final `dist` sampler. Convert JSON schemas ahead of time with `json_schema_to_grammar.py`, or at runtime with `json_schema_to_grammar()` from the `common` library. + Add a grammar sampler to the chain before the final `dist` sampler. Use a hand-written GBNF grammar, or convert a supported JSON schema with `json_schema_to_grammar()` from the `common` library. ```c const char * gbnf = /* contents of schema.gbnf */; diff --git a/deployment/on-device/sdk/advanced-features.mdx b/deployment/on-device/sdk/advanced-features.mdx index 5482647..1dede5e 100644 --- a/deployment/on-device/sdk/advanced-features.mdx +++ b/deployment/on-device/sdk/advanced-features.mdx @@ -158,36 +158,20 @@ The full surface is documented in [Function Calling](./function-calling); the ty ```swift - public struct LeapFunction { - public let name: String - public let description: String - public let parameters: [LeapFunctionParameter] - } - - public struct LeapFunctionParameter { - public let name: String - public let type: LeapFunctionParameterType - public let description: String - public let optional: Bool - } - - public indirect enum LeapFunctionParameterType: Codable, Equatable { - case string(StringType) - case number(NumberType) - case integer(IntegerType) - case boolean(BooleanType) - case array(ArrayType) - case object(ObjectType) - case null(NullType) - } - - public struct LeapFunctionCall { - public let name: String - public let arguments: [String: Any?] - } + let parameter = LeapFunctionParameter( + name: "city", + type: LeapFunctionParameterType.LeapStr(enumValues: nil, description: nil), + parameterDescription: "The city to query", + optional: false + ) + let function = LeapFunction( + name: "get_weather", + functionDescription: "Query the weather", + parameters: [parameter] + ) ``` - Type wrappers (`StringType`, `NumberType`, etc.) carry per-type metadata like `enumValues` for restricting valid inputs and `description` for prompt-time hints (used when the type is nested inside an array or object). + These are Kotlin classes bridged to Swift. `LeapFunctionParameterType` exposes nested classes such as `LeapStr`, `LeapInt`, `LeapArr`, and `LeapObj`; it is not a Swift enum with `.string`/`.number` cases. See [Function Calling](./function-calling) for registration and response handling. ```kotlin diff --git a/deployment/on-device/sdk/ai-agent-usage-guide.mdx b/deployment/on-device/sdk/ai-agent-usage-guide.mdx index 524ec22..371b819 100644 --- a/deployment/on-device/sdk/ai-agent-usage-guide.mdx +++ b/deployment/on-device/sdk/ai-agent-usage-guide.mdx @@ -5,6 +5,8 @@ description: "End-to-end recipes for building AI agents with the LEAP SDK — sa The LEAP SDK is deprecated and this page is no longer maintained. Build on llama.cpp directly instead — see [Migrating from LEAP SDK](/deployment/on-device/llama-cpp/migrating-from-leap-sdk). + +The hosted LEAP catalog and model-bundling service have been discontinued. Manifest downloads that call `leap.liquid.ai` are historical examples and no longer work against that service. Use a local model with [sideloaded loading](/deployment/on-device/sdk/model-loading#sideloaded-files) in an existing SDK app, or migrate to llama.cpp for new development. This guide walks through the patterns for building a real AI agent — multi-turn conversation, function calling with tool dispatch, multimodal inputs, and a complete view-model wiring. The cross-platform pages cover individual APIs in depth — start here for the full picture, then drill into the dedicated references when you need details. @@ -44,6 +46,8 @@ Every agent has the same shape: send a `ChatMessage`, iterate the response strea @MainActor private func handle(_ response: MessageResponse) { switch onEnum(of: response) { + case .error(let failure): + print("Generation failed: \(failure.message)") case .chunk(let chunk): currentText += chunk.text case .reasoningChunk(let reasoning): @@ -55,7 +59,7 @@ Every agent has the same shape: send a `ChatMessage`, iterate the response strea case .audioSample(let audio): // `audio.samples` is `KotlinFloatArray` — bridge to `[Float]` via // `LeapSDK.ArrayConversionsKt.floatArrayToNSData(array:)` if your - // renderer expects a Swift array (see the demo in leap-ui-demo/shared/). + // renderer expects a Swift array (convert KotlinFloatArray to a native Swift array first). audioPlayer.enqueue(audio.samples, sampleRate: Int(audio.sampleRate)) case .complete(let completion): currentText = "" @@ -70,6 +74,7 @@ Every agent has the same shape: send a `ChatMessage`, iterate the response strea ```kotlin suspend fun handle(response: MessageResponse) { when (response) { + is MessageResponse.Error -> throw IllegalStateException(response.message) is MessageResponse.Chunk -> _text.value += response.text is MessageResponse.ReasoningChunk -> Log.d(TAG, "Reasoning: ${response.reasoning}") is MessageResponse.FunctionCalls -> { @@ -101,6 +106,8 @@ The defining feature of an agent: the model emits `FunctionCalls`, you execute t var toolCalls: [LeapFunctionCall] = [] for try await response in workingConv.generateResponse(message: pending) { switch onEnum(of: response) { + case .error(let failure): + print("Generation failed: \(failure.message)") case .chunk(let c): appendUI(c.text) case .functionCalls(let payload): @@ -141,6 +148,7 @@ The defining feature of an agent: the model emits `FunctionCalls`, you execute t val toolCalls = mutableListOf() workingConv.generateResponse(pending).collect { response -> when (response) { + is MessageResponse.Error -> throw IllegalStateException(response.message) is MessageResponse.Chunk -> appendUI(response.text) is MessageResponse.FunctionCalls -> toolCalls.addAll(response.functionCalls) else -> {} @@ -179,7 +187,7 @@ Define `runtimeDispatch(_:)` as your tool-call → result router: validate argum // Vision-capable model let imageMessage = ChatMessage( role: .user, - content: [.text("Describe what you see."), ChatMessageContent.fromJPEGData(jpegData)], + content: [.text("Describe what you see."), try ChatMessageContent.fromJPEGData(jpegData)], reasoningContent: nil, functionCalls: nil ) @@ -187,7 +195,7 @@ Define `runtimeDispatch(_:)` as your tool-call → result router: validate argum // Audio-capable model — WAV blob let audioMessage = ChatMessage( role: .user, - content: [.text("Transcribe."), ChatMessageContent.fromWAVData(wavData)], + content: [.text("Transcribe."), try ChatMessageContent.fromWAVData(wavData)], reasoningContent: nil, functionCalls: nil ) @@ -196,7 +204,7 @@ Define `runtimeDispatch(_:)` as your tool-call → result router: validate argum let pcmMessage = ChatMessage( role: .user, content: [.text("How's my pronunciation?"), - ChatMessageContent.fromFloatSamples(samples, sampleRate: 16000)], + try ChatMessageContent.fromFloatSamples(samples, sampleRate: 16000)], reasoningContent: nil, functionCalls: nil ) @@ -256,7 +264,7 @@ A `ChatViewModel` that loads the model, registers a tool, drives generation, and private let downloader: ModelDownloader = { let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.path let modelsDir = (caches as NSString).appendingPathComponent("leap_models") - return ModelDownloader(config: LeapDownloaderConfig(saveDir: modelsDir)) + return ModelDownloader(config: LeapDownloaderConfig.with(saveDir: modelsDir)) }() private var modelRunner: ModelRunner? private var conversation: Conversation? @@ -272,7 +280,7 @@ A `ChatViewModel` that loads the model, registers a tool, drives generation, and ) modelRunner = runner conversation = runner.createConversation(systemPrompt: "You are a helpful assistant.") - conversation?.registerFunction(weatherFunction) + conversation?.registerFunction(function: weatherFunction) } catch { errorMessage = "Failed to load model: \(error.localizedDescription)" } @@ -311,6 +319,8 @@ A `ChatViewModel` that loads the model, registers a tool, drives generation, and @MainActor private func handle(_ response: MessageResponse) { switch onEnum(of: response) { + case .error(let failure): + print("Generation failed: \(failure.message)") case .chunk(let c): responseText += c.text case .reasoningChunk(let r): print("[thinking] \(r.reasoning)") case .functionCalls(let f): @@ -407,6 +417,7 @@ A `ChatViewModel` that loads the model, registers a tool, drives generation, and private suspend fun handle(response: MessageResponse) { when (response) { + is MessageResponse.Error -> throw IllegalStateException(response.message) is MessageResponse.Chunk -> _responseText.value += response.text is MessageResponse.ReasoningChunk -> Log.d(TAG, "Reasoning: ${response.reasoning}") is MessageResponse.FunctionCalls -> response.functionCalls.forEach { dispatch(it) } diff --git a/deployment/on-device/sdk/cloud-ai-comparison.mdx b/deployment/on-device/sdk/cloud-ai-comparison.mdx index b6e94a6..848ef1b 100644 --- a/deployment/on-device/sdk/cloud-ai-comparison.mdx +++ b/deployment/on-device/sdk/cloud-ai-comparison.mdx @@ -25,7 +25,7 @@ stream = client.chat.completions.create( for chunk in stream: if chunk.choices: - delta = chunk.choices[0].delta.get("content") + delta = chunk.choices[0].delta.content if delta: print(delta, end="", flush=True) print("\nGeneration done!") @@ -47,7 +47,7 @@ Cloud APIs create a thin client that points at a remote endpoint. LEAP downloads let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.path let modelsDir = (caches as NSString).appendingPathComponent("leap_models") - let downloader = ModelDownloader(config: LeapDownloaderConfig(saveDir: modelsDir)) + let downloader = ModelDownloader(config: LeapDownloaderConfig.with(saveDir: modelsDir)) let runner = try await downloader.loadModel( modelName: "LFM2.5-1.2B-Instruct", @@ -94,7 +94,7 @@ The cloud API takes a `messages` array and returns a stream. LEAP attaches messa ```swift let conversation = runner.createConversation() - let stream = conversation.generateResponse(userTextMessage: "Say 'double bubble bath' ten times fast.") + let stream = conversation.generateResponse(message: ChatMessage(role: .user, textContent: "Say 'double bubble bath' ten times fast.")) ``` @@ -116,7 +116,7 @@ Cloud APIs deliver deltas; you concatenate them. LEAP delivers `MessageResponse` ```python for chunk in stream: if chunk.choices: - delta = chunk.choices[0].delta.get("content") + delta = chunk.choices[0].delta.content if delta: print(delta, end="", flush=True) ``` @@ -125,6 +125,8 @@ Cloud APIs deliver deltas; you concatenate them. LEAP delivers `MessageResponse` ```swift for try await response in stream { switch onEnum(of: response) { + case .error(let failure): + print("Generation failed: \(failure.message)") case .chunk(let chunk): print(chunk.text, terminator: "") case .complete(let completion): @@ -139,6 +141,7 @@ Cloud APIs deliver deltas; you concatenate them. LEAP delivers `MessageResponse` ```kotlin flow.onEach { response -> when (response) { + is MessageResponse.Error -> throw IllegalStateException(response.message) is MessageResponse.Chunk -> print(response.text) is MessageResponse.Complete -> println("\nDone! Tokens: ${response.stats?.totalTokens}") else -> {} @@ -165,7 +168,7 @@ Both LEAP and the OpenAI Python streaming client run inside an async context. Th private let downloader: ModelDownloader = { let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.path let modelsDir = (caches as NSString).appendingPathComponent("leap_models") - return ModelDownloader(config: LeapDownloaderConfig(saveDir: modelsDir)) + return ModelDownloader(config: LeapDownloaderConfig.with(saveDir: modelsDir)) }() func loadModel() async { @@ -179,7 +182,7 @@ Both LEAP and the OpenAI Python streaming client run inside an async context. Th func sendMessage(_ text: String) { guard let conversation else { return } Task { - let message = ChatMessage(role: .user, content: [.text(text)]) + let message = ChatMessage(role: .user, textContent: text) for try await response in conversation.generateResponse(message: message) { if case .chunk(let c) = onEnum(of: response) { currentResponse += c.text diff --git a/deployment/on-device/sdk/conversation-generation.mdx b/deployment/on-device/sdk/conversation-generation.mdx index b2d2b2f..5a66d74 100644 --- a/deployment/on-device/sdk/conversation-generation.mdx +++ b/deployment/on-device/sdk/conversation-generation.mdx @@ -151,6 +151,8 @@ The async stream is the recommended way to drive generation — both platforms e generationOptions: options ) { switch onEnum(of: response) { + case .error(let failure): + print("Generation failed: \(failure.message)") case .chunk(let c): print(c.text, terminator: "") case .reasoningChunk(let r): @@ -198,6 +200,7 @@ The async stream is the recommended way to drive generation — both platforms e conversation?.generateResponse(userInput) ?.onEach { response -> when (response) { + is MessageResponse.Error -> throw IllegalStateException(response.message) is MessageResponse.Chunk -> _generatedText.value += response.text is MessageResponse.ReasoningChunk -> Log.d(TAG, "Reasoning: ${response.reasoning}") is MessageResponse.FunctionCalls -> handleFunctionCalls(response.functionCalls) @@ -257,20 +260,24 @@ A sealed type with one case per kind of incremental output the engine emits. ```swift - public enum MessageResponse { - case chunk(Chunk) // Chunk.text — partial assistant text - case reasoningChunk(ReasoningChunk) // ReasoningChunk.reasoning — thinking tokens - case functionCalls(FunctionCalls) // FunctionCalls.functionCalls — [LeapFunctionCall] - case audioSample(AudioSample) // AudioSample.samples, .sampleRate — PCM frames - case complete(Complete) // Complete.fullMessage, .finishReason, .stats + func handle(_ response: MessageResponse) { + switch onEnum(of: response) { + case .chunk(let value): print(value.text) + case .reasoningChunk(let value): print(value.reasoning) + case .functionCalls(let value): print(value.functionCalls) + case .audioSample(let value): print(value.sampleRate) + case .complete(let value): print(value.fullMessage) + case .error(let value): print("Generation failed: \(value.message)") + } } ``` - Each case wraps a small struct so SKIE can bridge Kotlin sealed classes losslessly. Use `onEnum(of:)` for exhaustive switching. + `MessageResponse` is a Kotlin interface. `onEnum(of:)` exposes its six variants as a Swift enum for exhaustive switching; the payloads are bridged classes. ```kotlin sealed interface MessageResponse { + data class Error(val throwable: Throwable, val message: String) : MessageResponse data class Chunk(val text: String) : MessageResponse data class ReasoningChunk(val reasoning: String) : MessageResponse data class FunctionCalls(val functionCalls: List) : MessageResponse @@ -289,7 +296,8 @@ A sealed type with one case per kind of incremental output the engine emits. - **`ReasoningChunk`** — thinking-style tokens emitted by reasoning models (wrapped between `` / `` upstream). Only fires when `GenerationOptions.enableThinking = true` *and* the model supports it. - **`FunctionCalls`** — one or more tool invocations the model wants you to execute. See [Function Calling](./function-calling). - **`AudioSample`** — float32 mono PCM frames from audio-capable checkpoints. The sample rate is constant for a generation; route the frames to a renderer. -- **`Complete`** — final marker. `fullMessage` is the assembled assistant `ChatMessage` (also present in `conversation.history`). `stats` is nullable (`GenerationStats?`); when present it holds `promptTokens`, `completionTokens`, `totalTokens`, `tokenPerSecond` (non-nullable `Float`), and `cachedPromptTokens`. +- **`Error`** — terminal generation failure. Swift consumers must handle this event: the bridged flow can otherwise end without throwing the failure. +- **`Complete`** — final success marker. `fullMessage` is the assembled assistant `ChatMessage` (also present in `conversation.history`). `stats` is nullable (`GenerationStats?`); when present it holds `promptTokens`, `completionTokens`, `totalTokens`, `tokenPerSecond` (non-nullable `Float`), and `cachedPromptTokens`. ### `GenerationFinishReason` diff --git a/deployment/on-device/sdk/desktop-platforms.mdx b/deployment/on-device/sdk/desktop-platforms.mdx index 6bf4b28..a07eaf1 100644 --- a/deployment/on-device/sdk/desktop-platforms.mdx +++ b/deployment/on-device/sdk/desktop-platforms.mdx @@ -53,13 +53,13 @@ The JVM target supports Kotlin and Java projects on macOS (Apple Silicon), Linux } dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") // Optional: OpenAI-compatible cloud chat client (JVM support added in v0.10.7) - // implementation("ai.liquid.leap:leap-openai-client:0.10.7") + // implementation("ai.liquid.leap:leap-openai-client:0.10.9") // Optional: Compose Multiplatform voice widget (also runs on JVM) - // implementation("ai.liquid.leap:leap-ui:0.10.7") + // implementation("ai.liquid.leap:leap-ui:0.10.9") } application { @@ -79,7 +79,7 @@ The JVM target supports Kotlin and Java projects on macOS (Apple Silicon), Linux } dependencies { - implementation 'ai.liquid.leap:leap-sdk:0.10.7' + implementation 'ai.liquid.leap:leap-sdk:0.10.9' } application { @@ -139,6 +139,7 @@ fun main() = runBlocking { ChatMessage(ChatMessage.Role.USER, "What is the capital of France?") ).collect { response -> when (response) { + is MessageResponse.Error -> throw IllegalStateException(response.message) is MessageResponse.Chunk -> print(response.text) is MessageResponse.Complete -> println("\n[${response.stats?.totalTokens} tokens]") else -> {} @@ -200,11 +201,11 @@ dependencyResolutionManagement { // build.gradle.kts plugins { kotlin("multiplatform") version "2.3.20" - id("ai.liquid.leap.nativelibs") version "0.10.7" + id("ai.liquid.leap.nativelibs") version "0.10.9" } dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") } kotlin { @@ -222,7 +223,7 @@ Build with the usual Kotlin/Native link tasks: The resulting binary lives at `build/bin/linuxX64/releaseExecutable/`, alongside the `.so` files the plugin installed (`libinference_engine.so`, `libinference_engine_llamacpp_backend.so`, `libie_zip.so`, plus their transitive dependencies). Keep them co-located when you ship — the cinterop manifest bakes `-rpath=$ORIGIN` into the binary so the dynamic linker resolves siblings. -Early 0.10.x releases had Kotlin/Native linking and packaging issues. Use **v0.10.7** for these archived recipes; fixes accumulated across several releases. Maven Central artifacts are immutable, so updating the version is necessary to pick up those fixes. See [the changelog](/deployment/on-device/leap-sdk-changelog#kotlin-native-linux-windows). +Early 0.10.x releases had Kotlin/Native linking and packaging issues. Use **v0.10.9** for these archived recipes; fixes accumulated across several releases. Maven Central artifacts are immutable, so updating the version is necessary to pick up those fixes. See [the changelog](/deployment/on-device/leap-sdk-changelog#kotlin-native-linux-windows). ### Manual recipe (if you can't apply the plugin) @@ -233,7 +234,7 @@ plugins { } dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") } val nativesDir = layout.buildDirectory.dir("bin/linuxX64/releaseExecutable") @@ -247,7 +248,7 @@ kotlin { val leapSdkNatives by configurations.creating dependencies { - leapSdkNatives("ai.liquid.leap:leap-sdk-linuxx64:0.10.7:natives@zip") + leapSdkNatives("ai.liquid.leap:leap-sdk-linuxx64:0.10.9:natives@zip") } val installLeapNatives by tasks.registering(Copy::class) { @@ -265,8 +266,8 @@ tasks.named("linkReleaseExecutableLinuxX64") { dependsOn(installLeapNatives) } The Maven coordinates for the `-natives.zip` artifacts: -- `ai.liquid.leap:leap-sdk-linuxx64:0.10.7:natives@zip` -- `ai.liquid.leap:leap-sdk-linuxarm64:0.10.7:natives@zip` +- `ai.liquid.leap:leap-sdk-linuxx64:0.10.9:natives@zip` +- `ai.liquid.leap:leap-sdk-linuxarm64:0.10.9:natives@zip` ## Windows native (MinGW x64) @@ -275,11 +276,11 @@ The same Kotlin/Native flow works for Windows x86_64 via the MinGW-w64 toolchain ```kotlin plugins { kotlin("multiplatform") version "2.3.20" - id("ai.liquid.leap.nativelibs") version "0.10.7" + id("ai.liquid.leap.nativelibs") version "0.10.9" } dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") } kotlin { @@ -297,7 +298,7 @@ The plugin installs `inference_engine.dll`, `libinference_engine_llamacpp_backen The Maven coordinates for the `-natives.zip` artifact: -- `ai.liquid.leap:leap-sdk-mingwx64:0.10.7:natives@zip` +- `ai.liquid.leap:leap-sdk-mingwx64:0.10.9:natives@zip` **Building from macOS or Linux for Windows?** Kotlin/Native does not support cross-compiling to MinGW from a non-Windows host as of 2.3.20 — the build must run on Windows (native or in CI). GitHub Actions `windows-latest` works without extra setup. @@ -322,8 +323,8 @@ Identical Swift API to iOS — same `ModelDownloader`, `Conversation`, `ChatMess ```swift .binaryTarget( name: "LeapSDK", - url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.7/LeapSDK.xcframework.zip", - checksum: "6f2721aa45d7555646f78cbcaedb57aba3d869f56b24d681ad332846e131ae3d" + url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.9/LeapSDK.xcframework.zip", + checksum: "1fdea67fe208ee56db3aba4313809b03a469e6520a49a855c212ebcfef4cea2e" ) ``` @@ -335,8 +336,8 @@ If you're targeting macOS as a JVM host — for example with Compose Multiplatfo ```kotlin dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") - implementation("ai.liquid.leap:leap-ui:0.10.7") // Compose voice widget runs on JVM too + implementation("ai.liquid.leap:leap-sdk:0.10.9") + implementation("ai.liquid.leap:leap-ui:0.10.9") // Compose voice widget runs on JVM too } ``` diff --git a/deployment/on-device/sdk/function-calling.mdx b/deployment/on-device/sdk/function-calling.mdx index 9e1656f..f2494af 100644 --- a/deployment/on-device/sdk/function-calling.mdx +++ b/deployment/on-device/sdk/function-calling.mdx @@ -105,6 +105,8 @@ Function calls arrive as the `MessageResponse.FunctionCalls` variant on both pla for try await response in conversation.generateResponse(message: userMessage) { switch onEnum(of: response) { + case .error(let failure): + print("Generation failed: \(failure.message)") case .functionCalls(let payload): for call in payload.functionCalls { print("Function call: \(call.name) \(call.arguments)") @@ -127,6 +129,7 @@ Function calls arrive as the `MessageResponse.FunctionCalls` variant on both pla ```kotlin conversation.generateResponse(userMessage).onEach { response -> when (response) { + is MessageResponse.Error -> throw IllegalStateException(response.message) is MessageResponse.Chunk -> { /* text chunk */ } is MessageResponse.FunctionCalls -> { response.functionCalls.forEach { call -> diff --git a/deployment/on-device/sdk/messages-content.mdx b/deployment/on-device/sdk/messages-content.mdx index 30d5500..13f17e3 100644 --- a/deployment/on-device/sdk/messages-content.mdx +++ b/deployment/on-device/sdk/messages-content.mdx @@ -95,20 +95,20 @@ Round-trip the message through `kotlinx.serialization` — there is no separate - `ChatMessageContent` is the Kotlin `sealed class` bridged to Swift — switch on its subclasses with SKIE's `onEnum(of:)` helper. There is no native Swift `enum`, no positional `.image(_:)` / `.audio(_:)` factory, and no `init(from json:)`. Use the static factories on the Swift overlay: + `ChatMessageContent` is the Kotlin `sealed class` bridged to Swift — switch on its subclasses with SKIE's `onEnum(of:)` helper. There is no native Swift `enum`, no positional `.image(_:)` / `.audio(_:)` factory, and no `init(from json:)`. Use the static factories on the Swift overlay. In v0.10.9 image/audio conversion can throw: call these factories with `try` inside a throwing function or `do`/`catch` block: ```swift // Text (cross-platform): ChatMessageContent.text(_ text: String) -> ChatMessageContent // Image: - ChatMessageContent.fromJPEGData(_ jpegData: Data) -> ChatMessageContent.Image + ChatMessageContent.fromJPEGData(_ jpegData: Data) throws -> ChatMessageContent.Image ChatMessageContent.image(url: String) -> ChatMessageContent.Image // data URL or remote URL // Audio: - ChatMessageContent.fromWAVData(_ wavData: Data) -> ChatMessageContent.Audio - ChatMessageContent.audio(data: Data, format: String = "wav") -> ChatMessageContent.Audio - ChatMessageContent.fromFloatSamples(_ samples: [Float], sampleRate: Int, channelCount: Int = 1) + ChatMessageContent.fromWAVData(_ wavData: Data) throws -> ChatMessageContent.Audio + ChatMessageContent.audio(data: Data, format: String = "wav") throws -> ChatMessageContent.Audio + ChatMessageContent.fromFloatSamples(_ samples: [Float], sampleRate: Int, channelCount: Int = 1) throws -> ChatMessageContent.Audio // iOS only — UIKit: @@ -213,7 +213,7 @@ The engine **only accepts WAV**. M4A, MP3, AAC, OGG, and other compressed format role: .user, content: [ .text("What is being said in this audio?"), - ChatMessageContent.fromWAVData(wavData) + try ChatMessageContent.fromWAVData(wavData) ], reasoningContent: nil, functionCalls: nil @@ -244,7 +244,7 @@ The engine **only accepts WAV**. M4A, MP3, AAC, OGG, and other compressed format // Float samples normalized to [-1.0, 1.0] let samples: [Float] = [0.1, 0.2, 0.15, -0.3 /* ... */] - let audioContent = ChatMessageContent.fromFloatSamples( + let audioContent = try ChatMessageContent.fromFloatSamples( samples, sampleRate: 16000, channelCount: 1 @@ -301,7 +301,7 @@ The engine **only accepts WAV**. M4A, MP3, AAC, OGG, and other compressed format recorder.stop() let wavData = try Data(contentsOf: audioURL) - let audioContent: ChatMessageContent = ChatMessageContent.fromWAVData(wavData) + let audioContent: ChatMessageContent = try ChatMessageContent.fromWAVData(wavData) ``` diff --git a/deployment/on-device/sdk/model-loading.mdx b/deployment/on-device/sdk/model-loading.mdx index 122d24e..7a241fe 100644 --- a/deployment/on-device/sdk/model-loading.mdx +++ b/deployment/on-device/sdk/model-loading.mdx @@ -5,6 +5,8 @@ description: "Reference for ModelDownloader, LeapDownloader, loadModel, loadSimp The LEAP SDK is deprecated and this page is no longer maintained. Build on llama.cpp directly instead — see [Migrating from LEAP SDK](/deployment/on-device/llama-cpp/migrating-from-leap-sdk). + +The hosted LEAP catalog and model-bundling service have been discontinued. Manifest downloads that call `leap.liquid.ai` are historical examples and no longer work against that service. Use a local model with [sideloaded loading](/deployment/on-device/sdk/model-loading#sideloaded-files) in an existing SDK app, or migrate to llama.cpp for new development. The LEAP SDK ships two downloader classes built on the same pipeline. They differ by what platform integration they add: @@ -62,7 +64,7 @@ All downloader classes return the same `ModelRunner` type. They share an on-disk ```swift let downloader = LeapDownloader( - config: LeapDownloaderConfig(saveDir: modelsDir, validateSha256: true) + config: LeapDownloaderConfig.with(saveDir: modelsDir, validateSha256: true) ) ``` @@ -128,7 +130,7 @@ Resolves the GGUF manifest for the given model + quantization slug, downloads an ```swift let downloader = ModelDownloader( - config: LeapDownloaderConfig(saveDir: modelsDir, validateSha256: true) + config: LeapDownloaderConfig.with(saveDir: modelsDir, validateSha256: true) ) let runner = try await downloader.loadModel( @@ -150,7 +152,7 @@ Resolves the GGUF manifest for the given model + quantization slug, downloads an ```swift let downloader = LeapDownloader( - config: LeapDownloaderConfig(saveDir: modelsDir, validateSha256: true) + config: LeapDownloaderConfig.with(saveDir: modelsDir, validateSha256: true) ) let runner = try await downloader.loadModel( @@ -235,7 +237,7 @@ Resolves the GGUF manifest for the given model + quantization slug, downloads an -Find available model and quantization slugs in the [LEAP Model Library](https://leap.liquid.ai/models). +The hosted LEAP model library is no longer available. For current checkpoints and format repositories, use the [model library](/lfm/models/complete-library); catalog slugs in the manifest examples above are historical. ## Sideloaded files @@ -244,7 +246,7 @@ Use this path when you ship the model as an app asset, `adb push` it for develop ```swift - public struct ModelSource { + public class ModelSource { public let modelPath: String public let mmprojPath: String? public let audioDecoderPath: String? @@ -274,9 +276,15 @@ Use this path when you ship the model as an app asset, `adb push` it for develop let runner = try await downloader.loadSimpleModel( model: ModelSource( modelPath: ggufURL.path, + mmprojPath: nil, + audioDecoderPath: nil, + audioTokenizerPath: nil, modelName: "LFM2-1.2B-Instruct", quantizationId: "Q4_K_M" - ) + ), + options: nil, + generationTimeParameters: nil, + downloadProgress: nil ) // Vision model with companion mmproj @@ -284,20 +292,29 @@ Use this path when you ship the model as an app asset, `adb push` it for develop model: ModelSource( modelPath: visionURL.path, mmprojPath: mmprojURL.path, + audioDecoderPath: nil, + audioTokenizerPath: nil, modelName: "LFM2.5-VL-1.6B", quantizationId: "Q4_K_M" - ) + ), + options: nil, + generationTimeParameters: nil, + downloadProgress: nil ) // Audio model with decoder + tokenizer let audioRunner = try await downloader.loadSimpleModel( model: ModelSource( modelPath: audioURL.path, + mmprojPath: nil, audioDecoderPath: decoderURL.path, audioTokenizerPath: tokenizerURL.path, modelName: "LFM2.5-Audio-1.5B", quantizationId: "Q4_0" - ) + ), + options: nil, + generationTimeParameters: nil, + downloadProgress: nil ) ``` diff --git a/deployment/on-device/sdk/openai-client.mdx b/deployment/on-device/sdk/openai-client.mdx index 1936aff..5f0a909 100644 --- a/deployment/on-device/sdk/openai-client.mdx +++ b/deployment/on-device/sdk/openai-client.mdx @@ -23,7 +23,7 @@ The LEAP SDK is deprecated and this page is no longer maintained. Build on llama ```swift dependencies: [ - .package(url: "https://github.com/Liquid4All/leap-sdk.git", from: "0.10.7") + .package(url: "https://github.com/Liquid4All/leap-sdk.git", from: "0.10.9") ] targets: [ @@ -41,8 +41,8 @@ The LEAP SDK is deprecated and this page is no longer maintained. Build on llama ```kotlin dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") - implementation("ai.liquid.leap:leap-openai-client:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") + implementation("ai.liquid.leap:leap-openai-client:0.10.9") } ``` @@ -51,18 +51,18 @@ The LEAP SDK is deprecated and this page is no longer maintained. Build on llama ```kotlin dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") - implementation("ai.liquid.leap:leap-openai-client:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") + implementation("ai.liquid.leap:leap-openai-client:0.10.9") } ``` - JVM support landed in v0.10.7 (the `jvm` slice was absent in the v0.10.0–v0.10.6 cascade). Pure-Maven JVM projects should consume the `-jvm` classifier directly: `ai.liquid.leap:leap-openai-client-jvm:0.10.7`. Bundles the CIO Ktor engine. + JVM support landed in v0.10.7 (the `jvm` slice was absent in the v0.10.0–v0.10.6 cascade). Pure-Maven JVM projects should consume the `-jvm` classifier directly: `ai.liquid.leap:leap-openai-client-jvm:0.10.9`. Bundles the CIO Ktor engine. ```kotlin dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") - implementation("ai.liquid.leap:leap-openai-client:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") + implementation("ai.liquid.leap:leap-openai-client:0.10.9") } ``` @@ -74,54 +74,42 @@ The LEAP SDK is deprecated and this page is no longer maintained. Build on llama - - The `leap-sdk-openai-client` Kotlin module does **not** apply the SKIE plugin in v0.10.7 (only `leap-sdk`, `leap-sdk-model-downloader`, and `leap-ui` do). That means `Flow` is **not** bridged to a Swift `AsyncSequence` and the `onEnum(of:)` helper is **not** generated for `ChatCompletionEvent`. Swift consumers on v0.10.7 must collect the Kotlin `Flow` through its native collector and downcast each event with `as?`. For most Swift apps that just need cloud chat completions, an off-the-shelf OpenAI Swift client is more ergonomic — use `LeapOpenAIClient` from Swift only if you need to share Kotlin code with Android. - - **Coming in the next release:** SKIE will be enabled on `leap-sdk-openai-client`, adding the same Swift-friendly surface as `LeapSDK` — `for try await event in client.streamChatCompletion(...)`, `onEnum(of: event)` exhaustive switching, and nested-class Swift names (`ChatCompletionEvent.Delta` instead of the current flattened `ChatCompletionEventDelta`). Swift convenience inits and builders for `OpenAiClientConfig` are also planned. Pin to v0.10.7 if you need the current behavior frozen; otherwise expect the more ergonomic surface to land soon. - - - Manual collection pattern (the `Flow.collect(...)` shape varies by Kotlin/Native version — check the framework header in your Xcode build for the exact label): - ```swift import LeapOpenAIClient - // The Kotlin top-level `fun OpenAiClient(config: OpenAiClientConfig)` exports as - // `OpenAiClientKt.OpenAiClient(config:)` (PascalCase preserved from the Kotlin - // function name). Without SKIE the K/N export also flattens Kotlin's nested - // class names — `ChatMessage.User` → `ChatMessageUser`, - // `ChatCompletionEvent.Delta` → `ChatCompletionEventDelta`, etc. - let client = OpenAiClientKt.OpenAiClient( - config: OpenAiClientConfig( - apiKey: "sk-…", - baseUrl: "https://api.openai.com/v1" + func makeCloudRequest(model: String, messages: [any LeapOpenAIClient.ChatMessage]) -> ChatCompletionRequest { + ChatCompletionRequest( + model: model, messages: messages, + temperature: nil, topP: nil, maxCompletionTokens: nil, maxTokens: nil, + frequencyPenalty: nil, presencePenalty: nil, stop: nil, stream: true, + topK: nil, repetitionPenalty: nil, minP: nil, topA: nil, + transforms: nil, models: nil, route: nil, provider: nil ) - ) + } - let request = ChatCompletionRequest( - model: "gpt-4o-mini", - messages: [ + func askCloud(apiKey: String) async throws { + let client = OpenAiClient(config: OpenAiClientConfig( + apiKey: apiKey, + baseUrl: "https://api.liquid.ai/openai/v1", + chatCompletionsPath: "/chat/completions", + extraHeaders: [:] + )) + defer { client.close() } + let request = makeCloudRequest(model: "lfm3-1.7b", messages: [ ChatMessageSystem(content: "You are a helpful assistant."), ChatMessageUser(content: "What is the capital of Japan?") - ], - temperature: 0.7 - ) - - // Pseudocode — actual collector signature depends on your Kotlin/Native version - // and framework headers. Without SKIE, there is no `for try await` integration. - try await client.streamChatCompletion(request: request).collect( - collector: FlowCollector { event in - if let delta = event as? ChatCompletionEventDelta { - print(delta.content, terminator: "") - } else if let done = event as? ChatCompletionEventDone { - if let usage = done.usage { print("\nTokens: \(usage.totalTokens)") } - } else if let err = event as? ChatCompletionEventError { - print("\nError: \(err.message)") + ]) + for try await event in client.streamChatCompletion(request: request) { + switch onEnum(of: event) { + case .delta(let value): print(value.content, terminator: "") + case .done(let value): print("\nUsage: \(String(describing: value.usage))") + case .error(let value): print("\nError: \(value.message)") } } - ) - - client.close() // closes the underlying URLSession-backed HttpClient + } ``` + + v0.10.8 and later ship SKIE-backed `AsyncSequence` streaming and `onEnum(of:)` switching. Swift still needs all constructor arguments shown above: Kotlin default parameters do not supply Swift defaults for `OpenAiClientConfig` or `ChatCompletionRequest`. Nullable fields use `nil` to keep the server defaults. The example sends a request only when you call `askCloud(apiKey:)` with your key. ```kotlin @@ -185,14 +173,12 @@ data class OpenAiClientConfig( ```swift - // The leap-sdk-openai-client module has no SKIE plugin applied, so the - // top-level Kotlin `fun OpenAiClient(config:)` factory is exported as - // `OpenAiClientKt.OpenAiClient(config:)`. See the [Basic usage](#basic-usage) - // warning for the full reasoning. - let client = OpenAiClientKt.OpenAiClient( + // v0.10.9 exports the Swift-friendly top-level factory. + let client = OpenAiClient( config: OpenAiClientConfig( apiKey: "sk-or-…", baseUrl: "https://openrouter.ai/api/v1", + chatCompletionsPath: "/chat/completions", extraHeaders: [ "HTTP-Referer": "https://yourapp.example.com", "X-Title": "Your App" @@ -222,10 +208,12 @@ data class OpenAiClientConfig( ```swift - let client = OpenAiClientKt.OpenAiClient( + let client = OpenAiClient( config: OpenAiClientConfig( apiKey: "anything", // Required by config but typically unused - baseUrl: "http://10.0.0.42:8000/v1" + baseUrl: "http://10.0.0.42:8000/v1", + chatCompletionsPath: "/chat/completions", + extraHeaders: [:] ) ) ``` @@ -274,7 +262,7 @@ data class ChatCompletionRequest( ## Response shape -`streamChatCompletion(request)` returns a `Flow` (Kotlin) — and the same `Flow` is exposed verbatim to Swift in v0.10.7 (no SKIE on this module yet, so it's not bridged to a Swift `AsyncSequence`; collect it via the native `Flow.collect(...)` shape shown above). Events: +`streamChatCompletion(request)` returns a `Flow` in Kotlin and a SKIE-backed `AsyncSequence` in Swift on v0.10.8 and later. Events: | Variant | Meaning | |---|---| @@ -292,49 +280,39 @@ Route simple prompts to a small on-device LFM; escalate harder prompts to a clou + Reuse `makeCloudRequest` from the usage example above. Qualify `ChatMessage` because both frameworks export a type with that name. + ```swift - import LeapModelDownloader + import LeapSDK import LeapOpenAIClient - @MainActor - final class HybridChatViewModel: ObservableObject { - private let onDevice: Conversation - private let cloud: OpenAiClient - - init(onDevice: Conversation, cloud: OpenAiClient) { - self.onDevice = onDevice - self.cloud = cloud - } - - func send(_ text: String, useCloud: Bool) async throws { - if useCloud { - // Cloud path: leap-sdk-openai-client has no SKIE — collect the Kotlin - // Flow manually and downcast each event with `as?`. Note the flattened - // Swift type names (`ChatMessageUser`, `ChatCompletionEventDelta`). - let request = ChatCompletionRequest( - model: "gpt-4o-mini", - messages: [ChatMessageUser(content: text)] - ) - try await cloud.streamChatCompletion(request: request).collect( - collector: FlowCollector { event in - if let delta = event as? ChatCompletionEventDelta { - appendChunk(delta.content) - } - } - ) - } else { - // On-device path: leap-sdk has SKIE — `for try await` + `onEnum(of:)` - // work as written. - let userMessage = ChatMessage(role: .user, textContent: text) - for try await response in onDevice.generateResponse(message: userMessage) { - if case let .chunk(c) = onEnum(of: response) { appendChunk(c.text) } + func send( + _ text: String, + useCloud: Bool, + onDevice: any LeapSDK.Conversation, + cloud: LeapOpenAIClient.OpenAiClient + ) async throws { + if useCloud { + let request = makeCloudRequest(model: "lfm3-1.7b", messages: [ + LeapOpenAIClient.ChatMessageUser(content: text) + ]) + for try await event in cloud.streamChatCompletion(request: request) { + switch onEnum(of: event) { + case .delta(let value): print(value.content, terminator: "") + case .done: break + case .error(let value): print(value.message) + } + } + } else { + let message = LeapSDK.ChatMessage(role: .user, textContent: text) + for try await response in onDevice.generateResponse(message: message) { + switch onEnum(of: response) { + case .chunk(let value): print(value.text, terminator: "") + case .error(let value): print(value.message) + case .reasoningChunk, .audioSample, .functionCalls, .complete: break } } } - - private func appendChunk(_ text: String) { /* … */ } - - deinit { cloud.close() } } ``` @@ -416,7 +394,7 @@ See [Cloud AI Comparison](./cloud-ai-comparison) for a side-by-side feature brea ## Lifecycle -The platform `OpenAiClient(config:)` factory (Kotlin `fun OpenAiClient(config:)` → Swift `OpenAiClientKt.OpenAiClient(config:)`) creates an `HttpClient` internally and ties it to the returned client — call `close()` when you're done. +The platform `OpenAiClient(config:)` factory (Kotlin `fun OpenAiClient(config:)`, also exported to Swift) creates an `HttpClient` internally and ties it to the returned client — call `close()` when you're done. @@ -424,7 +402,7 @@ The platform `OpenAiClient(config:)` factory (Kotlin `fun OpenAiClient(config:)` deinit { client.close() } ``` - The lower-level constructor that accepts an externally-managed `HttpClient` is part of the Kotlin/Ktor surface and isn't a useful entry point from Swift — the Ktor engine machinery isn't bridged into the public Swift API. Use `OpenAiClientKt.OpenAiClient(config:)` and let the SDK own the session. If multiple consumers share a client, share the `OpenAiClient` instance and `close()` once at teardown. + The lower-level constructor that accepts an externally-managed `HttpClient` is part of the Kotlin/Ktor surface and isn't a useful entry point from Swift — the Ktor engine machinery isn't bridged into the public Swift API. Use `OpenAiClient(config:)` and let the SDK own the session. If multiple consumers share a client, share the `OpenAiClient` instance and `close()` once at teardown. ```kotlin diff --git a/deployment/on-device/sdk/overview.mdx b/deployment/on-device/sdk/overview.mdx index 123570c..5ae773f 100644 --- a/deployment/on-device/sdk/overview.mdx +++ b/deployment/on-device/sdk/overview.mdx @@ -5,6 +5,8 @@ description: "The LEAP SDK is deprecated. This archived reference is kept for te The **LEAP SDK is deprecated** and no longer receives new releases. It was a Kotlin Multiplatform wrapper around llama.cpp, and everything it provided is available from llama.cpp directly. New projects should follow the [Build with llama.cpp](/deployment/on-device/llama-cpp/mobile) guides; existing users can find a concept-by-concept mapping in [Migrating from LEAP SDK](/deployment/on-device/llama-cpp/migrating-from-leap-sdk). + +The hosted LEAP catalog and model-bundling service have been discontinued. Manifest downloads that call `leap.liquid.ai` are historical examples and no longer work against that service. Use a local model with [sideloaded loading](/deployment/on-device/sdk/model-loading#sideloaded-files) in an existing SDK app, or migrate to llama.cpp for new development. Published LEAP SDK artifacts remain available (Swift Package Manager via [`Liquid4All/leap-sdk`](https://github.com/Liquid4All/leap-sdk), Maven Central under `ai.liquid.leap:*`), but they are frozen at their last release and are not updated for new LFM checkpoints. Sampling defaults, chat templates, and tool-call parsing for current models are maintained upstream in llama.cpp. diff --git a/deployment/on-device/sdk/quick-start.mdx b/deployment/on-device/sdk/quick-start.mdx index 6cc0f99..3893b72 100644 --- a/deployment/on-device/sdk/quick-start.mdx +++ b/deployment/on-device/sdk/quick-start.mdx @@ -5,9 +5,11 @@ description: "Install the LEAP SDK on iOS, macOS, Android, JVM, Linux, or Window The LEAP SDK is deprecated and this page is no longer maintained. Build on llama.cpp directly instead — see [Migrating from LEAP SDK](/deployment/on-device/llama-cpp/migrating-from-leap-sdk). + +The hosted LEAP catalog and model-bundling service have been discontinued. Manifest downloads that call `leap.liquid.ai` are historical examples and no longer work against that service. Use a local model with [sideloaded loading](/deployment/on-device/sdk/model-loading#sideloaded-files) in an existing SDK app, or migrate to llama.cpp for new development. -Latest version: `v0.10.7` +Archived stable version: `v0.10.9`. On Apple platforms, avoid v0.10.5–v0.10.8: v0.10.9 fixes the iOS launch crash and recursive downloader-config initializer. Swift configuration uses `LeapDownloaderConfig.with(...)`, and image/audio factories now require `try`. See the [release notes](https://github.com/Liquid4All/leap-sdk/releases/tag/v0.10.9). The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conversation` / `MessageResponse` API runs on every supported target. The code differs only in **language** (Swift vs. Kotlin) and **packaging** (SPM, Gradle, or Kotlin/Native plugin) — the call shapes are identical. For background on what the SDK is and what first-class LFM support means in practice, see the [Overview](/deployment/on-device/sdk/overview). @@ -19,7 +21,7 @@ The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conver - - Xcode 16.0+ with Swift 6.0. + - Xcode with Swift **6.2.3 or newer** for the v0.10.9 binary overlays. - iOS **17.0+** or macOS **15.0+** (Apple Silicon only — Mac Catalyst is **not** supported; the shipped XCFrameworks contain only `ios-arm64`, `ios-arm64-simulator`, and `macos-arm64` slices, and `Package.swift` declares only `.iOS(.v17)` / `.macOS(.v15)` platforms). - A physical iPhone or iPad with at least 3 GB RAM for best performance. The simulator works for development but runs models much slower. @@ -59,7 +61,7 @@ The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conver - **Windows runtime:** Windows 10+. - Early 0.10.x releases had Kotlin/Native linking and packaging issues. Use **v0.10.7** for these archived recipes, consistent with the [desktop guide](/deployment/on-device/sdk/desktop-platforms). See the [changelog](/deployment/on-device/leap-sdk-changelog#kotlin-native-linux-windows) for the release history. + Early 0.10.x releases had Kotlin/Native linking and packaging issues. Use **v0.10.9** for these archived recipes, consistent with the [desktop guide](/deployment/on-device/sdk/desktop-platforms). See the [changelog](/deployment/on-device/leap-sdk-changelog#kotlin-native-linux-windows) for the release history. @@ -72,7 +74,7 @@ The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conver 1. In Xcode choose **File → Add Package Dependencies**. 2. Enter `https://github.com/Liquid4All/leap-sdk.git`. - 3. Select the `0.10.7` release (or newer). + 3. Select the `0.10.9` release (or newer). 4. Add the products you need to your app target. The package vends five products. Most apps only need one or two: @@ -98,7 +100,7 @@ The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conver - For explicit pinning, declare each framework as a `.binaryTarget` in your `Package.swift`. The XCFramework assets live on the `Liquid4All/leap-sdk` v0.10.7 release page — copy the SHA-256 values from there. + For explicit pinning, declare each framework as a `.binaryTarget` in your `Package.swift`. The XCFramework assets live on the `Liquid4All/leap-sdk` v0.10.9 release page — copy the SHA-256 values from there. The constrained-generation macros (`@Generatable`, `@Guide`) are Swift macros, not XCFrameworks — they ship as the `LeapSDKMacros` source target inside the SPM package and **cannot be installed as a `.binaryTarget`**. If you need them, use the standard SPM package URL above (or add the `LeapSDKMacros` source target separately on top of your binary targets). @@ -107,23 +109,23 @@ The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conver ```swift .binaryTarget( name: "LeapSDK", - url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.7/LeapSDK.xcframework.zip", - checksum: "6f2721aa45d7555646f78cbcaedb57aba3d869f56b24d681ad332846e131ae3d" + url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.9/LeapSDK.xcframework.zip", + checksum: "1fdea67fe208ee56db3aba4313809b03a469e6520a49a855c212ebcfef4cea2e" ), .binaryTarget( name: "LeapModelDownloader", - url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.7/LeapModelDownloader.xcframework.zip", - checksum: "f649aa6c1aa3e87bbeb1073d5aeeb7224879359a24b18eeccc665d24abc725d8" + url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.9/LeapModelDownloader.xcframework.zip", + checksum: "41bc9a67b1a70c6b5bc42cc1433feb4c346b9f3ecb6bc831eae4ae8f81cdb2a0" ), .binaryTarget( name: "LeapOpenAIClient", - url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.7/LeapOpenAIClient.xcframework.zip", - checksum: "79bc5443a1cce6fcd4c49c91eeb85727034aaca10d3ef69582c061989c3d9b70" + url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.9/LeapOpenAIClient.xcframework.zip", + checksum: "fabdc0ebc3f355676271f6811bfe736af2b4486b49afdb344d2596108cb25a8e" ), .binaryTarget( name: "LeapUi", - url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.7/LeapUi.xcframework.zip", - checksum: "f1b198cef88c2a37eaf6dc1f36395d6aed024b0c6c2b43724d942e25b60d22e0" + url: "https://github.com/Liquid4All/leap-sdk/releases/download/v0.10.9/LeapUi.xcframework.zip", + checksum: "72247e66ce53ba9439f75af339540570172edd7f26ad2621db022889e23af696" ), ``` @@ -135,14 +137,14 @@ The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conver ```kotlin dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") - implementation("ai.liquid.leap:leap-model-downloader:0.10.7") // Android background downloads + implementation("ai.liquid.leap:leap-sdk:0.10.9") + implementation("ai.liquid.leap:leap-model-downloader:0.10.9") // Android background downloads // Optional: OpenAI-compatible cloud chat client - // implementation("ai.liquid.leap:leap-openai-client:0.10.7") + // implementation("ai.liquid.leap:leap-openai-client:0.10.9") // Optional: Voice assistant widget (Compose Multiplatform) - // implementation("ai.liquid.leap:leap-ui:0.10.7") + // implementation("ai.liquid.leap:leap-ui:0.10.9") } ``` @@ -151,7 +153,7 @@ The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conver ```toml [versions] - leapSdk = "0.10.7" + leapSdk = "0.10.9" [libraries] leap-sdk = { module = "ai.liquid.leap:leap-sdk", version.ref = "leapSdk" } @@ -195,11 +197,11 @@ The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conver } dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") // Optional: - // implementation("ai.liquid.leap:leap-openai-client:0.10.7") - // implementation("ai.liquid.leap:leap-ui:0.10.7") // Compose for Desktop voice widget + // implementation("ai.liquid.leap:leap-openai-client:0.10.9") + // implementation("ai.liquid.leap:leap-ui:0.10.9") // Compose for Desktop voice widget } ``` @@ -226,11 +228,11 @@ The Leap SDK is a Kotlin Multiplatform library: the same `ModelRunner` / `Conver // build.gradle.kts plugins { kotlin("multiplatform") version "2.3.20" - id("ai.liquid.leap.nativelibs") version "0.10.7" + id("ai.liquid.leap.nativelibs") version "0.10.9" } dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") } kotlin { @@ -264,7 +266,7 @@ The recommended path is **manifest-based** loading. On every platform, the platf return (caches as NSString).appendingPathComponent("leap_models") }() private lazy var downloader = ModelDownloader( - config: LeapDownloaderConfig(saveDir: modelsDir) + config: LeapDownloaderConfig.with(saveDir: modelsDir) // For background transfers, pass: // sessionConfiguration: .background(withIdentifier: "com.myapp.leap.downloads") ) @@ -404,9 +406,15 @@ When you already have a model file on disk — shipped as an app asset, `adb pus let runner = try await downloader.loadSimpleModel( model: ModelSource( modelPath: bundledURL.path, + mmprojPath: nil, + audioDecoderPath: nil, + audioTokenizerPath: nil, modelName: "LFM2-1.2B-Instruct", quantizationId: "Q4_K_M" - ) + ), + options: nil, + generationTimeParameters: nil, + downloadProgress: nil ) ``` @@ -460,6 +468,8 @@ Both platforms expose the same streaming shape: an async sequence of `MessageRes private func handle(_ response: MessageResponse) { // `onEnum(of:)` (v0.10.0+) gives exhaustive switching without a `default`. switch onEnum(of: response) { + case .error(let failure): + print("Generation failed: \(failure.message)") case .chunk(let chunk): print(chunk.text, terminator: "") case .reasoningChunk(let reasoning): @@ -488,6 +498,7 @@ Both platforms expose the same streaming shape: an async sequence of `MessageRes conversation?.generateResponse(userMessage) ?.onEach { response -> when (response) { + is MessageResponse.Error -> throw IllegalStateException(response.message) is MessageResponse.Chunk -> _responseText.value += response.text is MessageResponse.ReasoningChunk -> Log.d(TAG, "Reasoning: ${response.reasoning}") is MessageResponse.FunctionCalls -> handleFunctionCalls(response.functionCalls) @@ -517,11 +528,11 @@ If the loaded model is multimodal (and its companion files were detected), you c ```swift - // Text + image (vision-capable model). Use `ChatMessageContent.fromJPEGData(_:)` + // Text + image (vision-capable model). Use `try ChatMessageContent.fromJPEGData(_:)` // for raw JPEG bytes, or `.image(url:)` for a data URL / remote URL. let imageMessage = ChatMessage( role: .user, - content: [.text("Describe what you see."), ChatMessageContent.fromJPEGData(jpegData)], + content: [.text("Describe what you see."), try ChatMessageContent.fromJPEGData(jpegData)], reasoningContent: nil, functionCalls: nil ) @@ -530,7 +541,7 @@ If the loaded model is multimodal (and its companion files were detected), you c // use `.audio(data:format:)` if you already know the bytes are a supported format. let wavMessage = ChatMessage( role: .user, - content: [.text("Transcribe and summarize this clip."), ChatMessageContent.fromWAVData(wavData)], + content: [.text("Transcribe and summarize this clip."), try ChatMessageContent.fromWAVData(wavData)], reasoningContent: nil, functionCalls: nil ) @@ -540,7 +551,7 @@ If the loaded model is multimodal (and its companion files were detected), you c role: .user, content: [ .text("Give feedback on my pronunciation."), - ChatMessageContent.fromFloatSamples(samples, sampleRate: 16000) + try ChatMessageContent.fromFloatSamples(samples, sampleRate: 16000) ], reasoningContent: nil, functionCalls: nil diff --git a/deployment/on-device/sdk/utilities.mdx b/deployment/on-device/sdk/utilities.mdx index b0d78c4..0a2777e 100644 --- a/deployment/on-device/sdk/utilities.mdx +++ b/deployment/on-device/sdk/utilities.mdx @@ -5,6 +5,8 @@ description: "Error handling, serialization, Android-specific downloader interna The LEAP SDK is deprecated and this page is no longer maintained. Build on llama.cpp directly instead — see [Migrating from LEAP SDK](/deployment/on-device/llama-cpp/migrating-from-leap-sdk). + +The hosted LEAP catalog and model-bundling service have been discontinued. Manifest downloads that call `leap.liquid.ai` are historical examples and no longer work against that service. Use a local model with [sideloaded loading](/deployment/on-device/sdk/model-loading#sideloaded-files) in an existing SDK app, or migrate to llama.cpp for new development. This page covers error types, serialization helpers, and a few platform-specific entry points that don't fit in the main reference pages. @@ -214,7 +216,7 @@ A minimal end-to-end snippet exercising load → conversation → tool registrat ```swift let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.path let modelsDir = (caches as NSString).appendingPathComponent("leap_models") - let downloader = ModelDownloader(config: LeapDownloaderConfig(saveDir: modelsDir)) + let downloader = ModelDownloader(config: LeapDownloaderConfig.with(saveDir: modelsDir)) let runner = try await downloader.loadModel( modelName: "LFM2.5-1.2B-Instruct", diff --git a/deployment/on-device/sdk/voice-assistant.mdx b/deployment/on-device/sdk/voice-assistant.mdx index 293e305..061fcf5 100644 --- a/deployment/on-device/sdk/voice-assistant.mdx +++ b/deployment/on-device/sdk/voice-assistant.mdx @@ -7,6 +7,8 @@ description: "Drop-in Compose Multiplatform voice UI — runs on iOS, macOS, And The LEAP SDK is deprecated and this page is no longer maintained. Build on llama.cpp directly instead — see [Migrating from LEAP SDK](/deployment/on-device/llama-cpp/migrating-from-leap-sdk). +This page describes integration APIs, not a complete downloadable sample app. The public `leap-sdk` repository distributes packages and binaries; it does not include the `leap-ui-demo` source tree referenced by older versions of this guide. + The `leap-ui` module (introduced in v0.10.0) ships a ready-to-use voice assistant widget — an animated orb, mic button, and status label — backed by a state machine that handles recording, generation, and audio playback. Wire it to a model and it handles the rest. `leap-ui` is a Compose Multiplatform module, so the same widget runs on: @@ -15,7 +17,7 @@ The `leap-ui` module (introduced in v0.10.0) ships a ready-to-use voice assistan - **macOS** — bridged to AppKit via `VoiceAssistantNSViewController`. SwiftUI hosts via `NSViewControllerRepresentable` + `NSHostingController`. - **Android** — direct Compose for Android. - **JVM Desktop** — Compose for Desktop. Same Maven artifact; you provide audio I/O implementations (the demo apps in `leap-ui-demo/` ship patterns you can adapt). -- **Web (Wasm, experimental)** — present in the source tree (`leap-ui-demo/web`) but not yet covered by the stable release notes through v0.10.7 — treat as preview. +Web/Wasm is not covered by this archived binary integration guide. ## Add the dependency @@ -25,7 +27,7 @@ The `leap-ui` module (introduced in v0.10.0) ships a ready-to-use voice assistan ```swift dependencies: [ - .package(url: "https://github.com/Liquid4All/leap-sdk.git", from: "0.10.7") + .package(url: "https://github.com/Liquid4All/leap-sdk.git", from: "0.10.9") ] targets: [ @@ -50,8 +52,8 @@ The `leap-ui` module (introduced in v0.10.0) ships a ready-to-use voice assistan ```kotlin dependencies { - implementation("ai.liquid.leap:leap-sdk:0.10.7") - implementation("ai.liquid.leap:leap-ui:0.10.7") + implementation("ai.liquid.leap:leap-sdk:0.10.9") + implementation("ai.liquid.leap:leap-ui:0.10.9") } ``` @@ -71,7 +73,7 @@ VoiceAudioRecorder + VoiceAudioPlayer + VoiceConversation - **`VoiceAssistantStore`** owns the session lifecycle. Instantiate once when the screen appears; `close()` it when it goes away. - **`VoiceConversation`** is a thin interface you implement to bridge the store to your model. Wrap the SDK's `Conversation.generateResponse` and forward `AudioSample` chunks to `onAudioChunk`. -- **Audio I/O** uses `VoiceAudioRecorder` / `VoiceAudioPlayer` interfaces. iOS / macOS ship `AppleAudioRecorder` and `AppleAudioPlayer` defaults; Android / JVM reference implementations live in `leap-ui-demo/`. +- **Audio I/O** uses `VoiceAudioRecorder` / `VoiceAudioPlayer` interfaces. iOS / macOS ship `AppleAudioRecorder` and `AppleAudioPlayer` defaults; Android / JVM implementations must be supplied by your app. ## Wire the model @@ -91,7 +93,7 @@ The `VoiceConversation` adapter looks similar on every platform — both impleme private let downloader: ModelDownloader = { let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!.path let modelsDir = (caches as NSString).appendingPathComponent("leap_models") - return ModelDownloader(config: LeapDownloaderConfig(saveDir: modelsDir)) + return ModelDownloader(config: LeapDownloaderConfig.with(saveDir: modelsDir)) }() init() { @@ -152,9 +154,13 @@ The `VoiceConversation` adapter looks similar on every platform — both impleme import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch - class VoiceAssistantViewModel(application: Application) : AndroidViewModel(application) { - private val recorder = AndroidAudioRecorder() // see "Audio I/O implementations" below - private val player = AndroidAudioPlayer() + // Inject your own VoiceAudioRecorder and VoiceAudioPlayer implementations. + // Construct this ViewModel through an application-provided factory. + class VoiceAssistantViewModel( + application: Application, + private val recorder: ai.liquid.leap.ui.VoiceAudioRecorder, + private val player: ai.liquid.leap.ui.VoiceAudioPlayer, + ) : AndroidViewModel(application) { val store = VoiceAssistantStore(recorder = recorder, player = player, scope = viewModelScope) val state: StateFlow = store.state @@ -282,7 +288,7 @@ The `VoiceConversation` adapter looks similar on every platform — both impleme super.onCreate(savedInstanceState) setContent { MaterialTheme(colorScheme = darkColorScheme(background = Color.Black)) { - val vm = viewModel() + val vm = viewModel(factory = voiceAssistantFactory) // your factory supplies audio I/O val state by vm.state.collectAsState() VoiceAssistantWidget( @@ -306,7 +312,7 @@ The store calls into a `VoiceConversation` you provide. A minimal adapter that w - The `VoiceConversation` protocol comes from `LeapUI`, so its `audioSamples` and `onAudioChunk` parameters use `LeapUi.KotlinFloatArray` / `LeapUi.KotlinInt` — not native Swift `[Float]` / `Int32`. The on-device runner lives in `LeapSDK`, which has its own `LeapSDK.KotlinFloatArray`. Bridge between the two via the `floatArrayToNSData` / `nsDataToFloatArray` helpers exposed in both frameworks (see `leap-ui-demo/shared/AppleVoiceConversation.swift` for the canonical pattern). + The `VoiceConversation` protocol comes from `LeapUI`, so its `audioSamples` and `onAudioChunk` parameters use `LeapUi.KotlinFloatArray` / `LeapUi.KotlinInt` — not native Swift `[Float]` / `Int32`. The on-device runner lives in `LeapSDK`, which has its own `LeapSDK.KotlinFloatArray`. Bridge between the two via the `floatArrayToNSData` / `nsDataToFloatArray` helpers exposed in both frameworks (as in the adapter below). ```swift import LeapModelDownloader @@ -332,7 +338,7 @@ The store calls into a `VoiceConversation` you provide. A minimal adapter that w let nsData = LeapUi.ArrayConversionsKt.floatArrayToNSData(array: audioSamples) let samples: [Float] = nsData.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) } - let audioContent = ChatMessageContent.fromFloatSamples(samples, sampleRate: Int(sampleRate)) + let audioContent = try ChatMessageContent.fromFloatSamples(samples, sampleRate: Int(sampleRate)) let userMessage = ChatMessage( role: .user, content: [audioContent as ChatMessageContent], @@ -343,6 +349,8 @@ The store calls into a `VoiceConversation` you provide. A minimal adapter that w var stats: Leap_sdkGenerationStats? for try await response in conversation.generateResponse(message: userMessage) { switch onEnum(of: response) { + case .error(let failure): + print("Generation failed: \(failure.message)") case .audioSample(let chunk): // Bridge LeapSDK.KotlinFloatArray -> LeapUi.KotlinFloatArray via NSData. let data = LeapSDK.ArrayConversionsKt.floatArrayToNSData(array: chunk.samples) @@ -391,6 +399,7 @@ The store calls into a `VoiceConversation` you provide. A minimal adapter that w var stats: GenerationStats? = null conv.generateResponse(userMessage).collect { response -> when (response) { + is MessageResponse.Error -> throw IllegalStateException(response.message) is MessageResponse.AudioSample -> onAudioChunk(response.samples, response.sampleRate) is MessageResponse.Complete -> stats = response.stats else -> Unit @@ -445,7 +454,7 @@ interface VoiceAudioPlayer { Add `NSMicrophoneUsageDescription` to your `Info.plist`. - `AndroidAudioRecorder` and `AndroidAudioPlayer` aren't part of `leap-ui` — they're reference implementations shipped with the demo app at `leap-ui-demo/android/src/main/kotlin/ai/liquid/leap/uidemo/AudioPipeline.kt`. Copy the file into your project, or implement the contracts against your own audio stack. + No Android recorder/player implementation is included in the public `leap-ui` distribution. Implement `VoiceAudioRecorder` using Android `AudioRecord` and `VoiceAudioPlayer` using `AudioTrack`, then inject them through your ViewModel factory. The names `AndroidAudioRecorder` and `AndroidAudioPlayer` in older guides referred to unpublished demo classes; there is no public file to copy. Required permissions: @@ -457,7 +466,7 @@ interface VoiceAudioPlayer { Request `RECORD_AUDIO` at runtime via the standard `ActivityResultContracts.RequestPermission()` pattern (see [Quick Start](./quick-start)). - No bundled implementations — use `javax.sound.sampled.TargetDataLine` for capture and `SourceDataLine` for playback, wrapped to match the `VoiceAudioRecorder` / `VoiceAudioPlayer` contracts. The demo at `leap-ui-demo/jvm` (if present in your release) ships a working reference. + No bundled implementations — use `javax.sound.sampled.TargetDataLine` for capture and `SourceDataLine` for playback, wrapped to match the `VoiceAudioRecorder` / `VoiceAudioPlayer` contracts. There is no public `leap-ui-demo/jvm` project to copy. diff --git a/deployment/tools/model-bundling/authentication.mdx b/deployment/tools/model-bundling/authentication.mdx index 5ec6a1c..b5aef8d 100644 --- a/deployment/tools/model-bundling/authentication.mdx +++ b/deployment/tools/model-bundling/authentication.mdx @@ -5,6 +5,8 @@ description: "Authentication commands for the LEAP Bundle CLI" The LEAP Model Bundling Service is deprecated and no longer maintained. For new deployments, download GGUF files from [Hugging Face](https://huggingface.co/LiquidAI) and run them with [llama.cpp](/deployment/on-device/llama-cpp). + +The hosted `leap.liquid.ai` catalog, authentication, and bundling endpoints are no longer available. The commands below document the former service and cannot create or download new bundles. For current model downloads and conversion, use [Hugging Face and llama.cpp](/deployment/on-device/llama-cpp#converting-custom-models). ## `login` diff --git a/deployment/tools/model-bundling/bundle-creation.mdx b/deployment/tools/model-bundling/bundle-creation.mdx index 01e871f..f4e5eea 100644 --- a/deployment/tools/model-bundling/bundle-creation.mdx +++ b/deployment/tools/model-bundling/bundle-creation.mdx @@ -5,6 +5,8 @@ description: "Commands for creating and validating bundle requests in the LEAP B The LEAP Model Bundling Service is deprecated and no longer maintained. For new deployments, download GGUF files from [Hugging Face](https://huggingface.co/LiquidAI) and run them with [llama.cpp](/deployment/on-device/llama-cpp). + +The hosted `leap.liquid.ai` catalog, authentication, and bundling endpoints are no longer available. The commands below document the former service and cannot create or download new bundles. For current model downloads and conversion, use [Hugging Face and llama.cpp](/deployment/on-device/llama-cpp#converting-custom-models). ## `create` diff --git a/deployment/tools/model-bundling/bundle-management.mdx b/deployment/tools/model-bundling/bundle-management.mdx index 0efa897..585a1cb 100644 --- a/deployment/tools/model-bundling/bundle-management.mdx +++ b/deployment/tools/model-bundling/bundle-management.mdx @@ -5,6 +5,8 @@ description: "Commands for listing and canceling bundle requests in the LEAP Bun The LEAP Model Bundling Service is deprecated and no longer maintained. For new deployments, download GGUF files from [Hugging Face](https://huggingface.co/LiquidAI) and run them with [llama.cpp](/deployment/on-device/llama-cpp). + +The hosted `leap.liquid.ai` catalog, authentication, and bundling endpoints are no longer available. The commands below document the former service and cannot create or download new bundles. For current model downloads and conversion, use [Hugging Face and llama.cpp](/deployment/on-device/llama-cpp#converting-custom-models). ## `list` diff --git a/deployment/tools/model-bundling/changelog.mdx b/deployment/tools/model-bundling/changelog.mdx index dacaa1a..3628d75 100644 --- a/deployment/tools/model-bundling/changelog.mdx +++ b/deployment/tools/model-bundling/changelog.mdx @@ -6,6 +6,8 @@ description: "Release history for leap-bundle, the Liquid AI model bundling CLI The LEAP Model Bundling Service is deprecated and no longer maintained. For new deployments, download GGUF files from [Hugging Face](https://huggingface.co/LiquidAI) and run them with [llama.cpp](/deployment/on-device/llama-cpp). + +The hosted `leap.liquid.ai` catalog, authentication, and bundling endpoints are no longer available. The commands below document the former service and cannot create or download new bundles. For current model downloads and conversion, use [Hugging Face and llama.cpp](/deployment/on-device/llama-cpp#converting-custom-models). ## `v0.9.0` - 2026-01-02 diff --git a/deployment/tools/model-bundling/configuration.mdx b/deployment/tools/model-bundling/configuration.mdx index 336be0c..6b992b0 100644 --- a/deployment/tools/model-bundling/configuration.mdx +++ b/deployment/tools/model-bundling/configuration.mdx @@ -5,6 +5,8 @@ description: "Configuration commands and file format for the LEAP Bundle CLI" The LEAP Model Bundling Service is deprecated and no longer maintained. For new deployments, download GGUF files from [Hugging Face](https://huggingface.co/LiquidAI) and run them with [llama.cpp](/deployment/on-device/llama-cpp). + +The hosted `leap.liquid.ai` catalog, authentication, and bundling endpoints are no longer available. The commands below document the former service and cannot create or download new bundles. For current model downloads and conversion, use [Hugging Face and llama.cpp](/deployment/on-device/llama-cpp#converting-custom-models). ## `config` diff --git a/deployment/tools/model-bundling/data-privacy.mdx b/deployment/tools/model-bundling/data-privacy.mdx index e37bd28..38f9fe7 100644 --- a/deployment/tools/model-bundling/data-privacy.mdx +++ b/deployment/tools/model-bundling/data-privacy.mdx @@ -6,6 +6,8 @@ sidebar_position: 3 The LEAP Model Bundling Service is deprecated and no longer maintained. For new deployments, download GGUF files from [Hugging Face](https://huggingface.co/LiquidAI) and run them with [llama.cpp](/deployment/on-device/llama-cpp). + +The hosted `leap.liquid.ai` catalog, authentication, and bundling endpoints are no longer available. The commands below document the former service and cannot create or download new bundles. For current model downloads and conversion, use [Hugging Face and llama.cpp](/deployment/on-device/llama-cpp#converting-custom-models). ### Bundle Request Information diff --git a/deployment/tools/model-bundling/download.mdx b/deployment/tools/model-bundling/download.mdx index 231dc1b..189887c 100644 --- a/deployment/tools/model-bundling/download.mdx +++ b/deployment/tools/model-bundling/download.mdx @@ -5,6 +5,8 @@ description: "Download commands for bundle requests and LEAP models in the LEAP The LEAP Model Bundling Service is deprecated and no longer maintained. For new deployments, download GGUF files from [Hugging Face](https://huggingface.co/LiquidAI) and run them with [llama.cpp](/deployment/on-device/llama-cpp). + +The hosted `leap.liquid.ai` catalog, authentication, and bundling endpoints are no longer available. The commands below document the former service and cannot create or download new bundles. For current model downloads and conversion, use [Hugging Face and llama.cpp](/deployment/on-device/llama-cpp#converting-custom-models). The `download` command supports two modes of operation: diff --git a/deployment/tools/model-bundling/quick-start.mdx b/deployment/tools/model-bundling/quick-start.mdx index d49534a..bd33853 100644 --- a/deployment/tools/model-bundling/quick-start.mdx +++ b/deployment/tools/model-bundling/quick-start.mdx @@ -6,6 +6,8 @@ description: "The Bundling Service helps users create and manage model bundles f The LEAP Model Bundling Service is deprecated and no longer maintained. For new deployments, download GGUF files from [Hugging Face](https://huggingface.co/LiquidAI) and run them with [llama.cpp](/deployment/on-device/llama-cpp). + +The hosted `leap.liquid.ai` catalog, authentication, and bundling endpoints are no longer available. The commands below document the former service and cannot create or download new bundles. For current model downloads and conversion, use [Hugging Face and llama.cpp](/deployment/on-device/llama-cpp#converting-custom-models). The CLI supports two main workflows: diff --git a/deployment/tools/model-bundling/reference.mdx b/deployment/tools/model-bundling/reference.mdx index 0f5ba5a..4b53a55 100644 --- a/deployment/tools/model-bundling/reference.mdx +++ b/deployment/tools/model-bundling/reference.mdx @@ -5,6 +5,8 @@ description: "Reference information for the LEAP Bundle CLI including limitation The LEAP Model Bundling Service is deprecated and no longer maintained. For new deployments, download GGUF files from [Hugging Face](https://huggingface.co/LiquidAI) and run them with [llama.cpp](/deployment/on-device/llama-cpp). + +The hosted `leap.liquid.ai` catalog, authentication, and bundling endpoints are no longer available. The commands below document the former service and cannot create or download new bundles. For current model downloads and conversion, use [Hugging Face and llama.cpp](/deployment/on-device/llama-cpp#converting-custom-models). ## All Commands diff --git a/docs.json b/docs.json index 24301e0..c16e58a 100644 --- a/docs.json +++ b/docs.json @@ -391,6 +391,25 @@ ] }, "redirects": [ + {"source": "/leap", "destination": "/lfm/models/complete-library"}, + {"source": "/leap/index", "destination": "/lfm/models/complete-library"}, + {"source": "/leap/changelog", "destination": "/deployment/on-device/leap-sdk-changelog"}, + {"source": "/leap/edge-sdk/android/android-quick-start-guide", "destination": "/deployment/on-device/sdk/quick-start"}, + {"source": "/leap/edge-sdk/ios/ios-quick-start-guide", "destination": "/deployment/on-device/sdk/quick-start"}, + {"source": "/leap/find-model", "destination": "/lfm/models/complete-library"}, + {"source": "/leap/finetuning", "destination": "/lfm/fine-tuning/overview"}, + {"source": "/leap/laptop-support", "destination": "/deployment/overview"}, + {"source": "/leap/leap-bundle/cli-spec", "destination": "/deployment/tools/model-bundling/reference"}, + {"source": "/leap/vibe-check-models", "destination": "/lfm/models/complete-library"}, + {"source": "/docs/frameworks/outlines", "destination": "/lfm/key-concepts/text-generation-and-prompting"}, + {"source": "/docs/getting-started/intro", "destination": "/lfm/models/complete-library"}, + {"source": "/docs/models/lfm25-1.2b-base", "destination": "/lfm/models/lfm25-1.2b-base"}, + {"source": "/lfm/getting-started/quickstart", "destination": "/deployment/overview"}, + {"source": "/examples/deploy-models-on-ios/slogan-generator-app", "destination": "/deployment/on-device/llama-cpp/mobile"}, + {"source": "/docs", "destination": "/lfm/models/complete-library"}, + {"source": "/deployment/on-device/sdk/android-quick-start-guide", "destination": "/deployment/on-device/sdk/quick-start"}, + {"source": "/deployment/on-device/sdk/ios-quick-start-guide", "destination": "/deployment/on-device/sdk/quick-start"}, + {"source": "/deployment/tools/model-bundling/cli-spec", "destination": "/deployment/tools/model-bundling/reference"}, { "source": "/examples/android/leap-koog-agent", "destination": "/examples/android/tool-calling-agent" diff --git a/examples/agent-harnesses.mdx b/examples/agent-harnesses.mdx index c8ccdfd..b338215 100644 --- a/examples/agent-harnesses.mdx +++ b/examples/agent-harnesses.mdx @@ -262,8 +262,9 @@ port with the one your server prints and the model ID with the one returned by ` ```bash hermes ``` - > [!Note] - > If `web_search` is missing from the model's available tools, it may be due to `search` or `browser` being listed in `agent.disabled_toolsets`. Remove both entries in `hermes config edit` and restart Hermes. + + If `web_search` is missing from the model's available tools, it may be due to `search` or `browser` being listed in `agent.disabled_toolsets`. Remove both entries in `hermes config edit` and restart Hermes. + Docs: [Getting started](https://docs.openclaw.ai/start/getting-started) and [Local models](https://docs.openclaw.ai/gateway/local-models). diff --git a/examples/customize-models/home-assistant.mdx b/examples/customize-models/home-assistant.mdx index 39ce8c6..e68aad1 100644 --- a/examples/customize-models/home-assistant.mdx +++ b/examples/customize-models/home-assistant.mdx @@ -33,6 +33,7 @@ In this example, you will learn how to: ```bash git clone https://github.com/Liquid4All/cookbook.git cd cookbook/examples/home-assistant +export HOME_ASSISTANT_DIR="$PWD" ``` ### 2. Start the app server @@ -47,6 +48,8 @@ uv run uvicorn app.server:app --port 5173 --reload open http://localhost:5173 ``` +In `app/server.py`, correct the 350M baseline repository from `LiquidAI/LFM2-350M-Instruct-GGUF` to `LiquidAI/LFM2-350M-GGUF`; the former is not the published repository. + The UI includes a model selector. When you pick a model, the app automatically downloads and starts `llama-server` in the background. No manual model server setup is needed. ## Environment setup @@ -223,7 +226,7 @@ uv run python benchmark/run.py \ --hf-file LFM2.5-1.2B-Instruct-Q4_0.gguf ``` -Run a single task by number (1-101): +Run a single task by number (1-100): ```bash uv run python benchmark/run.py \ @@ -277,7 +280,9 @@ Generate 500 examples distributed across the benchmark taxonomy (requires `OPENA uv run python benchmark/datasets/generate.py --count 500 --output benchmark/datasets/sft_data.jsonl ``` -Then convert the dataset to the LFM2 text format and push it to Hugging Face so Modal can pull it during training: +Before uploading, set `REPO_ID_LFM2` in `finetune/prepare_data.py` to a dataset repository in **your own** Hugging Face namespace. Set `dataset.path` in `finetune/configs/LFM2-350M.yaml` to that same repository. The checked-in values belong to the author. Also replace `training_config.trackio_space_id` with your own Space (or set `training_config.tracker: "none"` and remove `trackio_space_id` to disable tracking). + +Then convert the dataset to the LFM2 text format and upload it so Modal can read it. The preparation script publishes to the configured repository; review the generated data first: ```bash uv run --group finetune python finetune/prepare_data.py \ @@ -309,39 +314,40 @@ sequenceDiagram ### Steps -**1. One-time setup.** Clone and install `liquid-finetune`, then authenticate with Hugging Face and Modal. +**1. One-time setup.** Clone `liquid-finetune` inside the example directory, then authenticate with Hugging Face and Modal. ```bash -git clone https://github.com/Liquid4All/liquid-finetune -cd liquid-finetune && uv sync && cd - -huggingface-cli login -modal setup +cd "$HOME_ASSISTANT_DIR" +git clone https://github.com/Liquid4All/liquid-finetune.git +export FINETUNE_DIR="$HOME_ASSISTANT_DIR/liquid-finetune" +uv sync --project "$FINETUNE_DIR" +uv run --project "$FINETUNE_DIR" hf auth login +uv run --project "$FINETUNE_DIR" modal setup ``` -**2. Kick off training on Modal.** Runs 5 epochs of LoRA SFT on an H100. Takes a few minutes and costs roughly $1.50. +**2. Start training on Modal.** The config runs five epochs of LoRA SFT on an H100. Runtime and cost depend on your dataset and configuration. ```bash -cd liquid-finetune -uv run liquid-finetune ../finetune/configs/LFM2-350M.yaml +uv run --project "$FINETUNE_DIR" liquid-finetune "$HOME_ASSISTANT_DIR/finetune/configs/LFM2-350M.yaml" ``` -**3. Download the checkpoint** from the Modal Volume once training finishes. +**3. Download the checkpoint** after training finishes. The config names the volume `leap-finetune`. `/outputs` is its container mount point, not a directory prefix in the volume CLI. List the volume root, then replace `` with the run shown in the listing: ```bash -cd liquid-finetune -uv run modal volume get liquid-finetune /outputs/home-assistant-350M ../finetune/output/350M-lora +uv run --project "$FINETUNE_DIR" modal volume ls leap-finetune / +uv run --project "$FINETUNE_DIR" modal volume get leap-finetune / "$HOME_ASSISTANT_DIR/finetune/output/350M-lora" ``` -**4. Export.** Merges the LoRA adapter into the base model, converts to GGUF, and pushes to Hugging Face. +**4. Export.** Merge the adapter locally first: ```bash -uv run --group export python finetune/export.py \ - --lora-path finetune/output/350M-lora \ - --output-path finetune/output/350M-merged \ - --push-to-hub \ - --quant-type q8_0 +uv run --project "$HOME_ASSISTANT_DIR" --group export python "$HOME_ASSISTANT_DIR/finetune/export.py" \ + --lora-path "$HOME_ASSISTANT_DIR/finetune/output/350M-lora" \ + --output-path "$HOME_ASSISTANT_DIR/finetune/output/350M-merged" ``` +To convert the merged weights without publishing them, follow [Convert to GGUF](/deployment/on-device/llama-cpp#converting-custom-models), using the merged directory as the input. If you choose the example's `--push-to-hub --quant-type q8_0` export option instead, it creates a **public** model repository in your authenticated Hugging Face namespace. + Re-run the benchmark with the flags printed by the export step: ```bash diff --git a/examples/customize-models/satellite-vlm.mdx b/examples/customize-models/satellite-vlm.mdx index 78e4e8e..b3150d8 100644 --- a/examples/customize-models/satellite-vlm.mdx +++ b/examples/customize-models/satellite-vlm.mdx @@ -20,16 +20,27 @@ Fine-tune [LiquidAI/LFM2.5-VL-450M](https://huggingface.co/LiquidAI/LFM2.5-VL-45 ## Quickstart -1. **Install and authenticate** (run from `cookbook/examples/satellite-vlm/`): +1. **Clone, install, and authenticate:** - Modal provides serverless GPUs you pay for per second. New accounts include $30 of free credit, enough to run this example end to end. No local GPU required. + Data preparation and training run on Modal. Check its current pricing before launching the full dataset run. ```bash + git clone https://github.com/Liquid4All/cookbook.git + cd cookbook/examples/satellite-vlm + export SATELLITE_DIR="$PWD" uv sync - uv run python -m modal setup - uv run huggingface-cli login + uv run modal setup + uv run hf auth login ``` + The training config already enables Weights & Biases and requests `wandb-secret`. Create that Modal secret before training: + + ```bash + uv run modal secret create wandb-secret WANDB_API_KEY="$WANDB_API_KEY" + ``` + + To disable tracking, set `training_config.tracker: "none"` and remove `wandb-secret` from `modal.secrets` in the config. + 2. **Prepare data** (~12 GB): the download and conversion run inside a Modal container, and the resulting data is pushed to a Modal volume where the fine-tuning job will pick it up. ```bash @@ -40,9 +51,9 @@ Fine-tune [LiquidAI/LFM2.5-VL-450M](https://huggingface.co/LiquidAI/LFM2.5-VL-45 ```bash git clone https://github.com/Liquid4All/liquid-finetune/ - cd liquid-finetune - uv sync - uv run liquid-finetune ../configs/vrsbench_multitask_modal.yaml + export FINETUNE_DIR="$SATELLITE_DIR/liquid-finetune" + uv sync --project "$FINETUNE_DIR" + uv run --project "$FINETUNE_DIR" liquid-finetune "$SATELLITE_DIR/configs/vrsbench_multitask_modal.yaml" ``` ## How It Works @@ -75,23 +86,23 @@ Output files (written to `./data/` locally, or to the Modal volume with `--modal ## Training -Run from the `liquid-finetune` root (cloned in the Quickstart): +Using the project paths set in the Quickstart: ```bash -uv run liquid-finetune ../configs/vrsbench_multitask_modal.yaml +uv run --project "$FINETUNE_DIR" liquid-finetune "$SATELLITE_DIR/configs/vrsbench_multitask_modal.yaml" ``` -The job runs on an H100, streams logs to your terminal, and saves checkpoints to the `satellite-vlm` Modal volume under `/satellite-vlm/outputs/`. +The job runs on an H100, streams logs to your terminal, and saves checkpoints to the `satellite-vlm` Modal volume under a run directory at the volume root. `/satellite-vlm` is the container mount point; do not include it in `modal volume get` paths. -To enable experiment tracking, uncomment `tracker: "wandb"` in the config. +The checked-in config enables `tracker: "wandb"`; use your own `wandb-secret` as described above. ## Retrieving Checkpoints List and download checkpoints from the Modal volume: ```bash -modal volume ls satellite-vlm outputs/ -modal volume get satellite-vlm /satellite-vlm/outputs/ ./outputs +uv run --project "$FINETUNE_DIR" modal volume ls satellite-vlm / +uv run --project "$FINETUNE_DIR" modal volume get satellite-vlm / "$SATELLITE_DIR/outputs" ``` ## Data Format @@ -115,15 +126,15 @@ Benchmarks run automatically during training at every `eval_steps`: - **VQA**: `short_answer` metric (case-insensitive substring match) - **Grounding**: `grounding_iou` metric (IoU@0.5 threshold) -- **Captioning**: `CIDEr` or `BLEU` metrics +- **Captioning**: `BLEU` in the checked-in config Each eval dataset can be limited (e.g., 500 samples) via the `limit` field in the YAML config for faster iteration. -**Running a full standalone evaluation:** to evaluate on the complete dataset without retraining, use `configs/vrsbench_full_eval.yaml`. Set `eval_on_start: true`, remove the `limit` fields, and point the config at your checkpoint path. The model runs the full evaluation at step 0, logs results to WandB, and terminates. +`eval_on_start: true` evaluates before training; it does **not** make a training configuration evaluation-only. For a separate evaluation job, use liquid-finetune's [standalone evaluation configuration](https://github.com/Liquid4All/liquid-finetune/blob/main/job_configs/eval_standalone_example.yaml), pointing it at your checkpoint and prepared dataset. Remove benchmark `limit` values only when you intend to evaluate the full dataset. ## AI in Space Hackathon -This example is the official starting point for the [**AI in Space Hackathon**](https://luma.com/n9cw58h0), a fully online event organised in partnership between [DPhi Space](https://github.com/DPhi-Space/SimSat) and Liquid AI, open to builders from all around the globe. +This example was developed as a starting point for the [**AI in Space Hackathon**](https://luma.com/n9cw58h0), an online event organised in partnership between [DPhi Space](https://github.com/DPhi-Space/SimSat) and Liquid AI, open to builders from all around the globe. Use this fine-tuning pipeline as your baseline and push it further with real satellite data. diff --git a/examples/customize-models/wildfire-prevention.mdx b/examples/customize-models/wildfire-prevention.mdx index 6509c3d..5a6569f 100644 --- a/examples/customize-models/wildfire-prevention.mdx +++ b/examples/customize-models/wildfire-prevention.mdx @@ -178,10 +178,13 @@ The system monitors 22 fixed locations. Each location is a single 5 km tile cent 3. Open the SimSat dashboard at `http://localhost:8000`, click **Start**, and verify the satellite position is moving. -4. Install Python dependencies: +4. In a second terminal, clone the cookbook and enter the wildfire example. Install [llama.cpp](/deployment/on-device/llama-cpp#installation) and confirm `llama-server` is on your PATH before selecting the local backend: ```bash + git clone https://github.com/Liquid4All/cookbook.git + cd cookbook/examples/wildfire-prevention uv sync + llama-server --version ``` 5. Start the watch loop: diff --git a/examples/laptop-examples/browser-control.mdx b/examples/laptop-examples/browser-control.mdx index 2f26d8c..cc283b3 100644 --- a/examples/laptop-examples/browser-control.mdx +++ b/examples/laptop-examples/browser-control.mdx @@ -155,6 +155,28 @@ To simplify things a bit, we will run both the `GRPOTrainer` and the `vLLM` on t We use [Modal](https://modal.com/) for serverless GPU infrastructure. Modal is a great option for AI engineers who don't want to worry too much about infrastructure and prefer to pay per usage. It provides on-demand GPU access with simple Python-based configuration, making it easy to scale training workloads without managing clusters or dealing with complex DevOps setup. +## Setup + +Run the experiments from their own project directory: + +```bash +git clone https://github.com/Liquid4All/cookbook.git +cd cookbook/examples/browser-control +uv sync +uv run modal setup +uv run hf auth login +``` + +The Modal image expects a secret named `wandb-secret`. Create it with your own Weights & Biases API key: + +```bash +uv run modal secret create wandb-secret WANDB_API_KEY="$WANDB_API_KEY" +``` + +In `configs/lfm2_350m.yaml` and `configs/lfm2_350m_lora.yaml`, set `browsergym_url` to a running BrowserGym/OpenEnv server you control. The author's Space can be asleep or unavailable. The [source project](https://github.com/Liquid4All/cookbook/tree/main/examples/browser-control) contains the environment integration. + +For the LoRA config, replace the Llama-style `lora_target_modules` with LFM2's `q_proj`, `k_proj`, `v_proj`, `out_proj`, `in_proj`, `w1`, `w2`, and `w3`. Set `push_to_hf: false` for a local experiment, or configure a writable destination before enabling model uploads. These are historical LFM2 experiments; their reported results do not establish LFM3 performance. + ## Experiments ### Full-fine tune @@ -162,7 +184,7 @@ We use [Modal](https://modal.com/) for serverless GPU infrastructure. Modal is a The first experiment we run is a full fine-tune of LFM2-350M: ```bash -make run config=lfm2_350m.yaml +make fine-tune config=lfm2_350m.yaml ``` The `click-test` task is an easy one, and the model is capable of solving it in less than 10 attempts from the beginning. @@ -176,7 +198,7 @@ The final checkpoint is available on HF: With LoRA we can match full fine-tune results with way less compute and time: ```bash -make run config=lfm2_350m_lora.yaml +make fine-tune config=lfm2_350m_lora.yaml ``` ## Next Steps diff --git a/examples/laptop-examples/build-a-game-with-decision-models.mdx b/examples/laptop-examples/build-a-game-with-decision-models.mdx index ffd8bd1..0f0fe92 100644 --- a/examples/laptop-examples/build-a-game-with-decision-models.mdx +++ b/examples/laptop-examples/build-a-game-with-decision-models.mdx @@ -188,7 +188,7 @@ By default, d1 runs through Liquid's API and Jev runs through OpenRouter: | Variable | Default | Description | | --- | --- | --- | | `LIQUID_API_KEY` | | API key for d1. Required. | -| `LIQUID_MODEL_NAME` | `d1:latest` | d1 model name. `d1:latest` always points to the newest d1 model. Set an exact name such as `d1.2` or `d1.2-ultra` to pin one. | +| `LIQUID_MODEL_NAME` | `d1:free` in the source | Override this legacy default with `d1.2` or `d1.2-ultra` for the current Liquid API. | | `LIQUID_BASE_URL` | `https://api.liquid.ai` | API host for d1. | | `OPENROUTER_API_KEY` | | OpenRouter API key. Required for Jev vs d1 mode. | | `OPENROUTER_MODEL_NAME` | `typesafe/jev-1.13` | Jev model name. | diff --git a/examples/laptop-examples/invoice-extractor-tool-with-liquid-nanos.mdx b/examples/laptop-examples/invoice-extractor-tool-with-liquid-nanos.mdx index 9d9a76d..90543f7 100644 --- a/examples/laptop-examples/invoice-extractor-tool-with-liquid-nanos.mdx +++ b/examples/laptop-examples/invoice-extractor-tool-with-liquid-nanos.mdx @@ -1,6 +1,6 @@ --- title: "Invoice extractor tool" -description: "Extract structured payment details from invoice PDFs using LFM2.5-VL-1.6B and llama.cpp, running fully local." +description: "Extract structured payment details from invoice images using LFM2.5-VL-1.6B and llama.cpp, running fully local." --- @@ -11,7 +11,7 @@ description: "Extract structured payment details from invoice PDFs using LFM2.5- **Newer model available:** This example uses LFM2.5-VL-1.6B. For new projects, see [LFM3-VL-2B](/lfm/models/lfm3-vl-2b). -A Python CLI that extracts payment details from invoice PDFs. +A Python CLI that extracts payment details from invoice images. ![Invoice extraction: a utility bill image goes through LFM2.5-VL-1.6B on llama.cpp and comes out as structured JSON](https://github.com/Liquid4All/cookbook/raw/main/examples/invoice-parser/media/diagram.jpg) @@ -95,13 +95,12 @@ The tool automatically starts and stops `llama-server` for you — no need to ru ### Watch mode -Run it as a background service that continuously monitors a directory and automatically parses invoice images as they land in the folder: +Run it as a background service that continuously monitors a directory and automatically parses invoice images as they land in the folder. Watch mode writes to `/bills.csv`; `--output` is available only in process mode: ```sh uv run python src/invoice_parser/main.py watch \ --dir invoices/ \ --image-model LiquidAI/LFM2.5-VL-1.6B-GGUF:Q8_0 \ - --output bills.csv \ --process-existing ``` diff --git a/examples/laptop-examples/lfm2-english-to-korean.mdx b/examples/laptop-examples/lfm2-english-to-korean.mdx index b77c97b..5825968 100644 --- a/examples/laptop-examples/lfm2-english-to-korean.mdx +++ b/examples/laptop-examples/lfm2-english-to-korean.mdx @@ -47,21 +47,21 @@ The system uses a two-stage training approach: ### Model Components -- **Base Model**: `gyung/lfm2-1.2b-koen-mt-v4-100k` - SFT fine-tuned LFM2 1.2B -- **Adapter**: `gyung/lfm2-1.2b-koen-mt-v5-rl-10k-adapter` - LoRA adapter trained with GRPO +- **Base Model**: `gyung/lfm2-1.2b-koen-mt-v6.4-merged` - SFT fine-tuned LFM2 1.2B +- **Adapter**: `gyung/lfm2-1.2b-koen-mt-v8-rl-10k-adapter` - LoRA adapter trained with GRPO - **Automatic Detection**: Regular expression pattern matching for Korean text (Hangul syllables, Jamo) The system automatically detects the input language and applies the appropriate translation direction, supporting both English→Korean and Korean→English translation. ## CLI Usage -```bash +```text uv run python main.py [OPTIONS] Options: --text TEXT Text to translate (required) - --model-name TEXT Base model name (default: gyung/lfm2-1.2b-koen-mt-v4-100k) - --adapter-name TEXT Adapter name (default: gyung/lfm2-1.2b-koen-mt-v5-rl-10k-adapter) + --model-name TEXT Base model name (default: gyung/lfm2-1.2b-koen-mt-v6.4-merged) + --adapter-name TEXT Adapter name (default: gyung/lfm2-1.2b-koen-mt-v8-rl-10k-adapter) --max-new-tokens INTEGER Maximum tokens to generate (default: 256) --temperature FLOAT Sampling temperature (default: 0.3) --min-p FLOAT Minimum probability threshold (default: 0.15) @@ -91,7 +91,7 @@ On Flores-200 benchmark (1,012 samples): | Model | Parameters | CHrF++ | BLEU | |-------|------------|--------|------| -| **LFM2-KoEn-v5-RL** | **1.2B** | **32.96** | **12.05** | +| **LFM2-KoEn-v8-RL** | **1.2B** | **32.96** | **12.05** | | Gemma-3-4B | 4B | 32.83 | 11.36 | | Qwen3-4B | 4B | 25.62 | 7.46 | diff --git a/examples/laptop-examples/meeting-summarization.mdx b/examples/laptop-examples/meeting-summarization.mdx index 3401287..b958deb 100644 --- a/examples/laptop-examples/meeting-summarization.mdx +++ b/examples/laptop-examples/meeting-summarization.mdx @@ -68,7 +68,7 @@ Isn't that beautiful? ```bash uv run summarize.py \ --model LiquidAI/LFM2-2.6B-Transcript-GGUF \ - --hf-model-file LFM2-2.6B-Transcript-1-GGUF.gguf \ + --hf-model-file LFM2-2.6B-Transcript-Q4_0.gguf \ --transcript-file transcripts/example_1.txt ``` @@ -79,9 +79,16 @@ The CLI uses the llama.cpp Python bindings to download and build the llama.cpp b Then, it uses the `LiquidAI/LFM2-2.6B-Transcript` model to summarize the transcript. ```python +from huggingface_hub import hf_hub_download +from llama_cpp import Llama + +model_path = hf_hub_download( + repo_id="LiquidAI/LFM2-2.6B-Transcript-GGUF", + filename="LFM2-2.6B-Transcript-Q4_0.gguf", +) model = Llama( - model_path="LiquidAI/LFM2-2.6B-Transcript-GGUF", - n_ctx=8192, + model_path=model_path, + n_ctx=16384, n_threads=4, verbose=False, ) diff --git a/examples/web/hand-voice-racer.mdx b/examples/web/hand-voice-racer.mdx index 677372e..4052ee1 100644 --- a/examples/web/hand-voice-racer.mdx +++ b/examples/web/hand-voice-racer.mdx @@ -56,6 +56,8 @@ The audio model loads from Hugging Face and is cached in IndexedDB after the fir ## Run locally ```bash +git clone https://github.com/Liquid4All/cookbook.git +cd cookbook/examples/hand-voice-racer npm install npm run dev ``` diff --git a/lfm/fine-tuning/liquid-finetune.mdx b/lfm/fine-tuning/liquid-finetune.mdx index 6ed9028..63ff8b1 100644 --- a/lfm/fine-tuning/liquid-finetune.mdx +++ b/lfm/fine-tuning/liquid-finetune.mdx @@ -33,7 +33,8 @@ uv sync For AMD/ROCm machines, sync the ROCm dependency group instead: ```bash -uv sync --no-group cuda --group rocm +export UV_PROJECT=envs/rocm +uv sync ``` Start Claude Code or Codex from the repo root: @@ -44,7 +45,7 @@ claude codex ``` -The repo includes `AGENTS.md`, `CLAUDE.md`, and mirrored skills under `.agents/skills/` and `.claude/skills/`. Those files help the agent choose the right workflow for data prep, training configs, eval suites, rewards, backend launch, checkpoint inspection, and export. +The repo includes `AGENTS.md` with instructions for coding agents. Read it alongside the current README and job configs for data preparation, training, evaluation, and export. Keep `UV_PROJECT=envs/rocm` set for subsequent ROCm commands; unset it when switching back to the root CUDA project. Good starter prompts: diff --git a/lfm/fine-tuning/unsloth.mdx b/lfm/fine-tuning/unsloth.mdx index 59cec4b..e411bd3 100644 --- a/lfm/fine-tuning/unsloth.mdx +++ b/lfm/fine-tuning/unsloth.mdx @@ -10,7 +10,7 @@ For a new LFM3 text adaptation, start with the [tested TRL path](/lfm/fine-tunin Use Unsloth for faster training with optimized kernels, reduced memory usage, and built-in quantization support. -LFM2.5 models are fully supported by Unsloth. For comprehensive guides and tutorials, see the [official Unsloth LFM2.5 documentation](https://unsloth.ai/docs/models/tutorials/lfm2.5). +The example below fine-tunes LFM2.5-1.2B-Instruct with Unsloth. For comprehensive guides and tutorials, see the [official Unsloth LFM2.5 documentation](https://unsloth.ai/docs/models/tutorials/lfm2.5). Different training methods require specific dataset formats. See [Datasets](/lfm/fine-tuning/datasets) for format requirements for [SFT](/lfm/fine-tuning/datasets#instruction-datasets-sft) and [GRPO](/lfm/fine-tuning/datasets#prompt-only-datasets-grpo). @@ -40,50 +40,67 @@ Get started quickly with these ready-to-run Colab notebooks: ## Quick Start +This two-step setup check was run on an H100 with Python 3.12. It verifies that LoRA adapters attach and training saves an adapter; use a real dataset and a longer run for useful adaptation. + +```bash +pip install "unsloth==2026.11.7" "unsloth_zoo==2026.11.7" "torch==2.14.0" "transformers==5.17.0" "trl==1.15.0" "peft==0.21.3" +``` + ```python from unsloth import FastLanguageModel -from trl import SFTTrainer, SFTConfig +from datasets import Dataset +from trl import SFTConfig, SFTTrainer -# Load model with Unsloth optimizations model, tokenizer = FastLanguageModel.from_pretrained( model_name="LiquidAI/LFM2.5-1.2B-Instruct", - max_seq_length=2048, - load_in_4bit=True, # Enable QLoRA for memory efficiency + max_seq_length=512, + load_in_4bit=True, ) - -# Apply LoRA with Unsloth's optimized gradient checkpointing model = FastLanguageModel.get_peft_model( model, - r=16, - target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"], - lora_alpha=32, - use_gradient_checkpointing="unsloth", # 2x faster than default + r=8, + target_modules=r".*\.(q_proj|k_proj|v_proj|out_proj|in_proj|w1|w2|w3)$", + lora_alpha=16, + use_gradient_checkpointing="unsloth", + random_state=42, ) - -# Train with TRL's SFTTrainer +adapter_modules = [name for name, module in model.named_modules() if hasattr(module, "lora_A")] +assert all(any(name.endswith("." + part) for name in adapter_modules) for part in + ("q_proj", "k_proj", "v_proj", "out_proj", "in_proj", "w1", "w2", "w3")) + +rows = [ + [{"role": "user", "content": "What is the capital of France?"}, + {"role": "assistant", "content": "Paris."}], + [{"role": "user", "content": "What is two plus two?"}, + {"role": "assistant", "content": "Four."}], +] +dataset = Dataset.from_dict({ + "text": [tokenizer.apply_chat_template(messages, tokenize=False) for messages in rows] +}) trainer = SFTTrainer( model=model, - args=SFTConfig(output_dir="./lfm2-unsloth", num_train_epochs=1, bf16=True), - train_dataset=dataset["train"], - tokenizer=tokenizer, + processing_class=tokenizer, + train_dataset=dataset, + args=SFTConfig( + output_dir="lfm25-unsloth", + max_steps=2, + max_length=256, + dataset_text_field="text", + per_device_train_batch_size=1, + gradient_accumulation_steps=1, + learning_rate=2e-4, + bf16=True, + report_to="none", + save_strategy="no", + ), ) trainer.train() - -# Fast inference -FastLanguageModel.for_inference(model) +trainer.save_model("lfm25-unsloth") ``` -## Key Features - -* **`load_in_4bit=True`**: Enable QLoRA to reduce memory by ~4x with minimal quality loss -* **`use_gradient_checkpointing="unsloth"`**: Optimized checkpointing that's 2x faster than default -* **`FastLanguageModel.for_inference()`**: Switch to optimized inference mode after training - -## Tips +LFM2.5 uses `out_proj`, `in_proj`, and `w1`/`w2`/`w3`, rather than Llama's `o_proj` and `gate_proj`/`up_proj`/`down_proj`. The regular expression selects those modules explicitly. The assertion catches changes that would silently leave some of them without adapters. -* **`max_seq_length`**: Set to your expected maximum sequence length; Unsloth pre-allocates memory for efficiency -* **Target modules**: Include MLP layers (`gate_proj`, `up_proj`, `down_proj`) for better quality on smaller models -* **Batch size**: Unsloth's optimizations allow larger batch sizes; experiment to maximize GPU utilization +Import Unsloth before Transformers or TRL. Keep the tested versions together: newer Transformers and TRL releases can exceed Unsloth's supported version range. ## Resources diff --git a/lfm/help/model-license.mdx b/lfm/help/model-license.mdx index 88ec4ee..42b0ffe 100644 --- a/lfm/help/model-license.mdx +++ b/lfm/help/model-license.mdx @@ -49,7 +49,7 @@ If your company's annual revenue is **$10 million USD or more**, commercial use -Any use for direct or indirect commercial advantage or monetary compensation. Internal research, testing, and evaluation are permitted without a commercial license. Using the models in your business can constitute commercial use, even if the models are not directly generating revenue. Contact [sales@liquid.ai](mailto:sales@liquid.ai) to discuss your use case and whether a commercial license is needed. +Any use for direct or indirect commercial advantage or monetary compensation. Internal research, testing, or evaluation is not a blanket exemption: assess whether the use provides direct or indirect commercial advantage under the license definition. Using the models in your business can constitute commercial use, even if the models are not directly generating revenue. Contact [sales@liquid.ai](mailto:sales@liquid.ai) to discuss your use case and whether a commercial license is needed. diff --git a/lfm/help/troubleshooting.mdx b/lfm/help/troubleshooting.mdx index 74520eb..4a2c1d7 100644 --- a/lfm/help/troubleshooting.mdx +++ b/lfm/help/troubleshooting.mdx @@ -19,12 +19,15 @@ Some checkpoints require `trust_remote_code=True` when loading the model, tokeni Try these solutions in order: 1. **Use a smaller model**: If [LFM3-1.7B](/lfm/models/lfm3-1.7b) exceeds your memory budget, evaluate [LFM2.5-350M](/lfm/models/lfm25-350m) or [LFM2.5-230M](/lfm/models/lfm25-230m) for a smaller footprint -2. **Enable quantization**: +2. **Enable quantization** on a compatible GPU with `bitsandbytes` installed. Use `quantization_config` with Transformers 5; review the selected checkpoint before enabling its custom code: ```python +from transformers import AutoModelForCausalLM, BitsAndBytesConfig + model = AutoModelForCausalLM.from_pretrained( model_id, - load_in_4bit=True, - device_map="auto" + quantization_config=BitsAndBytesConfig(load_in_4bit=True), + device_map="auto", + trust_remote_code=True, ) ``` 3. **Reduce batch size or sequence length** @@ -36,7 +39,7 @@ model.gradient_checkpointing_enable() - Check your internet connection -- Try using `huggingface-cli login` if the model requires authentication +- Try using `hf auth login` if the model requires authentication - Set a longer timeout: `HF_HUB_DOWNLOAD_TIMEOUT=600` - Try downloading with `snapshot_download`: ```python diff --git a/lfm/key-concepts/thinking.mdx b/lfm/key-concepts/thinking.mdx index 8810a3d..e9a61df 100644 --- a/lfm/key-concepts/thinking.mdx +++ b/lfm/key-concepts/thinking.mdx @@ -143,24 +143,32 @@ Install the OpenAI Python client (`uv pip install openai`) for the request examp - vLLM 0.33.0 does not support the LFM3 convolution layers. This example uses **LFM2.5-1.2B-Thinking**, which supports vLLM's reasoning parser. Use Transformers or a supported SGLang/llama.cpp build for LFM3. + Use **vLLM 0.34.0**, which includes native LFM3 support. Install the isolated environment in the [vLLM guide](/deployment/gpu-inference/vllm#installation), then launch: ```bash - vllm serve LiquidAI/LFM2.5-1.2B-Thinking --reasoning-parser qwen3 + vllm serve LiquidAI/LFM3-1.7B \ + --reasoning-parser qwen3 \ + --enable-auto-tool-choice --tool-call-parser qwen3_coder \ + --max-model-len 8192 ``` ```python from openai import OpenAI client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY") - response = client.chat.completions.create( - model="LiquidAI/LFM2.5-1.2B-Thinking", + model="LiquidAI/LFM3-1.7B", messages=[{"role": "user", "content": "What is 17 * 23 - 45?"}], temperature=0.1, - extra_body={"top_k": 50, "repetition_penalty": 1.05}, + max_tokens=4096, + extra_body={"top_k": 50, "repetition_penalty": 1.1}, ) + reasoning = getattr(response.choices[0].message, "reasoning", None) + print(reasoning) + print(response.choices[0].message.content) ``` + + Older thinking checkpoints use their own sampling and tool parsers. Follow the selected model's quickstart instead of reusing LFM3's tool parser. Use a build containing [LFM3 support](https://github.com/sgl-project/sglang/pull/46858), verified at commit `47361c57`. SGLang 0.5.23 does not run these LFM3 examples correctly. diff --git a/lfm/key-concepts/tool-use.mdx b/lfm/key-concepts/tool-use.mdx index a642834..bb657a5 100644 --- a/lfm/key-concepts/tool-use.mdx +++ b/lfm/key-concepts/tool-use.mdx @@ -118,8 +118,15 @@ def get_candidate_status(candidate_id: str): "date": "2023-11-20", }] +reasoning, separator, answer = response.partition("") +if not separator: + raise ValueError("The reasoning turn is incomplete; allow more output tokens.") +reasoning = reasoning.removeprefix("").strip() + messages.append({ "role": "assistant", + "content": "", + "reasoning": reasoning, "tool_calls": [{ "type": "function", "function": {"name": "get_candidate_status", "arguments": {"candidate_id": "12345"}}, diff --git a/lfm/models/complete-library.mdx b/lfm/models/complete-library.mdx index 856e0a7..c42582b 100644 --- a/lfm/models/complete-library.mdx +++ b/lfm/models/complete-library.mdx @@ -9,7 +9,7 @@ Start with **LFM3** for a new application: [LFM3-1.7B](/lfm/models/lfm3-1.7b) fo Across the library: -- Context length depends on the model: 32K tokens for most text, vision, audio, and omni models, 256K for LFM3-1.7B, 128K for LFM3-VL-2B, LFM2.5-8B-A1B, d1-2B, and d1-omni-2B, 131K for LFM2.5-24B-A2B, 8K for the LFM2.5 encoders, and 16K for d1-omni-600M. Each model page lists its exact limit. +- Context length depends on the model: 32K tokens for most text, vision, audio, and omni models, 256K for LFM3-1.7B, 128K for LFM3-VL-2B, the LFM2.5-VL Extract models, LFM2.5-8B-A1B, d1-2B, and d1-omni-2B, 131K for LFM2.5-24B-A2B, 8K for the LFM2.5 encoders, and 16K for d1-omni-600M. Each model page lists its exact limit. - Runtime support varies by checkpoint and modality. Start with the model page's supported [Transformers](/deployment/gpu-inference/transformers), [llama.cpp](/deployment/on-device/llama-cpp), [vLLM](/deployment/gpu-inference/vllm), [SGLang](/deployment/gpu-inference/sglang), [zml/llmd](/deployment/gpu-inference/zml-llmd), [MLX](/deployment/on-device/mlx), or app-based path. A downloadable format does not establish every runtime's support for it. - Training is also model-specific. Start with [TRL](/lfm/fine-tuning/trl) for LFM3 text LoRA; use [Liquid Finetune](/lfm/fine-tuning/liquid-finetune), [Unsloth](/lfm/fine-tuning/unsloth), or [Halo](/lfm/fine-tuning/halo) for their documented checkpoints and workflows. The **Trainable?** column below links the model's path. @@ -142,3 +142,5 @@ To compare speed and memory across quantizations and runtimes on real devices, s Looking for an older model? Deprecated models and their recommended replacements are listed on the [Deprecations](/lfm/help/deprecations) page. + +For continued pre-training, [LFM2.5-1.2B-Base](/lfm/models/lfm25-1.2b-base) provides the pre-trained checkpoint without instruction tuning. diff --git a/lfm/models/d1-omni-2b.mdx b/lfm/models/d1-omni-2b.mdx index da1dc51..db7a017 100644 --- a/lfm/models/d1-omni-2b.mdx +++ b/lfm/models/d1-omni-2b.mdx @@ -1,11 +1,11 @@ --- title: "d1-omni-2B" -description: "2.17B parameter decision model for text, pictures, and audio, built on LFM3-Omni-2B" +description: "2.17B parameter decision model for text, pictures, video, and audio, built on LFM3-Omni-2B" --- ← Back to Decision Models -d1-omni-2B is a 2.17B parameter decision model for text, pictures, and audio, built on [LFM3-Omni-2B](/lfm/models/lfm3-omni-2b). It returns calibrated answers in one forward pass, without generating tokens. Clips and spoken questions go through the same pass as text and pictures, so a voice request can be routed, checked, or answered just like a typed one. +d1-omni-2B is a 2.17B parameter decision model for text, pictures, video, and audio, built on [LFM3-Omni-2B](/lfm/models/lfm3-omni-2b). It returns calibrated answers in one forward pass, without generating tokens. Clips and spoken questions go through the same pass as text and pictures, so a voice request can be routed, checked, or answered just like a typed one.
HF @@ -102,6 +102,43 @@ d1-omni-2B is designed for decisions that depend on what is heard, such as call A spoken question takes a clip as its instructions: `{"type": "noul", "instructions": {"type": "audio", "path": "question.wav"}}`. + **Video input:** + + Pass decoded PIL frames and their sampling rate in `media`. The following samples one frame per second; `fps` describes the supplied frames, rather than the source video's original frame rate. + + ```bash + pip install opencv-python-headless + ``` + + ```python + import cv2 + from PIL import Image + + capture = cv2.VideoCapture("clip.mp4") + source_fps = capture.get(cv2.CAP_PROP_FPS) + if not capture.isOpened() or source_fps <= 0: + raise ValueError("Could not open clip.mp4 or determine its frame rate") + frames = [] + second = 0 + while True: + capture.set(cv2.CAP_PROP_POS_MSEC, second * 1000) + ok, frame = capture.read() + if not ok: + break + frames.append(Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))) + second += 1 + capture.release() + if not frames: + raise ValueError("The video contains no decodable frames") + + output = model.system_one(None, { + "outdoors": {"type": "noul", "instructions": "Does this video take place outdoors?"}, + }, media=[{"type": "video", "video": frames, "fps": 1}]) + print(output["answers"]["outdoors"]["noul"]) + ``` + + This example supplies video frames only. To include sound, also supply an audio clip using the audio input format above. The hosted [decisions API](/api/guides/decisions) has its own input contract and does not accept video. + **Image input:** ```python diff --git a/lfm/models/decision-models.mdx b/lfm/models/decision-models.mdx index 6bc35f8..9472844 100644 --- a/lfm/models/decision-models.mdx +++ b/lfm/models/decision-models.mdx @@ -55,13 +55,13 @@ Decision models are a new class of AI model purpose-built for structured decisio 2.2B Audio - Multimodal decision model (text + images or audio) with typed answers, built on LFM3-Omni-2B. + Multimodal decision model for text, images, video, and audio with typed answers, built on LFM3-Omni-2B. 587M Smallest - Multimodal decision model (text + images or audio) built on LFM2.5-Encoder-350M. + Multimodal decision model for text, images, video, and audio built on LFM2.5-Encoder-350M. diff --git a/lfm/models/lfm2-1.2b.mdx b/lfm/models/lfm2-1.2b.mdx index 2ae57c2..12314cf 100644 --- a/lfm/models/lfm2-1.2b.mdx +++ b/lfm/models/lfm2-1.2b.mdx @@ -3,10 +3,6 @@ title: "LFM2-1.2B" description: "1.2B parameter model (deprecated - use LFM2.5-1.2B-Instruct instead)" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -35,15 +31,118 @@ LFM2-1.2B was the original 1.2B parameter model in the LFM2 series. It has been - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2-1.2B","samplingParams":"do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2-1.2B" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-1.2B-GGUF","samplingFlags":"--temp 0.3 --min-p 0.15 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2-1.2B-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-1.2B-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2-1.2B","samplingParams":"temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2-1.2B", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2-1.2B","toolCallParser":"lfm2","samplingParams":"temperature=0.3,\n extra_body={\"min_p\": 0.15, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2-1.2B \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2-1.2B", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.3, + extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm2-2.6b-exp.mdx b/lfm/models/lfm2-2.6b-exp.mdx index f75b27a..a200fb9 100644 --- a/lfm/models/lfm2-2.6b-exp.mdx +++ b/lfm/models/lfm2-2.6b-exp.mdx @@ -3,10 +3,6 @@ title: "LFM2-2.6B-Exp" description: "RL-only post-trained 2.6B model with improved math and reasoning capabilities (deprecated - use LFM3-1.7B instead)" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -53,15 +49,118 @@ LFM2-2.6B-Exp is an experimental checkpoint of LFM2-2.6B post-trained with pure - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2-2.6B-Exp","samplingParams":"do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2-2.6B-Exp" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-2.6B-Exp-GGUF","samplingFlags":"--temp 0.3 --min-p 0.15 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2-2.6B-Exp-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-2.6B-Exp-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2-2.6B-Exp","samplingParams":"temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2-2.6B-Exp", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2-2.6B-Exp","toolCallParser":"lfm2","samplingParams":"temperature=0.3,\n extra_body={\"min_p\": 0.15, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2-2.6B-Exp \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2-2.6B-Exp", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.3, + extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm2-2.6b.mdx b/lfm/models/lfm2-2.6b.mdx index 24c8140..5aff295 100644 --- a/lfm/models/lfm2-2.6b.mdx +++ b/lfm/models/lfm2-2.6b.mdx @@ -3,10 +3,6 @@ title: "LFM2-2.6B" description: "Highly capable 2.6B parameter model for deployment on most phones and laptops (deprecated - use LFM3-1.7B instead)" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -53,15 +49,118 @@ LFM2-2.6B is a versatile mid-sized model delivering strong performance across ch - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2-2.6B","samplingParams":"do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2-2.6B" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-2.6B-GGUF","samplingFlags":"--temp 0.3 --min-p 0.15 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2-2.6B-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-2.6B-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2-2.6B","samplingParams":"temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2-2.6B", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2-2.6B","toolCallParser":"lfm2","samplingParams":"temperature=0.3,\n extra_body={\"min_p\": 0.15, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2-2.6B \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2-2.6B", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.3, + extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm2-24b-a2b.mdx b/lfm/models/lfm2-24b-a2b.mdx index 3ae865e..862f243 100644 --- a/lfm/models/lfm2-24b-a2b.mdx +++ b/lfm/models/lfm2-24b-a2b.mdx @@ -3,9 +3,6 @@ title: "LFM2-24B-A2B" description: "24B parameter Mixture-of-Experts model with 2B active parameters (deprecated - use LFM2.5-24B-A2B instead)" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -52,12 +49,86 @@ LFM2-24B-A2B was the largest model in the LFM2 series, a Mixture-of-Experts mode - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2-24B-A2B","samplingParams":"do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2-24B-A2B" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-24B-A2B-GGUF","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2-24B-A2B-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-24B-A2B-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2-24B-A2B","samplingParams":"temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2-24B-A2B", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.1, top_k=50, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm2-350m.mdx b/lfm/models/lfm2-350m.mdx index b220e23..6689140 100644 --- a/lfm/models/lfm2-350m.mdx +++ b/lfm/models/lfm2-350m.mdx @@ -3,10 +3,6 @@ title: "LFM2-350M" description: "Ultra-compact 350M parameter model (deprecated - use LFM2.5-350M instead)" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -53,15 +49,118 @@ LFM2-350M is the 350M parameter model in the LFM2 series, designed for edge devi - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2-350M","samplingParams":"do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2-350M" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-350M-GGUF","samplingFlags":"--temp 0.3 --min-p 0.15 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2-350M-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-350M-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2-350M","samplingParams":"temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2-350M", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2-350M","toolCallParser":"lfm2","samplingParams":"temperature=0.3,\n extra_body={\"min_p\": 0.15, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2-350M \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2-350M", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.3, + extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm2-700m.mdx b/lfm/models/lfm2-700m.mdx index e920598..0e0a409 100644 --- a/lfm/models/lfm2-700m.mdx +++ b/lfm/models/lfm2-700m.mdx @@ -3,10 +3,6 @@ title: "LFM2-700M" description: "Mid-sized 700M parameter model for deploying on most devices (deprecated - use LFM2.5-1.2B-Instruct instead)" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -53,15 +49,118 @@ LFM2-700M is a compact model balancing capability and efficiency. Suitable for d - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2-700M","samplingParams":"do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2-700M" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-700M-GGUF","samplingFlags":"--temp 0.3 --min-p 0.15 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2-700M-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-700M-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2-700M","samplingParams":"temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2-700M", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2-700M","toolCallParser":"lfm2","samplingParams":"temperature=0.3,\n extra_body={\"min_p\": 0.15, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2-700M \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2-700M", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.3, + extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm2-8b-a1b.mdx b/lfm/models/lfm2-8b-a1b.mdx index 935d4d1..692423f 100644 --- a/lfm/models/lfm2-8b-a1b.mdx +++ b/lfm/models/lfm2-8b-a1b.mdx @@ -3,10 +3,6 @@ title: "LFM2-8B-A1B" description: "8B parameter Mixture-of-Experts model with 1.5B active parameters (deprecated - use LFM2.5-8B-A1B instead)" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -53,15 +49,118 @@ LFM2-8B-A1B is Liquid AI's Mixture-of-Experts model, combining 8B total paramete - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2-8B-A1B","samplingParams":"do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2-8B-A1B" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-8B-A1B-GGUF","samplingFlags":"--temp 0.3 --min-p 0.15 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2-8B-A1B-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-8B-A1B-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2-8B-A1B","samplingParams":"temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2-8B-A1B", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2-8B-A1B","toolCallParser":"lfm2","samplingParams":"temperature=0.3,\n extra_body={\"min_p\": 0.15, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2-8B-A1B \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2-8B-A1B", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.3, + extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm2-vl-1.6b.mdx b/lfm/models/lfm2-vl-1.6b.mdx index 4a1ae13..92f499e 100644 --- a/lfm/models/lfm2-vl-1.6b.mdx +++ b/lfm/models/lfm2-vl-1.6b.mdx @@ -3,10 +3,6 @@ title: "LFM2-VL-1.6B" description: "1.6B vision-language model (deprecated - use LFM2.5-VL-1.6B instead)" --- -import { VlTransformers } from "/snippets/quickstart/vl-transformers.mdx"; -import { VlVllm } from "/snippets/quickstart/vl-vllm.mdx"; -import { VlSglang } from "/snippets/quickstart/vl-sglang.mdx"; -import { VlLlamacpp } from "/snippets/quickstart/vl-llamacpp.mdx"; ← Back to Vision Models @@ -37,15 +33,164 @@ LFM2-VL-1.6B was the original 1.6B vision-language model. It has been superseded - + {/* quickstart: {"source":"/snippets/quickstart/vl-transformers.mdx","component":"VlTransformers","props":{"modelId":"LiquidAI/LFM2-VL-1.6B"}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" pillow torch torchvision accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoProcessor, AutoModelForImageTextToText +from transformers.image_utils import load_image + +model_id = "LiquidAI/LFM2-VL-1.6B" +model = AutoModelForImageTextToText.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) + +processor = AutoProcessor.from_pretrained(model_id) + +url = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" +image = load_image(url) + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": "What is in this image?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + conversation, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + tokenize=True, +).to(model.device) + +outputs = model.generate(**inputs, do_sample=True, temperature=0.1, min_p=0.15, repetition_penalty=1.05, max_new_tokens=256) +input_length = inputs["input_ids"].shape[1] +response = processor.batch_decode(outputs[:, input_length:], skip_special_tokens=True)[0] +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-vllm.mdx","component":"VlVllm","props":{"modelId":"LiquidAI/LFM2-VL-1.6B"}} */} +**Install:** + +```bash +uv pip install "vllm==0.34.0" pillow +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +IMAGE_URL = "http://images.cocodataset.org/val2017/000000039769.jpg" + +llm = LLM( + model="LiquidAI/LFM2-VL-1.6B", + max_model_len=1024, + enforce_eager=True, +) + +sampling_params = SamplingParams( + temperature=0.1, min_p=0.15, repetition_penalty=1.05, + max_tokens=256, +) + +messages = [{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": IMAGE_URL}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], +}] + +outputs = llm.chat(messages, sampling_params) +print(outputs[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-sglang.mdx","component":"VlSglang","props":{"modelId":"LiquidAI/LFM2-VL-1.6B"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2-VL-1.6B \ + --host 0.0.0.0 \ + --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2-VL-1.6B", + messages=[{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": "http://images.cocodataset.org/val2017/000000039769.jpg"}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], + }], + temperature=0.1, extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, + max_tokens=256, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-llamacpp.mdx","component":"VlLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-VL-1.6B-GGUF","samplingFlags":"--temp 0.1 --min-p 0.15 --repeat-penalty 1.05"}} */} +llama.cpp enables efficient CPU inference for vision models. + +**Install:** + +```bash +brew install llama.cpp +``` + +Or download pre-built binaries from [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases). + +**Run:** + +```bash +llama cli \ + -hf LiquidAI/LFM2-VL-1.6B-GGUF:Q4_0 \ + --image test_image.jpg \ + -p "What's in this image?" \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-VL-1.6B-GGUF:Q4_0 \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model and its vision projector directly from Hugging Face. Use `--image-max-tokens` to control image token budget. + +For advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp#vision-models). +{/* /quickstart */} diff --git a/lfm/models/lfm2-vl-3b.mdx b/lfm/models/lfm2-vl-3b.mdx index b95a8a1..b9ec5a0 100644 --- a/lfm/models/lfm2-vl-3b.mdx +++ b/lfm/models/lfm2-vl-3b.mdx @@ -3,10 +3,6 @@ title: "LFM2-VL-3B" description: "3B vision-language model (deprecated - use LFM2.5-VL-3B instead)" --- -import { VlTransformers } from "/snippets/quickstart/vl-transformers.mdx"; -import { VlVllm } from "/snippets/quickstart/vl-vllm.mdx"; -import { VlSglang } from "/snippets/quickstart/vl-sglang.mdx"; -import { VlLlamacpp } from "/snippets/quickstart/vl-llamacpp.mdx"; ← Back to Vision Models @@ -55,15 +51,164 @@ LFM2-VL-3B was the largest model in the LFM2-VL series, built on the LFM2-2.6B l - + {/* quickstart: {"source":"/snippets/quickstart/vl-transformers.mdx","component":"VlTransformers","props":{"modelId":"LiquidAI/LFM2-VL-3B"}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" pillow torch torchvision accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoProcessor, AutoModelForImageTextToText +from transformers.image_utils import load_image + +model_id = "LiquidAI/LFM2-VL-3B" +model = AutoModelForImageTextToText.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) + +processor = AutoProcessor.from_pretrained(model_id) + +url = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" +image = load_image(url) + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": "What is in this image?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + conversation, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + tokenize=True, +).to(model.device) + +outputs = model.generate(**inputs, do_sample=True, temperature=0.1, min_p=0.15, repetition_penalty=1.05, max_new_tokens=256) +input_length = inputs["input_ids"].shape[1] +response = processor.batch_decode(outputs[:, input_length:], skip_special_tokens=True)[0] +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-vllm.mdx","component":"VlVllm","props":{"modelId":"LiquidAI/LFM2-VL-3B"}} */} +**Install:** + +```bash +uv pip install "vllm==0.34.0" pillow +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +IMAGE_URL = "http://images.cocodataset.org/val2017/000000039769.jpg" + +llm = LLM( + model="LiquidAI/LFM2-VL-3B", + max_model_len=1024, + enforce_eager=True, +) + +sampling_params = SamplingParams( + temperature=0.1, min_p=0.15, repetition_penalty=1.05, + max_tokens=256, +) + +messages = [{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": IMAGE_URL}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], +}] + +outputs = llm.chat(messages, sampling_params) +print(outputs[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-sglang.mdx","component":"VlSglang","props":{"modelId":"LiquidAI/LFM2-VL-3B"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2-VL-3B \ + --host 0.0.0.0 \ + --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2-VL-3B", + messages=[{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": "http://images.cocodataset.org/val2017/000000039769.jpg"}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], + }], + temperature=0.1, extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, + max_tokens=256, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-llamacpp.mdx","component":"VlLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-VL-3B-GGUF","samplingFlags":"--temp 0.1 --min-p 0.15 --repeat-penalty 1.05"}} */} +llama.cpp enables efficient CPU inference for vision models. + +**Install:** + +```bash +brew install llama.cpp +``` + +Or download pre-built binaries from [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases). + +**Run:** + +```bash +llama cli \ + -hf LiquidAI/LFM2-VL-3B-GGUF:Q4_0 \ + --image test_image.jpg \ + -p "What's in this image?" \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-VL-3B-GGUF:Q4_0 \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model and its vision projector directly from Hugging Face. Use `--image-max-tokens` to control image token budget. + +For advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp#vision-models). +{/* /quickstart */} diff --git a/lfm/models/lfm2-vl-450m.mdx b/lfm/models/lfm2-vl-450m.mdx index 1999cc4..b802a32 100644 --- a/lfm/models/lfm2-vl-450m.mdx +++ b/lfm/models/lfm2-vl-450m.mdx @@ -3,10 +3,6 @@ title: "LFM2-VL-450M" description: "Compact 450M vision-language model (deprecated - use LFM2.5-VL-450M instead)" --- -import { VlTransformers } from "/snippets/quickstart/vl-transformers.mdx"; -import { VlVllm } from "/snippets/quickstart/vl-vllm.mdx"; -import { VlSglang } from "/snippets/quickstart/vl-sglang.mdx"; -import { VlLlamacpp } from "/snippets/quickstart/vl-llamacpp.mdx"; ← Back to Vision Models @@ -55,15 +51,164 @@ LFM2-VL-450M was the smallest model in the LFM2-VL series, designed for edge dep - + {/* quickstart: {"source":"/snippets/quickstart/vl-transformers.mdx","component":"VlTransformers","props":{"modelId":"LiquidAI/LFM2-VL-450M"}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" pillow torch torchvision accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoProcessor, AutoModelForImageTextToText +from transformers.image_utils import load_image + +model_id = "LiquidAI/LFM2-VL-450M" +model = AutoModelForImageTextToText.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) + +processor = AutoProcessor.from_pretrained(model_id) + +url = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" +image = load_image(url) + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": "What is in this image?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + conversation, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + tokenize=True, +).to(model.device) + +outputs = model.generate(**inputs, do_sample=True, temperature=0.1, min_p=0.15, repetition_penalty=1.05, max_new_tokens=256) +input_length = inputs["input_ids"].shape[1] +response = processor.batch_decode(outputs[:, input_length:], skip_special_tokens=True)[0] +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-vllm.mdx","component":"VlVllm","props":{"modelId":"LiquidAI/LFM2-VL-450M"}} */} +**Install:** + +```bash +uv pip install "vllm==0.34.0" pillow +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +IMAGE_URL = "http://images.cocodataset.org/val2017/000000039769.jpg" + +llm = LLM( + model="LiquidAI/LFM2-VL-450M", + max_model_len=1024, + enforce_eager=True, +) + +sampling_params = SamplingParams( + temperature=0.1, min_p=0.15, repetition_penalty=1.05, + max_tokens=256, +) + +messages = [{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": IMAGE_URL}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], +}] + +outputs = llm.chat(messages, sampling_params) +print(outputs[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-sglang.mdx","component":"VlSglang","props":{"modelId":"LiquidAI/LFM2-VL-450M"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2-VL-450M \ + --host 0.0.0.0 \ + --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2-VL-450M", + messages=[{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": "http://images.cocodataset.org/val2017/000000039769.jpg"}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], + }], + temperature=0.1, extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, + max_tokens=256, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-llamacpp.mdx","component":"VlLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2-VL-450M-GGUF","samplingFlags":"--temp 0.1 --min-p 0.15 --repeat-penalty 1.05"}} */} +llama.cpp enables efficient CPU inference for vision models. + +**Install:** + +```bash +brew install llama.cpp +``` + +Or download pre-built binaries from [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases). + +**Run:** + +```bash +llama cli \ + -hf LiquidAI/LFM2-VL-450M-GGUF:Q4_0 \ + --image test_image.jpg \ + -p "What's in this image?" \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2-VL-450M-GGUF:Q4_0 \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model and its vision projector directly from Hugging Face. Use `--image-max-tokens` to control image token budget. + +For advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp#vision-models). +{/* /quickstart */} diff --git a/lfm/models/lfm25-1.2b-base.mdx b/lfm/models/lfm25-1.2b-base.mdx new file mode 100644 index 0000000..ff49283 --- /dev/null +++ b/lfm/models/lfm25-1.2b-base.mdx @@ -0,0 +1,33 @@ +--- +title: "LFM2.5-1.2B-Base" +description: "Pre-trained LFM2.5 checkpoint for continued pre-training and custom post-training." +--- + +LFM2.5-1.2B-Base is the pre-trained checkpoint behind the LFM2.5-1.2B variants. It is useful for continued pre-training on your own domain or language data. It has **not** been instruction-tuned: use raw text prompts rather than a chat template. + +For a ready-to-use text and tool-calling model, start with [LFM3-1.7B](/lfm/models/lfm3-1.7b). The older base checkpoint remains available for workflows that need to train their own assistant. + +## Download + +Get the original weights from [LiquidAI/LFM2.5-1.2B-Base](https://huggingface.co/LiquidAI/LFM2.5-1.2B-Base). The Instruct model's GGUF and ONNX repositories contain instruction-tuned weights; they are not conversions of this base checkpoint. + +## Text completion + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2.5-1.2B-Base" +tokenizer = AutoTokenizer.from_pretrained(model_id) +model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", dtype="auto") +inputs = tokenizer("The capital of France is", return_tensors="pt").to(model.device) +output = model.generate(**inputs, max_new_tokens=32, do_sample=False) +print(tokenizer.decode(output[0], skip_special_tokens=True)) +``` + +## Continued pre-training + +The [Unsloth notebooks](/lfm/fine-tuning/unsloth#notebooks) include text-completion and translation recipes for LFM2.5. Review the [LFM Open License](/lfm/help/model-license) before training or deploying a derivative. diff --git a/lfm/models/lfm25-1.2b-instruct.mdx b/lfm/models/lfm25-1.2b-instruct.mdx index 1711dd6..55304e1 100644 --- a/lfm/models/lfm25-1.2b-instruct.mdx +++ b/lfm/models/lfm25-1.2b-instruct.mdx @@ -3,12 +3,6 @@ title: "LFM2.5-1.2B-Instruct" description: "Instruction-tuned 1.2B parameter model optimized for chat and general-purpose tasks" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; -import { DsparkSglang } from "/snippets/quickstart/dspark-sglang.mdx"; -import { DsparkLlamacpp } from "/snippets/quickstart/dspark-llamacpp.mdx"; ← Back to Text Models @@ -52,16 +46,119 @@ LFM2.5-1.2B-Instruct is Liquid AI's general-purpose instruction-tuned model for - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2.5-1.2B-Instruct","samplingParams":"do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2.5-1.2B-Instruct" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-1.2B-Instruct-GGUF","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2.5-1.2B-Instruct-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-1.2B-Instruct-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2.5-1.2B-Instruct","samplingParams":"temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2.5-1.2B-Instruct", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.1, top_k=50, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2.5-1.2B-Instruct","toolCallParser":"lfm2","samplingParams":"temperature=0.1,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-1.2B-Instruct \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-1.2B-Instruct", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.1, + extra_body={"top_k": 50, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} @@ -69,9 +166,79 @@ LFM2.5-1.2B-Instruct is Liquid AI's general-purpose instruction-tuned model for - + {/* quickstart: {"source":"/snippets/quickstart/dspark-sglang.mdx","component":"DsparkSglang","props":{"modelId":"LiquidAI/LFM2.5-1.2B-Instruct","draftModelId":"LiquidAI/LFM2.5-1.2B-Instruct-DSpark","samplingParams":"temperature=0.1,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.05},"}} */} +**Install:** + +Requires a build of SGLang with DSpark support for LFM2 and LFM2-MoE targets ([PR #31041](https://github.com/sgl-project/sglang/pull/31041)). + +**Launch server with the drafter attached:** + +```bash +python -m sglang.launch_server \ + --model-path LiquidAI/LFM2.5-1.2B-Instruct \ + --speculative-algorithm DSPARK \ + --speculative-draft-model-path LiquidAI/LFM2.5-1.2B-Instruct-DSpark \ + --speculative-draft-attention-backend flashinfer \ + --disable-radix-cache --mem-fraction-static 0.75 --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-1.2B-Instruct", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.1, + extra_body={"top_k": 50, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` + +**Flags:** + +- `--speculative-algorithm DSPARK`: turns on DSpark speculative decoding. +- `--speculative-draft-model-path`: the drafter repo on Hugging Face, or a local path. +- `--speculative-draft-attention-backend flashinfer`: the attention backend the drafter runs on. +- Block size: read from the drafter's `config.json`, so you don't need to set it. +- `--disable-radix-cache`: turns off SGLang's prefix cache, as in the drafter's model card. +- `--mem-fraction-static`: the share of GPU memory SGLang reserves for weights and the KV cache. +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/dspark-llamacpp.mdx","component":"DsparkLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-1.2B-Instruct-GGUF","draftRepo":"LiquidAI/LFM2.5-1.2B-Instruct-DSpark-GGUF","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +DSpark needs a recent build. Check that `llama serve --help` lists `draft-dspark` under `--spec-type`. + +**Run the target with the draft sidecar:** + +```bash +llama serve \ + -hf LiquidAI/LFM2.5-1.2B-Instruct-GGUF:F16 \ + -hfd LiquidAI/LFM2.5-1.2B-Instruct-DSpark-GGUF:F16 \ + --spec-type draft-dspark --spec-draft-n-max 10 --spec-draft-n-min 0 \ + -ngl 99 -ngld 99 -fa on \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +**Flags:** + +- `-hf`: the target GGUF on Hugging Face, with its quantization tag. Use `-m` for a local file. +- `-hfd`: the draft sidecar GGUF. Use `-md` for a local file. The sidecar has no embeddings or LM head, so it cannot run on its own. +- `--spec-type draft-dspark`: turns on DSpark speculative decoding. +- `--spec-draft-n-max`: the most tokens the drafter proposes per step. llama.cpp clamps it to the drafter's block size. +- `--spec-draft-n-min`: the fewest tokens the drafter proposes per step. +- `-ngl 99` / `-ngld 99`: offload all target and drafter layers to the GPU. +- `-fa on`: turns on flash attention. +{/* /quickstart */} diff --git a/lfm/models/lfm25-1.2b-jp-202606.mdx b/lfm/models/lfm25-1.2b-jp-202606.mdx index 8b87437..4c89801 100644 --- a/lfm/models/lfm25-1.2b-jp-202606.mdx +++ b/lfm/models/lfm25-1.2b-jp-202606.mdx @@ -3,10 +3,6 @@ title: "LFM2.5-1.2B-JP-202606" description: "1.2B parameter Japanese chat model for Japanese and English assistants, tool use, and structured outputs" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -51,15 +47,118 @@ LFM2.5-1.2B-JP-202606 is Liquid AI's general-purpose Japanese chat model. It imp - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2.5-1.2B-JP-202606","samplingParams":"do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2.5-1.2B-JP-202606" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-1.2B-JP-202606-GGUF","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2.5-1.2B-JP-202606-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-1.2B-JP-202606-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2.5-1.2B-JP-202606","samplingParams":"temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2.5-1.2B-JP-202606", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.1, top_k=50, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2.5-1.2B-JP-202606","toolCallParser":"lfm2","samplingParams":"temperature=0.1,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-1.2B-JP-202606 \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-1.2B-JP-202606", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.1, + extra_body={"top_k": 50, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm25-1.2b-jp.mdx b/lfm/models/lfm25-1.2b-jp.mdx index 29e69fa..d464b53 100644 --- a/lfm/models/lfm25-1.2b-jp.mdx +++ b/lfm/models/lfm25-1.2b-jp.mdx @@ -3,10 +3,6 @@ title: "LFM2.5-1.2B-JP" description: "Japanese-specialized 1.2B parameter chat model (deprecated - use LFM2.5-1.2B-JP-202606 instead)" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -53,15 +49,117 @@ LFM2.5-1.2B-JP is a chat model optimized for Japanese, built on LFM2.5. It has b - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2.5-1.2B-JP","samplingParams":"do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2.5-1.2B-JP" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-1.2B-JP-GGUF","samplingFlags":"--temp 0.3 --min-p 0.15 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2.5-1.2B-JP-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-1.2B-JP-GGUF \ + --temp 0.3 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2.5-1.2B-JP","samplingParams":"temperature=0.3, min_p=0.15, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2.5-1.2B-JP", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.3, min_p=0.15, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2.5-1.2B-JP","samplingParams":"temperature=0.3,\n extra_body={\"min_p\": 0.15, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-1.2B-JP \ + --host 0.0.0.0 \ + --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-1.2B-JP", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.3, + extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm25-1.2b-thinking.mdx b/lfm/models/lfm25-1.2b-thinking.mdx index 7071d32..f1db683 100644 --- a/lfm/models/lfm25-1.2b-thinking.mdx +++ b/lfm/models/lfm25-1.2b-thinking.mdx @@ -3,10 +3,6 @@ title: "LFM2.5-1.2B-Thinking" description: "Reasoning-focused 1.2B parameter model with enhanced math and logical problem-solving" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -49,16 +45,120 @@ LFM2.5-1.2B-Thinking is optimized for reasoning tasks, delivering strong perform - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"maxTokens":8192,"modelId":"LiquidAI/LFM2.5-1.2B-Thinking","samplingParams":"do_sample=True, temperature=0.05, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2.5-1.2B-Thinking" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.05, top_k=50, repetition_penalty=1.05, max_new_tokens=8192) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-1.2B-Thinking-GGUF","samplingFlags":"--temp 0.05 --top-k 50 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2.5-1.2B-Thinking-GGUF \ + --temp 0.05 --top-k 50 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-1.2B-Thinking-GGUF \ + --temp 0.05 --top-k 50 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2.5-1.2B-Thinking","samplingParams":"temperature=0.05, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2.5-1.2B-Thinking", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.05, top_k=50, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2.5-1.2B-Thinking","reasoningParser":"qwen3-thinking","toolCallParser":"lfm2","samplingParams":"temperature=0.05,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-1.2B-Thinking \ + --host 0.0.0.0 \ + --port 30000 \ + --reasoning-parser qwen3-thinking \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-1.2B-Thinking", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.05, + extra_body={"top_k": 50, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm25-2.6b.mdx b/lfm/models/lfm25-2.6b.mdx index e79f554..69b1211 100644 --- a/lfm/models/lfm25-2.6b.mdx +++ b/lfm/models/lfm25-2.6b.mdx @@ -3,12 +3,6 @@ title: "LFM2.5-2.6B" description: "2.6B dense reasoning model trained for agentic workloads, with a 131K context window and native tool calling for on-device agents (deprecated - use LFM3-1.7B instead)" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; -import { DsparkSglang } from "/snippets/quickstart/dspark-sglang.mdx"; -import { DsparkLlamacpp } from "/snippets/quickstart/dspark-llamacpp.mdx"; ← Back to Text Models @@ -56,16 +50,120 @@ LFM2.5-2.6B is Liquid AI's 2.6B dense model built for agentic workloads with a 1 - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2.5-2.6B","samplingParams":"do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.1, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2.5-2.6B" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.1, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-2.6B-GGUF","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.1"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2.5-2.6B-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.1 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-2.6B-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.1 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2.5-2.6B","samplingParams":"temperature=0.1, top_k=50, repetition_penalty=1.1, ","maxTokens":"8192"}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2.5-2.6B", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.1, top_k=50, repetition_penalty=1.1, max_tokens=8192) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2.5-2.6B","reasoningParser":"qwen3-thinking","toolCallParser":"lfm2","samplingParams":"temperature=0.1,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.1},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-2.6B \ + --host 0.0.0.0 \ + --port 30000 \ + --reasoning-parser qwen3-thinking \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-2.6B", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.1, + extra_body={"top_k": 50, "repetition_penalty": 1.1}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} @@ -77,9 +175,79 @@ LFM2.5-2.6B always thinks before it answers. The chat template opens every assis - + {/* quickstart: {"source":"/snippets/quickstart/dspark-sglang.mdx","component":"DsparkSglang","props":{"modelId":"LiquidAI/LFM2.5-2.6B","draftModelId":"LiquidAI/LFM2.5-2.6B-DSpark","samplingParams":"temperature=0.1,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.1},"}} */} +**Install:** + +Requires a build of SGLang with DSpark support for LFM2 and LFM2-MoE targets ([PR #31041](https://github.com/sgl-project/sglang/pull/31041)). + +**Launch server with the drafter attached:** + +```bash +python -m sglang.launch_server \ + --model-path LiquidAI/LFM2.5-2.6B \ + --speculative-algorithm DSPARK \ + --speculative-draft-model-path LiquidAI/LFM2.5-2.6B-DSpark \ + --speculative-draft-attention-backend flashinfer \ + --disable-radix-cache --mem-fraction-static 0.75 --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-2.6B", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.1, + extra_body={"top_k": 50, "repetition_penalty": 1.1}, +) + +print(response.choices[0].message.content) +``` + +**Flags:** + +- `--speculative-algorithm DSPARK`: turns on DSpark speculative decoding. +- `--speculative-draft-model-path`: the drafter repo on Hugging Face, or a local path. +- `--speculative-draft-attention-backend flashinfer`: the attention backend the drafter runs on. +- Block size: read from the drafter's `config.json`, so you don't need to set it. +- `--disable-radix-cache`: turns off SGLang's prefix cache, as in the drafter's model card. +- `--mem-fraction-static`: the share of GPU memory SGLang reserves for weights and the KV cache. +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/dspark-llamacpp.mdx","component":"DsparkLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-2.6B-GGUF","draftRepo":"LiquidAI/LFM2.5-2.6B-DSpark-GGUF","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.1"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +DSpark needs a recent build. Check that `llama serve --help` lists `draft-dspark` under `--spec-type`. + +**Run the target with the draft sidecar:** + +```bash +llama serve \ + -hf LiquidAI/LFM2.5-2.6B-GGUF:F16 \ + -hfd LiquidAI/LFM2.5-2.6B-DSpark-GGUF:F16 \ + --spec-type draft-dspark --spec-draft-n-max 10 --spec-draft-n-min 0 \ + -ngl 99 -ngld 99 -fa on \ + --temp 0.1 --top-k 50 --repeat-penalty 1.1 +``` + +**Flags:** + +- `-hf`: the target GGUF on Hugging Face, with its quantization tag. Use `-m` for a local file. +- `-hfd`: the draft sidecar GGUF. Use `-md` for a local file. The sidecar has no embeddings or LM head, so it cannot run on its own. +- `--spec-type draft-dspark`: turns on DSpark speculative decoding. +- `--spec-draft-n-max`: the most tokens the drafter proposes per step. llama.cpp clamps it to the drafter's block size. +- `--spec-draft-n-min`: the fewest tokens the drafter proposes per step. +- `-ngl 99` / `-ngld 99`: offload all target and drafter layers to the GPU. +- `-fa on`: turns on flash attention. +{/* /quickstart */} diff --git a/lfm/models/lfm25-230m.mdx b/lfm/models/lfm25-230m.mdx index e15b0ab..6a9fce4 100644 --- a/lfm/models/lfm25-230m.mdx +++ b/lfm/models/lfm25-230m.mdx @@ -3,14 +3,10 @@ title: "LFM2.5-230M" description: "Ultra-compact 230M parameter model for data extraction and lightweight on-device agentic tasks" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models -LFM2.5-230M is Liquid AI's smallest LFM2.5 text model, designed for edge devices with the tightest memory and compute budgets. Built on the LFM2.5 architecture, it is tuned for data extraction and lightweight on-device agentic tasks such as tool calling. It is not recommended for reasoning-heavy workloads like advanced math, code generation, or creative writing — use [LFM2.5-350M](/lfm/models/lfm25-350m) or a larger model for those. +LFM2.5-230M is Liquid AI's smallest LFM2.5 text model, designed for edge devices with the tightest memory and compute budgets. Built on the LFM2.5 architecture, it is tuned for data extraction and lightweight on-device agentic tasks such as tool calling. It is not recommended for reasoning-heavy workloads like advanced math, code generation, or creative writing — start with [LFM3-1.7B](/lfm/models/lfm3-1.7b) and evaluate it on those tasks. LFM2.5-350M is another compact option for extraction and agents, not a programming-model recommendation.
HF @@ -49,15 +45,118 @@ LFM2.5-230M is Liquid AI's smallest LFM2.5 text model, designed for edge devices - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2.5-230M","samplingParams":"do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2.5-230M" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-230M-GGUF","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2.5-230M-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-230M-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2.5-230M","samplingParams":"temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2.5-230M", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.1, top_k=50, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2.5-230M","toolCallParser":"lfm2","samplingParams":"temperature=0.1,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-230M \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-230M", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.1, + extra_body={"top_k": 50, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm25-24b-a2b.mdx b/lfm/models/lfm25-24b-a2b.mdx index 2012324..3cc5f81 100644 --- a/lfm/models/lfm25-24b-a2b.mdx +++ b/lfm/models/lfm25-24b-a2b.mdx @@ -3,11 +3,6 @@ title: "LFM2.5-24B-A2B" description: "24B parameter Mixture-of-Experts reasoning model with 2B active parameters and 131K context, built for fast, private agents on-device" --- -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { DsparkSglang } from "/snippets/quickstart/dspark-sglang.mdx"; -import { DsparkLlamacpp } from "/snippets/quickstart/dspark-llamacpp.mdx"; ← Back to Text Models @@ -98,7 +93,29 @@ LFM2.5-24B-A2B is the largest LFM2.5 model, a Mixture-of-Experts model combining ``` - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-24B-A2B-GGUF","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2.5-24B-A2B-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-24B-A2B-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} **Install** (requires `mlx-lm>=0.32.0`, earlier versions route the experts incorrectly): @@ -136,10 +153,59 @@ LFM2.5-24B-A2B is the largest LFM2.5 model, a Mixture-of-Experts model combining 5-bit, 6-bit, and 8-bit builds are also available: [MLX-5bit](https://huggingface.co/LiquidAI/LFM2.5-24B-A2B-MLX-5bit), [MLX-6bit](https://huggingface.co/LiquidAI/LFM2.5-24B-A2B-MLX-6bit), [MLX-8bit](https://huggingface.co/LiquidAI/LFM2.5-24B-A2B-MLX-8bit). - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2.5-24B-A2B","samplingParams":"temperature=0.1, top_k=50, repetition_penalty=1.05, ","maxTokens":"4096"}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2.5-24B-A2B", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.1, top_k=50, repetition_penalty=1.05, max_tokens=4096) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2.5-24B-A2B","reasoningParser":"qwen3-thinking","toolCallParser":"lfm2","samplingParams":"temperature=0.1,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-24B-A2B \ + --host 0.0.0.0 \ + --port 30000 \ + --reasoning-parser qwen3-thinking \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-24B-A2B", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.1, + extra_body={"top_k": 50, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} @@ -149,10 +215,82 @@ LFM2.5-24B-A2B is the largest LFM2.5 model, a Mixture-of-Experts model combining - + {/* quickstart: {"source":"/snippets/quickstart/dspark-sglang.mdx","component":"DsparkSglang","props":{"modelId":"LiquidAI/LFM2.5-24B-A2B-FP8","draftModelId":"LiquidAI/LFM2.5-24B-A2B-DSpark","blockSize":9,"radixCache":true,"memFraction":"0.8","nativeHfConfig":true,"samplingParams":"temperature=0.1,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.05},"}} */} +**Install:** + +Requires a build of SGLang with DSpark support for LFM2 and LFM2-MoE targets ([PR #31041](https://github.com/sgl-project/sglang/pull/31041)) and native Hugging Face configuration support ([PR #43939](https://github.com/sgl-project/sglang/pull/43939)). + +**Launch server with the drafter attached:** + +```bash +python -m sglang.launch_server \ + --model-path LiquidAI/LFM2.5-24B-A2B-FP8 \ + --speculative-algorithm DSPARK \ + --speculative-draft-model-path LiquidAI/LFM2.5-24B-A2B-DSpark \ + --speculative-draft-attention-backend flashinfer \ + --speculative-dspark-block-size 9 \ + --speculative-num-draft-tokens 10 \ + --mem-fraction-static 0.8 --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-24B-A2B-FP8", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.1, + extra_body={"top_k": 50, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` + +**Flags:** + +- `--speculative-algorithm DSPARK`: turns on DSpark speculative decoding. +- `--speculative-draft-model-path`: the drafter repo on Hugging Face, or a local path. +- `--speculative-draft-attention-backend flashinfer`: the attention backend the drafter runs on. +- `--speculative-dspark-block-size`: how many tokens the drafter proposes per step. Use 9, the block size the drafter was trained with. +- `--speculative-num-draft-tokens`: the tokens the target verifies per step, which is the drafted block plus one bonus token from the target. +- `--mem-fraction-static`: the share of GPU memory SGLang reserves for weights and the KV cache. +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/dspark-llamacpp.mdx","component":"DsparkLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-24B-A2B-GGUF","draftRepo":"LiquidAI/LFM2.5-24B-A2B-DSpark-GGUF","draftNMax":"9","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +DSpark needs a recent build. Check that `llama serve --help` lists `draft-dspark` under `--spec-type`. + +**Run the target with the draft sidecar:** + +```bash +llama serve \ + -hf LiquidAI/LFM2.5-24B-A2B-GGUF:F16 \ + -hfd LiquidAI/LFM2.5-24B-A2B-DSpark-GGUF:F16 \ + --spec-type draft-dspark --spec-draft-n-max 9 --spec-draft-n-min 0 \ + -ngl 99 -ngld 99 -fa on \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +**Flags:** + +- `-hf`: the target GGUF on Hugging Face, with its quantization tag. Use `-m` for a local file. +- `-hfd`: the draft sidecar GGUF. Use `-md` for a local file. The sidecar has no embeddings or LM head, so it cannot run on its own. +- `--spec-type draft-dspark`: turns on DSpark speculative decoding. +- `--spec-draft-n-max`: the most tokens the drafter proposes per step. llama.cpp clamps it to the drafter's block size. +- `--spec-draft-n-min`: the fewest tokens the drafter proposes per step. +- `-ngl 99` / `-ngld 99`: offload all target and drafter layers to the GPU. +- `-fa on`: turns on flash attention. +{/* /quickstart */} diff --git a/lfm/models/lfm25-350m.mdx b/lfm/models/lfm25-350m.mdx index 84afdbc..de0e3a8 100644 --- a/lfm/models/lfm25-350m.mdx +++ b/lfm/models/lfm25-350m.mdx @@ -3,10 +3,6 @@ title: "LFM2.5-350M" description: "Ultra-compact 350M parameter model for edge devices and low latency deployments" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -49,15 +45,118 @@ LFM2.5-350M is a compact LFM2.5 text model designed for edge devices with strict - + {/* quickstart: {"source":"/snippets/quickstart/text-transformers.mdx","component":"TextTransformers","props":{"modelId":"LiquidAI/LFM2.5-350M","samplingParams":"do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" torch accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoModelForCausalLM, AutoTokenizer + +model_id = "LiquidAI/LFM2.5-350M" +model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) +tokenizer = AutoTokenizer.from_pretrained(model_id) + +inputs = tokenizer.apply_chat_template( + [{"role": "user", "content": "What is machine learning?"}], + add_generation_prompt=True, + return_tensors="pt", + tokenize=True, + return_dict=True, +).to(model.device) + +output = model.generate(**inputs, do_sample=True, temperature=0.1, top_k=50, repetition_penalty=1.05, max_new_tokens=512) +input_length = inputs["input_ids"].shape[1] +response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-350M-GGUF","samplingFlags":"--temp 0.1 --top-k 50 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2.5-350M-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-350M-GGUF \ + --temp 0.1 --top-k 50 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2.5-350M","samplingParams":"temperature=0.1, top_k=50, repetition_penalty=1.05, "}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2.5-350M", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.1, top_k=50, repetition_penalty=1.05, max_tokens=512) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2.5-350M","toolCallParser":"lfm2","samplingParams":"temperature=0.1,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-350M \ + --host 0.0.0.0 \ + --port 30000 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-350M", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.1, + extra_body={"top_k": 50, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} diff --git a/lfm/models/lfm25-8b-a1b.mdx b/lfm/models/lfm25-8b-a1b.mdx index d0c7167..7256379 100644 --- a/lfm/models/lfm25-8b-a1b.mdx +++ b/lfm/models/lfm25-8b-a1b.mdx @@ -3,12 +3,6 @@ title: "LFM2.5-8B-A1B" description: "8B parameter Mixture-of-Experts model with 1.5B active parameters for fast, reliable tool calling and 128K context" --- -import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx"; -import { TextVllm } from "/snippets/quickstart/text-vllm.mdx"; -import { TextSglang } from "/snippets/quickstart/text-sglang.mdx"; -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; -import { DsparkSglang } from "/snippets/quickstart/dspark-sglang.mdx"; -import { DsparkLlamacpp } from "/snippets/quickstart/dspark-llamacpp.mdx"; ← Back to Text Models @@ -94,13 +88,84 @@ LFM2.5-8B-A1B is Liquid AI's Mixture-of-Experts reasoning model, combining 8B to ``` - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-8B-A1B-GGUF","samplingFlags":"--temp 0.2 --top-k 80 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM2.5-8B-A1B-GGUF \ + --temp 0.2 --top-k 80 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-8B-A1B-GGUF \ + --temp 0.2 --top-k 80 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-vllm.mdx","component":"TextVllm","props":{"modelId":"LiquidAI/LFM2.5-8B-A1B","samplingParams":"temperature=0.2, top_k=80, repetition_penalty=1.05, ","maxTokens":"8192"}} */} +**Install:** + +```bash +uv pip install vllm==0.34.0 +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +llm = LLM(model="LiquidAI/LFM2.5-8B-A1B", enforce_eager=True) + +sampling_params = SamplingParams(temperature=0.2, top_k=80, repetition_penalty=1.05, max_tokens=8192) + +output = llm.chat([{"role": "user", "content": "What is machine learning?"}], sampling_params) +print(output[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/text-sglang.mdx","component":"TextSglang","props":{"modelId":"LiquidAI/LFM2.5-8B-A1B","reasoningParser":"qwen3","toolCallParser":"lfm2","samplingParams":"temperature=0.2,\n extra_body={\"top_k\": 80, \"repetition_penalty\": 1.05},"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-8B-A1B \ + --host 0.0.0.0 \ + --port 30000 \ + --reasoning-parser qwen3 \ + --tool-call-parser lfm2 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-8B-A1B", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.2, + extra_body={"top_k": 80, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} @@ -108,10 +173,80 @@ LFM2.5-8B-A1B is Liquid AI's Mixture-of-Experts reasoning model, combining 8B to - + {/* quickstart: {"source":"/snippets/quickstart/dspark-sglang.mdx","component":"DsparkSglang","props":{"modelId":"LiquidAI/LFM2.5-8B-A1B","draftModelId":"LiquidAI/LFM2.5-8B-A1B-DSpark","samplingParams":"temperature=0.2,\n extra_body={\"top_k\": 80, \"repetition_penalty\": 1.05},"}} */} +**Install:** + +Requires a build of SGLang with DSpark support for LFM2 and LFM2-MoE targets ([PR #31041](https://github.com/sgl-project/sglang/pull/31041)). + +**Launch server with the drafter attached:** + +```bash +python -m sglang.launch_server \ + --model-path LiquidAI/LFM2.5-8B-A1B \ + --speculative-algorithm DSPARK \ + --speculative-draft-model-path LiquidAI/LFM2.5-8B-A1B-DSpark \ + --speculative-draft-attention-backend flashinfer \ + --disable-radix-cache --mem-fraction-static 0.75 --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-8B-A1B", + messages=[{"role": "user", "content": "What is machine learning?"}], + temperature=0.2, + extra_body={"top_k": 80, "repetition_penalty": 1.05}, +) + +print(response.choices[0].message.content) +``` + +**Flags:** + +- `--speculative-algorithm DSPARK`: turns on DSpark speculative decoding. +- `--speculative-draft-model-path`: the drafter repo on Hugging Face, or a local path. +- `--speculative-draft-attention-backend flashinfer`: the attention backend the drafter runs on. +- Block size: read from the drafter's `config.json`, so you don't need to set it. +- `--disable-radix-cache`: turns off SGLang's prefix cache, as in the drafter's model card. +- `--mem-fraction-static`: the share of GPU memory SGLang reserves for weights and the KV cache. +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/dspark-llamacpp.mdx","component":"DsparkLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-8B-A1B-GGUF","draftRepo":"LiquidAI/LFM2.5-8B-A1B-DSpark-GGUF","samplingFlags":"--temp 0.2 --top-k 80 --repeat-penalty 1.05"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +DSpark needs a recent build. Check that `llama serve --help` lists `draft-dspark` under `--spec-type`. + +**Run the target with the draft sidecar:** + +```bash +llama serve \ + -hf LiquidAI/LFM2.5-8B-A1B-GGUF:F16 \ + -hfd LiquidAI/LFM2.5-8B-A1B-DSpark-GGUF:F16 \ + --spec-type draft-dspark --spec-draft-n-max 10 --spec-draft-n-min 0 \ + -ngl 99 -ngld 99 -fa on \ + --temp 0.2 --top-k 80 --repeat-penalty 1.05 +``` + +**Flags:** + +- `-hf`: the target GGUF on Hugging Face, with its quantization tag. Use `-m` for a local file. +- `-hfd`: the draft sidecar GGUF. Use `-md` for a local file. The sidecar has no embeddings or LM head, so it cannot run on its own. +- `--spec-type draft-dspark`: turns on DSpark speculative decoding. +- `--spec-draft-n-max`: the most tokens the drafter proposes per step. llama.cpp clamps it to the drafter's block size. +- `--spec-draft-n-min`: the fewest tokens the drafter proposes per step. +- `-ngl 99` / `-ngld 99`: offload all target and drafter layers to the GPU. +- `-fa on`: turns on flash attention. +{/* /quickstart */} diff --git a/lfm/models/lfm25-audio-1.5b-jp.mdx b/lfm/models/lfm25-audio-1.5b-jp.mdx index 55364b4..fb0fd0a 100644 --- a/lfm/models/lfm25-audio-1.5b-jp.mdx +++ b/lfm/models/lfm25-audio-1.5b-jp.mdx @@ -46,14 +46,14 @@ LFM2.5-Audio-1.5B-JP is the Japanese-focused variant of LFM2.5-Audio-1.5B. It us **Install:** ```bash - pip install liquid-audio torchcodec + pip install "liquid-audio==1.3.0" torchcodec pip install "liquid-audio[demo]" # optional, for demo dependencies pip install flash-attn --no-build-isolation # optional, for flash attention 2 ``` `torchaudio` loads audio files through `torchcodec`, which needs FFmpeg installed on the system (for example `brew install ffmpeg` or `apt install ffmpeg`). - **Multi-Turn Chat:** + **Voice chat:** ```python import torch import soundfile as sf @@ -69,8 +69,8 @@ LFM2.5-Audio-1.5B-JP is the Japanese-focused variant of LFM2.5-Audio-1.5B. It us chat.end_turn() chat.new_turn("user") - wav, sampling_rate = sf.read("question_jp.wav", dtype="float32") - wav = torch.from_numpy(wav).unsqueeze(0) + wav, sampling_rate = sf.read("question_jp.wav", dtype="float32", always_2d=True) + wav = torch.from_numpy(wav.mean(axis=1)).unsqueeze(0) chat.add_audio(wav, sampling_rate) chat.end_turn() @@ -79,24 +79,41 @@ LFM2.5-Audio-1.5B-JP is the Japanese-focused variant of LFM2.5-Audio-1.5B. It us text_out, audio_out, modality_out = [], [], [] for t in model.generate_interleaved(**chat, max_new_tokens=512, audio_temperature=1.0, audio_top_k=4): if t.numel() == 1: - print(processor.text.decode(t), end="", flush=True) text_out.append(t) modality_out.append(LFMModality.TEXT) else: audio_out.append(t) modality_out.append(LFMModality.AUDIO_OUT) + if text_out: + print(processor.text.decode(torch.stack(text_out).reshape(-1), skip_special_tokens=True)) + if len(audio_out) < 2: + raise RuntimeError("No complete audio was generated; increase max_new_tokens") audio_codes = torch.stack(audio_out[:-1], 1).unsqueeze(0) waveform = processor.decode(audio_codes) sf.write("answer_jp.wav", waveform.cpu()[0], 24_000) ``` + The following ASR and TTS examples reuse the imports, `processor`, and `model` initialized above. + **Japanese ASR:** ```python chat = ChatState(processor) chat.new_turn("system") chat.add_text("Perform ASR in japanese.") chat.end_turn() + chat.new_turn("user") + wav, sampling_rate = sf.read("question_jp.wav", dtype="float32", always_2d=True) + chat.add_audio(torch.from_numpy(wav.mean(axis=1)).unsqueeze(0), sampling_rate) + chat.end_turn() + chat.new_turn("assistant") + text_tokens = [ + token for token in model.generate_sequential(**chat, max_new_tokens=512) + if token.numel() == 1 + ] + if not text_tokens: + raise RuntimeError("No transcript was generated") + print(processor.text.decode(torch.stack(text_tokens).reshape(-1), skip_special_tokens=True)) ``` **Japanese TTS:** @@ -105,6 +122,20 @@ LFM2.5-Audio-1.5B-JP is the Japanese-focused variant of LFM2.5-Audio-1.5B. It us chat.new_turn("system") chat.add_text("Perform TTS in japanese.") chat.end_turn() + chat.new_turn("user") + chat.add_text("こんにちは。今日はどのようなご用件でしょうか。") + chat.end_turn() + chat.new_turn("assistant") + audio_out = [ + token for token in model.generate_sequential( + **chat, max_new_tokens=512, audio_temperature=0.8, audio_top_k=64 + ) if token.numel() > 1 + ] + if len(audio_out) < 2: + raise RuntimeError("No complete audio was generated; increase max_new_tokens") + audio_codes = torch.stack(audio_out[:-1], 1).unsqueeze(0) + waveform = processor.decode(audio_codes) + sf.write("tts_jp.wav", waveform.cpu()[0], 24_000) ``` diff --git a/lfm/models/lfm25-vl-1.6b.mdx b/lfm/models/lfm25-vl-1.6b.mdx index afdb081..5f28891 100644 --- a/lfm/models/lfm25-vl-1.6b.mdx +++ b/lfm/models/lfm25-vl-1.6b.mdx @@ -3,10 +3,6 @@ title: "LFM2.5-VL-1.6B" description: "1.6B vision-language model for image understanding, OCR, and multilingual visual Q&A" --- -import { VlTransformers } from "/snippets/quickstart/vl-transformers.mdx"; -import { VlVllm } from "/snippets/quickstart/vl-vllm.mdx"; -import { VlSglang } from "/snippets/quickstart/vl-sglang.mdx"; -import { VlLlamacpp } from "/snippets/quickstart/vl-llamacpp.mdx"; ← Back to Vision Models @@ -53,15 +49,164 @@ For new applications, start with [LFM3-VL-2B](/lfm/models/lfm3-vl-2b), which add - + {/* quickstart: {"source":"/snippets/quickstart/vl-transformers.mdx","component":"VlTransformers","props":{"modelId":"LiquidAI/LFM2.5-VL-1.6B"}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" pillow torch torchvision accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoProcessor, AutoModelForImageTextToText +from transformers.image_utils import load_image + +model_id = "LiquidAI/LFM2.5-VL-1.6B" +model = AutoModelForImageTextToText.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) + +processor = AutoProcessor.from_pretrained(model_id) + +url = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" +image = load_image(url) + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": "What is in this image?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + conversation, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + tokenize=True, +).to(model.device) + +outputs = model.generate(**inputs, do_sample=True, temperature=0.1, min_p=0.15, repetition_penalty=1.05, max_new_tokens=256) +input_length = inputs["input_ids"].shape[1] +response = processor.batch_decode(outputs[:, input_length:], skip_special_tokens=True)[0] +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-vllm.mdx","component":"VlVllm","props":{"modelId":"LiquidAI/LFM2.5-VL-1.6B"}} */} +**Install:** + +```bash +uv pip install "vllm==0.34.0" pillow +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +IMAGE_URL = "http://images.cocodataset.org/val2017/000000039769.jpg" + +llm = LLM( + model="LiquidAI/LFM2.5-VL-1.6B", + max_model_len=1024, + enforce_eager=True, +) + +sampling_params = SamplingParams( + temperature=0.1, min_p=0.15, repetition_penalty=1.05, + max_tokens=256, +) + +messages = [{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": IMAGE_URL}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], +}] + +outputs = llm.chat(messages, sampling_params) +print(outputs[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-sglang.mdx","component":"VlSglang","props":{"modelId":"LiquidAI/LFM2.5-VL-1.6B"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-VL-1.6B \ + --host 0.0.0.0 \ + --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-VL-1.6B", + messages=[{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": "http://images.cocodataset.org/val2017/000000039769.jpg"}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], + }], + temperature=0.1, extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, + max_tokens=256, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-llamacpp.mdx","component":"VlLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-VL-1.6B-GGUF","samplingFlags":"--temp 0.1 --min-p 0.15 --repeat-penalty 1.05"}} */} +llama.cpp enables efficient CPU inference for vision models. + +**Install:** + +```bash +brew install llama.cpp +``` + +Or download pre-built binaries from [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases). + +**Run:** + +```bash +llama cli \ + -hf LiquidAI/LFM2.5-VL-1.6B-GGUF:Q4_0 \ + --image test_image.jpg \ + -p "What's in this image?" \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-VL-1.6B-GGUF:Q4_0 \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model and its vision projector directly from Hugging Face. Use `--image-max-tokens` to control image token budget. + +For advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp#vision-models). +{/* /quickstart */} diff --git a/lfm/models/lfm25-vl-3b.mdx b/lfm/models/lfm25-vl-3b.mdx index c700b76..1dd876c 100644 --- a/lfm/models/lfm25-vl-3b.mdx +++ b/lfm/models/lfm25-vl-3b.mdx @@ -3,13 +3,6 @@ title: "LFM2.5-VL-3B" description: "Largest LFM2.5-VL vision-language model with grounding, screen understanding, and function calling" --- -import { VlTransformers } from "/snippets/quickstart/vl-transformers.mdx"; -import { VlVllm } from "/snippets/quickstart/vl-vllm.mdx"; -import { VlSglang } from "/snippets/quickstart/vl-sglang.mdx"; -import { VlLlamacpp } from "/snippets/quickstart/vl-llamacpp.mdx"; -import { DsparkSglang } from "/snippets/quickstart/dspark-sglang.mdx"; -import { DsparkLlamacpp } from "/snippets/quickstart/dspark-llamacpp.mdx"; -import { DsparkMlxVlm } from "/snippets/quickstart/dspark-mlx-vlm.mdx"; ← Back to Vision Models @@ -57,16 +50,165 @@ For new applications, start with [LFM3-VL-2B](/lfm/models/lfm3-vl-2b), which add - + {/* quickstart: {"source":"/snippets/quickstart/vl-transformers.mdx","component":"VlTransformers","props":{"modelId":"LiquidAI/LFM2.5-VL-3B","samplingArgs":"temperature=0.2, top_k=50, repetition_penalty=1.0"}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" pillow torch torchvision accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoProcessor, AutoModelForImageTextToText +from transformers.image_utils import load_image + +model_id = "LiquidAI/LFM2.5-VL-3B" +model = AutoModelForImageTextToText.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) + +processor = AutoProcessor.from_pretrained(model_id) + +url = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" +image = load_image(url) + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": "What is in this image?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + conversation, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + tokenize=True, +).to(model.device) + +outputs = model.generate(**inputs, do_sample=True, temperature=0.2, top_k=50, repetition_penalty=1.0, max_new_tokens=256) +input_length = inputs["input_ids"].shape[1] +response = processor.batch_decode(outputs[:, input_length:], skip_special_tokens=True)[0] +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-vllm.mdx","component":"VlVllm","props":{"modelId":"LiquidAI/LFM2.5-VL-3B","samplingArgs":"temperature=0.2, top_k=50, repetition_penalty=1.0"}} */} +**Install:** + +```bash +uv pip install "vllm==0.34.0" pillow +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +IMAGE_URL = "http://images.cocodataset.org/val2017/000000039769.jpg" + +llm = LLM( + model="LiquidAI/LFM2.5-VL-3B", + max_model_len=1024, + enforce_eager=True, +) + +sampling_params = SamplingParams( + temperature=0.2, top_k=50, repetition_penalty=1.0, + max_tokens=256, +) + +messages = [{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": IMAGE_URL}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], +}] + +outputs = llm.chat(messages, sampling_params) +print(outputs[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-sglang.mdx","component":"VlSglang","props":{"modelId":"LiquidAI/LFM2.5-VL-3B","samplingArgs":"temperature=0.2, extra_body={\"top_k\": 50, \"repetition_penalty\": 1.0}"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-VL-3B \ + --host 0.0.0.0 \ + --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-VL-3B", + messages=[{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": "http://images.cocodataset.org/val2017/000000039769.jpg"}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], + }], + temperature=0.2, extra_body={"top_k": 50, "repetition_penalty": 1.0}, + max_tokens=256, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-llamacpp.mdx","component":"VlLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-VL-3B-GGUF","samplingFlags":"--temp 0.2 --top-k 50 --repeat-penalty 1.0"}} */} +llama.cpp enables efficient CPU inference for vision models. + +**Install:** + +```bash +brew install llama.cpp +``` + +Or download pre-built binaries from [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases). + +**Run:** + +```bash +llama cli \ + -hf LiquidAI/LFM2.5-VL-3B-GGUF:Q4_0 \ + --image test_image.jpg \ + -p "What's in this image?" \ + --temp 0.2 --top-k 50 --repeat-penalty 1.0 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-VL-3B-GGUF:Q4_0 \ + --temp 0.2 --top-k 50 --repeat-penalty 1.0 +``` + +The `-hf` flag downloads the model and its vision projector directly from Hugging Face. Use `--image-max-tokens` to control image token budget. + +For advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp#vision-models). +{/* /quickstart */} @@ -74,12 +216,114 @@ For new applications, start with [LFM3-VL-2B](/lfm/models/lfm3-vl-2b), which add - + {/* quickstart: {"source":"/snippets/quickstart/dspark-sglang.mdx","component":"DsparkSglang","props":{"modelId":"LiquidAI/LFM2.5-VL-3B","draftModelId":"LiquidAI/LFM2.5-VL-3B-DSpark","vision":true,"samplingParams":"temperature=0.2,\n extra_body={\"top_k\": 50, \"repetition_penalty\": 1.0},"}} */} +**Install:** + +Requires [SGLang v0.5.19](https://github.com/sgl-project/sglang/releases/tag/v0.5.19) or newer. + +**Launch server with the drafter attached:** + +```bash +python -m sglang.launch_server \ + --model-path LiquidAI/LFM2.5-VL-3B \ + --speculative-algorithm DSPARK \ + --speculative-draft-model-path LiquidAI/LFM2.5-VL-3B-DSpark \ + --speculative-draft-attention-backend flashinfer \ + --speculative-dspark-block-size 9 \ + --disable-radix-cache --mem-fraction-static 0.8 --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-VL-3B", + messages=[{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": "http://images.cocodataset.org/val2017/000000039769.jpg"}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], + }], + temperature=0.2, + extra_body={"top_k": 50, "repetition_penalty": 1.0}, +) + +print(response.choices[0].message.content) +``` + +**Flags:** + +- `--speculative-algorithm DSPARK`: turns on DSpark speculative decoding. +- `--speculative-draft-model-path`: the drafter repo on Hugging Face, or a local path. +- `--speculative-draft-attention-backend flashinfer`: the attention backend the drafter runs on. +- `--speculative-dspark-block-size`: how many tokens the drafter proposes per step. Use 9, the block size the drafter was trained with. +- `--disable-radix-cache`: turns off SGLang's prefix cache, as in the drafter's model card. +- `--mem-fraction-static`: the share of GPU memory SGLang reserves for weights and the KV cache. +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/dspark-llamacpp.mdx","component":"DsparkLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-VL-3B-GGUF","draftRepo":"LiquidAI/LFM2.5-VL-3B-DSpark-GGUF","vision":true,"samplingFlags":"--temp 0.2 --top-k 50 --repeat-penalty 1.0"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +DSpark needs a recent build. Check that `llama serve --help` lists `draft-dspark` under `--spec-type`. + +**Run the target with the draft sidecar:** + +```bash +llama serve \ + -hf LiquidAI/LFM2.5-VL-3B-GGUF:F16 \ + -hfd LiquidAI/LFM2.5-VL-3B-DSpark-GGUF:F16 \ + --spec-type draft-dspark --spec-draft-n-max 8 --spec-draft-n-min 0 \ + -ngl 99 -ngld 99 -fa on \ + --temp 0.2 --top-k 50 --repeat-penalty 1.0 +``` + +**Flags:** + +- `-hf`: the target GGUF on Hugging Face, with its quantization tag. Use `-m` for a local file. +- `-hfd`: the draft sidecar GGUF. Use `-md` for a local file. The sidecar has no embeddings or LM head, so it cannot run on its own. +- `--spec-type draft-dspark`: turns on DSpark speculative decoding. +- `--spec-draft-n-max`: the most tokens the drafter proposes per step. The drafter was trained with block size 9. Use 8 on Apple silicon. +- `--spec-draft-n-min`: the fewest tokens the drafter proposes per step. +- `-ngl 99` / `-ngld 99`: offload all target and drafter layers to the GPU. +- `-fa on`: turns on flash attention. +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/dspark-mlx-vlm.mdx","component":"DsparkMlxVlm","props":{"modelId":"LiquidAI/LFM2.5-VL-3B","draftModelId":"LiquidAI/LFM2.5-VL-3B-DSpark"}} */} +**Install:** + +```bash +pip install "mlx-vlm>=0.7.2" +``` + +**Run with the drafter:** + +```bash +python -m mlx_vlm.generate \ + --model LiquidAI/LFM2.5-VL-3B \ + --draft-model LiquidAI/LFM2.5-VL-3B-DSpark \ + --draft-block-size 8 \ + --image /path/to/image.jpg \ + --prompt "Describe this image." \ + --max-tokens 256 \ + --temperature 0 +``` + +**Flags:** + +- `--draft-model`: the drafter repo on Hugging Face. MLX-VLM detects that it is a DSpark drafter. +- `--draft-block-size`: how many tokens the drafter proposes per step. Use 8 on Apple silicon. +- `--temperature 0`: DSpark in MLX-VLM currently supports greedy sampling only. +{/* /quickstart */} diff --git a/lfm/models/lfm25-vl-450m.mdx b/lfm/models/lfm25-vl-450m.mdx index 28cf641..f50b592 100644 --- a/lfm/models/lfm25-vl-450m.mdx +++ b/lfm/models/lfm25-vl-450m.mdx @@ -3,10 +3,6 @@ title: "LFM2.5-VL-450M" description: "Compact 450M vision-language model for edge deployment, with object detection and function calling" --- -import { VlTransformers } from "/snippets/quickstart/vl-transformers.mdx"; -import { VlVllm } from "/snippets/quickstart/vl-vllm.mdx"; -import { VlSglang } from "/snippets/quickstart/vl-sglang.mdx"; -import { VlLlamacpp } from "/snippets/quickstart/vl-llamacpp.mdx"; ← Back to Vision Models @@ -51,15 +47,164 @@ LFM2.5-VL-450M is Liquid AI's smallest vision-language model. It is a refreshed - + {/* quickstart: {"source":"/snippets/quickstart/vl-transformers.mdx","component":"VlTransformers","props":{"modelId":"LiquidAI/LFM2.5-VL-450M"}} */} +**Install:** + +```bash +pip install "transformers==5.23.0" pillow torch torchvision accelerate +``` + +**Download & Run:** + +```python +from transformers import AutoProcessor, AutoModelForImageTextToText +from transformers.image_utils import load_image + +model_id = "LiquidAI/LFM2.5-VL-450M" +model = AutoModelForImageTextToText.from_pretrained( + model_id, + device_map="auto", + dtype="bfloat16", +) + +processor = AutoProcessor.from_pretrained(model_id) + +url = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" +image = load_image(url) + +conversation = [ + { + "role": "user", + "content": [ + {"type": "image", "image": image}, + {"type": "text", "text": "What is in this image?"}, + ], + }, +] + +inputs = processor.apply_chat_template( + conversation, + add_generation_prompt=True, + return_tensors="pt", + return_dict=True, + tokenize=True, +).to(model.device) + +outputs = model.generate(**inputs, do_sample=True, temperature=0.1, min_p=0.15, repetition_penalty=1.05, max_new_tokens=256) +input_length = inputs["input_ids"].shape[1] +response = processor.batch_decode(outputs[:, input_length:], skip_special_tokens=True)[0] +print(response) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-vllm.mdx","component":"VlVllm","props":{"modelId":"LiquidAI/LFM2.5-VL-450M"}} */} +**Install:** + +```bash +uv pip install "vllm==0.34.0" pillow +``` + +**Run:** + +```python +from vllm import LLM, SamplingParams + +IMAGE_URL = "http://images.cocodataset.org/val2017/000000039769.jpg" + +llm = LLM( + model="LiquidAI/LFM2.5-VL-450M", + max_model_len=1024, + enforce_eager=True, +) + +sampling_params = SamplingParams( + temperature=0.1, min_p=0.15, repetition_penalty=1.05, + max_tokens=256, +) + +messages = [{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": IMAGE_URL}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], +}] + +outputs = llm.chat(messages, sampling_params) +print(outputs[0].outputs[0].text) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-sglang.mdx","component":"VlSglang","props":{"modelId":"LiquidAI/LFM2.5-VL-450M"}} */} +Use the configured CUDA image from the [SGLang installation guide](/deployment/gpu-inference/sglang#installation). Run the following launch command inside that image, or pass its model flags to the guide's Docker command. + +**Launch server:** + +```bash +sglang serve \ + --model-path LiquidAI/LFM2.5-VL-450M \ + --host 0.0.0.0 \ + --port 30000 +``` + +**Query (OpenAI-compatible):** + +```python +from openai import OpenAI + +client = OpenAI(base_url="http://localhost:30000/v1", api_key="None") + +response = client.chat.completions.create( + model="LiquidAI/LFM2.5-VL-450M", + messages=[{ + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": "http://images.cocodataset.org/val2017/000000039769.jpg"}}, + {"type": "text", "text": "Describe what you see in this image."}, + ], + }], + temperature=0.1, extra_body={"min_p": 0.15, "repetition_penalty": 1.05}, + max_tokens=256, +) + +print(response.choices[0].message.content) +``` +{/* /quickstart */} - + {/* quickstart: {"source":"/snippets/quickstart/vl-llamacpp.mdx","component":"VlLlamacpp","props":{"ggufRepo":"LiquidAI/LFM2.5-VL-450M-GGUF","samplingFlags":"--temp 0.1 --min-p 0.15 --repeat-penalty 1.05"}} */} +llama.cpp enables efficient CPU inference for vision models. + +**Install:** + +```bash +brew install llama.cpp +``` + +Or download pre-built binaries from [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases). + +**Run:** + +```bash +llama cli \ + -hf LiquidAI/LFM2.5-VL-450M-GGUF:Q4_0 \ + --image test_image.jpg \ + -p "What's in this image?" \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM2.5-VL-450M-GGUF:Q4_0 \ + --temp 0.1 --min-p 0.15 --repeat-penalty 1.05 +``` + +The `-hf` flag downloads the model and its vision projector directly from Hugging Face. Use `--image-max-tokens` to control image token budget. + +For advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp#vision-models). +{/* /quickstart */} diff --git a/lfm/models/lfm3-1.7b.mdx b/lfm/models/lfm3-1.7b.mdx index 5964a51..ae58d12 100644 --- a/lfm/models/lfm3-1.7b.mdx +++ b/lfm/models/lfm3-1.7b.mdx @@ -3,7 +3,6 @@ title: "LFM3-1.7B" description: "1.7B text model for local agents and specialized applications, with a 256K context window and native tool calling" --- -import { TextLlamacpp } from "/snippets/quickstart/text-llamacpp.mdx"; ← Back to Text Models @@ -91,7 +90,27 @@ On Apple Silicon, use [MLX-VLM 0.8.0](/deployment/on-device/mlx#lfm3-and-d1-mode Requires llama.cpp 0.8.0 (b11960) or later. Add a quantization tag to pick a file. - + {/* quickstart: {"source":"/snippets/quickstart/text-llamacpp.mdx","component":"TextLlamacpp","props":{"ggufRepo":"LiquidAI/LFM3-1.7B-GGUF:Q4_K_M"}} */} +**Install:** + +```bash +brew install llama.cpp +``` + +**Run:** + +```bash +llama cli -hf LiquidAI/LFM3-1.7B-GGUF:Q4_K_M +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM3-1.7B-GGUF:Q4_K_M +``` + +The `-hf` flag downloads the model directly from Hugging Face. For other installation methods and advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp). +{/* /quickstart */} The recommended sampling parameters are stored in the GGUF, so no sampling flags are needed. For math and science, override them with `--temp 1.0 --top-p 0.95 --top-k 20 --repeat-penalty 1.0`. diff --git a/lfm/models/lfm3-audio-2b.mdx b/lfm/models/lfm3-audio-2b.mdx index fee9715..6dbdf1c 100644 --- a/lfm/models/lfm3-audio-2b.mdx +++ b/lfm/models/lfm3-audio-2b.mdx @@ -3,7 +3,6 @@ title: "LFM3-Audio-2B" description: "2B audio model for multilingual speech recognition, speech synthesis, voice chat, audio understanding, and tool calling" --- -import { AudioLlamacpp } from "/snippets/quickstart/audio-llamacpp.mdx"; ← Back to Audio Models @@ -229,6 +228,40 @@ On Apple Silicon, use [MLX-VLM 0.8.0](/deployment/on-device/mlx#lfm3-and-d1-mode To run it without the command line, use the [Llama app](/deployment/on-device/llama), with audio input. - + {/* quickstart: {"source":"/snippets/quickstart/audio-llamacpp.mdx","component":"AudioLlamacpp","props":{"ggufRepo":"LiquidAI/LFM3-Audio-2B-GGUF","ttsFlags":"--tts-voice male","asrAutoLanguage":true}} */} +Requires llama.cpp 0.8.0 (b11960) or later. Add a quantization tag to pick a file; with `-hf`, llama.cpp also downloads the projector. + +**Web chat and API server:** + +Start a web chat UI and an OpenAI-compatible API at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM3-Audio-2B-GGUF:Q4_K_M +``` + +The server also handles real-time voice conversations, including tool calls, on its `/v1/realtime` WebSocket API. The recommended sampling parameters are stored in the GGUF, so no sampling flags are needed. To ask one question from the command line, use `llama cli`. + +**ASR (Audio to Text):** + +Use the system prompt `Perform ASR in .`, or `Perform ASR.` to let the model infer the language. Pass it with `-sys`: as a regular prompt, the model describes the audio instead of transcribing it. + +```bash +llama cli -hf LiquidAI/LFM3-Audio-2B-GGUF:Q4_K_M \ + --audio speech.wav -sys "Perform ASR in English." -p "<__media__>" +``` + +**TTS (Text to Audio):** + +`--tts-lang` takes a language code (default `en`) and `--tts-voice` is `female` (default) or `male`. The audio sampling parameters from the model card are stored in the GGUF. + +```bash +hf download LiquidAI/LFM3-Audio-2B-GGUF LFM3-Audio-2B-Q4_K_M.gguf mmproj-LFM3-Audio-2B-Q8_0.gguf --local-dir . + +llama-tts -m LFM3-Audio-2B-Q4_K_M.gguf -mm mmproj-LFM3-Audio-2B-Q8_0.gguf \ + -p "Hello world" --tts-voice male -o out.wav +``` + +For more options, see the [llama.cpp guide](/deployment/on-device/llama-cpp#audio-and-omni-models). +{/* /quickstart */} diff --git a/lfm/models/lfm3-omni-2b.mdx b/lfm/models/lfm3-omni-2b.mdx index 1d1d3f5..6aef256 100644 --- a/lfm/models/lfm3-omni-2b.mdx +++ b/lfm/models/lfm3-omni-2b.mdx @@ -3,7 +3,6 @@ title: "LFM3-Omni-2B" description: "2B omni model that understands text, images, video, and audio, and answers in text, speech, or both" --- -import { OmniLlamacpp } from "/snippets/quickstart/omni-llamacpp.mdx"; ← Back to Omni Models @@ -163,7 +162,58 @@ On Apple Silicon, use [MLX-VLM 0.8.0](/deployment/on-device/mlx#lfm3-and-d1-mode LFM3-Omni-2B is a non-reasoning model, so the server command uses `--reasoning off`. - + {/* quickstart: {"source":"/snippets/quickstart/omni-llamacpp.mdx","component":"OmniLlamacpp","props":{"ggufRepo":"LiquidAI/LFM3-Omni-2B-GGUF","serveFlags":"--reasoning off"}} */} +Requires llama.cpp 0.8.0 (b11960) or later. Add a quantization tag to pick a file; with `-hf`, llama.cpp also downloads the vision and audio projector. + +**Web chat and API server:** + +Start a web chat UI and an OpenAI-compatible API at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM3-Omni-2B-GGUF:Q4_K_M --reasoning off +``` + +The server also handles real-time voice conversations, including tool calls, on its `/v1/realtime` WebSocket API. The recommended sampling parameters are stored in the GGUF, so no sampling flags are needed. To ask one question from the command line, use `llama cli`. + +**ASR (Audio to Text):** + +Use the system prompt `Perform ASR in .` Pass it with `-sys`: as a regular prompt, the model describes the audio instead of transcribing it. + +```bash +llama cli -hf LiquidAI/LFM3-Omni-2B-GGUF:Q4_K_M \ + --audio speech.wav -sys "Perform ASR in English." -p "<__media__>" +``` + +**Image understanding:** + +```bash +llama cli -hf LiquidAI/LFM3-Omni-2B-GGUF:Q4_K_M \ + --image photo.png -p "Describe this image." +``` + +**Video understanding:** the model sees the frames and hears the soundtrack of the video. Use the system prompt `Answer questions about the video using what you see and hear.` Video input needs `ffmpeg` in `PATH`. + +```bash +curl -sL -o reading.mp4 https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/4cba700bd771f44d72b549253da025c32e944d42/sample_demo_1.mp4 # a child reading a book + +llama cli -hf LiquidAI/LFM3-Omni-2B-GGUF:Q4_K_M \ + --video reading.mp4 -sys "Answer questions about the video using what you see and hear." \ + -p "What happens here, and what can you hear?" +``` + +**TTS (Text to Audio):** + +`--tts-lang` takes a language code (default `en`) and `--tts-voice` is `female` (default) or `male`. The audio sampling parameters from the model card are stored in the GGUF. + +```bash +hf download LiquidAI/LFM3-Omni-2B-GGUF LFM3-Omni-2B-Q4_K_M.gguf mmproj-LFM3-Omni-2B-Q8_0.gguf --local-dir . + +llama-tts -m LFM3-Omni-2B-Q4_K_M.gguf -mm mmproj-LFM3-Omni-2B-Q8_0.gguf \ + -p "Hello world" -o out.wav +``` + +For more options, see the [llama.cpp guide](/deployment/on-device/llama-cpp#audio-and-omni-models). +{/* /quickstart */} diff --git a/lfm/models/lfm3-vl-2b.mdx b/lfm/models/lfm3-vl-2b.mdx index 04064c3..de40623 100644 --- a/lfm/models/lfm3-vl-2b.mdx +++ b/lfm/models/lfm3-vl-2b.mdx @@ -3,7 +3,6 @@ title: "LFM3-VL-2B" description: "2B vision-language model with video understanding, thinking, and spatial reasoning for on-device deployment" --- -import { VlLlamacpp } from "/snippets/quickstart/vl-llamacpp.mdx"; ← Back to Vision Models @@ -160,7 +159,38 @@ On Apple Silicon, use [MLX-VLM 0.8.0](/deployment/on-device/mlx#lfm3-and-d1-mode Requires llama.cpp 0.8.0 (b11960) or later. The `:Q4_0` tag selects the Quantization-Aware Distillation (QAD) checkpoint. - + {/* quickstart: {"source":"/snippets/quickstart/vl-llamacpp.mdx","component":"VlLlamacpp","props":{"ggufRepo":"LiquidAI/LFM3-VL-2B-GGUF","samplingFlags":"--top-p 1.0 --min-p 0.0 --no-reasoning-preserve"}} */} +llama.cpp enables efficient CPU inference for vision models. + +**Install:** + +```bash +brew install llama.cpp +``` + +Or download pre-built binaries from [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases). + +**Run:** + +```bash +llama cli \ + -hf LiquidAI/LFM3-VL-2B-GGUF:Q4_0 \ + --image test_image.jpg \ + -p "What's in this image?" \ + --top-p 1.0 --min-p 0.0 --no-reasoning-preserve +``` + +**Web chat UI and OpenAI-compatible API** at `http://localhost:9931`: + +```bash +llama serve -hf LiquidAI/LFM3-VL-2B-GGUF:Q4_0 \ + --top-p 1.0 --min-p 0.0 --no-reasoning-preserve +``` + +The `-hf` flag downloads the model and its vision projector directly from Hugging Face. Use `--image-max-tokens` to control image token budget. + +For advanced usage, see the [llama.cpp guide](/deployment/on-device/llama-cpp#vision-models). +{/* /quickstart */} The GGUF stores the recommended temperature, top-k, and repetition penalty. `--top-p 1.0 --min-p 0.0` sets the two recommended values it doesn't store, and `--no-reasoning-preserve` keeps earlier reasoning out of the conversation history. The server is OpenAI-compatible, so you can query it with the SGLang example above by changing `base_url` to `http://localhost:9931/v1`. diff --git a/link-snapshot.yaml b/link-snapshot.yaml index 9fab5af..a03b834 100644 --- a/link-snapshot.yaml +++ b/link-snapshot.yaml @@ -85,11 +85,13 @@ active: - /deployment/on-device/onnx - /deployment/on-device/sdk/advanced-features - /deployment/on-device/sdk/ai-agent-usage-guide + - /deployment/on-device/sdk/android-quick-start-guide - /deployment/on-device/sdk/cloud-ai-comparison - /deployment/on-device/sdk/constrained-generation - /deployment/on-device/sdk/conversation-generation - /deployment/on-device/sdk/desktop-platforms - /deployment/on-device/sdk/function-calling + - /deployment/on-device/sdk/ios-quick-start-guide - /deployment/on-device/sdk/messages-content - /deployment/on-device/sdk/model-loading - /deployment/on-device/sdk/openai-client @@ -103,17 +105,21 @@ active: - /deployment/tools/model-bundling/bundle-creation - /deployment/tools/model-bundling/bundle-management - /deployment/tools/model-bundling/changelog + - /deployment/tools/model-bundling/cli-spec - /deployment/tools/model-bundling/configuration - /deployment/tools/model-bundling/data-privacy - /deployment/tools/model-bundling/download - /deployment/tools/model-bundling/quick-start - /deployment/tools/model-bundling/reference + - /docs - /docs/fine-tuning/datasets - /docs/fine-tuning/leap-finetune - /docs/fine-tuning/trl - /docs/fine-tuning/unsloth - /docs/fine-tuning/workbench + - /docs/frameworks/outlines - /docs/getting-started/connect-ai-tools + - /docs/getting-started/intro - /docs/getting-started/welcome - /docs/inference/baseten-deployment - /docs/inference/fal-deployment @@ -126,6 +132,7 @@ active: - /docs/inference/sglang - /docs/inference/transformers - /docs/inference/vllm + - /docs/models/lfm25-1.2b-base - /examples/agent-harnesses - /examples/android/leap-koog-agent - /examples/android/recipe-generator-constrained-output @@ -138,6 +145,7 @@ active: - /examples/customize-models/home-assistant - /examples/customize-models/satellite-vlm - /examples/customize-models/wildfire-prevention + - /examples/deploy-models-on-ios/slogan-generator-app - /examples/index - /examples/laptop-examples/audio-car-cockpit - /examples/laptop-examples/audio-to-text-in-real-time @@ -154,7 +162,17 @@ active: - /guides/hardware-evaluation - /guides/migration-guide - /guides/use-case-evaluation + - /leap + - /leap/changelog + - /leap/edge-sdk/android/android-quick-start-guide + - /leap/edge-sdk/ios/ios-quick-start-guide - /leap/edge-sdk/overview + - /leap/find-model + - /leap/finetuning + - /leap/index + - /leap/laptop-support + - /leap/leap-bundle/cli-spec + - /leap/vibe-check-models - /lfm/fine-tuning - /lfm/fine-tuning/datasets - /lfm/fine-tuning/halo @@ -167,6 +185,7 @@ active: - /lfm/getting-started/connect-ai-tools - /lfm/getting-started/intro - /lfm/getting-started/model-license + - /lfm/getting-started/quickstart - /lfm/getting-started/text-generation-and-prompting - /lfm/getting-started/vision - /lfm/getting-started/welcome diff --git a/scripts/generate_snippets.py b/scripts/generate_snippets.py index 62a6d51..2c66773 100644 --- a/scripts/generate_snippets.py +++ b/scripts/generate_snippets.py @@ -27,7 +27,7 @@ SNIPPET_CONFIG = { "text-transformers": { "component_name": "TextTransformers", - "props": "{ modelId, samplingParams }", + "props": "{ modelId, samplingParams, maxTokens = 512 }", "replacement_group": "text", "source": "config", "sections": [ @@ -55,7 +55,7 @@ " return_dict=True,\n" ").to(model.device)\n" "\n" - "output = model.generate(**inputs, ${samplingParams}max_new_tokens=512)\n" + "output = model.generate(**inputs, ${samplingParams}max_new_tokens=${maxTokens})\n" 'input_length = inputs["input_ids"].shape[1]\n' "response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True)\n" "print(response)" diff --git a/scripts/materializeQuickstarts.mjs b/scripts/materializeQuickstarts.mjs new file mode 100644 index 0000000..9d993c5 --- /dev/null +++ b/scripts/materializeQuickstarts.mjs @@ -0,0 +1,94 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import vm from 'node:vm'; +import { fileURLToPath } from 'node:url'; +import ts from 'typescript'; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const components = new Map(); +const CodeBlock = Symbol('CodeBlock'); +const React = { + Fragment: Symbol('Fragment'), + createElement: (type, props, ...children) => ({ type, props: props ?? {}, children }), +}; + +// Evaluate only the repository's trusted JSX templates, without Node globals. +function evaluate(source) { + const compiled = ts.transpileModule(source, { + fileName: 'template.tsx', + compilerOptions: { jsx: ts.JsxEmit.React, module: ts.ModuleKind.CommonJS }, + }).outputText; + const context = { React, CodeBlock, exports: {} }; + vm.runInNewContext(compiled, context, { timeout: 1000 }); + return context.exports; +} + +export function markdown(node) { + if (node == null || typeof node === 'boolean') return ''; + if (Array.isArray(node)) return node.map(markdown).join(''); + if (typeof node !== 'object') return String(node); + const text = node.children.map(markdown).join(''); + if (node.type === CodeBlock) return `\n\n\`\`\`${node.props.language ?? ''}\n${text}\n\`\`\`\n\n`; + if (node.type === React.Fragment) return text; + switch (node.type) { + case 'div': return text; + case 'p': return `\n\n${text}\n\n`; + case 'strong': return `**${text}**`; + case 'code': return `\`${text}\``; + case 'a': return `[${text}](${node.props.href})`; + case 'ul': return `\n\n${text}\n`; + case 'li': return `- ${text}\n`; + default: throw new Error(`Unsupported template element: ${String(node.type)}`); + } +} + +export function renderQuickstart(metadata) { + if (!/^\/snippets\/quickstart\/[a-z-]+\.mdx$/.test(metadata.source)) { + throw new Error(`Invalid quickstart source: ${metadata.source}`); + } + if (!components.has(metadata.source)) { + components.set(metadata.source, evaluate(fs.readFileSync(path.join(root, metadata.source), 'utf8'))); + } + const component = components.get(metadata.source)[metadata.component]; + if (typeof component !== 'function') throw new Error(`Missing component: ${metadata.component}`); + return markdown(component(metadata.props)).trim().split(/(```[\s\S]*?```)/g) + .map((part, index) => index % 2 ? part : part.replace(/\n{3,}/g, '\n\n')).join(''); +} + +const marker = /\{\/\* quickstart: (.+?) \*\/\}\n[\s\S]*?\n\{\/\* \/quickstart \*\/\}/g; +const block = (metadata) => `{/* quickstart: ${JSON.stringify(metadata)} */}\n${renderQuickstart(metadata)}\n{/* /quickstart */}`; + +export function materialize(source) { + let result = source.replace(marker, (_, json) => block(JSON.parse(json))); + const imports = [...result.matchAll(/^import \{ (\w+) \} from "(\/snippets\/quickstart\/[a-z-]+\.mdx)";?\n/gm)]; + for (const [importLine, name, modulePath] of imports) { + const calls = new RegExp(`<${name}\\b[\\s\\S]*?(?:\\/>|><\\/${name}>)`, 'g'); + result = result.replace(calls, (call) => { + const jsx = call.replace(new RegExp(`^<${name}`), '$`), ''); + const compiled = ts.transpileModule(`exports.props = (${jsx});`, { + fileName: 'props.tsx', compilerOptions: { jsx: ts.JsxEmit.React }, + }).outputText; + const context = { exports: {}, Capture: 'Capture', React }; + vm.runInNewContext(compiled, context, { timeout: 1000 }); + return block({ source: modulePath, component: name, props: context.exports.props.props }); + }); + if (!new RegExp(`<${name}\\b`).test(result)) result = result.replace(importLine, ''); + } + return result; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const check = process.argv.includes('--check'); + const changed = []; + for (const name of fs.readdirSync(path.join(root, 'lfm/models')).filter((name) => name.endsWith('.mdx'))) { + const file = path.join(root, 'lfm/models', name); + const original = fs.readFileSync(file, 'utf8'); + const updated = materialize(original); + if (original !== updated) { + changed.push(name); + if (!check) fs.writeFileSync(file, updated); + } + } + if (check && changed.length) throw new Error(`Regenerate quickstarts with node scripts/materializeQuickstarts.mjs: ${changed.join(', ')}`); + console.log(check ? 'Model quickstarts are current.' : `Updated ${changed.length} model pages with literal Markdown code fences.`); +} diff --git a/scripts/materializeQuickstarts.test.mjs b/scripts/materializeQuickstarts.test.mjs new file mode 100644 index 0000000..c80e785 --- /dev/null +++ b/scripts/materializeQuickstarts.test.mjs @@ -0,0 +1,28 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import test from 'node:test'; +import { materialize, renderQuickstart } from './materializeQuickstarts.mjs'; + +test('text quickstarts retain literal Python and shell syntax in Markdown', () => { + const input = 'import { TextTransformers } from "/snippets/quickstart/text-transformers.mdx";\n'; + const result = materialize(input); + assert.match(result, /```python\nfrom transformers import/); + assert.match(result, /from_pretrained\(/); + assert.doesNotMatch(result, /from\\_pretrained| { + const result = renderQuickstart({ source: '/snippets/quickstart/audio-llamacpp.mdx', component: 'AudioLlamacpp', props: { ggufRepo: 'LiquidAI/LFM3-Audio-2B-GGUF', ttsFlags: '--tts-lang ja' } }); + assert.match(result, /```bash\nhf download[^`]*\nllama-tts/); + assert.match(result, /-p "<__media__>"/); + assert.match(result, /--tts-lang ja -o out.wav/); + assert.doesNotMatch(result, /undefined|<\*\*media\*\*>/); +}); + +test('all checked-in model quickstarts match the shared templates', () => { + for (const file of fs.readdirSync('lfm/models').filter((name) => name.endsWith('.mdx'))) { + const source = fs.readFileSync(`lfm/models/${file}`, 'utf8'); + assert.equal(materialize(source), source, file); + } +}); diff --git a/scripts/supplementOpenApi.mjs b/scripts/supplementOpenApi.mjs new file mode 100644 index 0000000..5bfcd47 --- /dev/null +++ b/scripts/supplementOpenApi.mjs @@ -0,0 +1,173 @@ +import fs from 'node:fs'; +import { fileURLToPath } from 'node:url'; + +const string = (description) => ({ type: 'string', ...(description ? { description } : {}) }); +const object = (properties, required = []) => ({ type: 'object', properties, ...(required.length ? { required } : {}) }); +const array = (items) => ({ type: 'array', items }); +const enumeration = (...values) => ({ type: 'string', enum: values }); +const ref = (name) => ({ $ref: `#/components/schemas/${name}` }); +const probability = { type: 'number', minimum: 0, maximum: 1 }; +const nullable = (schema) => ({ anyOf: [schema, { type: 'null' }] }); +const structured = { anyOf: [{ type: 'string' }, { type: 'object', additionalProperties: true }, { type: 'array', items: {} }] }; +const dictionary = (schema) => ({ type: 'object', additionalProperties: schema }); +const pair = (items) => ({ type: 'array', items, minItems: 2, maxItems: 2 }); +const textPart = object({ type: { const: 'text' }, text: string() }, ['type', 'text']); +const imagePart = object({ type: { const: 'image_url' }, image_url: object({ url: string('Public HTTP(S) image URL or base64 image data URL.'), detail: enumeration('auto', 'low', 'high') }, ['url']) }, ['type', 'image_url']); +const audioPart = object({ type: { const: 'input_audio' }, input_audio: object({ data: string('Base64 WAV bytes, without a data URL prefix.'), format: { const: 'wav', type: 'string' } }, ['data', 'format']) }, ['type', 'input_audio']); +const functionCall = object({ name: string(), arguments: string('JSON-encoded function arguments.') }, ['name', 'arguments']); +const toolCall = object({ id: string(), type: { const: 'function', type: 'string' }, function: functionCall }, ['id', 'type', 'function']); +const toolDefinition = object({ type: { const: 'function', type: 'string' }, function: object({ name: string(), description: string(), parameters: { type: 'object', additionalProperties: true, description: 'JSON Schema for function arguments.' }, strict: { type: 'boolean' } }, ['name']) }, ['type', 'function']); +const replyAudio = object({ id: string(), data: string('Base64 audio bytes.'), transcript: string(), expires_at: { type: 'integer' } }); +const replyMessage = object({ role: { const: 'assistant' }, content: nullable(string()), reasoning: nullable(string('Reasoning text when returned by the model/parser.')), reasoning_content: nullable(string('Provider-compatible reasoning field, when returned.')), tool_calls: array(ref('FunctionToolCall')), audio: ref('ReplyAudio') }, ['role']); +const span = pair({ type: 'integer', minimum: 0 }); +const read = { text: nullable(string()), span: nullable(span), found: probability, path: string('JSON Pointer for a span in a JSON state, when provided.') }; +const edges = object({ top: probability, bottom: probability, left: probability, right: probability }, ['top', 'bottom', 'left', 'right']); +const counted = { count: { type: 'integer', minimum: 0 }, at_least: { type: 'boolean' }, presence: array(probability) }; +const question = (type, fields = {}, required = []) => object({ type: { const: type, type: 'string' }, instructions: structured, ...fields }, ['type', 'instructions', ...required]); +const answer = (type, fields) => object({ type: { const: type, type: 'string' }, ...fields }, ['type', ...Object.keys(fields).filter((name) => name !== 'path')]); + +export function supplement(spec) { + spec.components.schemas ??= {}; + Object.assign(spec.components.schemas, { + FunctionToolCall: toolCall, + FunctionTool: toolDefinition, + ChatMessage: { + oneOf: [ + object({ role: enumeration('system', 'developer'), content: { anyOf: [string(), array(textPart)] }, name: string() }, ['role', 'content']), + object({ role: { const: 'user', type: 'string' }, content: { anyOf: [string(), array({ oneOf: [textPart, imagePart, audioPart] })] }, name: string() }, ['role', 'content']), + { ...object({ role: { const: 'assistant', type: 'string' }, content: nullable({ anyOf: [string(), array(textPart)] }), reasoning: nullable(string()), reasoning_content: nullable(string()), tool_calls: array(ref('FunctionToolCall')), name: string() }, ['role']), anyOf: [{ required: ['content'] }, { required: ['tool_calls'] }] }, + object({ role: { const: 'tool', type: 'string' }, content: { anyOf: [string(), array({ oneOf: [textPart, imagePart] })] }, tool_call_id: string() }, ['role', 'content', 'tool_call_id']), + ], + description: 'Role-specific OpenAI-compatible messages. Tool results must use the corresponding tool_call_id. Preserve returned reasoning with an assistant tool-call turn when the model requires it. Earlier spoken replies must be sent as their transcript in content; audio.id alone is not supported.', + }, + ReplyAudio: replyAudio, + DecisionQuestion: { + oneOf: [ + question('noul', { criteria: nullable(object({ true: structured, false: structured })) }), + question('choice', { multiple: { type: 'boolean', default: false }, criteria: { ...dictionary(nullable(structured)), minProperties: 2, maxProperties: 255 } }, ['criteria']), + question('score', { criteria: { ...array(structured), minItems: 2, maxItems: 10 } }, ['criteria']), + question('text'), question('date'), + question('number', { unit: string(), range: { ...pair({ type: 'number' }), description: 'Ascending [low, high] interval for estimation. Without range, read a number from the state.' }, step: { type: 'number', exclusiveMinimum: 0, description: 'Requires range and must divide it into equal parts.' } }), + question('box'), + question('boxes', { max: { type: 'integer', minimum: 1, maximum: 64 } }), + question('spans', { max: { type: 'integer', minimum: 1, maximum: 64 } }), + ], + description: 'Named typed question. box and boxes require exactly one image. Instructions are written text or JSON; send audio clips in the request audio array, not as spoken instructions.', + }, + DecisionAnswer: { + oneOf: [ + answer('noul', { noul: probability }), + answer('choice', { choice: string(), probabilities: dictionary(probability), confidence: probability }), + answer('choice', { choices: array(string()), probabilities: dictionary(probability) }), + answer('score', { score: { type: 'number' }, legend: dictionary(string()), probabilities: dictionary(probability), confidence: probability }), + answer('text', read), + answer('date', { date: nullable(string()), ...read }), + answer('number', { number: nullable({ type: 'number' }), unit: nullable(string()), ...read }), + answer('number', { number: { type: 'number' }, interval: pair({ type: 'number' }), unit: nullable(string()) }), + answer('box', { box: nullable(edges), found: probability, confidence: probability }), + answer('boxes', { boxes: array(object({ box: edges, found: probability, confidence: probability }, ['box', 'found', 'confidence'])), ...counted }), + answer('spans', { spans: array(object(read, ['text', 'span', 'found'])), ...counted }), + ], + description: 'An answer for the question under the same key. Read values are null when found < 0.5. Spans are [start, end) Unicode code-point offsets into the state (JSON states use two-space indentation). Box edges are fractions of the image. Estimate interval is [p10, p90].', + }, + ApiError: object({ error: object({ message: string(), type: string(), param: nullable(string()), code: nullable(string()) }, ['message', 'type', 'param', 'code']) }, ['error']), + }); + const chat = spec.paths['/openai/v1/chat/completions'].post; + const body = chat.requestBody.content['application/json'].schema; + body.properties.messages.items = ref('ChatMessage'); + body.properties.messages.minItems = 1; + body.properties.modalities.items = enumeration('text', 'audio'); + body.properties.audio.properties = { format: enumeration('pcm16', 'wav'), voice: { anyOf: [string(), object({ id: string() }, ['id'])], description: 'Accepted for compatibility; does not change the voice.' } }; + Object.assign(body.properties, { + temperature: { type: 'number', description: 'Sampling temperature; supported values depend on the model.' }, + top_p: { type: 'number', description: 'Nucleus sampling probability.' }, + top_k: { type: 'integer', description: 'Top-k sampling, when supported by the model.' }, + repetition_penalty: { type: 'number' }, + max_tokens: { type: 'integer', minimum: 1, description: 'Maximum generated tokens, including reasoning. Leave enough room for a final answer.' }, + max_completion_tokens: { type: 'integer', minimum: 1, description: 'OpenAI-compatible output budget; model support may vary. Use one output-budget field per request.' }, + stop: { anyOf: [string(), array(string())] }, + tools: array(ref('FunctionTool')), + tool_choice: { anyOf: [enumeration('none', 'auto', 'required'), object({ type: { const: 'function' }, function: object({ name: string() }, ['name']) }, ['type', 'function'])] }, + response_format: { oneOf: [object({ type: { const: 'text' } }, ['type']), object({ type: { const: 'json_object' } }, ['type']), object({ type: { const: 'json_schema' }, json_schema: object({ name: string(), description: string(), schema: { type: 'object', additionalProperties: true }, strict: { type: 'boolean' } }, ['name', 'schema']) }, ['type', 'json_schema'])], description: 'Structured output format, where supported by the selected model.' }, + stream_options: object({ include_usage: { type: 'boolean' } }), + user: string('Optional caller identifier.'), + }); + const choice = object({ index: { type: 'integer' }, message: replyMessage, finish_reason: nullable(string()) }, ['index', 'message', 'finish_reason']); + chat.responses['200'].content['application/json'].schema.properties.choices.items = choice; + chat.responses['200'].content['text/event-stream'] = { + schema: { type: 'string', description: 'Server-sent events when stream=true. Each data event is a chat.completion.chunk with choices[].delta (content, reasoning, tool_calls, or audio) and finish_reason. A usage chunk may have an empty choices array. The stream ends with data: [DONE].' }, + example: 'data: {"object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}\n\ndata: [DONE]\n\n', + }; + chat.description = 'Generate a model response for a chat conversation. See [Text generation](https://docs.liquid.ai/api/guides/text-generation). Sampling, tool calling, reasoning, and structured output support depend on the selected model. With stream=true the response is text/event-stream, rather than a JSON completion.'; + + const decisions = spec.paths['/decisions/v1/systemone'].post; + const decisionBody = decisions.requestBody.content['application/json'].schema; + decisionBody.properties.model.description = 'A decision model id from GET /decisions/v1/models, such as d1.2 or d1.2-ultra. Use the exact id returned for your organization.'; + decisionBody.properties.questions = { ...dictionary(ref('DecisionQuestion')), minProperties: 1, maxProperties: 128, description: 'Up to 128 named questions. Each question reads the state and media. d1.2 and d1.2-ultra allow 65,536 input tokens per question and 250,000 bytes of text; the entire request must fit the 4.5 MiB body limit.' }; + const media = (types) => ({ oneOf: [string('Base64 data URL with a matching media content type.'), object({ content_type: enumeration(...types), base64: string('Base64-encoded file bytes.') }, ['content_type', 'base64'])] }); + decisionBody.properties.images.items = media(['image/jpeg', 'image/png', 'image/webp']); + decisionBody.properties.images.maxItems = 8; + decisionBody.properties.images.description = 'Up to 8 JPEG, PNG, or WebP images as base64 data URLs or {content_type, base64} objects. Remote URLs are not accepted. Each image is at most 5 MiB, subject to the smaller 4.5 MiB whole-request limit. box and boxes require exactly one image. Check input_modalities in GET /decisions/v1/models for model support.'; + decisionBody.properties.audio = { ...array(media(['audio/wav', 'audio/mpeg', 'audio/flac', 'audio/ogg'])), maxItems: 8, description: 'Up to 8 WAV, MP3, FLAC, or OGG clips, at most 300 seconds combined, subject to the whole-request body limit. The declared content type must match the bytes. Check input_modalities for model support. Video is not accepted.' }; + const decisionReply = decisions.responses['200'].content['application/json'].schema; + decisionReply.properties.answers = { ...dictionary(ref('DecisionAnswer')), description: 'One typed answer per question id, under the same keys.' }; + decisions.description = 'Answer named typed questions about text, JSON, images, or audio. Supports noul, choice (including multiple=true), score, text, date, number, box, boxes, and spans. See [Decisions](https://docs.liquid.ai/api/guides/decisions) for examples. The hosted endpoint does not accept video or spoken question instructions; open-weight model APIs have different input shapes.'; + for (const [operation, statuses] of [[chat, ['400','401','402','403','404','413','422','502','503','504']], [decisions, ['400','401','402','403','404','413','422','502','503','504']]]) { + const descriptions = { 400: 'Invalid request or unsupported modality.', 401: 'Missing or invalid API key.', 402: 'Insufficient credit.', 403: 'Access denied.', 404: 'Unknown or unavailable model id.', 413: 'Request body exceeds the endpoint limit.', 422: 'Request validation failed or the model input limit was exceeded.', 502: 'Inference backend failed.', 503: 'Model temporarily unavailable.', 504: 'Inference deadline exceeded.' }; + for (const status of statuses) operation.responses[status] = { description: descriptions[status], content: { 'application/json': { schema: ref('ApiError') } } }; + operation.responses['429'].content['application/json'].schema = ref('ApiError'); + } + const jsonReply = (operation) => operation.responses['200'].content['application/json'].schema; + const model = object({ id: string(), object: { const: 'model' }, created: { type: 'integer' }, owned_by: string() }, ['id', 'object', 'created', 'owned_by']); + spec.components.schemas.Model = model; + jsonReply(spec.paths['/openai/v1/models'].get).properties.data.items = ref('Model'); + spec.paths['/openai/v1/models/{model}'].get.responses['200'].content['application/json'].schema = ref('Model'); + const decisionModel = object({ name: string('Model id to pass in the request.'), description: string(), release_date: { type: 'string', format: 'date' }, input_modalities: array(enumeration('text', 'image', 'audio')) }, ['name','description','release_date','input_modalities']); + spec.components.schemas.DecisionModel = decisionModel; + const decisionModels = spec.paths['/decisions/v1/models'].get; + jsonReply(decisionModels).properties.models.items = ref('DecisionModel'); + jsonReply(decisionModels).properties.models.description = 'Decision models available to your organization, including accepted input modalities. Current d1.2 models accept text, images, and audio.'; + const decisionExample = decisionModels.responses['200'].content['application/json'].example; + if (decisionExample?.models) decisionExample.models = [{ name: 'd1.2', description: 'Typed decisions over text, images, and audio.', release_date: decisionExample.models[0]?.release_date ?? '2026-01-01', input_modalities: ['text','image','audio'] }]; + const fileSchema = structuredClone(spec.components.schemas.File ?? jsonReply(spec.paths['/openai/v1/files/{id}'].get)); + fileSchema.properties.expires_at = { type: 'integer', description: 'Unix expiry timestamp, when an expiry is set.' }; + spec.components.schemas.File = fileSchema; + spec.paths['/openai/v1/files/{id}'].get.responses['200'].content['application/json'].schema = ref('File'); + jsonReply(spec.paths['/openai/v1/files'].get).properties.data.items = ref('File'); + const batch = structuredClone(spec.components.schemas.Batch ?? jsonReply(spec.paths['/openai/v1/batches'].post)); + for (const field of ['created_at','in_progress_at','finalizing_at','completed_at','failed_at','expires_at','cancelled_at']) batch.properties[field] = { type: 'integer', description: 'Unix timestamp in seconds; optional until the corresponding event occurs.' }; + batch.properties.request_counts = object({ total: { type: 'integer' }, completed: { type: 'integer' }, failed: { type: 'integer' } }, ['total','completed','failed']); + batch.properties.errors = object({ object: { const: 'list' }, data: array(object({ code: string(), message: string(), param: nullable(string()), line: { type: 'integer' } })) }); + batch.properties.metadata = dictionary(string()); + spec.components.schemas.Batch = batch; + for (const [route, method] of [['/openai/v1/batches','post'],['/openai/v1/batches/{id}','get'],['/openai/v1/batches/{id}/cancel','post']]) spec.paths[route][method].responses['200'].content['application/json'].schema = ref('Batch'); + jsonReply(spec.paths['/openai/v1/batches'].get).properties.data.items = ref('Batch'); + const content = spec.paths['/openai/v1/files/{id}/content'].get; + delete content.responses['200']; + content.responses['302'] = { description: 'Redirect to a short-lived presigned download URL. Use curl -L to retrieve the file bytes.', headers: { Location: { required: true, schema: { type: 'string', format: 'uri' }, description: 'Presigned file download URL.' } } }; + spec.paths['/openai/v1/files'].get.description = 'List all files for the organization in descending creation order. Pagination parameters are not supported.'; + for (const operations of Object.values(spec.paths)) { + for (const operation of Object.values(operations)) { + for (const sample of operation['x-codeSamples'] ?? []) { + sample.source = sample.source.replace(/\$DECISION_MODEL_ID/g, 'd1.2').replace(/\$MODEL_ID/g, 'lfm3-1.7b'); + } + } + } + spec.info.description = spec.info.description.replace(/\*\*Decision models\*\*[\s\S]*$/, '**Decision models** — `POST /decisions/v1/systemone` answers typed questions using models such as `d1.2` and `d1.2-ultra`.'); + function fillModelExamples(value) { + if (!value || typeof value !== 'object') return; + for (const [key, child] of Object.entries(value)) { + if (typeof child === 'string') value[key] = child.replaceAll('$DECISION_MODEL_ID', 'd1.2').replaceAll('$MODEL_ID', 'lfm3-1.7b'); + else fillModelExamples(child); + } + } + fillModelExamples(spec); + return spec; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const file = process.argv[2] ?? 'api/openapi.json'; + const spec = supplement(JSON.parse(fs.readFileSync(file, 'utf8'))); + fs.writeFileSync(file, `${JSON.stringify(spec, null, 2)}\n`); + console.log(`Updated endpoint documentation in ${file}`); +} diff --git a/scripts/supplementOpenApi.test.mjs b/scripts/supplementOpenApi.test.mjs new file mode 100644 index 0000000..c074347 --- /dev/null +++ b/scripts/supplementOpenApi.test.mjs @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import test from 'node:test'; +import { supplement } from './supplementOpenApi.mjs'; + +const spec = JSON.parse(fs.readFileSync('api/openapi.json', 'utf8')); +test('schema supplements are idempotent and the checked-in export is current', () => { + assert.deepEqual(supplement(structuredClone(spec)), spec); +}); + +test('every local schema reference resolves', () => { + function visit(value) { + if (!value || typeof value !== 'object') return; + if (value.$ref?.startsWith('#/')) { + const target = value.$ref.slice(2).split('/').reduce((node, key) => node?.[key.replaceAll('~1', '/').replaceAll('~0', '~')], spec); + assert.ok(target, value.$ref); + } + Object.values(value).forEach(visit); + } + visit(spec); +}); + +test('request and response examples retain complete object and list schemas', () => { + for (const operations of Object.values(spec.paths)) { + for (const operation of Object.values(operations)) { + for (const response of Object.values(operation.responses ?? {})) { + const json = response.content?.['application/json']; + if (json?.example && json.schema?.properties?.data) { + assert.ok(json.schema.properties.data.items.$ref); + } + } + } + } + const content = spec.paths['/openai/v1/files/{id}/content'].get.responses; + assert.ok(content['302'].headers.Location); + assert.equal(content['200'], undefined); +}); diff --git a/scripts/validation/claude-audit-followup.md b/scripts/validation/claude-audit-followup.md new file mode 100644 index 0000000..ca7acb1 --- /dev/null +++ b/scripts/validation/claude-audit-followup.md @@ -0,0 +1,38 @@ +# Documentation audit follow-up + +Checked on 2026-11-19 in PR #186, after merging current main. This record is repository maintenance content and must remain excluded by `.mintignore`. + +## Remaining findings addressed + +| Findings | Resolution | +| --- | --- | +| G6-01 | Follow the file-content redirect with `curl -L`. | +| G6-02, G6-03, G6-05, G6-10 | Add typed chat messages, request controls, tools, structured output, streaming, typed decision questions/answers, audio, model/file/batch lists, timestamps, and errors. Model examples use current ids. The content download is a 302, not a JSON 200. | +| G6-04, G6-14 | Remove unverified blanket hosted context values; direct readers to Console for hosted limits. Identify the direct online inference endpoints covered by ZDR and distinguish stored batch files and other surfaces. Checked against current endpoint validation and capture behavior, without assuming native checkpoint limits apply to hosting. | +| G3-08 | Replace the undefined Unsloth dataset, obsolete trainer argument, and incorrect LoRA targets with a complete, pinned two-step example. Assert adapter coverage rather than silently training only a subset. | +| G3-09, G3-10 | Use Liquid Finetune's `envs/rocm` environment and actual `AGENTS.md` guidance. | +| G3-16, G3-19, G3-20, G3-23 | Use native vLLM 0.34.0 LFM3 support, modern quantization configuration and HF authentication, and preserve current-turn reasoning in tool history. | +| G3-21 | Remove the blanket internal-evaluation exemption that the license does not state. | +| G7-01, G7-02, G7-03, G7-05, G7-06, G7-07, G7-08, G7-10 | Correct browser training targets, transcript filename/download path, invoice watch options, dataset ownership setup, W&B secrets, working directories, and Modal volume paths. | +| G7-11, G7-12, G7-14, G7-16, G7-17, G7-18, G7-25 | Correct the home-assistant baseline repository, wildfire/browser/racer setup, the racing game's legacy model default, translation checkpoint defaults, and image/audio descriptions. Scope historical measurements to their original models. | +| G5-01–G5-10 | Use stable 0.10.9 pins/checksums, update Swift configuration/media factories, handle in-band Error events, use SKIE cloud streaming, correct bridged function types/call labels and sideloaded argument lists, and remove instructions to copy unpublished audio adapters. Distinguish API integration fragments from a complete sample app. | +| G5-05, G5-06 | Explicitly mark the LEAP catalog/auth/bundling service unavailable and point to current downloads or local sideloading. Preserve useful archived SDK documentation. | +| G8-10 | Add explicit redirects for the historical routes and their previously missing wildcard destinations. Restore the useful pre-trained LFM2.5 base checkpoint page without presenting Instruct conversions as base weights. | +| G1-10, G2-16 | Materialize shared quickstarts as literal Markdown code fences on 26 model pages. Keep template parameters in generation comments and check freshness in CI. | +| G4-08 | Replace the removed Python grammar helper with current server JSON-schema support and the C++ helper. | +| G1-01, G1-03, G2-03, G2-09 | Document d1 Omni video frames, include Extract models in the 128K summary, fix the 230M recommendation, and complete Japanese ASR/TTS. Decode Japanese text after collecting tokens to avoid split UTF-8 characters. | + +These are the outstanding substantive findings from the comparison, plus related defects found while checking their sources. Findings already resolved in #183 or the earlier #186 commits are preserved. Intentional navigation choices and deprecated model coverage are not publication exclusions. + +## Executed validation + +- Unsloth on Modal H100: Python 3.12, Unsloth/Unsloth Zoo 2026.11.7, Torch 2.14.0, Transformers 5.17.0, TRL 1.15.0, PEFT 0.21.3. Two training steps completed, all eight requested module types received adapters, and the adapter was saved. This is a setup smoke test, not a quality benchmark. +- Restored LFM2.5 base example: Transformers 5.23.0 / Torch 2.15.0 in Modal; generated 32 completion tokens from a raw prompt. +- Japanese audio: liquid-audio 1.3.0 in Modal. Transcribed the model card's Japanese recording, retained the expected phrase without Unicode replacement characters, and generated a nonempty 24 kHz WAV. Tested the exact ASR/TTS code blocks with their shared initialization. +- d1 Omni video: Transformers 5.23.0 on Modal H100. Executed the exact video block against a two-second synthetic MP4, sampled two frames at 1 fps, and received a valid probability. This checks the video input API, not decision quality. +- Swift 6.2.3, macOS 15 SDK, released 0.10.9 XCFrameworks: type-checked configuration, throwing media conversion, all six response variants, function registration, cloud streaming/hybrid routing, provider configuration, and local text/vision/audio sideloading. No iOS device runtime test was performed. +- Invoice project: installed its dependencies and ran the real `watch --help`; `--output` is absent. Browser-control: dry-ran the documented Makefile target. Home-assistant and satellite dataset, secret, tracker, and checkpoint paths were checked against their current source/configs and Liquid Finetune's output-directory resolver. Full training/data publication jobs were not launched. +- OpenAPI 3.1 document validated with `openapi-spec-validator`; local references and deterministic supplements checked. No authenticated hosted inference/batch execution was performed in this follow-up. +- Ten publication/generation/schema regression tests, generated-snippet freshness, link snapshot, Python/shell syntax checks, Mintlify build validation, and internal link scan passed. + +Preview HTTP routes, redirects, Markdown exports, and excluded internal files are checked after deployment. Full GPU framework/notebook checks from #183 and the speculative decoding tests from earlier #186 commits remain recorded in `lfm3-modernization.md` and the previous PR evidence. diff --git a/snippets/quickstart/text-transformers.mdx b/snippets/quickstart/text-transformers.mdx index 117b73f..2e0244e 100644 --- a/snippets/quickstart/text-transformers.mdx +++ b/snippets/quickstart/text-transformers.mdx @@ -1,4 +1,4 @@ -export const TextTransformers = ({ modelId, samplingParams }) => ( +export const TextTransformers = ({ modelId, samplingParams, maxTokens = 512 }) => (

Install:

@@ -24,7 +24,7 @@ inputs = tokenizer.apply_chat_template( return_dict=True, ).to(model.device) -output = model.generate(**inputs, ${samplingParams}max_new_tokens=512) +output = model.generate(**inputs, ${samplingParams}max_new_tokens=${maxTokens}) input_length = inputs["input_ids"].shape[1] response = tokenizer.decode(output[0][input_length:], skip_special_tokens=True) print(response)`} From d9e818ec9d469bf917a4c735803862b476308e2f Mon Sep 17 00:00:00 2001 From: alay2shah Date: Thu, 19 Nov 2026 10:15:09 -0600 Subject: [PATCH 5/5] Track restored base checkpoint in URL regression snapshot --- link-snapshot.yaml | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/link-snapshot.yaml b/link-snapshot.yaml index a03b834..82b9943 100644 --- a/link-snapshot.yaml +++ b/link-snapshot.yaml @@ -243,6 +243,7 @@ active: - /lfm/models/lfm2-vl-1.6b - /lfm/models/lfm2-vl-3b - /lfm/models/lfm2-vl-450m + - /lfm/models/lfm25-1.2b-base - /lfm/models/lfm25-1.2b-instruct - /lfm/models/lfm25-1.2b-jp - /lfm/models/lfm25-1.2b-jp-202606 @@ -280,6 +281,4 @@ active: # # Or, if you want the reason inline: # - url: /lfm/another-old-thing # reason: "Page retired in DOC-12; no substitute exists." -deleted: - - url: /lfm/models/lfm25-1.2b-base - reason: Base models are not included in the documentation. +deleted: []