[LangChain] 09. Runnable接口 - 2
RunnableSequence
.pipe() 是逐個拼接,RunnableSequence.from([...]) 則是顯式聲明流程結構,將多個步驟寫成數組更清晰。
課堂練習:快速上手示例
import { ChatOllama } from "@langchain/ollama";
import { PromptTemplate } from "@langchain/core/prompts";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { RunnableLambda, RunnableSequence } from "@langchain/core/runnables";
// 1. 創建 Prompt 模板
const pt = PromptTemplate.fromTemplate("請使用中文解釋以下概念:{topic}");
// 2. 創建本地模型
const model = new ChatOllama({ model: "llama3", temperature: 0.7 });
// 3. 創建字符串解析器
const parser = new StringOutputParser();
// 4. 插件
const fn = (text) => {
return text.replace(/閉包/g, "*&*閉包*&*");
};
const highlight = RunnableLambda.from(fn);
const chain = RunnableSequence.from([pt, model, parser, highlight]);
const res = await chain.invoke({
topic: "閉包",
});
console.log(res);
RunnablePassthrough
將輸入原樣傳給輸出,中間不做任何處理。
import { RunnablePassthrough } from "@langchain/core/runnables";
const passthrough = new RunnablePassthrough();
// 相當于輸入什么,輸出就是什么
const result = await passthrough.invoke("Hello, LangChain!");
console.log(result); // 輸出:Hello, LangChain!
?? 這有什么意義?
實例化 RunnablePassthrough 的時候,接收一個配置對象,該對象中可以配置 func 副作用函數,用于對輸入做一些副作用處理,例如記錄日志、寫入數據庫、做埋點等。
import { RunnablePassthrough } from "@langchain/core/runnables";
const logger = new RunnablePassthrough({
// 一個副作用函數
func: async (input) => {
console.log("收到輸入:", input);
// 對輸入做一些副作用處理,例如記錄日志、寫入數據庫、做埋點等
},
});
const res = await logger.invoke("LangChain");
console.log(res);
有時希望為傳入的對象補充字段(如時間戳、用戶信息、API 結果等),這時可以使用 .assign()。 它的作用是“給上下文添加字段”,就像在中間插入一步 Object.assign:
import { RunnablePassthrough } from "@langchain/core/runnables";
const injector = RunnablePassthrough.assign({
timestamp: async () => new Date().toISOString(),
meta: async () => ({
region: "us-east",
requestId: "req-456",
}),
});
const result = await injector.invoke({ query: "Vue 是什么?" });
console.log(result);
/*
{
query: 'Vue 是什么?',
timestamp: '2025-08-11T08:07:35.358Z',
meta: { region: 'us-east', requestId: 'req-456' }
}
*/
可以用它來:
- 插入時間戳、用戶 ID、請求 ID
- 注入工具結果:摘要、標簽、翻譯、情緒分析
- 為 Prompt 添加額外字段
練習:
- 打印用戶輸入日志
- 注入 userId
- 拼接 prompt
- 調用本地模型
- 解析返回結果
import { RunnablePassthrough } from "@langchain/core/runnables";
const passthrough = new RunnablePassthrough({
func: async (input) => {
console.log("Received input:", input);
},
});
const res = await passthrough.invoke("什么是閉包");
console.log(res);

浙公網安備 33010602011771號