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

构建CSV对话LLM链时遇LLMChain ValidationError问题求助

解决ConversationalRetrievalChain的"llm需为Runnable类型实例"错误

问题根源

Langchain v0.1版本后,核心组件全面切换到Runnable接口体系,ConversationalRetrievalChain不再接受旧版的LLM类实例,必须传入符合Runnable标准的对象。如果你的代码基于旧版Langchain写法(直接用TransformersPipeline或LLM子类),就会触发该验证错误。

具体修复方案

1. 确认并升级Langchain版本

先检查当前Langchain版本:

pip show langchain

如果版本低于0.1,升级到最新稳定版:

pip install --upgrade langchain langchain-community langchain-core

2. 适配Runnable接口包装LLM

以Mistral-7B-Instruct-v0.1为例,将模型包装为符合要求的Runnable实例,同时适配ConversationalRetrievalChain的新版用法:

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_community.llms.huggingface_pipeline import HuggingFacePipeline
from langchain.chains import ConversationalRetrievalChain
from langchain.chains.combine_documents import create_stuff_documents_chain
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
from langchain_community.vectorstores import FAISS
from langchain_text_splitters import CharacterTextSplitter

# 加载CSV数据并构建FAISS检索器(示例代码)
# 假设你已经完成CSV数据加载、文本分割、向量化,得到faiss_db
# faiss_db = FAISS.from_documents(split_docs, embedding_model)
retriever = faiss_db.as_retriever()

# 加载Mistral模型和tokenizer
model_name = "mistralai/Mistral-7B-Instruct-v0.1"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name)

# 创建符合Runnable标准的HuggingFacePipeline
pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    max_new_tokens=512,
    temperature=0.7,
    top_p=0.95,
    repetition_penalty=1.15
)
llm = HuggingFacePipeline(pipeline=pipe)

# 构建对话提示模板
prompt = ChatPromptTemplate.from_messages([
    ("system", "你是基于CSV数据的助手,根据提供的上下文回答用户问题:\n{context}"),
    ("human", "对话历史:{chat_history}\n当前问题:{question}")
])

# 创建文档合并链,再实例化对话检索链
combine_docs_chain = create_stuff_documents_chain(llm, prompt)
retrieval_chain = ConversationalRetrievalChain.from_llm(
    llm=llm,
    retriever=retriever,
    combine_docs_chain=combine_docs_chain
)

3. 关键注意事项

  • HuggingFacePipeline在Langchain v0.1+中已实现Runnable接口,可直接作为llm参数传入
  • 确保retriever是FAISS对应的Langchain Retriever实例(通过FAISS.as_retriever()生成)
  • 若使用ChatHuggingFace类,同样符合Runnable要求,可替代HuggingFacePipeline

验证修复

测试对话功能:

chat_history = []
question = "CSV数据中的XX字段代表什么?"
result = retrieval_chain.invoke({"question": question, "chat_history": chat_history})
print(result["answer"])

内容的提问来源于stack exchange,提问作者aadil gani

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 19:19:51