Spaces:
Sleeping
Sleeping
Update utils.py
Browse files
utils.py
CHANGED
|
@@ -1,70 +1,83 @@
|
|
| 1 |
import pandas as pd
|
| 2 |
-
import io
|
| 3 |
import csv
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
from
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
| 10 |
-
MODEL_ID = "mistralai/Mistral-7B-Instruct-v0.2"
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
"""
|
| 17 |
try:
|
| 18 |
-
# Decode the first
|
| 19 |
-
sample =
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
| 22 |
return dialect.delimiter
|
| 23 |
-
except Exception
|
| 24 |
-
|
| 25 |
return ','
|
| 26 |
|
| 27 |
-
def query_agent(
|
| 28 |
"""
|
| 29 |
-
Initializes and
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
"""
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
# Reset stream position to the beginning before reading with pandas
|
| 38 |
-
uploaded_file_bytes.seek(0)
|
| 39 |
-
|
| 40 |
-
try:
|
| 41 |
-
# Read the file using the detected delimiter
|
| 42 |
-
df = pd.read_csv(uploaded_file_bytes, sep=delimiter, encoding='utf-8')
|
| 43 |
-
except Exception as e:
|
| 44 |
-
return f"Error loading data with detected delimiter '{delimiter}': {e}"
|
| 45 |
|
| 46 |
-
# 2. Initialize HuggingFace LLM
|
| 47 |
try:
|
| 48 |
-
#
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
)
|
| 53 |
-
except Exception as e:
|
| 54 |
-
return f"Error initializing LLM (HuggingFaceHub). Ensure API key is set and valid: {e}"
|
| 55 |
|
| 56 |
-
|
| 57 |
-
try:
|
| 58 |
agent = create_pandas_dataframe_agent(
|
| 59 |
llm,
|
| 60 |
df,
|
| 61 |
verbose=True,
|
| 62 |
-
|
| 63 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
)
|
| 65 |
|
| 66 |
# 4. Run the query
|
| 67 |
-
response = agent.run(
|
|
|
|
| 68 |
return response
|
|
|
|
| 69 |
except Exception as e:
|
| 70 |
-
|
|
|
|
|
|
| 1 |
import pandas as pd
|
|
|
|
| 2 |
import csv
|
| 3 |
+
import io
|
| 4 |
+
# Changed LLM import to HuggingFaceEndpoint
|
| 5 |
+
from langchain_community.llms import HuggingFaceEndpoint
|
| 6 |
+
from langchain_community.agent_toolkits import create_pandas_dataframe_agent
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
import os
|
| 9 |
|
| 10 |
+
# Load environment variables from .env file
|
| 11 |
+
load_dotenv()
|
|
|
|
| 12 |
|
| 13 |
+
# --- Hugging Face Model Configuration ---
|
| 14 |
+
HF_REPO_ID = "mistralai/Mistral-7B-Instruct-v0.2"
|
| 15 |
+
|
| 16 |
+
def detect_delimiter(file_content: bytes) -> str:
|
| 17 |
+
"""Detects the delimiter of a CSV file content."""
|
| 18 |
try:
|
| 19 |
+
# Decode the first few lines to sample the content
|
| 20 |
+
sample = file_content.decode('utf-8').splitlines()[:5]
|
| 21 |
+
if not sample:
|
| 22 |
+
return ',' # Default to comma if empty
|
| 23 |
+
|
| 24 |
+
# Use csv.Sniffer to guess the dialect (and thus the delimiter)
|
| 25 |
+
dialect = csv.Sniffer().sniff('\n'.join(sample))
|
| 26 |
return dialect.delimiter
|
| 27 |
+
except Exception:
|
| 28 |
+
# Fallback to a comma if sniffing fails
|
| 29 |
return ','
|
| 30 |
|
| 31 |
+
def query_agent(uploaded_file_content: bytes, query: str, hf_api_token: str) -> str:
|
| 32 |
"""
|
| 33 |
+
Initializes a LangChain Pandas Agent and processes a natural language query using a Hugging Face LLM.
|
| 34 |
+
|
| 35 |
+
Args:
|
| 36 |
+
uploaded_file_content: The byte content of the uploaded CSV file.
|
| 37 |
+
query: The natural language question from the user.
|
| 38 |
+
hf_api_token: The API token for the Hugging Face Hub.
|
| 39 |
|
| 40 |
+
Returns:
|
| 41 |
+
The response generated by the agent.
|
| 42 |
"""
|
| 43 |
+
if not hf_api_token:
|
| 44 |
+
# Updated error message for Hugging Face
|
| 45 |
+
return "Error: HUGGINGFACEHUB_API_TOKEN is not configured."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
|
|
|
|
| 47 |
try:
|
| 48 |
+
# 1. Robustly read CSV content using detected delimiter
|
| 49 |
+
delimiter = detect_delimiter(uploaded_file_content)
|
| 50 |
+
data_io = io.StringIO(uploaded_file_content.decode('utf-8'))
|
| 51 |
+
df = pd.read_csv(data_io, sep=delimiter)
|
| 52 |
+
|
| 53 |
+
# 2. Initialize the LLM using HuggingFaceEndpoint
|
| 54 |
+
llm = HuggingFaceEndpoint(
|
| 55 |
+
repo_id=HF_REPO_ID,
|
| 56 |
+
huggingfacehub_api_token=hf_api_token,
|
| 57 |
+
temperature=0.0, # Keep reasoning deterministic
|
| 58 |
+
max_new_tokens=512
|
| 59 |
)
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
# 3. Create the Pandas DataFrame Agent
|
|
|
|
| 62 |
agent = create_pandas_dataframe_agent(
|
| 63 |
llm,
|
| 64 |
df,
|
| 65 |
verbose=True,
|
| 66 |
+
# Include a system prompt to guide the agent's behavior
|
| 67 |
+
agent_kwargs={
|
| 68 |
+
"system_message": (
|
| 69 |
+
"You are an expert data analysis assistant. You are interacting with a pandas DataFrame "
|
| 70 |
+
"named 'df'. Use Python code only to answer questions about the data. "
|
| 71 |
+
"Do not make up facts. Always show the code you executed before giving the final answer."
|
| 72 |
+
)
|
| 73 |
+
}
|
| 74 |
)
|
| 75 |
|
| 76 |
# 4. Run the query
|
| 77 |
+
response = agent.run(query)
|
| 78 |
+
|
| 79 |
return response
|
| 80 |
+
|
| 81 |
except Exception as e:
|
| 82 |
+
# Catch and report any exceptions during processing
|
| 83 |
+
return f"An error occurred during analysis: {e}"
|