langchain-ai / langchain

🦜🔗 Build context-aware reasoning applications
https://python.langchain.com
MIT License
88.49k stars 13.9k forks source link

create_sql_query_chain returns SQL queries with SQL markdowns #22208

Open SahasPunchihewa opened 1 month ago

SahasPunchihewa commented 1 month ago

Checked other resources

Example Code

import os

from langchain.chains.sql_database.query import create_sql_query_chain from langchain_community.utilities import SQLDatabase from langchain_openai import ChatOpenAI

db_user = "" db_password = "" db_host = "" db_name = ""

db = SQLDatabase.from_uri(f"postgresql+psycopg2://{db_user}:{db_password}@{db_host}/{db_name}")

os.environ["OPENAI_API_KEY"] = ""

llm = ChatOpenAI(model="gpt-4o")

chain = create_sql_query_chain(llm, db) response = chain.invoke({"question": "How many users are there"}) print(response)

Error Message and Stack Trace (if applicable)

"```sql SELECT COUNT(*) AS "user_count" FROM "users";



### Description

I'm trying to create an NL2SQL model with Lang chain with Postgres SQL database.
So I've expected a SQL query as plain text as the output but it returns a Query with markdowns that will cause issues when executing it

### System Info

platform: windows
python: 3.12
keenborder786 commented 1 month ago

Do the following:

chain = create_sql_query_chain(llm, db)
chain | RunnableLambda(lambda x:x.replace('```','').replace('sql',''))