def predict(question,history):
    try:
#         if username not in user_sessions:
#             return 'User Authentication Failed.'
        preprocessed_question_var = fn_preprocess_question(question)
        for predefined_question_var,predefined_answer_var in dict_predefined_answers.items():
            if fn_preprocess_question(predefined_question_var) in preprocessed_question_var:
                return predefined_answer_var




        #--------------------------------------
#         predefined_answer = predefined_answers.get(question)
#         if predefined_answer:
#             return predefined_answer
        #--------------------------------------
        #--------------------------------------
        # Check if the user's question closely matches a predefined question
#         matched_question = next((predefined_question for predefined_question in predefined_answers.keys()
#                                 if match_question(question, predefined_question)), None)

#         if matched_question:
#             return predefined_answers[matched_question]
        #--------------------------------------
        conn_local = sqlite3.connect("sales_database.db",check_same_thread=False)
        cursor_local = conn_local.cursor()

        ### Answer Given the database schema,here is the SQL query that answers [QUESTION]{question}[/QUESTION] [SQL] """.format(question=question)
        prompt = """### Instructions:
        You are a prompt engineer and a sql developer,Your task is to first convert `{question}` into a meaningful prompt that should have context and values and data values as defined in comments of sqlite3 schema from the below mentioned sqlite3 database schema and then create a SQL query using that meaningful prompt,using the same sqlite3 database schema.
        Adhere to these rules:
        - **Deliberately go through the question and database schema word by word** to appropriately answer the question
        - **Use Table Aliases** to prevent ambiguity. For example, `SELECT table1.col1, table2.col1 FROM table1 JOIN table2 ON table1.id = table2.id`.
        - When creating a ratio, always cast the numerator as int
        - Ensure that the SQL queries generated do not perform any typecasting and maintain the original data types,even during rounding off any value.Please adjust the queries accoridngly
        - While calculating contribution, always include '%' sign in the header
        - When asked for 'Market share' use this formula:
            market share of a product or competitor = 100 * sum(counterselloutvalue of that product)/sum(total aggregated countersellout value of all products)
        - Counter share means total countersellout value of that product/competitor and then divide it by toal of all other products/competitor
        ### Input:
        Generate a SQL query that answers the question generated by you as a prompt and say two precise lines about the answer.
        This query will run on a database whose schema is represented in this string:        
         CREATE TABLE IF NOT EXISTS sales (
        salestype TEXT, --Type of sales like Sellin, SellThru, Sellout
        salescategory TEXT,--Sales Category like Normal, Demo, Free of Cost etc
        channel TEXT,--Sales Channel like General Trade, Modern Trade, Online, Business to Business or NA
        priceband TEXT, --Price bands of Product like Less than 6K, 6K to 10K, 10K to 15K, 15K to 20K, 20K to 30K, 30K to 40K, Greater than 40K etc
        region TEXT,--Sales Regions like Online, B2B and for GT the regions are East1, East2, West1, West2, West3, North1, North2, North3, North4, South1, South2, South3
        year INTEGER,--Year of sale
        month INTEGER,--Month of sale
        day INTEGER,--Day of sale
        date INTEGER,--Date of sale
        weekyear TEXT,--Week and Year of sale
        segment TEXT,--Segment of sale like Smatphone, Tablet, Note PC Laptop, Wearables
        model TEXT,--Product name or Market name or Model name
        quantity INTEGER,--Sales quantity
        amount INTEGER,--Sales amount in INR
        mtdquantity INTEGER,--Month till date Quantity
        mtdamount INTEGER,--Month till date Amount in INR
        lmtdquantity INTEGER,--Last Month till date quantity
        lmtdamount INTEGER,--Last Month till date amount in INR
      );

        CREATE TABLE IF NOT EXISTS sales_dlb (
                      year INTEGER, -- year of sellout/sale,
                     week TEXT,--week of sellout,
                     month INteger,--month of sellout
                     counterselloutvalue INTEGER,-- value of sellout/amount
                     counterselloutvolume INTEGER,-- volume of sellout
                     region TEXT,-- region of sale
                     competitor TEXT,--competitor/competition name
                     priceband TEXT,-- price bands of different model/modelcode sold
                     salestype TEXT,-- salestype of the sale
                     channel TEXT,-- channel through which it is sold
                     status TEXT, -- status of sale
                     modelname TEXT,-- market name
                     productgroup TEXT -- product group
        );
        ### Response:
        Based on your instructions, here is the prompt and SQL query I have generated to answer the question `{question}`:
        ```sql prompt
        """.format(question=question)

        eos_token_id = tokenizer.convert_tokens_to_ids(["```"])[0]
#         CREATE TABLE IF NOT EXISTS sales_dlb (
#             Year INTEGER,
#             SuperRegion TEXT,
#             CounterSelloutVal INTEGER,
#             CounterSelloutVol INTEGER,
#             Region TEXT,
#             StoreCode TEXT,
#             Competitor TEXT,
#             SurveyDate TEXT,
#             PriceBand TEXT,
#             SalesType TEXT,
#             ModelCode TEXT,
#             Channel TEXT,
#             Status TEXT,
#             SAMSModelCode TEXT,
#             MarketName TEXT,
#             ProductGroup TEXT );
        

        inputs = tokenizer(prompt, return_tensors="pt").to(device)
        generated_ids = model.generate(
            **inputs,
            num_return_sequences=1,
            eos_token_id=eos_token_id,
            pad_token_id=eos_token_id,
            max_new_tokens=1096,
            num_beams=5,
            temperature = 0.001,
            do_sample=True
        )


        outputs = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
        print('outputs',outputs[0])
        generated_sql = outputs[0].split("```sql")[-1].split("```")[0].split(";")[0].strip()
        print(generated_sql)
        generated_sql = generated_sql.replace('::numeric','')
    #     result = execute_sql_query(generated_sql)
    #     for row in result:
    #         print(row)
    #     df = pd.DataFrame(result,columns=[desc[0] for desc in cursor.description])
    # #     df_str = df.to_string(index=False)
    #     res_html = df.to_html(index=False)
#         generated_sql ='''100 * SUM(CASE WHEN sales_dlb.competitor = 'SAMSUNG' THEN sales_dlb.counterselloutval ELSE 0 END) / NULLIF(SUM(sales_dlb.counterselloutval), 0) AS percentage_of_counterselloutval
#         FROM   sales_dlb'''
        cursor_local.execute(generated_sql)
        result = cursor_local.fetchall()
#         print(result)
        cursor_local.close()
        conn_local.close()
#         for row in result:
#             print(row)
        df = pd.DataFrame(result,columns=[desc[0] for desc in cursor_local.description])
        sql_datagram = generated_sql

        # Create a DataFrame with the SQL datagram as the first row
        df_sql_row = pd.DataFrame([{'Generated_SQL': sql_datagram}])

        # Concatenate the SQL row with your existing DataFrame (df)
        df_with_sql = pd.concat([df,df_sql_row], keys=['',''],ignore_index=True)

        # Convert the DataFrame with SQL to HTML
        df_html_with_sql = df.to_html(index=False)
        predict 
#         df_final = df + dff
    #     df_str = df.to_string(index=False)
        html_output_1 = f"<h3>Sql Query : \n\n{generated_sql}\n\n</h3>{df_html_with_sql}\n<h2>Above results are derived using the Generated SQL query.</h2>"
        
        return html_output_1
    except Exception as e:
        print(f"An exception occurred:{str(e)}")
        return "The answer for this query is not available right now.Kindly modify the query that can best fit the database schema.Please provide updated query."



i wnat to give output of this sql query which is basically dataframe again to the same model such it will generate few insights about the dataframe data.
How can we do it more efficient way such that memory requirements are minimum and object and models donot load again and again