iT邦幫忙

2024 iThome 鐵人賽

DAY 10
0

接下來這篇要來介紹另一個langchain強大的功能,就是chain,其實就是能夠將多個對象組合在一起,直接讓它形成一個與模型溝通的流程,例如我們在前面的llm和promptTemplate直接兜在一起,我們之後想要用就可以接用這個chain來一次運行這些流程了!


LLMChain

首先我們先介紹一種類別,叫做LLMChain,主要會用到他的參數有: llm、prompt、memory等等
馬上就來實做看看:
首先要先一樣要先將要用到的庫import進來

from langchain_community.chat_models.ollama import ChatOllama
from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain

前面我們一樣用promptTemplate來做prompt模板

llm = ChatOllama(model="llama3")

template = """System: You are a pro gamer. Let's work this out in a step by step way to be sure we have the right answer.
Question: {question}"""
prompt_template = PromptTemplate.from_template(template)

然後就可以用LLMChain將流程串起來了

llm_chain = LLMChain(llm=llm, prompt=prompt_template, verbose=True)

這邊我們先沒有用memory這個參數,memory的部分會在之後的章節詳細講解,我們只用了llm、prompt、verbose這三個參數,verbose這個參數=True會將模型再輸入輸出時的更多訊息顯示再terminal,讓你可以更好的去理解模型、chain的運作,或是幫助你做各式各樣的微調等。

接下來就可以來跑這個chain測試了

response = llm_chain.run({"question": "Who is Malenia?"})
print(response)

成功跟模型交互的話,我們就可以在控制台看到模型的response了!

現在用的LLMChain是chain中的基本款,我們再來介紹一些好用,能做更多應用的chain!

SequentialChain

那我們就來看這個 SequentialChain,顧名思義,他就是能將多個步驟、chain按照順序串起來,每一個步驟的output都會是下一步的input,所以在需要複雜步驟時的場景下,他會是很強的實現工具。
那我們就馬上來用用看吧,首先一樣要先將會用到的庫import進來

from langchain_core.prompts import PromptTemplate
from langchain.chains import LLMChain, SequentialChain
from langchain_community.chat_models.ollama import ChatOllama

這邊一樣會用到LLMChain來當作我們基本步驟的Chain
然後就將兩個prompt模板和我想連接起來的兩個chain定義出來

llm = ChatOllama(model="llama3")

template_1 = PromptTemplate.from_template("Who is {AKA} in Elden Ring?")
template_2 = PromptTemplate.from_template("Give me some facts about {Name}")

llm_chain_1 = LLMChain(llm=llm, prompt=template_1, output_key = "Name")
llm_chain_2 = LLMChain(llm=llm, prompt=template_2, output_key = "Ans")

這邊可以發現在兩個llm_chain中,多指定了一個參數,就是output_key,他其實就是幫這個chain的output去命名,幫這兩個chain命名output_key,一來我們可以讓第二個Chain的template正確吃到"Name"這個模板內的參數,二來,因為我們現在有兩個Chain,或說兩個工作階段,將這兩個階段的output命名出來,我之後也就可以將兩個output分別print出來,分別查看。
接著就是寫SequentialChain的部分了

sequential_chain = SequentialChain(
    chains=[llm_chain1, llm_chain2], 
    input_variables=["AKA"], 
    output_variables=["Name", "Ans"],  
    verbose=True
)

這邊會先將要串的chain寫進來,記得chains裡面的chain是有順序性的,先寫的就會先跑
最後再加上

# 測試 SequentialChain
result = sequential_chain({"AKA": "Godfrey"})
print(result["Name"])  # 第一個 Chain 的輸出
print(result["Ans"])   # 第二個 Chain 的輸出

這樣我們的sequentialChain實作就成功了!

之後的篇幅會繼續介紹langchain實用的class!


上一篇
<玩轉大語言模型> LangChain: PromptTemplate
下一篇
<玩轉大語言模型> LangChain: Agent
系列文
LangChain、RAG、HuggingFace: 玩轉大語言模型12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言