解释器模式:为 LLM 构建迷你 DSL 解释器,实现 Prompt 编排语言

解释器模式用于:

把一种语言(DSL)解析成语法树,再按规则执行。

非常适合 LLM,比如:

  • Prompt DSL
  • Chain-of-Thought DSL
  • Function Call DSL
  • Workflow DSL
  • Agent DSL

下面给你一个真正"解释器模式"的强例子。


⭐ 真·Interpreter 实现:自定义 Prompt DSL

目标:支持这样一个迷你语言:

复制代码
DEFINE PERSON = "Jack"
ASK "What is PERSON doing?"
ASK "Write a poem about PERSON"

最终会发送两个 Prompt:

  • What is Jack doing?
  • Write a poem about Jack

Step 1:定义语法节点(终结符与非终结符)

python 复制代码
class Expression:
    def interpret(self, context):
        raise NotImplementedError

终结符表达式:常量赋值

python 复制代码
class DefineExpression(Expression):
    def __init__(self, variable, value):
        self.variable = variable
        self.value = value

    def interpret(self, context):
        context[self.variable] = self.value

终结符表达式:发起询问

python 复制代码
class AskExpression(Expression):
    def __init__(self, message):
        self.message = message

    def interpret(self, context):
        # 替换变量
        for var, value in context.items():
            self.message = self.message.replace(var, value)
        print(">>> LLM 请求:", self.message)
        return self.message

非终结符表达式:语句列表

python 复制代码
class SequenceExpression(Expression):
    def __init__(self, expressions):
        self.expressions = expressions

    def interpret(self, context):
        results = []
        for expr in self.expressions:
            res = expr.interpret(context)
            if res:
                results.append(res)
        return results

Step 2:解析 DSL 生成语法树(重点!)

这是真正的解释器模式核心。

python 复制代码
def parse_script(script: str):
    expressions = []

    for line in script.splitlines():
        line = line.strip()

        if line.startswith("DEFINE"):
            _, var, _, value = line.split(maxsplit=3)
            value = value.strip('"')
            expressions.append(DefineExpression(var, value))

        elif line.startswith("ASK"):
            msg = line[4:].strip().strip('"')
            expressions.append(AskExpression(msg))

    return SequenceExpression(expressions)

Step 3:执行 DSL

python 复制代码
script = """
DEFINE PERSON = "Jack"
ASK "What is PERSON doing?"
ASK "Write a poem about PERSON"
"""

tree = parse_script(script)
context = {}
tree.interpret(context)

输出:

复制代码
>>> LLM 请求: What is Jack doing?
>>> LLM 请求: Write a poem about Jack

⭐ 真正体现 Interpreter 模式的点

  • 语言
  • 语法规则
  • 语法树(AST)
  • 解释执行逻辑
  • 各种表达式(Define/Ask/Sequence)对应 终结符 / 非终结符
  • 无需动客户端

这就是 100% 正宗的 解释器模式

相关推荐
无凭9 分钟前
字节跳动 DeerFlow:Agent Harness 怎么让大模型主动向用户提问?
人工智能·python
蜀道山老天师9 分钟前
Python + Playwright 实现问卷星自动化填写
python
Zane199419 分钟前
多开几个线程,为什么算数字反而没变快?一文讲透 CPython 的 GIL
后端·python
W_3260029 分钟前
Python-OpenCV边缘检测与阈值分割:Sobel、Scharr、Laplacian、Canny、全局与自适应阈值
开发语言·图像处理·python·opencv·机器学习
青 春 记 忆1 小时前
LeetCode 121. 买卖股票的最佳时机|Python 解法详解
python·算法·leetcode
满怀冰雪1 小时前
21-图像分类实战:从 MNIST 到 CIFAR-10
人工智能·python·深度学习·分类·数据挖掘·paddlepaddle
Logintern091 小时前
Celery 的底层架构正是进程池、事件循环、epoll 和协程全部组合在了一起
python·架构·消息队列·进程·celery·事件循环
用户0332126663671 小时前
在 Word 文档快速中插入图片【Python 教程】
python
盖伦发发1 小时前
RAG 能跑≠能用:用 EDD 把 Eval 做成基础设施 (附源码)
人工智能·后端·python·功能测试
SHIPKING3932 小时前
【Harness Engineering】07_多代理与验证:用分工和验证管理不稳定性
prompt·harness