Update app.py
Browse files
app.py
CHANGED
|
@@ -6,13 +6,13 @@ import json
|
|
| 6 |
import re
|
| 7 |
|
| 8 |
# — Page config
|
| 9 |
-
st.set_page_config(page_title="
|
| 10 |
|
| 11 |
-
# — Title & image
|
| 12 |
-
st.title("
|
| 13 |
st.image("./nadi-lok-image.png")
|
| 14 |
|
| 15 |
-
# — Sidebar: CSV upload (
|
| 16 |
st.sidebar.header("Upload CSV File")
|
| 17 |
uploaded_file = st.sidebar.file_uploader("Choose a CSV file", type="csv")
|
| 18 |
|
|
@@ -22,6 +22,7 @@ if uploaded_file:
|
|
| 22 |
st.sidebar.success("File uploaded successfully!")
|
| 23 |
st.sidebar.write("Preview of the uploaded file:")
|
| 24 |
st.sidebar.dataframe(df.head())
|
|
|
|
| 25 |
csv_text = df.to_csv(index=False)
|
| 26 |
except Exception as e:
|
| 27 |
st.sidebar.error(f"Error reading file: {e}")
|
|
@@ -31,53 +32,31 @@ else:
|
|
| 31 |
df = None
|
| 32 |
csv_text = None
|
| 33 |
|
| 34 |
-
# —
|
| 35 |
-
with st.form("user_form"):
|
| 36 |
-
st.header("Welcome to Streamlit Form!")
|
| 37 |
-
user_input = st.text_input("Enter your name:")
|
| 38 |
-
age = st.slider("Select your age:", 0, 100, 25)
|
| 39 |
-
submit_button = st.form_submit_button("Submit")
|
| 40 |
-
|
| 41 |
-
if submit_button:
|
| 42 |
-
if user_input:
|
| 43 |
-
st.success(f"Hello, {user_input}!")
|
| 44 |
-
st.info(f"You are {age} years old.")
|
| 45 |
-
else:
|
| 46 |
-
st.error("Please enter your name.")
|
| 47 |
-
|
| 48 |
-
# — AI Agent section (from Code 2)
|
| 49 |
-
st.subheader("🔎 CSV-Backed AI Agent")
|
| 50 |
-
|
| 51 |
-
# Load OpenAI key
|
| 52 |
-
api_key = os.getenv("OPENAI_API_KEY")
|
| 53 |
-
if not api_key:
|
| 54 |
-
st.error("❌ Secret OPENAI_API_KEY not set! Add it under Settings → Secrets.")
|
| 55 |
-
st.stop()
|
| 56 |
-
|
| 57 |
-
# Show loaded CSV info
|
| 58 |
if df is not None:
|
| 59 |
st.markdown(f"**Loaded CSV:** {df.shape[0]} rows × {df.shape[1]} columns")
|
| 60 |
|
| 61 |
-
# Prompt input
|
| 62 |
prompt = st.text_area(
|
| 63 |
"Enter your prompt for the agent",
|
| 64 |
placeholder="e.g. Which products have price > 100?",
|
| 65 |
height=150
|
| 66 |
)
|
| 67 |
|
| 68 |
-
# Run the
|
| 69 |
if st.button("Run Agent"):
|
|
|
|
| 70 |
if df is None:
|
| 71 |
st.error("Please upload a CSV file first.")
|
| 72 |
elif not prompt.strip():
|
| 73 |
st.error("Please enter a prompt.")
|
| 74 |
else:
|
| 75 |
-
# Build
|
| 76 |
system_msg = {
|
| 77 |
"role": "system",
|
| 78 |
"content": (
|
| 79 |
"You are an AI agent that reads the provided CSV data and answers the user's query. "
|
| 80 |
-
"Return your answer as JSON
|
| 81 |
)
|
| 82 |
}
|
| 83 |
csv_msg = {
|
|
@@ -86,7 +65,12 @@ if st.button("Run Agent"):
|
|
| 86 |
}
|
| 87 |
user_msg = {"role": "user", "content": prompt}
|
| 88 |
|
| 89 |
-
# Call OpenAI
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
response = requests.post(
|
| 91 |
"https://api.openai.com/v1/chat/completions",
|
| 92 |
headers={
|
|
@@ -102,24 +86,27 @@ if st.button("Run Agent"):
|
|
| 102 |
timeout=60,
|
| 103 |
)
|
| 104 |
|
|
|
|
| 105 |
if response.status_code != 200:
|
| 106 |
st.error(f"API Error {response.status_code}: {response.text}")
|
| 107 |
else:
|
| 108 |
answer = response.json()["choices"][0]["message"]["content"]
|
| 109 |
-
|
|
|
|
| 110 |
txt = re.sub(r'```(?:json)?', '', answer).strip()
|
| 111 |
start = txt.find("{")
|
| 112 |
end = txt.rfind("}") + 1
|
| 113 |
parsed = None
|
| 114 |
if start >= 0 and end > 0:
|
| 115 |
frag = txt[start:end]
|
|
|
|
| 116 |
frag = re.sub(r',\s*([}\]])', r'\1', frag)
|
| 117 |
try:
|
| 118 |
parsed = json.loads(frag)
|
| 119 |
except json.JSONDecodeError:
|
| 120 |
parsed = None
|
| 121 |
|
| 122 |
-
#
|
| 123 |
if parsed is not None:
|
| 124 |
st.subheader("✅ JSON Output")
|
| 125 |
st.json(parsed)
|
|
|
|
| 6 |
import re
|
| 7 |
|
| 8 |
# — Page config
|
| 9 |
+
st.set_page_config(page_title="CSV-Backed AI Agent", layout="wide")
|
| 10 |
|
| 11 |
+
# — Title & (optional) image
|
| 12 |
+
st.title("CSV-Backed AI Agent")
|
| 13 |
st.image("./nadi-lok-image.png")
|
| 14 |
|
| 15 |
+
# — Sidebar: CSV upload & preview (identical to your working code)
|
| 16 |
st.sidebar.header("Upload CSV File")
|
| 17 |
uploaded_file = st.sidebar.file_uploader("Choose a CSV file", type="csv")
|
| 18 |
|
|
|
|
| 22 |
st.sidebar.success("File uploaded successfully!")
|
| 23 |
st.sidebar.write("Preview of the uploaded file:")
|
| 24 |
st.sidebar.dataframe(df.head())
|
| 25 |
+
# Convert DataFrame back to CSV text to feed into the agent
|
| 26 |
csv_text = df.to_csv(index=False)
|
| 27 |
except Exception as e:
|
| 28 |
st.sidebar.error(f"Error reading file: {e}")
|
|
|
|
| 32 |
df = None
|
| 33 |
csv_text = None
|
| 34 |
|
| 35 |
+
# — Show basic info about the loaded CSV
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
if df is not None:
|
| 37 |
st.markdown(f"**Loaded CSV:** {df.shape[0]} rows × {df.shape[1]} columns")
|
| 38 |
|
| 39 |
+
# — Prompt input
|
| 40 |
prompt = st.text_area(
|
| 41 |
"Enter your prompt for the agent",
|
| 42 |
placeholder="e.g. Which products have price > 100?",
|
| 43 |
height=150
|
| 44 |
)
|
| 45 |
|
| 46 |
+
# — Run the AI Agent
|
| 47 |
if st.button("Run Agent"):
|
| 48 |
+
# 1️⃣ Validation
|
| 49 |
if df is None:
|
| 50 |
st.error("Please upload a CSV file first.")
|
| 51 |
elif not prompt.strip():
|
| 52 |
st.error("Please enter a prompt.")
|
| 53 |
else:
|
| 54 |
+
# 2️⃣ Build the "memory + prompt" messages
|
| 55 |
system_msg = {
|
| 56 |
"role": "system",
|
| 57 |
"content": (
|
| 58 |
"You are an AI agent that reads the provided CSV data and answers the user's query. "
|
| 59 |
+
"Return your answer strictly as JSON (no additional explanation)."
|
| 60 |
)
|
| 61 |
}
|
| 62 |
csv_msg = {
|
|
|
|
| 65 |
}
|
| 66 |
user_msg = {"role": "user", "content": prompt}
|
| 67 |
|
| 68 |
+
# 3️⃣ Call OpenAI
|
| 69 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 70 |
+
if not api_key:
|
| 71 |
+
st.error("❌ OPENAI_API_KEY not set in Secrets.")
|
| 72 |
+
st.stop()
|
| 73 |
+
|
| 74 |
response = requests.post(
|
| 75 |
"https://api.openai.com/v1/chat/completions",
|
| 76 |
headers={
|
|
|
|
| 86 |
timeout=60,
|
| 87 |
)
|
| 88 |
|
| 89 |
+
# 4️⃣ Handle API response
|
| 90 |
if response.status_code != 200:
|
| 91 |
st.error(f"API Error {response.status_code}: {response.text}")
|
| 92 |
else:
|
| 93 |
answer = response.json()["choices"][0]["message"]["content"]
|
| 94 |
+
|
| 95 |
+
# Strip any ``` fences and pull out the JSON object
|
| 96 |
txt = re.sub(r'```(?:json)?', '', answer).strip()
|
| 97 |
start = txt.find("{")
|
| 98 |
end = txt.rfind("}") + 1
|
| 99 |
parsed = None
|
| 100 |
if start >= 0 and end > 0:
|
| 101 |
frag = txt[start:end]
|
| 102 |
+
# remove trailing commas
|
| 103 |
frag = re.sub(r',\s*([}\]])', r'\1', frag)
|
| 104 |
try:
|
| 105 |
parsed = json.loads(frag)
|
| 106 |
except json.JSONDecodeError:
|
| 107 |
parsed = None
|
| 108 |
|
| 109 |
+
# 5️⃣ Display
|
| 110 |
if parsed is not None:
|
| 111 |
st.subheader("✅ JSON Output")
|
| 112 |
st.json(parsed)
|