LMQL

LMQL

LMQL is a query language for large language models that brings types, templates, constraints and an optimizing runtime to prompt engineering. Instead of string hacking, you write declarative queries where the runtime translates character-level constraints into subtoken masks and enforces them during generation, so output format is guaranteed rather than hoped for. It supports scripted prompting with Python control flow, nested queries, tool augmentation, decoder control and distribution measurement, and runs across OpenAI, Azure, Replicate, Hugging Face Transformers and llama.cpp by switching one line. Built by the SRI Lab at ETH Zurich, it targets developers and researchers building reliable, portable LLM pipelines and chatbots.

Coding
Visit website
Added on
Nov 4, 2026
Constrained decodingPython-nativeMulti-backendNested queriesPlayground IDEOpen sourcePrompt DSL
Product information

Everything worth knowing about LMQL

The complete picture — from everyday features to the technical detail builders and IT folks dig for.

Core features

What it actually does

Constraint-Based Prompting
Attach `where` clauses to prompt statements to enforce hard logical constraints on model output, such as length limits, type checks, regex matches, or membership in a fixed set — the runtime guarantees they hold.
Scripted Prompt Control Flow
Build prompts like ordinary programs: use Python loops, conditionals, branching and string interpolation to compose multi-part prompts and react to model output mid-generation. The LLM always sees the full accumulated context.
Multi-Backend Portability
Switch between OpenAI, Azure, Replicate, Hugging Face Transformers and llama.cpp with a single line of code. Write the query once, run it against hosted or self-hosted models.
Nested Queries
Modularize prompts by defining reusable local sub-queries inside a parent query. Enables procedural programming patterns for prompting — local instructions, component re-use and cleaner composition.
Python-Native Queries
Annotate a Python function with `@lmql.query` and the query body becomes a callable. Generated variables are exposed directly to Python, so you can validate, branch and return typed values like ints without parsing strings.
Technical capabilities
Token-Level Constraint Compilation
Character-level constraints (e.g. `len(RESPONSE) < 25`, `STOPS_AT`, regex, int types) are automatically translated into subtoken masks that the runtime enforces eagerly during generation rather than post-hoc filtering.
Decoder Declarations
The runtime exposes pluggable decoding algorithms — argmax (default), sample with temperature, beam search, and best_k — declared inline at the top of a query program.
Must watch videos
LMQL: Language Model Query Language Technical Analysis
8:04
Tutorial8:04
LMQL: Language Model Query Language Technical Analysis
The source provides an extensive technical analysis and overview of the Language Model Query Language (LMQL), a programming language developed at ETH Zurich designed to structure and optimize interactions with Large Language Models (LLMs). The report introduces the Language Model Programming (LMP) paradigm, which combines natural language prompting with standard algorithmic control flow and declarative constraints to address the fragility and inefficiency of traditional prompting methods. A major focus is the core technical innovation of eager constraint enforcement via dynamic logit masking, which guarantees output integrity (e.g., correct JSON or numeric types) by restricting the LLM's vocabulary during token generation. This mechanism, along with an optimizing runtime, leads to substantial cost savings and efficiency gains (reported between 26% and 85%) by preventing the generation of invalid tokens. Finally, the analysis positions LMQL not as a competitor to orchestration frameworks like LangChain, but as a specialized, complementary tool that provides reliable, structured output for complex, production-grade LLM applications while offering broad backend portability.
Beyond Basic Prompting: Supercharging Open Source LLMs with LMQL's Structured Generation
45:36
Tutorial45:36
Beyond Basic Prompting: Supercharging Open Source LLMs with LMQL's Structured Generation
🔊 Recorded at PyCon DE & PyData 2025, April 23, 2025 https://2025.pycon.de/program/DQTMJB/ 🎓 This technical deep-dive explores how LMQL enables structured generation with open-source LLMs, from basic prompting to building evaluated RAG systems. Speakers: Christiaan Swart Description: In this presentation, Christiaan Swart explores advanced techniques for structured generation with open source Large Language Models (LLMs) using LMQL, a domain-specific language that enables interweaving of prompts and code. The talk demonstrates how LMQL's capabilities can enhance LLM outputs through logit biasing, type constraints, and control flow mechanisms. Swart examines practical applications including structured object generation, sentiment analysis, and retrieval-augmented generation (RAG) systems. Using a Wikipedia-based RAG implementation as a case study, he evaluates system performance through metrics including factual correctness, context recall, and faithfulness. The presentation highlights both the potential and limitations of small open-source LLMs, particularly in reasoning tasks. While LMQL itself is no longer actively maintained, the underlying concepts of logit processing and structured generation remain valuable, with alternative tools like Guidance and Outlines offering similar functionality. The key takeaway emphasizes the importance of workflow-based approaches over agent-based systems for production environments, with structured generation techniques providing more controlled and measurable outcomes. ⭐️ About PyCon DE & PyData: The PyCon DE & PyData conference unite the Python, AI, and data science communities, offering a unique platform for collaboration and innovation. The PyCon DE & PyData 2025 conference, provided an exceptional experience, fostering deeper connections within the Python community while showcasing advancements in AI and data science. Attendees enjoyed a diverse and engaging program, solidifying the event as a highlight for Python and AI enthusiasts nationwide. Follow us: • LinkedIn: https://www.linkedin.com/company/28908640/ • X: https://www.x.com/pyconde Links: • Conference website: http://pycon.de • Other sessions: https://2025.pycon.de/talks/ The conference is organized by • Python Softwareverband e.V.: http://pysv.org • NumFOCUS Inc.: http://numfocus.org • Pioneers Hub gemeinnützige GmbH: http://pioneershub.org If you enjoyed this session, please like, comment, and subscribe to our channel for more insightful talks and discussions. Share this video with your network to spread the knowledge! Hashtags: #Python #PyConDE #PyData #OpenSource #AI #DataScience #MachineLearning #SoftwareDevelopment #LLMs #Community Acknowledgements: Special thanks to all the volunteers and sponsors who made this event possible. About: Python Softwareverband e.V.: PySV is a non-profit that promotes the use and development of Python in Germany through events, education, and advocacy, fostering an open Python community. NumFOCUS Inc. supports open-source scientific computing by providing financial and logistical support to key projects like NumPy and Jupyter, promoting sustainable development and collaboration. Pioneers Hub gemeinnützige GmbH: is a non-profit fostering innovation in AI and tech by connecting experts and promoting knowledge exchange through events and collaborative initiatives. www.pydata.org PyData is an educational program of NumFOCUS, a 501(c)3 non-profit organization in the United States. PyData provides a forum for the international community of users and developers of data analysis tools to share ideas and learn from each other. The global PyData network promotes discussion of best practices, new approaches, and emerging technologies for data management, processing, analytics, and visualization. PyData communities approach data science using many languages, including (but not limited to) Python, Julia, and R.
LMQL Programming Large Language Models
58:40
Tutorial58:40
LMQL Programming Large Language Models
Speakers: Marc Fisher: https://www.sri.inf.ethz.ch/people/marc Luca Beurer-Kellner (ETH Zürich): A Ph.D. student in the Department of Computer Science at ETH Zurich, under the supervision of Professor Martin Vechev. He holds a Bachelor's degree in Computer Science from Humboldt University of Berlin and a Master's degree from ETH Zurich. Luca's research focuses on the intersection of programming languages and machine learning. Most recently, he worked on controlled and constrained text generation with Large Language Models. He is the lead author of the LMQL (Language Model Query Language) paper in 2023, presenting an innovative query language for LLMs, enabling precise control over generated text. Abstract: Large language models have recently demonstrated outstanding performance on a wide range of tasks. However, to obtain state-of-the-art performance or adapt language models for specific tasks, complex task- and model-specific programs have to be implemented, which may still require ad-hoc interaction or laborious result parsing. To address this we implement LMQL (short for Language Model Query Language). LMQL is a programming language for language model interaction and generalizes natural language prompting, making it more expressive while remaining accessible. For this, LMQL builds on top of Python, allowing users to express natural language prompts as well as control flow, allowing the user to steer the LLM's reasoning process. In LMQL, users can specify high-level, logical constraints over the language model output. These constraints are then automatically converted into token-level prediction masks, which can be enforced eagerly during text generation. This allows to enforce constraints strictly, making it impossible for the model to generate content that does not satisfy the requirements. Try it now on https://lmql.ai

Who uses it

Real use cases, no hype
Structured Output Extraction
Force the model to emit valid ints, regex matches or enum values every time.
Multi-Step Prompting
Chain prompts with Python control flow, loops and branching logic.
Backend Swapping
Prototype on OpenAI, then run the same query on local llama.cpp.
Tool-Augmented Agents
Interleave LLM calls with function/tool calls inside one query.
Chatbot Logic
Use LMQL's chat library with internal reasoning and injection defenses.
Distribution Measurement
Sample multiple trajectories and measure model output distributions.
Prompt Research
Run reproducible experiments with inference certificates and decoding control.
What's great
  • Python-native syntax — writes like normal functions
  • Constraints guarantee output format, no post-hoc parsing
  • Swap OpenAI, Transformers or llama.cpp with one line
  • Free, open-source, backed by ETH Zurich research
Technical strengths
  • Constraints compile to subtoken masks enforced mid-decode
  • Built-in decoders: argmax, sample, beam, best_k
  • Nested queries make prompt components reusable and modular
Where it falls short
  • Steep learning curve — it's a whole new DSL
  • Small community and thin ecosystem vs. LangChain
  • Research-first tool, not a production serving stack
  • Local install required for self-hosted models
Technical limitations
  • Subtoken masking support varies by backend and tokenizer
  • Writing custom constraints is fiddly and error-prone
  • No batching/throughput tricks like vLLM or TGI
For technical folks

The deep-dive specs

Supported Backends
OpenAI, Azure, Replicate, Hugging Face Transformers, llama.cpp
Decoding Algorithms
argmax (default), sample (temperature), beam, best_k
Constraint Enforcement
Character-level constraints translated to subtoken masks and enforced eagerly during generation
Integrations
Python, LangChain, LlamaIndex, Pandas
Deployment Options
Local installation, Docker, web-based Playground IDE

FAQ

Includes technical Q&A
A programming language for LLMs. You write prompt queries with typed variables and constraints, and the runtime enforces those constraints during generation — no post-processing or retries.

Traffic Insights

Monthly Visits

—

November 2026

Growth Rate

0%

vs last month

Dominance

0%

in Coding

Top Country

—

Top Countries Breakdown

—

Growth Trend

Stable

Traffic has remained stable.

Pricing overview
Open Source Pricing

LMQL Pricing

LMQL uses a open source pricing structure. Real-time rates, custom enterprise quotas, and plan details are managed directly on their official platform.

Check Pricing on LMQL
Reviews

What the internet actually thinks

Data refreshed weekly. No paid placements.

Trustpilot
Not reviewed yet
G2
G2
Not reviewed yet
C
Capterra
Not reviewed yet
Product Hunt
Not reviewed yet
COMMUNITY COMMENTS

Leave a Comment

Help others make informed decisions. Your honest feedback shapes the community's understanding of this tool.

Tips for commenting

  • •Be specific about features you used
  • •Share real use cases and results
  • •Mention both pros and cons
  • •Keep it honest and constructive
to leave a comment

Your comment is published immediately.

Filter:
Sort:

No comments yet

Be the first to share your experience with this tool.

Alternatives

Not quite the right fit?

Here's what else is out there.