在 LangChain 使用 Hugging Face 模型!
在 Hugging Face 上有成千上萬個可自由下載與使用的模型。Hugging Face 透過合作的 langchain-huggingface 函式庫與 LangChain 深度整合,你可以直接使用。
在這個練習中,你會載入並呼叫來自 Hugging Face 的 crumb/nano-mistral 模型。這是一個超輕量的 LLM,設計用於經過微調後可獲得更高效能。
本練習屬於課程
使用 LangChain 開發 LLM 應用
練習說明
- 從
langchain_huggingface匯入HuggingFacePipeline,以便操作 Hugging Face 模型。 - 透過呼叫
HuggingFacePipeline.from_model_id()定義一個文字生成 LLM。 - 設定
model_id參數來指定要使用哪個 Hugging Face 模型。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import the HuggingFacePipeline class for defining Hugging Face pipelines
from langchain_huggingface import ____
# Define the LLM from the Hugging Face model ID
llm = ____.from_model_id(
____="crumb/nano-mistral",
task="text-generation",
pipeline_kwargs={"max_new_tokens": 20}
)
prompt = "Hugging Face is"
# Invoke the model
response = llm.invoke(prompt)
print(response)