Using create_sql_query_chain with some models generates incorrect SQL what am i doing wrong? #26811
Replies: 1 comment 6 replies
-
Hey there, @RollsChris! I'm here to help you out with any bugs, questions, or contributions while you wait for a human maintainer. Let's dive in and tackle this issue together! I found a similar solved discussion that might help you with your issue [1]. The error you're encountering is due to the SQL query being wrapped in triple backticks, which is not valid SQL syntax. To resolve this issue, you need to ensure that the query generated by the LLM does not include these backticks. Here’s how you can modify your code to handle this:
from langchain_community.tools.sql_database.tool import QuerySQLDataBaseTool
class CustomQuerySQLDataBaseTool(QuerySQLDataBaseTool):
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> Union[str, Sequence[Dict[str, Any]], Result]:
# Clean up the query by removing triple backticks
cleaned_query = query.strip("```sql\n").strip("\n```")
return self.db.run_no_throw(cleaned_query)
import os
from dotenv import load_dotenv
from langchain_community.utilities import SQLDatabase
from langchain_openai import AzureChatOpenAI
from langchain.chains import create_sql_query_chain
load_dotenv()
db_url = f"sqlite:///{os.getenv('DB_PATH')}"
db = SQLDatabase.from_uri(db_url)
llm = AzureChatOpenAI(
temperature=0,
azure_endpoint=os.environ["AZURE_OPENAI_ENDPOINT"],
azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"],
openai_api_version=os.environ["AZURE_OPENAI_API_VERSION"],
)
# Use the custom tool
execute_query = CustomQuerySQLDataBaseTool(db=db)
write_query = create_sql_query_chain(llm, db)
chain = write_query | execute_query
response = chain.invoke({"question": "How many artists are there"})
print(response) This should ensure that the SQL query generated by the LLM is correctly formatted and executable by the SQLite database. Additionally, make sure you are using the correct configurations and settings for SQLite databases to avoid syntax errors. Refer to the |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Checked other resources
Commit to Help
Example Code
Description
The output of the above code using
gpt-4o-mini
:which when run against the db fails with:
The generated SQL Prompt is:
Please note i do get a successful query to run from
gpt-3.5-turbo
Thanks for any help given
System Info
langchain==0.3.0
langchain-anthropic==0.2.1
langchain-chroma==0.1.4
langchain-community==0.3.0
langchain-core==0.3.2
langchain-openai==0.2.0
langchain-text-splitters==0.3.0
langchainhub==0.1.21
System: Docker devcontainer mcr.microsoft.com/devcontainers/miniconda:1-3
python --version = 3.12.4
Beta Was this translation helpful? Give feedback.
All reactions