SuperAPI AI Directory

LMQL: Programming Large Language Models

LMQL: Programming Large Language Models

Open website

About this tool

LMQL stands for Language Model Query Language, and is a programming language for large language models (LLMs). It was created by SRI Lab @ ETH Zurich and contributors, and aims to enable robust and modular LLM prompting through types, templates, constraints, and an optimized runtime.

Main capabilities

  • Use typed variables to guarantee output formats, for example "The answer is [NUM: int]".
  • Support constraints, for example limiting length or stop conditions during generation: len(ANSWER) < 120 and STOPS_AT(ANSWER, ".").
  • Query programs are essentially Python functions and can be called directly in Python, with results directly accessible.
  • Support nested queries, bringing procedural programming into prompt writing and enabling modular local instructions and reuse of prompt components.
  • Prompt construction and generation are implemented through expressive Python control flow and string interpolation.
  • Automatically make LLM code portable across multiple backends, switchable with just one line of code, for example llama.cpp, OpenAI, Transformers.

Usage LMQL uses the @lmql.query decorator to define query functions. Inside the function, the top-level string is the prompt, and generation is done through (constrained) variables. Query programs can return values and can be called in Python like ordinary functions. For example:

lmql @lmql.query def meaning_of_life(): '''lmql "Q: What is the answer to life, the universe and everything?" "A: [ANSWER]" where len(ANSWER) < 120 and STOPS_AT(ANSWER, ".") print("LLM returned", ANSWER) "The answer is [NUM: int]" return NUM '''

Call meaning_of_life() to execute it.

Applicable scenarios

  • LLM applications that need to constrain the length or format of generated results.
  • Scenarios that need typed output guarantees (such as integers, date formats).
  • Complex prompt engineering that needs modular, reusable prompt components.
  • Projects that need to easily switch between different LLM backends.
  • Developers who want to build prompts using Python control flow and string interpolation.

Limitations Detailed information about pricing, specific platform support scope, performance metrics, or usage restrictions is not yet provided.