Instructions to use LiquidAI/LFM2.5-Audio-1.5B-GGUF with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use LiquidAI/LFM2.5-Audio-1.5B-GGUF with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16 # Run inference directly in the terminal: llama cli -hf LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16 # Run inference directly in the terminal: llama cli -hf LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16 # Run inference directly in the terminal: ./build/bin/llama cli -hf LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
Use Docker
docker model run hf.co/LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
- Llama new
- LM Studio
- Jan
- Ollama
How to use LiquidAI/LFM2.5-Audio-1.5B-GGUF with Ollama:
ollama run hf.co/LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
- Unsloth Desktop
- Pi
How to use LiquidAI/LFM2.5-Audio-1.5B-GGUF with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use LiquidAI/LFM2.5-Audio-1.5B-GGUF with Docker Model Runner:
docker model run hf.co/LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
- Lemonade
How to use LiquidAI/LFM2.5-Audio-1.5B-GGUF with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
Run and chat with the model
lemonade run user.LFM2.5-Audio-1.5B-GGUF-F16
List all available models
lemonade list
- Hermes Agent
How to use LiquidAI/LFM2.5-Audio-1.5B-GGUF with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:9931/v1 hermes config set model.default LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use LiquidAI/LFM2.5-Audio-1.5B-GGUF with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:9931/v1 \ --custom-model-id "LiquidAI/LFM2.5-Audio-1.5B-GGUF:F16" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Add readme, license, demo and example
Browse filesFiles changed (4)
- LICENSEAdded+41
- README.mdAdded+89
- demo.mp4Added+3
- liquid_audio_chat.pyAdded+554
1234567891011121314151617181920212223242526272829303132333435363738394041LICENSE TEXT
LFM Open License v1.0
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by this document.
"Licensor" shall mean Liquid AI, Inc.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work.
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
"Commercial Use" shall mean any use of the Work for direct or indirect commercial advantage or monetary compensation.
"Qualified Non-Profit Organization" shall mean a Legal Entity that is organized and operated exclusively for religious, charitable, scientific, testing for public safety, literary, or educational purposes, and which is exempt from federal income tax under Section 501(c)(3) of the United States Internal Revenue Code of 1986, as amended, or any equivalent non-profit or charitable organization in a foreign jurisdiction.
"Non-Commercial or Research Purposes" shall mean purposes that do not involve any use of the Work or a Derivative Work for Commercial Use.
"Threshold" shall mean annual revenue of 10 million United States dollars ($10,000,000) or more.
2. Grant of Copyright License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, including the Commercial Use limitation set forth in Section 5, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Commercial Use Limitation.
(a) The rights granted under this License for Commercial Use are conditioned upon You or Your Legal Entity not exceeding the Threshold.
(b) Any Commercial Use of the Work or a Derivative Work by a Legal Entity that exceeds the Threshold is not licensed under this Agreement.
(c) The Threshold shall not apply to a Qualified Non-Profit Organization's use of the Work or a Derivative Work for Non-Commercial or Research Purposes.
6. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
7. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except for the reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
8. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
9. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
10. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
11. Termination. This License will terminate automatically and immediately if You fail to comply with any of its terms and conditions. Upon termination, You must cease all use of the Work and any Derivative Works and delete all copies in Your possession.
END OF TERMS AND CONDITIONS1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889---license: otherlicense_name: lfm1.0license_link: LICENSElanguage:- entags:- liquid- lfm2.5- edge- llama.cpp- audio- speech- ggufbase_model:- LiquidAI/LFM2.5-Audio-1.5B---
<div align="center"> <img src="https://cdn-uploads.huggingface.co/production/uploads/61b8e2ba285851687028d395/2b08LKpev0DNEk6DlnWkY.png" alt="Liquid AI" style="width: 100%; max-width: 100%; height: auto; display: inline-block; margin-bottom: 0.5em; margin-top: 0.5em;" /> <div style="display: flex; justify-content: center; gap: 0.5em; margin-bottom: 1em;"> <a href="https://playground.liquid.ai/"><strong>Try LFM</strong></a> • <a href="https://docs.liquid.ai/lfm"><strong>Documentation</strong></a> • <a href="https://leap.liquid.ai/"><strong>LEAP</strong></a> </div></div>
# LFM2.5-Audio-1.5B
Find more details in the original model card: https://huggingface.co/LiquidAI/LFM2.5-Audio-1.5B
## Runners
`runners` folder contains runners for various architectures including
- llama-liquid-audio-cli- llama-liquid-audio-server
# 🏃 How to run LFM2.5
## CLI
Set env variables.```export CKPT=/path/to/LFM2.5-Audio-1.5B-GGUFexport INPUT_WAV=/path/to/input.wavexport OUTPUT_WAV=/path/to/output.wav```
### ASR (audio -> text)
```bash./llama-liquid-audio-cli -m $CKPT/LFM2.5-Audio-1.5B-Q4_0.gguf -mm $CKPT/mmproj-LFM2.5-Audio-1.5B-Q4_0.gguf -mv $CKPT/vocoder-LFM2.5-Audio-1.5B-Q4_0.gguf --tts-speaker-file $CKPT/tokenizer-LFM2.5-Audio-1.5B-Q4_0.gguf -sys "Perform ASR." --audio $INPUT_WAV```
### TTS (text -> audio)
```bash./llama-liquid-audio-cli -m $CKPT/LFM2.5-Audio-1.5B-Q4_0.gguf -mm $CKPT/mmproj-LFM2.5-Audio-1.5B-Q4_0.gguf -mv $CKPT/vocoder-LFM2.5-Audio-1.5B-Q4_0.gguf --tts-speaker-file $CKPT/tokenizer-LFM2.5-Audio-1.5B-Q4_0.gguf -sys "Perform TTS." -p "Hi, how are you?" --output $OUTPUT_WAV```
### Interleaved (audio/text -> audio + text)
```bash./llama-liquid-audio-cli -m $CKPT/LFM2.5-Audio-1.5B-Q4_0.gguf -mm $CKPT/mmproj-LFM2.5-Audio-1.5B-Q4_0.gguf -mv $CKPT/vocoder-LFM2.5-Audio-1.5B-Q4_0.gguf --tts-speaker-file $CKPT/tokenizer-LFM2.5-Audio-1.5B-Q4_0.gguf -sys "Respond with interleaved text and audio." --audio $INPUT_WAV --output $OUTPUT_WAV```
## Server
Start server```export CKPT=/path/to/LFM2.5-Audio-1.5B-GGUF./llama-liquid-audio-server -m $CKPT/LFM2.5-Audio-1.5B-Q4_0.gguf -mm $CKPT/mmproj-LFM2.5-Audio-1.5B-Q4_0.gguf -mv $CKPT/vocoder-LFM2.5-Audio-1.5B-Q4_0.gguf --tts-speaker-file $CKPT/tokenizer-LFM2.5-Audio-1.5B-Q4_0.gguf```
Use `liquid_audio_chat.py` script to communicate with the server.
```bashuv run liquid_audio_chat.py```
# Demo
<video controls src="demo.mp4"></video>123version https://git-lfs.github.com/spec/v1oid sha256:8b43013964e179460e36fe5f6a4166df031a753f6988b699c1f194c5e697a9bbsize 41272798123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554#!/usr/bin/env python3# /// script# requires-python = ">=3.10"# dependencies = [# "numpy",# "pyaudio",# "soundfile",# "openai",# "prompt_toolkit",# ]# ///"""Interactive CLI chat tool for LFM2.5-Audio server."""
import argparseimport base64import ioimport osimport shutilimport structimport subprocessimport sysimport tempfileimport threadingimport timefrom queue import Queue
import numpy as npimport pyaudioimport soundfile as sffrom openai import OpenAIfrom prompt_toolkit import promptfrom prompt_toolkit.history import InMemoryHistoryfrom prompt_toolkit.auto_suggest import AutoSuggestFromHistory
# Suppress ALSA/JACK warnings during PyAudio initimport osimport contextlib
@contextlib.contextmanagerdef suppress_stderr(): """Temporarily redirect stderr to /dev/null.""" devnull = os.open(os.devnull, os.O_WRONLY) old_stderr = os.dup(2) os.dup2(devnull, 2) try: yield finally: os.dup2(old_stderr, 2) os.close(devnull) os.close(old_stderr)
class AudioPlayer: """Streams audio samples to speakers via PyAudio (non-blocking)."""
def __init__(self, sample_rate=24000): self.sample_rate = sample_rate self.all_samples = [] self.pyaudio = None self.stream = None self.queue = Queue() self.thread = None self.running = False
def _playback_thread(self): """Background thread that writes audio to the stream.""" while self.running or not self.queue.empty(): try: pcm_data = self.queue.get(timeout=0.1) if self.stream: self.stream.write(pcm_data) except: pass
def start(self): """Start the audio stream.""" self.all_samples = [] self.running = True with suppress_stderr(): self.pyaudio = pyaudio.PyAudio() self.stream = self.pyaudio.open( format=pyaudio.paFloat32, channels=1, rate=self.sample_rate, output=True, ) self.thread = threading.Thread(target=self._playback_thread, daemon=True) self.thread.start()
def add_samples(self, samples): """Add samples to playback queue (non-blocking).""" self.all_samples.extend(samples) pcm_data = np.array(samples, dtype=np.float32).tobytes() self.queue.put(pcm_data)
def stop(self, output_file="output.wav"): """Stop the audio stream.""" self.running = False if self.thread: self.thread.join() self.thread = None if self.stream: self.stream.stop_stream() self.stream.close() self.stream = None if self.pyaudio: self.pyaudio.terminate() self.pyaudio = None
class AudioRecorder: """Records audio from microphone using PyAudio."""
def __init__(self, sample_rate=16000): self.sample_rate = sample_rate self.recording = False self.samples = [] self.available = self._check_available()
def _check_available(self): """Check if audio input is available.""" try: with suppress_stderr(): p = pyaudio.PyAudio() has_input = p.get_default_input_device_info() is not None p.terminate() return has_input except Exception: return False
def record(self, duration=None): """Record audio. Press Enter to stop if duration is None.""" if not self.available: print("[No microphone available. Use /wav to load audio files.]") return None
self.samples = [] self.recording = True
print("Recording... (Press Enter to stop)")
# Start recording in background stop_event = threading.Event()
def record_audio(): try: with suppress_stderr(): p = pyaudio.PyAudio() stream = p.open( format=pyaudio.paFloat32, channels=1, rate=self.sample_rate, input=True, frames_per_buffer=1024, ) while not stop_event.is_set(): data = stream.read(1024, exception_on_overflow=False) samples = np.frombuffer(data, dtype=np.float32) self.samples.extend(samples.tolist()) stream.stop_stream() stream.close() p.terminate() except Exception as e: print(f"[Recording error: {e}]")
record_thread = threading.Thread(target=record_audio) record_thread.start()
# Wait for Enter key input() stop_event.set() record_thread.join()
self.recording = False if self.samples: print(f"Recorded {len(self.samples) / self.sample_rate:.2f}s of audio")
return self.samples if self.samples else None
def to_wav_bytes(self): """Convert recorded samples to WAV bytes.""" if not self.samples: return None buffer = io.BytesIO() sf.write(buffer, np.array(self.samples), self.sample_rate, format="WAV") buffer.seek(0) return buffer.read()
SYSTEM_PROMPTS = { "asr": "Perform ASR.", "tts": "Perform TTS. Use the UK female voice.", "interleaved": "Respond with interleaved text and audio.",}
def create_text_message(text): """Create a text user message.""" return {"role": "user", "content": text}
def create_audio_message(wav_data): """Create an audio user message.""" encoded = base64.b64encode(wav_data).decode("utf-8") return { "role": "user", "content": [ { "type": "input_audio", "input_audio": {"data": encoded, "format": "wav"}, } ], }
def create_stream_single_shot(client, mode, text=None, wav_data=None, max_tokens=512): """Create a single-shot request for ASR/TTS (always resets context).""" messages = [{"role": "system", "content": SYSTEM_PROMPTS[mode]}]
if mode == "asr" and wav_data: messages.append(create_audio_message(wav_data)) elif mode == "tts" and text: messages.append(create_text_message(text))
return client.chat.completions.create( model="", messages=messages, stream=True, max_tokens=max_tokens, extra_body={"reset_context": True}, )
def create_stream_chat(client, messages, max_tokens=512, reset_context=False): """Create a chat request for interleaved mode (maintains context).""" return client.chat.completions.create( model="", messages=messages, stream=True, max_tokens=max_tokens, extra_body={"reset_context": reset_context}, )
def process_stream(stream, audio_player=None): """Process streaming response, playing audio and printing text.""" t0 = time.time() ttft = None text_chunks = [] audio_chunks = [] total_samples = 0 completed = False
for chunk in stream: if chunk.choices[0].finish_reason == "stop": completed = True break
delta = chunk.choices[0].delta
# Handle text if text := delta.content: if ttft is None: ttft = time.time() - t0 text_chunks.append((time.time(), text)) print(text, end="", flush=True)
# Handle audio if hasattr(delta, "audio_chunk") and delta.audio_chunk: if ttft is None: ttft = time.time() - t0 chunk_data = delta.audio_chunk["data"] pcm_bytes = base64.b64decode(chunk_data) samples = struct.unpack(f"<{len(pcm_bytes) // 4}f", pcm_bytes) audio_chunks.append((time.time(), samples)) total_samples += len(samples)
# Print note symbol for audio progress print("♪", end="", flush=True)
if audio_player: audio_player.add_samples(samples)
if text_chunks or audio_chunks: print() # Newline after output
if not completed: print("[Warning: Server disconnected before completion]")
# Calculate and display stats (single line) total_time = time.time() - t0 full_text = "".join(t for _, t in text_chunks)
stats = [] if ttft is not None: stats.append(f"ttft {ttft:.3f}s")
if text_chunks and len(text_chunks) > 1: text_duration = text_chunks[-1][0] - text_chunks[0][0] if text_duration > 0: stats.append(f"text {len(text_chunks)} tok @ {len(text_chunks)/text_duration:.1f} tok/s")
if audio_chunks: # Calculate from ttft to last chunk for accurate throughput first_audio_time = audio_chunks[0][0] last_audio_time = audio_chunks[-1][0] audio_duration = last_audio_time - first_audio_time audio_secs = total_samples / 24000 stats.append(f"audio {audio_secs:.1f}s @ {total_samples/audio_duration:.0f} samples/s")
stats.append(f"total {total_time:.3f}s") print(f"\n[{' | '.join(stats)}]")
return full_text, total_samples
def print_help(): """Print help information.""" print( """Commands: /mode <asr|tts|interleaved> - Switch mode /reset - Reset context (interleaved mode only) /record - Record and transcribe/process audio /wav <path> - Load and transcribe/process audio file /help - Show this help /quit or /exit - Exit the program
Modes: ASR (single-shot): - Use /record or /wav to transcribe audio - Each request is independent
TTS (single-shot): - Type text to synthesize audio - Each request is independent
Interleaved (chat): - Type text or use /record or /wav - Context is maintained across requests - Use /reset to start fresh""" )
def main(): parser = argparse.ArgumentParser(description="Interactive LFM2.5-Audio chat client") parser.add_argument( "--base-url", type=str, default="http://127.0.0.1:8080/v1", help="Server base URL", ) parser.add_argument( "--mode", type=str, choices=["asr", "tts", "interleaved"], default="interleaved", help="Initial mode", ) parser.add_argument( "--max-tokens", type=int, default=512, help="Maximum tokens to generate", ) parser.add_argument( "--no-audio-playback", action="store_true", help="Disable audio playback (save to file instead)", ) args = parser.parse_args()
client = OpenAI(base_url=args.base_url, api_key="dummy") recorder = AudioRecorder() mode = args.mode wav_data = None enable_playback = not args.no_audio_playback
# Check audio capabilities audio_input_ok = recorder.available
# Track if first message in interleaved mode (need to send system prompt) is_first_message = True
# Command history for prompt_toolkit cmd_history = InMemoryHistory()
print("=" * 50) print("LFM2.5-Audio Interactive Chat") print("=" * 50) print(f"Server: {args.base_url}") print("Audio output: pyaudio") print(f"Audio input: {'microphone' if audio_input_ok else 'file only (/wav)'}") print("Type /help for commands") print("=" * 50) print(f"Mode: {mode}" + (" (single-shot)" if mode in ("asr", "tts") else " (chat)"))
while True: try: # Show prompt with mode indicator mode_indicator = {"asr": "[ASR]", "tts": "[TTS]", "interleaved": "[INT]"} audio_indicator = " [audio]" if wav_data else ""
prompt_str = f"{mode_indicator[mode]}{audio_indicator}> " user_input = prompt( prompt_str, history=cmd_history, auto_suggest=AutoSuggestFromHistory(), ).strip()
if not user_input: if mode == "asr" and wav_data: # In ASR mode with audio, pressing Enter transcribes pass else: continue
# Handle commands if user_input.startswith("/"): parts = user_input.split(maxsplit=1) cmd = parts[0].lower() arg = parts[1] if len(parts) > 1 else None
if cmd in ("/quit", "/exit"): print("Goodbye!") break
elif cmd == "/help": print_help() continue
elif cmd == "/mode": if arg in ("asr", "tts", "interleaved"): if arg != mode: mode = arg is_first_message = True print(f"Mode: {mode}" + (" (single-shot)" if mode in ("asr", "tts") else " (chat)")) else: print(f"Already in {mode} mode") else: print("Usage: /mode <asr|tts|interleaved>") continue
elif cmd == "/reset": if mode != "interleaved": print("Reset only available in interleaved mode") continue is_first_message = True print("Context reset") continue
elif cmd == "/record": if mode == "tts": print("Recording not available in TTS mode") continue samples = recorder.record() if samples: wav_data = recorder.to_wav_bytes() # Start inference immediately user_input = "" else: continue
elif cmd == "/wav": if mode == "tts": print("Audio input not available in TTS mode") continue if arg: try: with open(arg, "rb") as f: wav_data = f.read() # Start inference immediately user_input = "" except Exception as e: print(f"Error loading file: {e}") continue else: print("Usage: /wav <path>") continue
else: print(f"Unknown command: {cmd}") continue
# Prepare request based on mode text_input = user_input if user_input and not user_input.startswith("/") else None
if mode == "asr": if not wav_data: print("ASR mode requires audio. Use /record or /wav first.") continue text_input = None # ASR ignores text input elif mode == "tts": if not text_input: print("TTS mode requires text input.") continue wav_data = None # TTS ignores audio input
# Create audio player if needed audio_player = None if enable_playback: audio_player = AudioPlayer() audio_player.start()
try: print() # Blank line before response
if mode in ("asr", "tts"): # Single-shot mode: system + one message, always reset stream = create_stream_single_shot( client, mode, text=text_input, wav_data=wav_data, max_tokens=args.max_tokens ) else: # Interleaved chat mode: only send new messages messages = []
# First message needs system prompt and reset if is_first_message: messages.append({"role": "system", "content": SYSTEM_PROMPTS["interleaved"]})
# Add user message(s) if text_input: messages.append(create_text_message(text_input)) if wav_data: messages.append(create_audio_message(wav_data))
stream = create_stream_chat( client, messages, max_tokens=args.max_tokens, reset_context=is_first_message ) is_first_message = False
response_text, _ = process_stream(stream, audio_player)
except Exception as e: print(f"Error: {e}")
finally: if audio_player: audio_player.stop()
# Clear audio after use if wav_data: wav_data = None
except KeyboardInterrupt: print("\nUse /quit to exit") except EOFError: print("\nGoodbye!") break
if __name__ == "__main__": main()LICENSEAdded+41
README.mdAdded+89
demo.mp4Added+3
liquid_audio_chat.pyAdded+554