code: import streamlit as st
  from sqlalchemy import create_engine, inspect, text
  from typing import Dict, Any
  
  from llama_index import (
      VectorStoreIndex,
      ServiceContext,
      download_loader,
  )
  from llama_index.llama_pack.base import BaseLlamaPack
  from llama_index.llms import OpenAI
  import openai
  import os
  import pandas as pd
  
  from llama_index.llms.palm import PaLM
  
  from llama_index import (
      SimpleDirectoryReader,
      ServiceContext,
      StorageContext,
      VectorStoreIndex,
      load_index_from_storage,
  )
  import sqlite3
  
  from llama_index import SQLDatabase, ServiceContext
  from llama_index.indices.struct_store import NLSQLTableQueryEngine
  
  os.environ['OPENAI_API_KEY'] = st.secrets['OPENAI_API_KEY']
  
  
  class StreamlitChatPack(BaseLlamaPack):
  
      def __init__(
          self,
          page: str = "Natural Language to SQL Query",
          run_from_main: bool = False,
          **kwargs: Any,
      ) -> None:
          """Init params."""
          
          self.page = page
  
      def get_modules(self) -> Dict[str, Any]:
          """Get modules."""
          return {}
  
      def run(self, *args: Any, **kwargs: Any) -> Any:
          """Run the pipeline."""
          import streamlit as st
  
          st.set_page_config(
              page_title=f"{self.page}",
              layout="centered",
              initial_sidebar_state="auto",
              menu_items=None,
          )
  
          if "messages" not in st.session_state:  # Initialize the chat messages history
              st.session_state["messages"] = [
                  {"role": "assistant", "content": f"Hello. Ask me anything related to the database."}
              ]
  
          st.title(
              f"{self.page}💬"
          )
          st.info(
              f"Explore Snowflake views with this AI-powered app. Pose any question and receive exact SQL queries.",
              icon="ℹ️",
          )
  
          def add_to_message_history(role, content):
              message = {"role": role, "content": str(content)}
              st.session_state["messages"].append(
                  message
              )  # Add response to message history
  
          def get_table_data(table_name, conn):
              query = f"SELECT * FROM {table_name}"
              df = pd.read_sql_query(query, conn)
              return df
  
          @st.cache_resource
          def load_db_llm():
              # Load the SQLite database
              #engine = create_engine("sqlite:///ecommerce_platform1.db")
              engine = create_engine("sqlite:///ecommerce_platform1.db?mode=ro", connect_args={"uri": True})
  
              sql_database = SQLDatabase(engine) #include all tables
  
              # Initialize LLM
              #llm2 = PaLM(api_key=os.environ["GOOGLE_API_KEY"])  # Replace with your API key
              llm2 = OpenAI(temperature=0.1, model="gpt-3.5-turbo-1106")
  
              service_context = ServiceContext.from_defaults(llm=llm2, embed_model="local")
              
              return sql_database, service_context, engine
  
          sql_database, service_context, engine = load_db_llm()
  
  
         # Sidebar for database schema viewer
          st.sidebar.markdown("## Database Schema Viewer")
  
          # Create an inspector object
          inspector = inspect(engine)
  
          # Get list of tables in the database
          table_names = inspector.get_table_names()
  
          # Sidebar selection for tables
          selected_table = st.sidebar.selectbox("Select a Table", table_names)
  
          db_file = 'ecommerce_platform1.db'
          conn = sqlite3.connect(db_file)
      
          # Display the selected table
          if selected_table:
              df = get_table_data(selected_table, conn)
              st.sidebar.text(f"Data for table '{selected_table}':")
              st.sidebar.dataframe(df)
      
          # Close the connection
          conn.close()
                  
          # Sidebar Intro
          st.sidebar.markdown('## App Created By')
          st.sidebar.markdown("""
          Harshad Suryawanshi: 
          [Linkedin](https://www.linkedin.com/in/harshadsuryawanshi/), [Medium](https://harshadsuryawanshi.medium.com/), [X](https://twitter.com/HarshadSurya1c)
          """)
          
          
          st.sidebar.markdown('## Other Projects')
          st.sidebar.markdown("""
          - [Pokemon Go! Inspired AInimal GO! - Multimodal RAG App](https://www.linkedin.com/posts/harshadsuryawanshi_llamaindex-ai-deeplearning-activity-7134632983495327744-M7yy)
          - [Building My Own GPT4-V with PaLM and Kosmos](https://lnkd.in/dawgKZBP)
          - [AI Equity Research Analyst](https://ai-eqty-rsrch-anlyst.streamlit.app/)
          - [Recasting "The Office" Scene](https://blackmirroroffice.streamlit.app/)
          - [Story Generator](https://appstorycombined-agaf9j4ceit.streamlit.app/)
          """)
          
          st.sidebar.markdown('## Disclaimer')
          st.sidebar.markdown("""This application is for demonstration purposes only and may not cover all aspects of real-world data complexities. Please use it as a guide and not as a definitive source for decision-making.""")
      
          if "query_engine" not in st.session_state:  # Initialize the query engine
              st.session_state["query_engine"] = NLSQLTableQueryEngine(
                  sql_database=sql_database,
                  synthesize_response=True,
                  service_context=service_context
              )
  
          for message in st.session_state["messages"]:  # Display the prior chat messages
              with st.chat_message(message["role"]):
                  st.write(message["content"])
  
  
          if prompt := st.chat_input(
              "Enter your natural language query about the database"
          ):  # Prompt for user input and save to chat history
              with st.chat_message("user"):
                  st.write(prompt)
              add_to_message_history("user", prompt)
  
          # If last message is not from assistant, generate a new response
          if st.session_state["messages"][-1]["role"] != "assistant":
              with st.spinner():
                  with st.chat_message("assistant"):
                      response = st.session_state["query_engine"].query("User Question:"+prompt+". ")
                      sql_query = f"```sql\n{response.metadata['sql_query']}\n```\n**Response:**\n{response.response}\n"
                      response_container = st.empty()
                      response_container.write(sql_query)
                      # st.write(response.response)
                      add_to_message_history("assistant", sql_query)
  
  if __name__ == "__main__":
      StreamlitChatPack(run_from_main=True).run()
  
apis: llama_index.llms.OpenAI llama_index.ServiceContext.from_defaults llama_index.indices.struct_store.NLSQLTableQueryEngine llama_index.SQLDatabase
extract_api: [((1194, 1309), 'streamlit.set_page_config', 'st.set_page_config', ([], {'page_title': 'f"""{self.page}"""', 'layout': '"""centered"""', 'initial_sidebar_state': '"""auto"""', 'menu_items': 'None'}), "(page_title=f'{self.page}', layout='centered',\n    initial_sidebar_state='auto', menu_items=None)\n", (1212, 1309), True, 'import streamlit as st\n'), ((1622, 1647), 'streamlit.title', 'st.title', (['f"""{self.page}💬"""'], {}), "(f'{self.page}💬')\n", (1630, 1647), True, 'import streamlit as st\n'), ((1678, 1809), 'streamlit.info', 'st.info', (['f"""Explore Snowflake views with this AI-powered app. Pose any question and receive exact SQL queries."""'], {'icon': '"""ℹ️"""'}), "(\n    f'Explore Snowflake views with this AI-powered app. Pose any question and receive exact SQL queries.'\n    , icon='ℹ️')\n", (1685, 1809), True, 'import streamlit as st\n'), ((3050, 3098), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""## Database Schema Viewer"""'], {}), "('## Database Schema Viewer')\n", (3069, 3098), True, 'import streamlit as st\n'), ((3157, 3172), 'sqlalchemy.inspect', 'inspect', (['engine'], {}), '(engine)\n', (3164, 3172), False, 'from sqlalchemy import create_engine, inspect, text\n'), ((3334, 3385), 'streamlit.sidebar.selectbox', 'st.sidebar.selectbox', (['"""Select a Table"""', 'table_names'], {}), "('Select a Table', table_names)\n", (3354, 3385), True, 'import streamlit as st\n'), ((3445, 3469), 'sqlite3.connect', 'sqlite3.connect', (['db_file'], {}), '(db_file)\n', (3460, 3469), False, 'import sqlite3\n'), ((3803, 3843), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""## App Created By"""'], {}), "('## App Created By')\n", (3822, 3843), True, 'import streamlit as st\n'), ((3852, 4087), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""\n        Harshad Suryawanshi: \n        [Linkedin](https://www.linkedin.com/in/harshadsuryawanshi/), [Medium](https://harshadsuryawanshi.medium.com/), [X](https://twitter.com/HarshadSurya1c)\n        """'], {}), '(\n    """\n        Harshad Suryawanshi: \n        [Linkedin](https://www.linkedin.com/in/harshadsuryawanshi/), [Medium](https://harshadsuryawanshi.medium.com/), [X](https://twitter.com/HarshadSurya1c)\n        """\n    )\n', (3871, 4087), True, 'import streamlit as st\n'), ((4104, 4144), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""## Other Projects"""'], {}), "('## Other Projects')\n", (4123, 4144), True, 'import streamlit as st\n'), ((4153, 4707), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""\n        - [Pokemon Go! Inspired AInimal GO! - Multimodal RAG App](https://www.linkedin.com/posts/harshadsuryawanshi_llamaindex-ai-deeplearning-activity-7134632983495327744-M7yy)\n        - [Building My Own GPT4-V with PaLM and Kosmos](https://lnkd.in/dawgKZBP)\n        - [AI Equity Research Analyst](https://ai-eqty-rsrch-anlyst.streamlit.app/)\n        - [Recasting "The Office" Scene](https://blackmirroroffice.streamlit.app/)\n        - [Story Generator](https://appstorycombined-agaf9j4ceit.streamlit.app/)\n        """'], {}), '(\n    """\n        - [Pokemon Go! Inspired AInimal GO! - Multimodal RAG App](https://www.linkedin.com/posts/harshadsuryawanshi_llamaindex-ai-deeplearning-activity-7134632983495327744-M7yy)\n        - [Building My Own GPT4-V with PaLM and Kosmos](https://lnkd.in/dawgKZBP)\n        - [AI Equity Research Analyst](https://ai-eqty-rsrch-anlyst.streamlit.app/)\n        - [Recasting "The Office" Scene](https://blackmirroroffice.streamlit.app/)\n        - [Story Generator](https://appstorycombined-agaf9j4ceit.streamlit.app/)\n        """\n    )\n', (4172, 4707), True, 'import streamlit as st\n'), ((4715, 4751), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""## Disclaimer"""'], {}), "('## Disclaimer')\n", (4734, 4751), True, 'import streamlit as st\n'), ((4760, 4984), 'streamlit.sidebar.markdown', 'st.sidebar.markdown', (['"""This application is for demonstration purposes only and may not cover all aspects of real-world data complexities. Please use it as a guide and not as a definitive source for decision-making."""'], {}), "(\n    'This application is for demonstration purposes only and may not cover all aspects of real-world data complexities. Please use it as a guide and not as a definitive source for decision-making.'\n    )\n", (4779, 4984), True, 'import streamlit as st\n'), ((2185, 2215), 'pandas.read_sql_query', 'pd.read_sql_query', (['query', 'conn'], {}), '(query, conn)\n', (2202, 2215), True, 'import pandas as pd\n'), ((2425, 2515), 'sqlalchemy.create_engine', 'create_engine', (['"""sqlite:///ecommerce_platform1.db?mode=ro"""'], {'connect_args': "{'uri': True}"}), "('sqlite:///ecommerce_platform1.db?mode=ro', connect_args={\n    'uri': True})\n", (2438, 2515), False, 'from sqlalchemy import create_engine, inspect, text\n'), ((2539, 2558), 'llama_index.SQLDatabase', 'SQLDatabase', (['engine'], {}), '(engine)\n', (2550, 2558), False, 'from llama_index import SQLDatabase, ServiceContext\n'), ((2720, 2771), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'temperature': '(0.1)', 'model': '"""gpt-3.5-turbo-1106"""'}), "(temperature=0.1, model='gpt-3.5-turbo-1106')\n", (2726, 2771), False, 'from llama_index.llms import OpenAI\n'), ((2803, 2862), 'llama_index.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {'llm': 'llm2', 'embed_model': '"""local"""'}), "(llm=llm2, embed_model='local')\n", (2831, 2862), False, 'from llama_index import SQLDatabase, ServiceContext\n'), ((3605, 3659), 'streamlit.sidebar.text', 'st.sidebar.text', (['f"""Data for table \'{selected_table}\':"""'], {}), '(f"Data for table \'{selected_table}\':")\n', (3620, 3659), True, 'import streamlit as st\n'), ((3672, 3696), 'streamlit.sidebar.dataframe', 'st.sidebar.dataframe', (['df'], {}), '(df)\n', (3692, 3696), True, 'import streamlit as st\n'), ((5113, 5224), 'llama_index.indices.struct_store.NLSQLTableQueryEngine', 'NLSQLTableQueryEngine', ([], {'sql_database': 'sql_database', 'synthesize_response': '(True)', 'service_context': 'service_context'}), '(sql_database=sql_database, synthesize_response=True,\n    service_context=service_context)\n', (5134, 5224), False, 'from llama_index.indices.struct_store import NLSQLTableQueryEngine\n'), ((5491, 5560), 'streamlit.chat_input', 'st.chat_input', (['"""Enter your natural language query about the database"""'], {}), "('Enter your natural language query about the database')\n", (5504, 5560), True, 'import streamlit as st\n'), ((5389, 5421), 'streamlit.chat_message', 'st.chat_message', (["message['role']"], {}), "(message['role'])\n", (5404, 5421), True, 'import streamlit as st\n'), ((5439, 5467), 'streamlit.write', 'st.write', (["message['content']"], {}), "(message['content'])\n", (5447, 5467), True, 'import streamlit as st\n'), ((5651, 5674), 'streamlit.chat_message', 'st.chat_message', (['"""user"""'], {}), "('user')\n", (5666, 5674), True, 'import streamlit as st\n'), ((5692, 5708), 'streamlit.write', 'st.write', (['prompt'], {}), '(prompt)\n', (5700, 5708), True, 'import streamlit as st\n'), ((5919, 5931), 'streamlit.spinner', 'st.spinner', ([], {}), '()\n', (5929, 5931), True, 'import streamlit as st\n'), ((5954, 5982), 'streamlit.chat_message', 'st.chat_message', (['"""assistant"""'], {}), "('assistant')\n", (5969, 5982), True, 'import streamlit as st\n'), ((6244, 6254), 'streamlit.empty', 'st.empty', ([], {}), '()\n', (6252, 6254), True, 'import streamlit as st\n')]