Adam Xia
Adam Xia

Reputation: 73

LangChain SQLDatabase Agent always has errors querying database

I tried to ask it a simple task which involves joining two different tables and the agents seems to be including extra an ' which leads to this error (this error does not appear when the prompt is simple and just asks about one table) has anyone else encountered this problem ??


Thought: The table names are correct. I should query the schema of these tables.
Action: schema_sql_db
Action Input: 'ods_crs_reservation, ods_crs_reservation_room_history'
Observation: Error: table_names {"ods_crs_reservation_room_history'", "'ods_crs_reservation"} not found in database
Thought: I must have made a typo. I should double check the table names.
Action: list_tables_sql_db
Action Input: ""

Upvotes: 2

Views: 3162

Answers (2)

Amir
Amir

Reputation: 16587

The following code works for langchain to 0.2.12:

from langchain import hub
from langchain_community.agent_toolkits import create_sql_agent, SQLDatabaseToolkit
from langchain_community.llms import HuggingFaceTextGenInference
from langchain_community.utilities import SQLDatabase

db = SQLDatabase.from_uri("sqlite:///static/Chinook.db")
ENDPOINT_URL = "YOUR TGI endpoint"

llm = HuggingFaceTextGenInference(
    inference_server_url=ENDPOINT_URL,
    max_new_tokens=512,
)

prompt_template = hub.pull("langchain-ai/sql-agent-system-prompt")
system_message = prompt_template.format(dialect="SQLite", top_k=5)

toolkit = SQLDatabaseToolkit(db=db, llm=llm)

agent_executor = create_sql_agent(
    llm, toolkit, state_modifier=system_message, verbose=True,
)

print(agent_executor.invoke({"input": "how many artists are there?"}))

Upvotes: 0

Erymenn
Erymenn

Reputation: 53

I got the same error and solved it by not using the toolkit but loading the tools separately with a slight modification on the schema one

from langchain.tools.sql_database.tool import (
InfoSQLDatabaseTool,
ListSQLDatabaseTool,
QueryCheckerTool,
QuerySQLDataBaseTool,
)

# assign your llm and db

info_sql_database_tool_description = """Input to this tool is a comma separated list of tables, output is the schema and sample rows for those tables.Be sure that the tables actually exist by calling list_tables_sql_db first! Example Input: table1, table2, table3"""

tools = [
QuerySQLDataBaseTool(db=db),
InfoSQLDatabaseTool(db=db, description=info_sql_database_tool_description),
ListSQLDatabaseTool(db=db),
QueryCheckerTool(db=db, llm=llm),
]

Upvotes: 2

Related Questions