Upsonic 表达式语言(UEL)完全指南:用管道符组合 Prompt、模型与解析器的 Runnable 编排层
Upsonic 表达式语言(UEL)完全指南:用管道符组合 Prompt、模型与解析器的 Runnable 编排层
导读
UEL(Upsonic Expression Language)是 Upsonic 中负责"编排"的基础层:它让提示模板、模型、解析器、普通 Python 函数、字典甚至子图,都能通过管道符(|)自由拼接,并用统一的 invoke / ainvoke 接口执行。本文基于当前仓库 documents/ai/explanation/uel/uel.md 与 src/upsonic/uel/ 源码,完整讲解 UEL 的设计动机、全部组件、管道强制转换规则,以及与 models、graphv2 等模块的集成方式。读完你将掌握:如何用 5 行代码构建 prompt | model | parser 线性链,如何用字典语法做并行 fan-out,如何用 RunnableBranch 做条件路由,如何用 @chain 将任意函数变成链式步骤,以及如何把任意链路渲染成 ASCII 树或 Mermaid 图。
一、UEL 是什么:一个刻意保持小巧的 LCEL 风格组合层
upsonic.uel 是 Upsonic 的 Upsonic Expression Language —— 一个受 LangChain LCEL 启发的组合原语层。它的设计意图与 LCEL 一致:声明式地构建链路、自动处理同步/异步分发、让纯 Python(函数、字典、operator.itemgetter)也能无缝参与组合。
该模块刻意与任何具体模型/提供商解耦,只定义四类东西:
- 一个抽象基类
Runnable[Input, Output],通过重载__or__把a | b变成RunnableSequence; - 一组覆盖 LLM 流水线结构模式的具象 Runnable 类型:序列、并行、分支、lambda、透传/赋值、提示模板、输出解析器;
- 一个
@chain装饰器,把普通 Python 函数变成 Runnable; - 一个图视图(
RunnableGraph),对任意链路(或graphv2的StateGraph)做内省并渲染为 ASCII 或 Mermaid。
UEL 是高层 Upsonic 原语所依赖的"管道"(plumbing):
| Upsonic 类 | 继承自 | 效果 |
|---|---|---|
upsonic.models.Model(所有 provider 的基类) |
Runnable[Any, Any] |
每个模型都可以作为 prompt | model | parser 的一环 |
upsonic.graphv2.state_graph.StateGraph |
Runnable |
编译后的状态图是一等公民链步骤 |
upsonic.uel.ChatPromptTemplate |
Runnable |
渲染成 ModelRequest / ModelMessage 列表 |
upsonic.uel.BaseOutputParser |
Runnable |
消费 ModelResponse |
二、文件夹布局与公共 API
UEL 刻意保持扁平,共 11 个文件、约 2K 行代码,无子目录:
src/upsonic/uel/
├── __init__.py # 惰性公共 API 面 + 支持管道的 itemgetter
├── runnable.py # 抽象 Runnable[Input, Output] + 管道操作符
├── sequence.py # RunnableSequence —— 按序执行步骤链
├── parallel.py # RunnableParallel —— 扇出,返回字典结果
├── branch.py # RunnableBranch —— 条件路由
├── lambda_runnable.py # RunnableLambda + coerce_to_runnable() 辅助
├── passthrough.py # RunnablePassthrough(.assign) —— 输入透传
├── prompt.py # ChatPromptTemplate —— 字符串/消息模板
├── output_parser.py # BaseOutputParser、StrOutputParser、PydanticOutputParser
├── decorator.py # @chain 装饰器(函数 -> Runnable)
└── graph.py # RunnableGraph —— ASCII / Mermaid 可视化
惰性导入的公共面
init.py 使用模块级 __getattr__ 实现惰性加载:from upsonic.uel import X 只有在真正访问属性时才触发实际导入,从而让 import upsonic 保持廉价。导出的名字与其来源:
| 导出名 | 所在文件 | 类型 |
|---|---|---|
Runnable |
runnable.py |
抽象基类 |
RunnableSequence |
sequence.py |
线性链 |
RunnableParallel |
parallel.py |
并发扇出 |
RunnableLambda |
lambda_runnable.py |
包装函数 |
RunnableBranch |
branch.py |
条件路由 |
RunnablePassthrough |
passthrough.py |
恒等 / .assign(...) |
ChatPromptTemplate |
prompt.py |
提示构建器 |
BaseOutputParser |
output_parser.py |
抽象解析器 |
StrOutputParser |
output_parser.py |
文本提取器 |
PydanticOutputParser |
output_parser.py |
JSON → Pydantic |
chain |
decorator.py |
装饰器 |
itemgetter |
__init__.py(合成) |
支持管道的 operator.itemgetter 替代品 |
其中 itemgetter 是本模块独有:它返回一个 RunnableLambda,因此 itemgetter("k") | something 能直接在 UEL 链路内工作:
from upsonic.uel import itemgetter
chain = itemgetter("key") | (lambda x: f"Value: {x}")
chain.invoke({"key": "test"}) # "Value: test"
其实现(init.py)本质是:调用原版 operator.itemgetter(*items) 生成 getter,再用 RunnableLambda(getter) 包一层。
三、Runnable 协议:invoke / ainvoke / __or__ / __ror__
Runnable<a href="https://link.gitcode.com/i/c249a7ea6623b45ddd1b31d6cfecd9e6" target="_blank">Input, Output] 是用户通常唯一需要子类化的抽象类,定义于 [runnable.py。核心契约如下:
class Runnable(ABC, Generic[Input, Output]):
@abstractmethod
def invoke(self, input: Input, config: dict | None = None) -> Output: ...
async def ainvoke(self, input, config=None):
# 默认实现:在线程池中运行同步 invoke
loop = asyncio.get_event_loop()
return await loop.run_in_executor(None, self.invoke, input, config)
def __or__(self, other) -> "Runnable":
# a | b -> RunnableSequence(steps=[a, b])
# 若 self 已是 sequence,则原地追加新步骤
# `other` 通过 coerce_to_runnable() 强制转换
def __ror__(self, other) -> "Runnable":
# 支持 dict | runnable、callable | runnable
几个关键设计点:
__or__负责强制转换:所以prompt | model | (lambda r: r.text)无需用户手动包装 lambda 也能工作;__ror__让左侧非 Runnable(可调用对象或字典)也能参与管道,这正是{"a": chain1, "b": chain2} | next_step能工作的原因;- 默认
ainvoke回退到 executor 中的invoke:任何子类只实现invoke就天然可 await。
源码中 runnable.py 的实现细节:__or__ 先对 other 调用 coerce_to_runnable;若 self 已经是 RunnableSequence 则扩展其 steps,否则新建 RunnableSequence(steps=[self, other_runnable])。__ror__ 则构造 RunnableSequence(steps=[other_runnable, self])。
Runnable ABI 一览
| 方法 | 签名 | 说明 |
|---|---|---|
invoke(input, config=None) |
同步执行,必须实现 | |
ainvoke(input, config=None) |
异步执行,默认为线程池中的 invoke |
|
__or__(other) |
强制转换 other 并返回 RunnableSequence |
|
__ror__(other) |
对普通字典/可调用对象的反向管道支持 |
四、六大结构性 Runnable 详解
4.1 RunnableSequence:线性顺序链
sequence.py 维护一个扁平的 list[Runnable],invoke 遍历列表,把第 n 步的输出串入第 n+1 步的输入:
class RunnableSequence(Runnable[Any, Any]):
def __init__(self, steps: list[Runnable]): ...
def invoke(self, input, config=None):
result = input
for step in self.steps:
result = step.invoke(result, config)
return result
async def ainvoke(self, input, config=None):
result = input
for step in self.steps:
result = await step.ainvoke(result, config)
return result
def __or__(self, other):
# 扩展而非嵌套
return RunnableSequence(steps=self.steps + [coerce_to_runnable(other)])
def get_graph(self) -> "RunnableGraph": ...
def get_prompts(self) -> list[ChatPromptTemplate]: ...
注意两个细节:__init__ 要求至少一个 step(否则抛 ValueError);__or__ 返回扁平扩展的新序列而非嵌套序列。get_prompts() 会递归下钻(通过 .steps 遍历 RunnableSequence/RunnableParallel),收集链路上的每一个 ChatPromptTemplate,可用于提示词管理与检查。
4.2 RunnableParallel:并发扇出
parallel.py 把同一个输入分发给 N 个具名 runnable,把各自输出汇总为一个字典:
RunnableParallel(joke=joke_chain, poem=poem_chain).invoke({"topic": "bears"})
# -> {"joke": ModelResponse(...), "poem": ModelResponse(...)}
行为要点(与源码一致):
invoke()内部调用asyncio.run(self.ainvoke(...));ainvoke()用asyncio.gather对runnable.ainvoke(input, config)做真正并行。任一分支抛异常时,其余未完成任务会被取消并向上传播异常(见 parallel.py);- 每个 kwargs 值都会被强制转换:
Runnable保留;dict变成嵌套的RunnableParallel.from_dict;任何可调用对象包装为RunnableLambda;其他类型抛TypeError; - 由于
coerce_to_runnable(dict)返回RunnableParallel.from_dict(dict),纯字典可直接入链:
chain = {"joke": joke_chain, "poem": poem_chain} | next_step
等价于 RunnableParallel(joke=…, poem=…) | next_step。
4.3 RunnableBranch:条件路由
分支.py 为链路提供命令式的 if/elif/.../else:
RunnableBranch(
(lambda x: "upsonic" in x["topic"].lower(), upsonic_chain),
(lambda x: "anthropic" in x["topic"].lower(), anthropic_chain),
general_chain, # 默认分支 —— 必须是最后一个参数
)
__init__ 中的校验规则:
| 位置 | 必需形式 | 失败 |
|---|---|---|
| 最后一个位置参数 | Runnable 或可调用对象(不能是元组) |
ValueError |
| 前面的位置参数 | (condition, runnable) 二元组 |
ValueError |
condition |
可调用对象 | ValueError |
运行期行为:
- 条件按顺序求值,第一个返回真值的分支胜出,后续分支不再求值;
- 求值
condition(input)时抛异常被当作"不匹配"(continue),而非硬失败(源码见 branch.py); ainvoke会额外检测inspect.iscoroutinefunction(condition),对协程条件进行await;- 所有分支都不匹配时,调用默认 runnable。
4.4 RunnableLambda 与 coerce_to_runnable
RunnableLambda(func) 包装任意可调用对象(lambda_runnable.py):
class RunnableLambda(Runnable[Input, Output]):
def __init__(self, func): ...
def invoke(self, input, config=None):
if self.is_coroutine:
# 若从异步上下文调用:分发到拥有自己事件循环的线程
try:
asyncio.get_running_loop()
with concurrent.futures.ThreadPoolExecutor() as ex:
return ex.submit(asyncio.run, self.func(input)).result()
except RuntimeError:
return asyncio.run(self.func(input))
return self.func(input)
async def ainvoke(self, input, config=None):
return await self.func(input) if self.is_coroutine \
else await asyncio.get_event_loop().run_in_executor(None, self.func, input)
coerce_to_runnable(thing) 是核心类型桥,被 __or__、RunnableSequence.__or__、RunnablePassthrough、RunnableBranch 共同使用:
| 输入类型 | 返回值 |
|---|---|
Runnable |
原样返回 |
dict |
RunnableParallel.from_dict(dict) |
| 可调用对象 | RunnableLambda(callable) |
| 其他 | TypeError |
4.5 RunnablePassthrough:恒等与赋值
passthrough.py 默认是恒等变换;配合 .assign(**kwargs) 则向输入字典合并新键,且赋值按顺序计算——后面的赋值可以读取前面已算好的值:
chain = (
RunnablePassthrough.assign(
formatted_question=lambda x: f"Question: {x['question']}",
).assign(
context=lambda x: retrieve_context(x['question']),
)
| prompt
| model
)
assign 通过自定义描述符(AssignDescriptor)实现,因此同一个标识符既可用作类方法(RunnablePassthrough.assign(...) 返回新实例),也可用作实例方法(existing.assign(...) 合并其 assignments 并返回新实例)。
输入规则:
- 无赋值 → 原样返回
input(任意类型); - 有赋值 →
input必须是 dict,否则抛TypeError; - 每个赋值值都会
coerce_to_runnable,然后用运行中的结果字典调用,返回值存入对应键。
4.6 ChatPromptTemplate:提示模板
prompt.py 构建两种产物:普通格式化字符串(旧式 template= 构造器)或 ModelRequest / ModelMessage 列表(多消息提示)。两个工厂方法:
ChatPromptTemplate.from_template("Tell me a {adj} joke about {topic}")
# -> 单条 human 消息模板;变量通过正则自动提取
ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant"),
("placeholder", {"variable_name": "chat_history"}),
("human", "Tell me about {topic}"),
])
支持的消息角色:
| 角色 | 归一化为 |
|---|---|
"system" |
SystemPromptPart(放在第一个 ModelRequest 中) |
"human" / "user" |
UserPromptPart |
"ai" / "assistant" |
ModelResponse(parts=[TextPart])(用于 few-shot 示例) |
"placeholder" |
从 input[variable_name] 动态注入 |
invoke 强制的转换规则:
- 恰好一个
SystemPromptPart,且只挂到第一个ModelRequest; - 每个
ModelRequest一个UserPromptPart;相邻 human 消息用空格合并; - 每个
ModelResponse一个TextPart(针对aifew-shot 轮); - 会话按 Request → Response → Request → Response 交替;
- 若
input已经是ModelMessage或ModelMessage列表(通过.kind in ('request', 'response')检测),原样返回——这让 memory/history 可以不经改动地流过提示步骤; - 缺少必需变量抛
KeyError;非 dict / 非消息输入抛TypeError。
Placeholder 接受 (role, content) 元组列表(视为聊天历史)或字符串(作为用户提示追加)。源码中从 upsonic.messages 导入 ModelRequest、SystemPromptPart、UserPromptPart、ModelResponse,并用 RequestUsage 与 now_utc() 构造 few-shot AI 轮的占位 ModelResponse。
4.7 输出解析器家族:从 ModelResponse 到 str / Pydantic
output_parser.py 中,BaseOutputParser[T] 是 Runnable[ModelResponse, T],子类只需实现 parse(response: ModelResponse) -> T:
| 类 | parse 行为 |
|---|---|
StrOutputParser |
若最后一个 part 是 TextPart,返回 response.parts[-1].content,否则返回 "" |
PydanticOutputParser(Model) |
对最后一个 TextPart 做 JSON 解析,并用传入的 Pydantic 类校验(优先 model_validate,否则 Model(**parsed));空 parts、非文本末 part、JSON 错误或 schema 校验失败均抛 ValueError |
两者都是 prompt | model | parser 链路的现成尾步。
五、@chain 装饰器:函数即 Runnable
decorator.py 把同步或异步函数变成 Runnable:
@chain
def custom_chain(text):
p = ChatPromptTemplate.from_template("Tell me a joke about {topic}")
out = infer_model("openai/gpt-4o").invoke(p.invoke({"topic": text}))
return (ChatPromptTemplate.from_template("Subject of joke: {joke}")
| infer_model("openai/gpt-4o")).invoke({"joke": out})
custom_chain.invoke("bears")
值得注意的语义:
- 内部构建一个私有
ChainRunnable(Runnable),并调用functools.update_wrapper,因此__name__、__doc__等元数据得以保留; - 若被包装函数返回一个
Runnable,装饰器会用同样的输入(和同样的config)调用那个返回的 runnable,从而支持动态链路:
@chain
def dynamic(input_):
return complex_chain if input_["use_complex"] else simple_chain
- 同步
invoke携带async函数体时,若在运行中的事件循环内调用会快速失败——抛RuntimeError引导调用方改用await runnable.ainvoke(...)(源码见 decorator.py)。
六、RunnableGraph:链路内省与可视化
graph.py 提供静态内省与可视化能力:
| 方法 | 输出 |
|---|---|
to_ascii() / print_ascii() |
带 ` |
to_mermaid() |
graph TD ... Mermaid 源码;并行分叉用带分支键标签的虚线边,顺序边用 ==> |
get_structure_details() |
逐节点拆解:并行分支、合并目标、顺序边 |
它接受 UEL Runnable(通过 _build_graph 自动展开 RunnableSequence/RunnableParallel)或 graphv2.StateGraph / CompiledStateGraph(通过 _build_state_graph):
- 普通
StateGraph边变成顺序edges_to; - 条件边变成
parallel_branches(渲染为虚线 Mermaid 箭头),让动态路由在视觉上可区分; - 引用到
START(__start__)和END时添加对应标记; - 若某节点同时有普通边与条件边,只保留条件视图(运行期条件优先)。
内部的 _StateGraphNodeRef 是一个不可执行的 Runnable 代理,纯粹作为标签载体,用于可视化那些节点本身不是 runnable 的图。
七、管道强制转换规则(速查表)
| 左侧 | 右侧 | | 之后的类型 |
|---|---|---|
| Runnable | Runnable | RunnableSequence |
| Runnable | 可调用对象 | RunnableSequence(右端包装为 RunnableLambda) |
| Runnable | dict[str, Runnable|callable] | RunnableSequence(右端变为 RunnableParallel) |
| dict | Runnable | RunnableSequence(左端变为 RunnableParallel) |
| 可调用对象 | Runnable | RunnableSequence(左端包装为 RunnableLambda) |
八、与 Upsonic 其余模块的集成
UEL 是基础层,多个模块依赖它:
| 模块 | 如何使用 UEL |
|---|---|
| src/upsonic/models/init.py | 基类 Model 是 class Model(Runnable[Any, Any]),重写 invoke/ainvoke,因此任何 provider 子类(OpenAI、Anthropic、Bedrock…)都能放进 UEL 链路;模型模块还从 upsonic.uel.output_parser 导入 StrOutputParser、PydanticOutputParser 用于结构化输出配置 |
src/upsonic/graphv2/state_graph.py |
StateGraph(及 CompiledStateGraph)继承 upsonic.uel.runnable.Runnable,状态图本身就是链步骤;图模块也调用 upsonic.uel.graph 的 RunnableGraph 渲染节点/边结构 |
src/upsonic/messages(被消费) |
UEL 从 upsonic.messages 导入 ModelRequest、ModelResponse、SystemPromptPart、UserPromptPart、TextPart(用于 prompt.py 与 output_parser.py) |
src/upsonic/usage、src/upsonic/_utils |
prompt.py 导入 RequestUsage 与 now_utc() 构造 few-shot AI 轮的占位 ModelResponse |
因此,典型的 Upsonic Agent 路径是:
ChatPromptTemplate (Runnable) | Model (Runnable, provider 子类) | OutputParser (Runnable)
同样的组合方式也用于 graphv2 节点内部,以及更高层的预构建 Agent(src/upsonic/prebuilt/...)中任何需要确定性 prompt-model-parse 步骤的场景。
九、端到端示例
9.1 线性流水线追踪
from upsonic.uel import ChatPromptTemplate, StrOutputParser
from upsonic import infer_model
prompt = ChatPromptTemplate.from_template("Tell me a joke about {topic}")
model = infer_model("openai/gpt-4o")
parser = StrOutputParser()
chain = prompt | model | parser
result = chain.invoke({"topic": "bears"})
运行期发生了什么:
prompt | model——Runnable.__or__执行:coerce_to_runnable(model)→ 返回model(本身已是Runnable);- 构建
RunnableSequence(steps=[prompt, model])。
(prompt | model) | parser——RunnableSequence.__or__执行:- 返回
RunnableSequence(steps=[prompt, model, parser])(扁平,非嵌套)。
- 返回
chain.invoke({"topic": "bears"}):prompt.invoke({"topic": "bears"})→ModelRequest(parts=[UserPromptPart("Tell me a joke about bears")]);model.invoke(<ModelRequest>)→ 调用 provider,返回ModelResponse;parser.invoke(<ModelResponse>)→ 返回response.parts[-1].content作为str。
9.2 并行 + 赋值 + 分支的组合链路
from upsonic.uel import (
ChatPromptTemplate, RunnablePassthrough, RunnableBranch,
RunnableParallel, StrOutputParser, itemgetter,
)
from upsonic import infer_model
model = infer_model("openai/gpt-4o")
summarize = ChatPromptTemplate.from_template("Summarize: {text}") | model | StrOutputParser()
classify = ChatPromptTemplate.from_template("Classify topic of: {text}") | model | StrOutputParser()
short_chain = ChatPromptTemplate.from_template("Short reply about: {text}") | model | StrOutputParser()
long_chain = ChatPromptTemplate.from_template("Long essay about: {text}") | model | StrOutputParser()
pipeline = (
RunnablePassthrough.assign(
word_count=lambda x: len(x["text"].split()),
)
| RunnableParallel(
summary=summarize,
topic=classify,
original=itemgetter("text"),
)
| RunnableBranch(
(lambda d: len(d["original"]) < 200, short_chain | (lambda s: {"reply": s})),
long_chain | (lambda s: {"reply": s}),
)
)
print(pipeline.invoke({"text": "Once upon a time ..."}))
逐步解读:
RunnablePassthrough.assign(word_count=...)—— 复制输入字典,基于运行中字典计算并存储word_count;RunnableParallel(summary=…, topic=…, original=itemgetter("text"))—— 通过asyncio.gather并发执行 3 个ainvoke,返回{"summary": str, "topic": str, "original": str};RunnableBranch—— 检查len(d["original"]) < 200,路由到short_chain或默认的long_chain;此处分支臂本身是包含尾部 lambda(把字符串包进 dict)的RunnableSequence。
9.3 可视化链路
print(pipeline.get_graph().to_ascii())
输出缩进树,并行分支以 ├─> / └─> 标记并带并行键名。pipeline.get_graph().to_mermaid() 返回可粘贴进任意 Mermaid 渲染器的源码:并行分叉以带分支键标签的虚线箭头输出,顺序边为 ==>。
9.4 可视化 StateGraph
from upsonic.graphv2.state_graph import StateGraph
g = StateGraph(SomeState).add_node("a", a_fn).add_node("b", b_fn).add_edge("__start__", "a").add_edge("a", "b")
print(g.get_graph().to_mermaid()) # 内部使用 RunnableGraph
StateGraph 的条件边渲染为虚线 Mermaid 箭头,与静态边视觉区分;引用到时添加 START / END。
9.5 通过 @chain 构建动态链路
@chain
def smart_route(data: dict):
if data["needs_rag"]:
return rag_chain # ChainRunnable 会用 data 调用它
return ChatPromptTemplate.from_template("Answer: {q}") | model | StrOutputParser()
smart_route.invoke({"needs_rag": True, "q": "What is Upsonic?"})
smart_route 本身就是一个 Runnable,因此可以作为任何更大链路中的合法步骤。
十、测试验证与实现佐证
仓库中针对 UEL 有直接的测试覆盖:tests/smoke_tests/uel/test_all_scenarios.py 从 upsonic.uel 导入 ChatPromptTemplate、RunnablePassthrough、StrOutputParser,覆盖四种内存模式(auto / always / never / record_all)、placeholder 注入、多链 RAG 模式、空历史、顺序占位符调用等场景——验证了 ChatPromptTemplate 的 placeholder 动态注入与消息透传行为正是 UEL 提示模板与模型内存系统协同工作的关键路径。另有 tests/unit_tests/test_lcel.py 与 tests/unit_tests/test_lcel_focused_issues.py 从 LCEL 视角验证链式组合的正确性。
结语
UEL 刻意保持小巧:它只形式化"步骤如何连接"(Runnable、管道操作符、sequence/parallel/branch/passthrough)、"任意 Python 如何进入链路"(RunnableLambda、coerce_to_runnable、@chain)以及"链路如何被内省"(RunnableGraph)。一切领域相关的部分(模型、工具、内存、Agent、RAG、安全)都位于该文件夹之外,仅仅是 使用 Runnable 协议而已。理解 UEL,就等于理解了整个 Upsonic 一切组合能力的底层语法。