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

相关推荐
hboot20 小时前
AI工程师第二课 - 数据处理
人工智能·python·数据分析
用户8356290780511 天前
使用 Python 自动化 PowerPoint 形状布局与格式设置
后端·python
用户8356290780511 天前
用 Python 自动化 PowerPoint 演讲者备注添加
后端·python
黄忠1 天前
01-系统架构设计-LangGraph状态机与多源异构RAG
python
zzzzzz3101 天前
假如我是掘金管理员,我先给评论区装个'代码审查'系统
python·程序员·机器人
砍材农夫1 天前
python环境|conda安装和使用(2)
后端·python
程序员龙叔2 天前
编写高质量 Skill 系列 -- 如何设计需求分析与用例生成的 SKILL
自动化测试·软件测试·python·软件测试工程师·接口测试·性能测试·skill·ai测试
用户8356290780512 天前
使用 Python 操作 Word 内容控件
后端·python
码云骑士2 天前
32-慢查询排查全流程(下)-索引优化实战与最左前缀原则
python