import pandas as pd from dotenv import load_dotenv import os from openai import OpenAI import json import numpy as np # the newest OpenAI model is "gpt-4o" which was released May 13, 2024. # do not change this unless explicitly requested by the user #OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY") # Check for API key load_dotenv() # Load environment variables from .env OPENAI_API_KEY = os.getenv("OPENAI_API_KEY") client = OpenAI(api_key=OPENAI_API_KEY) def validate_csv(file): try: df = pd.read_csv(file, low_memory=False) return True, df except Exception as e: return False, str(e) def get_data_description(dfs): """Generate a concise description of the available data""" description = [] for name, df in dfs.items(): cols = df.columns.tolist() rows = len(df) description.append(f"File '{name}': {rows} rows, columns: {', '.join(cols)}") return "\n".join(description) def prepare_data_sample(df): """Prepare first row sample of the dataframe""" sample = df.head(1) # Convert to string and limit column width for readability return sample.to_string(max_cols=None, max_colwidth=20) def get_numeric_columns(df): """Get list of numeric columns from dataframe""" return df.select_dtypes(include=[np.number]).columns.tolist() def get_categorical_columns(df): """Get list of categorical columns from dataframe""" return df.select_dtypes(include=['object', 'category']).columns.tolist() def calculate_basic_stats(df, column): """Calculate basic statistics for a numeric column""" stats = { 'mean': df[column].mean(), 'median': df[column].median(), 'std': df[column].std(), 'min': df[column].min(), 'max': df[column].max() } return stats def prepare_analysis_prompt(question, dfs): """Prepare the prompt for OpenAI analysis""" # Prepare context about the data context = get_data_description(dfs) # Prepare first row samples from all files data_samples = [] total_files = len(dfs) for name, df in dfs.items(): sample = prepare_data_sample(df) data_samples.append(f"First row from {name}:\n{sample}") prompt = f"""Question: {question} Available data ({total_files} files total): {context} Data preview (first row from each file): {chr(10).join(data_samples)} Note: Showing first row from each file to provide context about data structure. Please provide a clear, data-driven answer using all available data.""" return prompt def analyze_data(question, dfs): """Analyze data using OpenAI API with optimized prompt and data handling""" try: prompt = prepare_analysis_prompt(question, dfs) response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": "You are a data analysis expert. Provide clear, accurate answers based on the CSV data provided."}, {"role": "user", "content": prompt} ], max_tokens=1000 ) return True, response.choices[0].message.content, prompt except Exception as e: error_message = str(e) if "string too long" in error_message: error_message = "Error: The dataset is too large. Please try asking about specific columns or use a smaller dataset." return False, error_message, None