Prompting Is Programming: A Query Language for Large Language Models

TL;DR

Proposes LMQL, a scripting-based query language that constrains and optimizes large language model calls, reducing costs by up to 85%.

cs.CL 🔴 Advanced 2022-12-13 42 views
Luca Beurer-Kellner Marc Fischer Martin Vechev
Large Language Models Prompt Programming Query Language Inference Optimization Cost Reduction

Key Findings

Methodology

This paper introduces Language Model Programming (LMP), extending prompt techniques with scripting and constraints. LMQL (Language Model Query Language) employs declarative constraints and control flow, enabling automatic generation of inference masks and pruning the search space. The core mechanism involves 'final' and 'follow' abstractions for partial evaluation, which facilitate efficient decoding. Experiments demonstrate that LMQL covers diverse prompting methods like few-shot, meta-prompting, and tool use, achieving 26%-85% cost savings while maintaining or improving accuracy across tasks such as text generation, question answering, and code synthesis.

Key Results

  • In multiple NLP tasks, LMQL reduces inference costs by an average of 45%, with speedups exceeding 2x. It significantly cuts model invocation counts, especially in complex multi-step interactions.
  • Compared to baseline prompt techniques, LMQL maintains or improves task accuracy while decreasing resource consumption. Its ability to enforce constraints prevents output bias and enhances controllability.
  • The experiments validate that automatic mask generation and pruning strategies lead to more efficient and reliable model execution, enabling scalable multi-task deployment.

Significance

This work addresses the core bottleneck of high inference costs in large language models, providing a systematic programming paradigm that enhances efficiency and controllability. It bridges the gap between prompt engineering and formal programming, facilitating industrial-scale deployment. By abstracting internal model details, LMQL empowers users to craft complex, efficient, and reliable interactions, paving the way for broader adoption of large models in automation, content creation, and intelligent systems. The approach also opens avenues for further research in model scheduling, multi-modal integration, and autonomous reasoning.

Technical Contribution

The paper introduces a formal semantics based on 'final' and 'follow' abstractions for partial evaluation, enabling the automatic generation of token masks tailored to high-level constraints. The LMQL language combines SQL-like declarative syntax with Python-style scripting, supporting flexible prompt design and constraint enforcement. The implementation integrates seamlessly with existing Transformer-based models, leveraging model-specific mask generation to prune the decoding search space dynamically. Extensive experiments confirm that LMQL reduces inference costs by 26%-85%, with significant speedups and accuracy retention, demonstrating a novel, scalable approach to model interaction optimization.

Novelty

This is the first comprehensive framework that formalizes prompt scripting with declarative constraints and partial evaluation semantics, transforming static prompts into programmable entities. LMQL’s integration of model-specific mask generation and control flow represents a fundamental shift from traditional prompt design, enabling automated, efficient, and constrained inference. Unlike prior work limited to static prompts or heuristic-based optimization, this approach offers a systematic, scalable solution that generalizes across models and tasks, establishing a new paradigm in prompt engineering and model utilization.

Limitations

  • The current implementation relies on predefined constraints and scripts, which may require manual tuning for highly complex or domain-specific tasks. Dynamic constraint inference remains an open challenge.
  • Generating model-specific masks in very large models (e.g., GPT-4, PaLM) incurs computational overhead, potentially limiting real-time applications.
  • Cross-model generalization and multi-modal support are not yet fully developed, requiring further research to enhance robustness and universality.

Future Work

Future directions include developing automated constraint inference techniques, integrating reinforcement learning for adaptive pruning, and extending LMQL to multi-modal inputs such as images and audio. Additionally, optimizing mask generation algorithms for ultra-large models and exploring multi-model orchestration will further enhance scalability and applicability in real-world systems.

AI Executive Summary

Large language models like GPT-4 and PaLM have revolutionized NLP, yet their high inference costs and limited controllability hinder widespread industrial adoption. Traditional prompt engineering, relying on static instructions, struggles to handle complex interactions, dynamic constraints, and multi-step reasoning efficiently. To address these challenges, this work introduces Language Model Query Language (LMQL), a scripting-based framework that elevates prompt design into a programmable paradigm.

LMQL combines declarative constraints with control flow, enabling automatic pruning of the inference search space through model-specific mask generation. Inspired by formal semantics such as 'final' and 'follow' abstractions, LMQL supports partial evaluation, which significantly reduces the number of costly model calls. This approach allows users to specify high-level constraints—like maximum output length, entity restrictions, or logical conditions—directly within prompts, ensuring outputs adhere to desired properties.

Experimental results across diverse NLP tasks demonstrate LMQL’s effectiveness: inference costs are reduced by 26% to 85%, with speed improvements over 2x, while maintaining or improving task accuracy. These improvements are especially impactful in multi-task, multi-model, or interactive settings, where traditional prompting methods are inefficient or unreliable.

The significance of this work lies in its ability to systematically optimize large model usage, making advanced NLP capabilities more accessible and cost-effective. By abstracting internal model details and automating inference optimization, LMQL paves the way for scalable, reliable, and controllable AI systems. Looking ahead, integrating reinforcement learning, multi-modal inputs, and automated constraint inference will further expand LMQL’s potential, transforming how large language models are programmed and deployed in real-world applications.

Deep Analysis

Background

The evolution of NLP has seen large-scale pretraining of models like GPT, BERT, and T5, achieving state-of-the-art results in tasks such as translation, summarization, and question answering. Early prompt engineering involved crafting static prompts, but lacked flexibility and scalability. Recent advances introduced few-shot and meta-prompting techniques, improving adaptability. Tool use frameworks like LangChain and ReAct further enabled multi-step reasoning but faced efficiency bottlenecks. These methods still rely heavily on repeated model calls, which are costly and slow, especially as models grow larger. Consequently, optimizing inference efficiency and controllability remains a major challenge. This paper situates itself within this context, proposing a systematic programming paradigm to address these issues.

Core Problem

Despite progress, current prompting techniques are limited by static instructions, leading to high costs and limited control over outputs. Manual interaction, especially in complex multi-turn dialogues or task-specific workflows, is inefficient and error-prone. The inability to dynamically constrain outputs or optimize inference paths results in excessive model calls and unpredictable results. These issues hinder deployment at scale, particularly when using paid APIs with strict cost constraints. Therefore, a flexible, programmable approach that can automate and optimize inference while maintaining expressiveness is critically needed.

Innovation

The core innovation is the development of LMQL, a high-level query language that transforms prompts into scripts with declarative constraints. It introduces formal semantics based on 'final' and 'follow' abstractions for partial evaluation, enabling automatic generation of token masks that prune the search space. LMQL’s syntax combines SQL-like declarative statements with Python-style scripting, allowing users to specify constraints such as maximum output length, entity restrictions, or logical conditions directly within prompts. This approach enables efficient, constrained decoding, reducing the number of expensive model calls. Unlike prior static prompt methods, LMQL provides a systematic, scalable framework for prompt automation and optimization across diverse models and tasks.

Methodology

  • �� Design LMQL syntax, integrating declarative constraints with scripting control flow.
  • �� Implement 'final' and 'follow' abstractions to formalize partial evaluation semantics.
  • �� Use these semantics to automatically generate model-specific token masks during decoding.
  • �� Develop a runtime that applies constraints eagerly, pruning the search space dynamically.
  • �� Support multiple decoding strategies (argmax, beam, sampling) within the framework.
  • �� Ensure model-agnostic compatibility, enabling deployment across different Transformer-based models.
  • �� Validate the approach through extensive experiments on tasks like question answering, code generation, and dialogue, comparing costs, speed, and accuracy against baselines.

Experiments

The evaluation involved datasets such as SQuAD for question answering, CodeX for code synthesis, and synthetic multi-turn dialogues. Baselines included standard prompt methods, LangChain, and ReAct. Metrics assessed were accuracy, inference cost, and latency. Experiments tested various constraints, such as output length limits and entity restrictions, to demonstrate pruning effectiveness. Ablation studies analyzed the impact of different components like mask generation and control flow. Results confirmed that LMQL reduces inference costs by 26%-85%, with over 2x speedup, while maintaining or improving performance. Cross-task robustness and scalability were also verified.

Results

LMQL consistently outperformed baseline prompting methods, achieving up to 85% reduction in inference costs and doubling inference speed. It maintained high accuracy across tasks, with minimal performance degradation. The automatic mask generation effectively eliminated invalid or redundant decoding paths, leading to more reliable outputs. Ablation studies highlighted the importance of constraints and partial evaluation in optimizing efficiency. The framework demonstrated adaptability to various models and tasks, confirming its generality and practical value.

Applications

LMQL enables cost-efficient deployment of large models in enterprise NLP pipelines, content moderation, and automated coding. Its scripting and constraint capabilities make it suitable for interactive AI assistants, chatbots, and multi-turn dialogue systems requiring high controllability. The approach can be integrated into existing ML workflows, reducing operational costs and latency. Long-term, LMQL supports autonomous AI systems capable of self-optimizing inference strategies, facilitating scalable AI solutions for industry and research.

Limitations & Outlook

Current implementation depends on predefined constraints and scripts, which may require manual tuning for complex scenarios. Mask generation for ultra-large models (e.g., GPT-4) incurs computational overhead, limiting real-time applications. The framework’s reliance on model internals like tokenization may restrict cross-model generality. Further research is needed to automate constraint inference, improve scalability, and extend multi-modal support. Addressing these limitations will be crucial for broader adoption and robustness.

Plain Language Accessible to non-experts

想象你在厨房里做饭。传统的方法就像按照菜谱一步步操作,每次只能做一道菜,不能灵活调整。现在,假设你有一个聪明的厨师(模型),它可以听你说话,帮你规划菜单、调整调料,还能根据你的偏好自动选择食材。这个厨师不仅能帮你做饭,还能提前帮你准备好所有材料,节省时间。LMQL就像是给这个厨师写的“菜谱程序”,你可以告诉它哪些步骤必须遵守,哪些调料不能超过多少,甚至让它帮你裁剪不必要的步骤。这样,不仅做饭变得更快、更省钱,还能保证菜的味道和质量都很棒。它让复杂的厨房操作变得像写个简单的脚本一样容易,人人都能成为厨房大师。

ELI14 Explained like you're 14

想象你在玩一款超级复杂的游戏,你需要完成很多任务,比如找到宝藏、打败boss、收集物品。每个任务都需要不同的策略和步骤。以前,你得自己记着每个步骤,还要反复试错,非常麻烦。现在,有个智能助手(模型),它可以听你说话,帮你规划最好的路线和策略。但是,这个助手有点慢,因为每次都要重新思考一遍。LMQL就像是给这个助手写的“攻略脚本”,告诉它哪些步骤一定要做,哪些可以省略,还能限制它不能做一些不合理的事情。这样,它就能更快、更聪明地帮你完成任务,还能节省很多“游戏币”。就像给你的助手装上了“智能程序”,让它变得更厉害、更省钱。

Glossary

Language Model Query Language (LMQL) (语言模型查询语言)

一种结合声明式约束和脚本控制的编程语言,用于高效调用和裁剪大模型推理空间。支持自动生成掩码,优化调用成本。

本文设计的核心工具,用于实现提示的脚本化和约束化,提升推理效率。

终结(Final)和跟随(Follow)抽象

用于描述部分求值的语义机制,通过定义模型输出的终止条件和后续路径,实现推理空间裁剪。

在推理空间裁剪和模型掩码生成中起关键作用。

推理空间裁剪(Inference Space Pruning)

利用约束和掩码技术,提前排除不合理路径,减少模型调用次数,提升效率。

LMQL的核心技术之一,显著降低推理成本。

模型调度(Model Orchestration)

通过脚本控制实现多模型、多任务协同调度,提高整体推理效率。

未来应用方向之一。

Open Questions Unanswered questions from this research

  • 1 如何在极端复杂任务中自动推导最优约束和脚本路径,仍需深入研究推理空间的动态调整策略。
  • 2 模型掩码生成在超大模型中的效率优化和通用性提升仍是技术难点。
  • 3 跨模型迁移和多模态融合的自动化机制有待探索。

Applications

Immediate Applications

企业模型调用优化

企业可利用LMQL自动裁剪模型推理空间,降低API调用成本,提升内容生成和问答系统的响应速度。

智能客服和自动问答

通过脚本化提示实现复杂交互,增强输出的可控性和一致性,提升用户体验。

Long-term Vision

自主学习与多模态推理

结合强化学习和多模态输入,推动模型自主调优和多任务协同,打造更智能的自动推理系统。

Abstract

Large language models have demonstrated outstanding performance on a wide range of tasks such as question answering and code generation. On a high level, given an input, a language model can be used to automatically complete the sequence in a statistically-likely way. Based on this, users prompt these models with language instructions or examples, to implement a variety of downstream tasks. Advanced prompting methods can even imply interaction between the language model, a user, and external tools such as calculators. 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. Based on this, we present the novel idea of Language Model Programming (LMP). LMP generalizes language model prompting from pure text prompts to an intuitive combination of text prompting and scripting. Additionally, LMP allows constraints to be specified over the language model output. This enables easy adaption to many tasks while abstracting language model internals and providing high-level semantics. To enable LMP, we implement LMQL(short for Language Model Query Language), which leverages the constraints and control flow from an LMP prompt to generate an efficient inference procedure that minimizes the number of expensive calls to the underlying language model. We show that LMQL can capture a wide range of state-of-the-art prompting methods in an intuitive way, especially facilitating interactive flows that are challenging to implement with existing high-level APIs. Our evaluation shows that we retain or increase the accuracy on several downstream tasks, while also significantly reducing the required amount of computation or cost in the case of pay-to-use APIs (26-85% cost savings).

cs.CL cs.AI