上篇文章《5分鐘了解LangChain的路由鏈》里主要介紹了路由鏈,核心類是LLMRouterChain和MultiPromptChain。本文介紹LangChain里的另外1個重要的鏈:轉(zhuǎn)換鏈。

在開發(fā)AI Agent(智能體)時,我們經(jīng)常需要對輸入數(shù)據(jù)進行預(yù)處理,這樣可以更好地利用LLM。LangChain提供了一個強大的工具——轉(zhuǎn)換鏈(TransformChain),它可以幫我們輕松實現(xiàn)這一任務(wù)。
轉(zhuǎn)換鏈(TransformChain)主要是將 給定的數(shù)據(jù) 按照某個函數(shù)進行轉(zhuǎn)換,再將 轉(zhuǎn)換后的結(jié)果 輸出給LLM。 所以轉(zhuǎn)換鏈的核心是:根據(jù)業(yè)務(wù)邏輯編寫合適的轉(zhuǎn)換函數(shù)。
其實,轉(zhuǎn)換鏈的設(shè)計也很精妙,從源碼可以看出,它只是做了一條鏈,然后具體的任務(wù)完全丟給了外部的函數(shù)來實現(xiàn)。在LangChain里只要是鏈,就可以隨處鏈接。

轉(zhuǎn)換鏈只有1個核心類,TransformChain。
有時,我們在將數(shù)據(jù)發(fā)送給LLM之前,希望對其做一些操作時(比如替換一些字符串、截取部分文本等等),就會用到轉(zhuǎn)換鏈。TransformChain 在 NLP 中很重要,有些場景還很實用。
一般使用轉(zhuǎn)換鏈有幾個固定步驟:
比如,給定LLM一篇很長的文章,但是我只想讓LLM幫我總結(jié)文章前3自然段的內(nèi)容,同時,總結(jié)之前,我還需要將自然段里的 部分字段 替換成 給定字段。
具體代碼如下:
from langchain.prompts import PromptTemplatefrom langchain.chains import LLMChain, TransformChain, SimpleSequentialChainfrom langchain_openai import OpenAI, ChatOpenAIfile_content = ""with open("./file_data.txt", "r") as file: file_content = file.read()# 定義轉(zhuǎn)換函數(shù),截取文章前8段,再替換部分字符串def transform_func(data): text = data["input_text"] shortened_text = "/n".join(text.split("/n")[:7]) transform_shortened_text: str = shortened_text.replace( "PVC", "PersistentVolumeClaim" ).replace("PV", "PersistentVolume") return {"output_text": transform_shortened_text}# 定義轉(zhuǎn)換鏈transform_chain = TransformChain( input_variables=["input_text"], output_variables=["output_text"], transform=transform_func,)# 定義LLMmodel = ChatOpenAI( model_name="gpt-3.5-turbo", openai_api_key="sk-xxxxxx", openai_api_base="https://api.302.ai/v1",)# 定義提示詞模板 和 LLM鏈prompt_template = """請你對下面的文字進行總結(jié):{output_text}總結(jié):"""prompt = PromptTemplate(input_variables=["output_text"], template=prompt_template)llm_chain = LLMChain( llm=model, prompt=prompt,)# 使用順序鏈連接起來final_chain = SimpleSequentialChain(chains=[transform_chain, llm_chain])res = final_chain.run(file_content)print(res)代碼執(zhí)行結(jié)果符合預(yù)期??偨Y(jié)的結(jié)果很精通,同時也是按照給定的字符串返回的。
這篇博客主要介紹了LangChain中的轉(zhuǎn)換鏈(TransformChain)的概念,它主要用在需要對輸入的內(nèi)容進行轉(zhuǎn)換的場景下。希望對你有幫助!
本文鏈接:http://m.www897cc.com/showinfo-26-96420-0.htmlLangChain轉(zhuǎn)換鏈:讓數(shù)據(jù)處理更精準(zhǔn)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。郵件:2376512515@qq.com