Sinaptik-AI / pandas-ai

Chat with your database (SQL, CSV, pandas, polars, mongodb, noSQL, etc). PandasAI makes data analysis conversational using LLMs (GPT 3.5 / 4, Anthropic, VertexAI) and RAG.
https://pandas-ai.com
Other
11.69k stars 1.08k forks source link

The generated code has a shifted alignment on the top line which leads to NameError on exec #1177

Open metalshanked opened 1 month ago

metalshanked commented 1 month ago

System Info

2.0.43 OS Windows/Linux

🐛 Describe the bug

                            from datetime import date, datetime
import pandas as pd
import plotly.graph_objects as go
from plotly.offline import plot
location_info = 'ST'
today = date.today()
start_year = today.year
exec(code, environment)
 File "<string>", line 2, in <module>
NameError: name 'date' is not defined

image

dosubot[bot] commented 1 month ago

Hey @metalshanked! I'm here to help you with any bugs, questions, or contributions while you wait for a human maintainer. Let's tackle this issue together!

The issue you're encountering with the shifted alignment on the top line of the generated code can be addressed by utilizing the CodeCleaning class in the pandas-ai repository. This class includes methods for cleaning and formatting code to ensure proper structure and prevent errors like NameError.

Here's an example of how you can use the CodeCleaning class to clean and format your code:

from pandasai.pipelines.chat.code_cleaning import CodeCleaning
from pandasai.pipelines.chat.code_execution import CodeExecutionContext
from pandasai.helpers.logger import Logger

# Initialize the necessary components
code_cleaning = CodeCleaning()
context = CodeExecutionContext()
logger = Logger(save_logs=True, verbose=True)

# Your generated code
code = """
                            from datetime import date, datetime
import pandas as pd
import plotly.graph_objects as go
from plotly.offline import plot
location_info = 'ST'
today = date.today()
start_year = today.year
"""

# Clean the code
cleaned_code = code_cleaning._clean_code(code, context)

# Execute the cleaned code
try:
    exec(cleaned_code, globals())
except Exception as e:
    logger.log(f"Error executing code: {e}", level=logging.ERROR)

This will help ensure that the code is properly aligned and free of errors before execution [1].

#### Details **About Dosu** This response is meant to be useful and save you time. It is **not meant to be a precise solution**, but rather a starting point for your own research. Help me be more useful! Please leave a 👍 if this is helpful and 👎 if it is irrelevant.

To continue the conversation, mention @dosu.