2026-10-21 05:32:15
langchain_huggingface 是由 Hugging Face 和 LangChain 共同维护的合作伙伴包,旨在将 Hugging Face 的最新功能高效引入 LangChain 生态,提供无缝集成体验,并缩短新功能落地周期。
核心功能与优势技术整合与同步更新
包由双方共同维护,确保 Hugging Face 生态的新功能(如模型、API)能快速集成到 LangChain 中,减少社区贡献类因缺乏内部视角导致的废弃问题。
支持 Hugging Face 工具箱中的通用工具(如 transformers 的 Pipeline 类),并针对 LangChain 的 RAG 和 Agent 场景优化,聚焦文本生成、摘要、翻译等任务。
资源利用灵活性
本地运行:通过 HuggingFacePipeline 直接加载模型至本地,适合资源充足的场景,但受限于本机硬件(如 GPU 内存)。
无服务器 API:通过 HuggingFaceEndpoint 调用远程部署的模型(如 TGI 实例),支持专业账户或企业 Hub 的用户,普通用户可通过设置 HF 令牌在免费配额内使用。
HuggingFacePipeline
直接加载模型:使用 from_model_id 方法指定模型 ID 和任务类型(如 text-generation),并配置生成参数(如 max_new_tokens、temperature)。
from langchain_huggingface import HuggingFacePipelinellm = HuggingFacePipeline.from_model_id( model_id="microsoft/Phi-3-mini-4k-instruct", task="text-generation", pipeline_kwargs={"max_new_tokens": 100, "temperature": 0.1})llm.invoke("Hugging Face is")自定义流水线:通过 transformers 库手动构建模型、分词器和流水线,再传入 HuggingFacePipeline 类。
from transformers import AutoModelForCausalLM, AutoTokenizer, pipelinemodel = AutoModelForCausalLM.from_pretrained("microsoft/Phi-3-mini-4k-instruct", load_in_4bit=True)pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)llm = HuggingFacePipeline(pipeline=pipe)HuggingFaceEndpoint
通过模型仓库 ID 调用:指定 repo_id 和任务类型,适用于 Hugging Face Hub 上的公开模型。
from langchain_huggingface import HuggingFaceEndpointllm = HuggingFaceEndpoint( repo_id="meta-llama/Meta-Llama-3-8B-Instruct", task="text-generation", max_new_tokens=100)通过终端 URL 调用:适用于自定义部署的 TGI 实例,需配置 endpoint_url 和认证令牌。
llm = HuggingFaceEndpoint( endpoint_url="<endpoint_url>", task="text-generation", huggingfacehub_api_token="<HF_TOKEN>")HuggingFaceEmbeddings
基于 sentence-transformers 计算嵌入,需本地运行模型(如 mixedbread-ai/mxbai-embed-large-v1),适合小规模文本处理。
from langchain_huggingface.embeddings import HuggingFaceEmbeddingsembeddings = HuggingFaceEmbeddings(model_name="mixedbread-ai/mxbai-embed-large-v1")embeddings.embed_documents(["Hello, world!", "How are you?"])HuggingFaceEndpointEmbeddings
通过 InferenceClient 调用远程嵌入模型,支持 Hub 模型或本地/在线部署的 TEI 实例,适合大规模或高性能需求。
from langchain_huggingface.embeddings import HuggingFaceEndpointEmbeddingsembeddings = HuggingFaceEndpointEmbeddings( model="mixedbread-ai/mxbai-embed-large-v1", task="feature-extraction", huggingfacehub_api_token="<HF_TOKEN>")