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

使用SQL LangChain Agent操作SQLite数据库时生成SQL缺失列指定

问题解决:LangChain SQL Agent生成SQL缺失列

问题分析

你使用LangChain结合Gemini-1.5-flash构建SQL Agent时,执行描述reports_details表的请求,生成的SQL语句SELECT FROM reports_details LIMIT ? OFFSET ?缺少列指定,核心原因是使用了专为OpenAI设计的openai-functions agent类型,与Gemini模型的工具调用逻辑不兼容,导致模型无法正确生成获取表结构的SQL指令。

解决方案

1. 更换适配Gemini的Agent类型

将agent_type改为"tool-calling",这是LangChain为支持工具调用的模型(包括Gemini)设计的通用类型:

def get_conversational_model():
    model = ChatGoogleGenerativeAI(
        model="gemini-1.5-flash",
        temperature=0,
        max_tokens=None,
        timeout=None,
        max_retries=2)
        
    db = SQLDatabase.from_uri(f"sqlite:///{database}")
    # 更换为tool-calling类型的agent
    agent_executor = create_sql_agent(model, db=db, agent_type="tool-calling", verbose=True)
    response = agent_executor.invoke(f"获取{TABLE_NAME}表的完整结构,包括所有列名、数据类型和约束")
    print(response)
    
get_conversational_model()

2. 明确指令表述

避免使用自然语言中的"Describe",改为更明确的指令,比如"获取表的完整结构",减少模型歧义。

3. 手动指定数据库表(可选)

如果数据库表较多,可通过include_tables参数指定要访问的表,帮助Agent聚焦目标表:

db = SQLDatabase.from_uri(f"sqlite:///{database}", include_tables=[TABLE_NAME])

验证效果

调整后,Agent会生成正确的SQL来查询表结构,比如SQLite中获取表结构的语句通常是:

SELECT name, type, notnull, dflt_value, pk FROM pragma_table_info('reports_details');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 08:25:57