LangChain Hugging Face Integration

1.2.1 · active · verified Sat Apr 11

Langchain-huggingface provides integrations to leverage Hugging Face models and pipelines within the LangChain ecosystem. This includes support for various Hugging Face LLMs and embeddings, allowing users to connect to the Hugging Face Hub, Inference Endpoints, or run models locally via the transformers library. As of its current version 1.2.1, it's a dedicated integration package that follows LangChain's modular architecture, with frequent updates aligning with the broader LangChain ecosystem.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `HuggingFacePipeline` to load a model and perform text generation. It uses `google/flan-t5-small` as an example, which works well for `text2text-generation` tasks. Ensure `transformers` and a deep learning backend (like `torch`) are installed.

import os
from langchain_huggingface.llms import HuggingFacePipeline
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser

# Set your Hugging Face API token if accessing models from the Hub
# os.environ["HUGGINGFACEHUB_API_TOKEN"] = os.environ.get("HUGGINGFACEHUB_API_TOKEN", "")

# Initialize the HuggingFacePipeline with a small, accessible model
# Ensure 'transformers' and a deep learning backend (e.g., 'torch') are installed.
llm = HuggingFacePipeline.from_model_id(
    model_id="google/flan-t5-small",
    task="text2text-generation",
    pipeline_kwargs={"max_new_tokens": 100},
    # Pass token explicitly if needed, e.g., for private models or inference endpoints
    # model_kwargs={"huggingfacehub_api_token": os.environ.get("HUGGINGFACEHUB_API_TOKEN", "")}
)

# Create a simple prompt template
template = "Question: {question}\nAnswer:"
prompt = PromptTemplate.from_template(template)

# Create a chain
chain = prompt | llm | StrOutputParser()

# Invoke the chain
question = "What is the capital of France?"
response = chain.invoke({"question": question})
print(response)

view raw JSON →