解释器模式:为 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% 正宗的 解释器模式

相关推荐
aiguangyuan几秒前
基于BiLSTM-CRF的命名实体识别模型:原理剖析与实现详解
人工智能·python·nlp
禹凕4 分钟前
Python编程——进阶知识(MYSQL引导入门)
开发语言·python·mysql
阿钱真强道7 分钟前
13 JetLinks MQTT:网关设备与网关子设备 - 温控设备场景
python·网络协议·harmonyos
我的xiaodoujiao10 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 47--设置Selenium以无头模式运行代码
python·学习·selenium·测试工具·pytest
寻星探路6 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
ValhallaCoder9 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
猫头虎9 小时前
如何排查并解决项目启动时报错Error encountered while processing: java.io.IOException: closed 的问题
java·开发语言·jvm·spring boot·python·开源·maven
八零后琐话10 小时前
干货:程序员必备性能分析工具——Arthas火焰图
开发语言·python
青春不朽51211 小时前
Scrapy框架入门指南
python·scrapy