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

相关推荐
xcLeigh2 小时前
提示词基础:什么是Prompt以及它为何如此重要
人工智能·ai·大模型·prompt·ai写作·提示词
飞猪~3 小时前
LangChain python 版本 第一集
开发语言·python·langchain
2601_956319884 小时前
最新AI量化提效,先做可验证的小流程
人工智能·python
开飞机的舒克_5 小时前
FastAPI 实战入门:从路由、参数校验到依赖注入的后端开发指南
python·fastapi
霸道流氓气质6 小时前
Kiro 中反编译 JAR 包并分析字节码的流程指南
chrome·python·jar
人工智能时代 准备好了吗6 小时前
AI回答内容进入率监测:引用识别、文本匹配与语义判断
开发语言·人工智能·python
Metaphor6927 小时前
使用 Python 冻结 Excel 文件中的行、列和单元格
开发语言·python·excel
言乐67 小时前
Python实现建造微服务商城后台
开发语言·python·算法·微服务·架构
fenglllle7 小时前
chromadb emmbedding 向量检索
人工智能·python·embedding
cui_ruicheng8 小时前
Python从入门到实战(六):非序列容器
开发语言·python