iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0

上一篇我們介紹了LangChain並且簡單使用了一下,今天我們再繼續介紹一些常見的基礎用法!

各位應該都清楚知道prompt是什麼,我們在使用大語言模型時,prompt也是很重要的一環,你希望模型怎麼回答你,output遵循怎麼樣的格式,又或者是扮演一個怎樣的角色,而LangChain裡就有很好用的class,叫做PromptTemplate。


promptTemplate

promptTemplate是LnagChain裡很實用的一個class,你可以自己寫出你的prompt模板,再用實際的文本去替換,若是你之後想把這隻程式寫成一個application,像是一支對話api的話,就可以使用他動態生成prompt,達到想要實現的效果,下面就來簡單實做一下這種寫法

from langchain_core.prompts import PromptTemplate
from langchain_community.chat_models.ollama import ChatOllama

# 初始化模型
llm = ChatOllama(model="llama3", temperature=0.5, max_token=500)

# 設定 PromptTemplate 模板
template = """System: {system_prompt}

Question: {question}"""

prompt = PromptTemplate.from_template(template)

# 填入 system_prompt 和 question
system_prompt = "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 = "Who is Malenia? Who is Miqulle?"

full_prompt = prompt.format(system_prompt=system_prompt, question=question)

# 與模型交互
response = llm.invoke(full_prompt)
print(response)

這邊就是用PromptTemplate.from_template來創一個模板,之後再用.format來將system.prompt和question帶入生成最後給模型的prompt。

並且在model那邊設定了一些參數,能夠對模型做些微的調整,像是temperature,能夠控制模型輸出的方向,temperature越高,模型的輸出會更隨機多樣、更創新豐富,而temperature低的話,模型的輸出則會更保守、精確,並且一致性會更高,所以若是我需要的是一些準確的專業技術問答,或者是需要高準確率的預測結果,我的temperature可能就會設低一點。
這樣就完成了一個基礎的promptTemplate的使用!

之後我們會再繼續介紹LangChain其他好用的class!


上一篇
<玩轉大語言模型> LangChain: 玩轉語言模型的框架
下一篇
<玩轉大語言模型> LangChain: Chain 當我們鍊在一起
系列文
LangChain、RAG、HuggingFace: 玩轉大語言模型12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言