Spaces:
Build error
Build error
Update utils.py
Browse files12345678910111213145 unmodified lines20212223242526274 unmodified lines3233343536373839404142436 unmodified lines505152535455565758596061from langchain_community.llms import LlamaCppfrom dotenv import load_dotenvimport osimport pandas as pd# Load environment variablesload_dotenv()MODEL_PATH = os.getenv("MODEL_PATH", "TheBloke/gemma-2b-it-GGUF/gemma-2b-it.Q4_K_M.gguf")def summarize_dataframe(df: pd.DataFrame, max_rows: int = 30) -> str:"""Summarize a dataframe to avoid overloading the context window."""summary = f"Columns: {', '.join(df.columns)}\n\n"if len(df) > max_rows:sample = df.sample(max_rows, random_state=42)5 unmodified linesreturn summarydef query_agent(df: pd.DataFrame, query: str) -> str:"""Query a CSV/DataFrame using your local Gemma model with context-aware limits."""# Attempt to handle simple analytical questions directly with pandasquery_lower = query.lower()try:if "most common" in query_lower or "most frequent" in query_lower:4 unmodified linesexcept Exception as e:print("Direct analysis failed:", e)# Otherwise summarize dataset for LLMdata_text = summarize_dataframe(df)prompt = f"""You are a data analysis assistant with expertise in statistics and data interpretation.Analyze the dataset sample below and answer the user's question in a **clear, detailed, and well-explained way**.Include both the **direct answer** and a short **explanation or reasoning** behind it.6 unmodified linesAnswer (with explanation):"""llm = LlamaCpp(model_path=MODEL_PATH,temperature=0.7,max_new_tokens=1024,n_ctx=16384,verbose=True,)answer = llm(prompt)1234567891011125 unmodified lines1819202122234 unmodified lines282930313233343536376 unmodified lines44454647484950515253545556from langchain_community.llms import HuggingFaceHubfrom dotenv import load_dotenvimport osimport pandas as pd# Load .env variables (still useful for local dev)load_dotenv()def summarize_dataframe(df: pd.DataFrame, max_rows: int = 30) -> str:summary = f"Columns: {', '.join(df.columns)}\n\n"if len(df) > max_rows:sample = df.sample(max_rows, random_state=42)5 unmodified linesreturn summarydef query_agent(df: pd.DataFrame, query: str) -> str:query_lower = query.lower()try:if "most common" in query_lower or "most frequent" in query_lower:4 unmodified linesexcept Exception as e:print("Direct analysis failed:", e)data_text = summarize_dataframe(df)prompt = f"""You are a data analysis assistant with expertise in statistics and data interpretation.Analyze the dataset sample below and answer the user's question in a **clear, detailed, and well-explained way**.Include both the **direct answer** and a short **explanation or reasoning** behind it.6 unmodified linesAnswer (with explanation):"""# Use a hosted model instead of local LlamaCppllm = HuggingFaceHub(repo_id="google/gemma-2b-it", # or another model like mistralai/Mistral-7B-Instruct-v0.2model_kwargs={"temperature": 0.7,"max_new_tokens": 1024,})answer = llm(prompt)
utils.py+9-14