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

使用LangChain SQLDatabaseToolkit遇ValidationError:llm参数类型错误

排查LangChain结合Dolly-v2-12b创建SQL Agent时的ValidationError问题

问题现象

报错信息:

ValidationError: 1 validation error for SQLDatabaseToolkit
llm
value is not a valid dict (type=type_error.dict).

问题根源

直接将Hugging Face原生的model对象传入SQLDatabaseToolkit和create_sql_agent,但LangChain的工具组件不接受原生HF模型实例,需要使用LangChain封装的HF模型适配器完成兼容。

修正步骤

  • 导入LangChain的HuggingFacePipeline类,用于将transformers pipeline转换为LangChain兼容的LLM接口
  • 用transformers的pipeline封装原生模型,再通过HuggingFacePipeline生成LangChain可用的LLM对象
  • 将原代码中所有传入原生model的位置替换为封装后的LLM实例

修正后的完整代码

import torch
from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
from langchain.agents import create_sql_agent
from langchain.agents.agent_toolkits import SQLDatabaseToolkit
from langchain.sql_database import SQLDatabase
from langchain.llms import HuggingFacePipeline

# 定义模型和tokenizer
model_name = "databricks/dolly-v2-12b"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(
    model_name, 
    device_map="auto", 
    torch_dtype=torch.bfloat16
)

# 创建文本生成pipeline,配置生成参数
pipe = pipeline(
    "text-generation",
    model=model,
    tokenizer=tokenizer,
    max_new_tokens=512,
    temperature=0.7,
    top_p=0.95,
    repetition_penalty=1.15
)

# 封装为LangChain兼容的LLM实例
llm = HuggingFacePipeline(pipeline=pipe)

# 初始化SQL数据库
db = SQLDatabase.from_databricks(catalog="samples", schema="nyctaxi")

# 初始化SQL工具包
toolkit = SQLDatabaseToolkit(llm=llm, db=db)

# 创建SQL Agent
agent = create_sql_agent(llm=llm, toolkit=toolkit, verbose=True)

# 执行查询
query = "What is the longest trip distance and how long did it take?"
response = agent.run(query)

print(response)

关键说明

LangChain的SQLDatabaseToolkit和Agent体系依赖自身定义的LLM抽象接口,原生HF模型无法直接适配。HuggingFacePipeline作为中间适配器,将transformers的生成pipeline转换为LangChain能识别的LLM类型,从而实现和LangChain工具链的无缝对接。

内容的提问来源于stack exchange,提问作者Selva Nagamanickam

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 16:52:43