You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

LangChain遍历LLM模型报错:prompt非有效字典问题咨询

问题原因与解决方案

核心问题

Flan-T5系列模型属于文本到文本的编码器-解码器架构,HuggingFaceHub调用它时,要求输入是包含inputs键的字典格式;而OpenAI模型接受普通字符串提示,LLMChain默认按字符串传递输入,导致Flan-T5的输入格式不匹配,触发ValidationError。

解决方法

方法1:直接适配HuggingFaceHub的输入格式

跳过LLMChain,直接给HuggingFaceHub实例传入符合要求的字典输入:

from langchain.llms import OpenAI, HuggingFaceHub

models = [
    OpenAI(api_key="your_openai_key"),
    HuggingFaceHub(repo_id="google/flan-t5-xl", huggingfacehub_api_token="your_hf_token")
]

prompt_text = "Answer this question: What is AI?"

for llm in models:
    if isinstance(llm, HuggingFaceHub):
        # 按HF Inference API要求传入字典
        response = llm.predict(inputs=prompt_text)
    else:
        # OpenAI直接用字符串提示
        response = llm(prompt_text)
    print(response)

方法2:用HuggingFacePipeline包装模型,兼容LLMChain

如果想继续使用LLMChain统一流程,用HuggingFacePipeline把Flan-T5包装成LangChain兼容的LLM实例,pipeline会自动处理输入格式:

from langchain.llms import OpenAI, HuggingFacePipeline
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from transformers import pipeline, AutoModelForSeq2SeqLM, AutoTokenizer

# 包装Flan-T5模型
model_id = "google/flan-t5-xl"
tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
text_gen_pipeline = pipeline(
    "text2text-generation",
    model=model,
    tokenizer=tokenizer,
    max_new_tokens=150
)
flan_t5_llm = HuggingFacePipeline(pipeline=text_gen_pipeline)

# 统一流程
prompt = PromptTemplate(
    input_variables=["question"],
    template="Answer this question: {question}"
)
models = [OpenAI(api_key="your_openai_key"), flan_t5_llm]

for llm in models:
    chain = LLMChain(llm=llm, prompt=prompt)
    response = chain.run(question="What is AI?")
    print(response)

关键说明

  • OpenAI的LLM实现内部已经处理了提示到模型输入的转换,所以支持字符串直接输入。
  • HuggingFaceHub调用的是Hugging Face远程推理API,不同模型的输入格式要求不同:文本生成模型(如GPT系列)接受字符串,文本到文本模型(如Flan-T5)要求字典格式的输入。
  • 使用HuggingFacePipeline本地加载模型时,pipeline组件会自动处理输入的格式化,因此可以无缝对接LLMChain。

内容的提问来源于stack exchange,提问作者Yogesh Haribhau Kulkarni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 12:34:53