在Colab上试跑langchain 和 huggingface的整合

文章讲述了如何在Colab环境中配置HuggingFace的APIToken,利用HuggingFaceHub加载模型`google/flan-t5-large`创建问答提示模板,并通过LLMChain进行用户问题的回答,展示了一个基于HuggingFace的问答系统实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

环境准备:

获取【HUGGINGFACEHUB_API_TOKEN】,登录huggingface官网并完成注册。

官网:https://huggingface.co/

获取token:https://huggingface.co/settings/tokens

在colab上安装 huggingface_hub

!pip install -q huggingface_hub

【1】创建问答提示模版Creating a Question-Answering Prompt Template

from langchain import PromptTemplate

template = """Question: {question}

Answer: """
prompt = PromptTemplate(
        template=template,
    input_variables=['question']
)

# user question
question = "What is the capital city of China?"

【2】使用huggingface_hub模型“google/flan-t5-large”来回答问题,huggingfaceHub 类将连接到 HuggingFace 的推理 API 并加载指定的模型。

from langchain import HuggingFaceHub, LLMChain

# initialize Hub LLM
hub_llm = HuggingFaceHub(
        repo_id='google/flan-t5-large',
    model_kwargs={'temperature':0},
    huggingfacehub_api_token='your huggingfacehub_api_token'
)

# create prompt template > LLM chain
llm_chain = LLMChain(
    prompt=prompt,
    llm=hub_llm
)

# ask the user question about the capital of France
print(llm_chain.run(question))

【3】输出结果

beijing

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值