Umang Bisht
Umang Bisht

Reputation: 21

Langchain : Querying from postgresql database using SQLDatabaseChain

i am querying postgresql database using langchain. For this i am using Claude llm whose api key is anthropic_api_key. I am connecting postgresql database using SQLDatabase.from_uri() method.

this is my code inside file postgres_db.py

from langchain import  SQLDatabase
from constants import anthropic_key
from langchain.chat_models import ChatAnthropic
from langchain_experimental.sql import SQLDatabaseChain
from langchain.agents.agent_toolkits import SQLDatabaseToolkit
from langchain.agents import create_sql_agent
from langchain.agents.agent_types import AgentType
import os

os.environ["ANTHROPIC_API_KEY"] = anthropic_key

API_KEY = anthropic_key

# Setup database
db = SQLDatabase.from_uri(
    f"postgresql+psycopg2://postgres:umang123@localhost:5432/delhi_cime_2",
)

# setup llm
llm = ChatAnthropic(temperature=0)

# Create db chain
QUERY = """
Given an input question, first create a syntactically correct postgresql query to run, then look at the results of the query and return the answer.
Use the following format:

"Question": "Question here"
"SQLQuery": "SQL Query to run"
"SQLResult": "Result of the SQLQuery"
"Answer": "Final answer here"

"{question}"
"""

# Setup the database chain
db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)


def get_prompt():
    print("Type 'exit' to quit")

    while True:
        prompt = input("Enter a prompt: ")

        if prompt.lower() == 'exit':
            print('Exiting...')
            break
        else:
            try:
                question = QUERY.format(question=prompt)
                result = db_chain.run(question)
                print(result)
            except Exception as e:
                print("eeeeeeeeeeeeeeeeeee",e)
                pass

get_prompt()

when i am executing the above script using python postgres_db.py command stuck in this error which i am attaching as a screenshot of terminal. SQL query is correct in this screenshot as when i am executing this query i am getting the correct records i.e. 6 records from the database but it showing only 1 also giving a syntax error. Please help me in solving this.

error on terminal image file

Thanks in advance

Upvotes: 1

Views: 5126

Answers (1)

ZKS
ZKS

Reputation: 2816

The error that you are getting is because of parsing issue. Output parser is an issue when you work with different chain and LLM.

You can try with DatabaseToolkit

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

    agent_executor = create_sql_agent(
        llm=self.llm,
        toolkit=toolkit,
        verbose=True
    )

    with get_openai_callback() as cb:
        res = agent_executor.run(query)
        print("SQL Query Result:")
        print(res)
        

Upvotes: 2

Related Questions