Transformation(轉換鏈)是 LangChain 中用于“自定義數據處理”的鏈式工具,允許你在鏈路中插入任意 Python 代碼,對輸入或中間結果進行靈活處理。常用于:
- 對輸入/輸出做格式化、過濾、摘要、拆分等自定義操作
- 作為 LLMChain 等鏈的前置或后置處理環節
典型用法舉例
假設你有一段長文本,想先用 Python 代碼提取前3段,再交給大模型總結:
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI
from langchain.chains import SimpleSequentialChain# 讀取待處理文本內容
with open("letter.txt", "r") as f:letters = f.read()from langchain.chains import (LLMChain,SimpleSequentialChain,TransformChain
)# 定義轉換函數:只取前三個段落
def transform_func(inputs:dict) -> dict:text = inputs["content"]trans_text = "\n\n".join(text.split("\n\n")[:3])return {"summary": trans_text}# 構建文檔轉換鏈,將原始內容轉換為摘要內容
transform_chain = TransformChain(input_variables=["content"],output_variables=["summary"],transform=transform_func
)# 總結用的prompt模板
template = """總結下面的內容:
{summary}
總結:"""prompt = PromptTemplate(input_variables=["summary"],template=template
)print(prompt) # 打印prompt模板# 使用騰訊混元大模型作為LLM
llm = ChatOpenAI(api_key=SecretStr(os.environ.get("HUNYUAN_API_KEY", "")),base_url="https://api.hunyuan.cloud.tencent.com/v1",model="hunyuan-t1-latest",temperature=0,
)# 構建LLM鏈,輸入為summary,輸出為總結
llm_chain = LLMChain(llm=llm,prompt=prompt
)# 順序鏈:先transform,再總結
sequential_chain = SimpleSequentialChain(chains=[transform_chain, llm_chain],verbose=True
)# 執行順序鏈,輸出最終結果
print(sequential_chain.run(letters))
輸出:
input_variables=['summary'] template='總結下面的內容:\n{summary}\n總結:'> Entering new SimpleSequentialChain chain...
Dear Dr. Smith,I hope this letter finds you well. I am writing to express my sincere gratitude for your guidance and support throughout my recent research project on "Deep Learning-Based Image Recognition for Medical Diagnosis." Specifically, my research focused on applying convolutional neural networks (CNNs) to the automatic detection and classification of medical images, such as identifying pathological features in X-rays and MRI scans. I explored methods to improve model accuracy and robustness, including data augmentation, transfer learning, and the integration of attention mechanisms to enhance feature extraction. Your expertise and encouragement have been invaluable to my academic growth, and I truly appreciate the time and effort you have dedicated to mentoring me.The insights you provided, especially regarding the optimization of convolutional neural network architectures and the interpretation of experimental results, not only helped me overcome several challenges but also inspired me to explore new directions in my work. I am especially grateful for your constructive feedback during our discussions, which greatly improved the quality of my research.
這是一封致Dr. Smith的感謝信,作者主要表達對其在“基于深度學習的醫學診斷圖像識別”研究項目中的指導與支持的誠摯謝意。研究聚焦于應用卷積神經網絡(CNN)實現醫學影像(如X光、MRI)的自動檢測與分類,并探索了數據增強、遷移學習及注意力機制等方法以提升模型準確性與魯棒性。作者特別感謝Dr. Smith在優化CNN架構、解讀實驗結果等方面的專業建議,以及討論中提供的建設性反饋,這些幫助其克服挑戰并提升了研究質量,對其學術成長意義重大。> Finished chain.
這是一封致Dr. Smith的感謝信,作者主要表達對其在“基于深度學習的醫學診斷圖像識別”研究項目中的指導與支持的誠摯謝意。研究聚焦于應用卷積神經網絡(CNN)實現醫學影像(如X光、MRI)的自動檢測與分類,并探索了數據增強、遷移學習及注意力機制等方法以提升模型準確性與魯棒性。作者特別感謝Dr. Smith在優化CNN架構、解讀實驗結果等方面的專業建議,以及討論中提供的建設性反饋,這些幫助其克服挑戰并提升了研究質量,對其學術成長意義重大。
關鍵點說明
- TransformChain 允許插入任意 Python 邏輯,極大增強鏈式流程的靈活性。
- 可與 LLMChain、SimpleSequentialChain 等組合,實現“預處理-大模型-后處理”流水線。
- 適合數據清洗、格式轉換、摘要、實體提取等場景。