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

相关推荐
孟健11 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞13 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽15 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程20 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪20 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook20 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战2 天前
Pydantic配置管理最佳实践(一)
python