開始使用免費開始

在 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)
編輯並執行程式碼