[Python] Chat with Sql: I want to show query result table in the form of dataframe in my web...

Discussão em 'Python' iniciado por Stack, Dezembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    The code generates a SQL query, executes it, and stores the result in a variable named result. I want to display this result as a data frame, including the column names from the original query. I am using the latest version of every library.

    #To load the database
    os.environ["OPENAI_API_KEY"]=os.getenv("OPENAI_API_KEY")

    def load_db(db_name):
    db=SQLDatabase.from_uri(f"sqlite:///Chinook.db")
    return db

    # to create sql query chain to execute queries
    def chain_create(db):
    llm = ChatOpenAI(model="gpt-3.5-turbo")
    chain = create_sql_query_chain(llm, db)
    return chain

    # To create another chain to answer the queries based on the data retrieved by querying

    def sql_infer(db,chain,user_question):
    sql_query=chain.invoke({"question":user_question})
    result=db.run(sql_query)
    print(result)
    print(type(result))

    st.code(sql_query)
    st.write(result)

    answer_prompt=PromptTemplate.from_template(
    """Given the following user question, corresponding SQL query, and SQL result,
    generate a proper reply to give to user

    Question:{question}
    SQL Query:{query}
    SQL Result:{result}
    Answer:"""
    )
    llm_model=ChatOpenAI(model="gpt-3.5-turbo")
    llm=LLMChain(llm=llm_model,prompt=answer_prompt)
    ans=llm(inputs={"question":user_question,"query":sql_query,"result":result})
    return ans["text"]


    Can anyone give me a hint on how I should approach this?

    Continue reading...

Compartilhe esta Página