Akshayram1
commited on
Upload 2 files
Browse files- app.py +193 -0
- requirements.txt +7 -0
app.py
ADDED
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import json
|
3 |
+
import re
|
4 |
+
import sys
|
5 |
+
import io
|
6 |
+
import contextlib
|
7 |
+
import warnings
|
8 |
+
from typing import Optional, List, Any, Tuple
|
9 |
+
from PIL import Image
|
10 |
+
import streamlit as st
|
11 |
+
import pandas as pd
|
12 |
+
import base64
|
13 |
+
from io import BytesIO
|
14 |
+
from together import Together
|
15 |
+
from e2b_code_interpreter import Sandbox
|
16 |
+
|
17 |
+
warnings.filterwarnings("ignore", category=UserWarning, module="pydantic")
|
18 |
+
|
19 |
+
pattern = re.compile(r"```python\n(.*?)\n```", re.DOTALL)
|
20 |
+
|
21 |
+
def code_interpret(e2b_code_interpreter: Sandbox, code: str) -> Optional[List[Any]]:
|
22 |
+
with st.spinner('Executing code in E2B sandbox...'):
|
23 |
+
stdout_capture = io.StringIO()
|
24 |
+
stderr_capture = io.StringIO()
|
25 |
+
|
26 |
+
with contextlib.redirect_stdout(stdout_capture), contextlib.redirect_stderr(stderr_capture):
|
27 |
+
with warnings.catch_warnings():
|
28 |
+
warnings.simplefilter("ignore")
|
29 |
+
exec = e2b_code_interpreter.run_code(code)
|
30 |
+
|
31 |
+
if stderr_capture.getvalue():
|
32 |
+
print("[Code Interpreter Warnings/Errors]", file=sys.stderr)
|
33 |
+
print(stderr_capture.getvalue(), file=sys.stderr)
|
34 |
+
|
35 |
+
if stdout_capture.getvalue():
|
36 |
+
print("[Code Interpreter Output]", file=sys.stdout)
|
37 |
+
print(stdout_capture.getvalue(), file=sys.stdout)
|
38 |
+
|
39 |
+
if exec.error:
|
40 |
+
print(f"[Code Interpreter ERROR] {exec.error}", file=sys.stderr)
|
41 |
+
return None
|
42 |
+
return exec.results
|
43 |
+
|
44 |
+
def match_code_blocks(llm_response: str) -> str:
|
45 |
+
match = pattern.search(llm_response)
|
46 |
+
if match:
|
47 |
+
code = match.group(1)
|
48 |
+
return code
|
49 |
+
return ""
|
50 |
+
|
51 |
+
def chat_with_llm(e2b_code_interpreter: Sandbox, user_message: str, dataset_path: str) -> Tuple[Optional[List[Any]], str]:
|
52 |
+
# Update system prompt to include dataset path information
|
53 |
+
system_prompt = f"""You're a Python data scientist and data visualization expert. You are given a dataset at path '{dataset_path}' and also the user's query.
|
54 |
+
You need to analyze the dataset and answer the user's query with a response and you run Python code to solve them.
|
55 |
+
IMPORTANT: Always use the dataset path variable '{dataset_path}' in your code when reading the CSV file."""
|
56 |
+
|
57 |
+
messages = [
|
58 |
+
{"role": "system", "content": system_prompt},
|
59 |
+
{"role": "user", "content": user_message},
|
60 |
+
]
|
61 |
+
|
62 |
+
with st.spinner('Getting response from Together AI LLM model...'):
|
63 |
+
client = Together(api_key=st.session_state.together_api_key)
|
64 |
+
response = client.chat.completions.create(
|
65 |
+
model=st.session_state.model_name,
|
66 |
+
messages=messages,
|
67 |
+
)
|
68 |
+
|
69 |
+
response_message = response.choices[0].message
|
70 |
+
python_code = match_code_blocks(response_message.content)
|
71 |
+
|
72 |
+
if python_code:
|
73 |
+
code_interpreter_results = code_interpret(e2b_code_interpreter, python_code)
|
74 |
+
return code_interpreter_results, response_message.content
|
75 |
+
else:
|
76 |
+
st.warning(f"Failed to match any Python code in model's response")
|
77 |
+
return None, response_message.content
|
78 |
+
|
79 |
+
def upload_dataset(code_interpreter: Sandbox, uploaded_file) -> str:
|
80 |
+
dataset_path = f"./{uploaded_file.name}"
|
81 |
+
|
82 |
+
try:
|
83 |
+
code_interpreter.files.write(dataset_path, uploaded_file)
|
84 |
+
return dataset_path
|
85 |
+
except Exception as error:
|
86 |
+
st.error(f"Error during file upload: {error}")
|
87 |
+
raise error
|
88 |
+
|
89 |
+
|
90 |
+
def main():
|
91 |
+
"""Main Streamlit application."""
|
92 |
+
st.set_page_config(page_title="π AI Data Visualization Agent", page_icon="π", layout="wide")
|
93 |
+
|
94 |
+
st.title("π AI Data Visualization Agent")
|
95 |
+
st.write("Upload your dataset and ask questions about it!")
|
96 |
+
|
97 |
+
# Initialize session state variables
|
98 |
+
if 'together_api_key' not in st.session_state:
|
99 |
+
st.session_state.together_api_key = ''
|
100 |
+
if 'e2b_api_key' not in st.session_state:
|
101 |
+
st.session_state.e2b_api_key = ''
|
102 |
+
if 'model_name' not in st.session_state:
|
103 |
+
st.session_state.model_name = ''
|
104 |
+
|
105 |
+
# Sidebar for API keys and model configuration
|
106 |
+
with st.sidebar:
|
107 |
+
st.header("π API Keys and Model Configuration")
|
108 |
+
st.session_state.together_api_key = st.text_input("Together AI API Key", type="password")
|
109 |
+
st.info("π‘ Everyone gets a free $1 credit by Together AI - AI Acceleration Cloud platform")
|
110 |
+
st.markdown("[Get Together AI API Key](https://api.together.ai/signin)")
|
111 |
+
|
112 |
+
st.session_state.e2b_api_key = st.text_input("Enter E2B API Key", type="password")
|
113 |
+
st.markdown("[Get E2B API Key](https://e2b.dev/docs/legacy/getting-started/api-key)")
|
114 |
+
|
115 |
+
# Add model selection dropdown
|
116 |
+
model_options = {
|
117 |
+
"Meta-Llama 3.1 405B": "meta-llama/Meta-Llama-3.1-405B-Instruct-Turbo",
|
118 |
+
"DeepSeek V3": "deepseek-ai/DeepSeek-V3",
|
119 |
+
"Qwen 2.5 7B": "Qwen/Qwen2.5-7B-Instruct-Turbo",
|
120 |
+
"Meta-Llama 3.3 70B": "meta-llama/Llama-3.3-70B-Instruct-Turbo"
|
121 |
+
}
|
122 |
+
st.session_state.model_name = st.selectbox(
|
123 |
+
"Select Model",
|
124 |
+
options=list(model_options.keys()),
|
125 |
+
index=0 # Default to first option
|
126 |
+
)
|
127 |
+
st.session_state.model_name = model_options[st.session_state.model_name]
|
128 |
+
|
129 |
+
# Main content layout
|
130 |
+
col1, col2 = st.columns([1, 2]) # Split the main content into two columns
|
131 |
+
|
132 |
+
with col1:
|
133 |
+
st.header("π Upload Dataset")
|
134 |
+
uploaded_file = st.file_uploader("Choose a CSV file", type="csv", key="file_uploader")
|
135 |
+
|
136 |
+
if uploaded_file is not None:
|
137 |
+
# Display dataset with toggle
|
138 |
+
df = pd.read_csv(uploaded_file)
|
139 |
+
st.write("### Dataset Preview")
|
140 |
+
show_full = st.checkbox("Show full dataset")
|
141 |
+
if show_full:
|
142 |
+
st.dataframe(df)
|
143 |
+
else:
|
144 |
+
st.write("Preview (first 5 rows):")
|
145 |
+
st.dataframe(df.head())
|
146 |
+
|
147 |
+
with col2:
|
148 |
+
if uploaded_file is not None:
|
149 |
+
st.header("β Ask a Question")
|
150 |
+
query = st.text_area(
|
151 |
+
"What would you like to know about your data?",
|
152 |
+
"Can you compare the average cost for two people between different categories?",
|
153 |
+
height=100
|
154 |
+
)
|
155 |
+
|
156 |
+
if st.button("Analyze", type="primary", key="analyze_button"):
|
157 |
+
if not st.session_state.together_api_key or not st.session_state.e2b_api_key:
|
158 |
+
st.error("Please enter both API keys in the sidebar.")
|
159 |
+
else:
|
160 |
+
with Sandbox(api_key=st.session_state.e2b_api_key) as code_interpreter:
|
161 |
+
# Upload the dataset
|
162 |
+
dataset_path = upload_dataset(code_interpreter, uploaded_file)
|
163 |
+
|
164 |
+
# Pass dataset_path to chat_with_llm
|
165 |
+
code_results, llm_response = chat_with_llm(code_interpreter, query, dataset_path)
|
166 |
+
|
167 |
+
# Display LLM's text response
|
168 |
+
st.header("π€ AI Response")
|
169 |
+
st.write(llm_response)
|
170 |
+
|
171 |
+
# Display results/visualizations
|
172 |
+
if code_results:
|
173 |
+
st.header("π Analysis Results")
|
174 |
+
for result in code_results:
|
175 |
+
if hasattr(result, 'png') and result.png: # Check if PNG data is available
|
176 |
+
# Decode the base64-encoded PNG data
|
177 |
+
png_data = base64.b64decode(result.png)
|
178 |
+
|
179 |
+
# Convert PNG data to an image and display it
|
180 |
+
image = Image.open(BytesIO(png_data))
|
181 |
+
st.image(image, caption="Generated Visualization", use_container_width=True)
|
182 |
+
elif hasattr(result, 'figure'): # For matplotlib figures
|
183 |
+
fig = result.figure # Extract the matplotlib figure
|
184 |
+
st.pyplot(fig) # Display using st.pyplot
|
185 |
+
elif hasattr(result, 'show'): # For plotly figures
|
186 |
+
st.plotly_chart(result)
|
187 |
+
elif isinstance(result, (pd.DataFrame, pd.Series)):
|
188 |
+
st.dataframe(result)
|
189 |
+
else:
|
190 |
+
st.write(result)
|
191 |
+
|
192 |
+
if __name__ == "__main__":
|
193 |
+
main()
|
requirements.txt
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
together==1.3.10
|
2 |
+
e2b-code-interpreter==1.0.3
|
3 |
+
e2b==1.0.5
|
4 |
+
Pillow==10.4.0
|
5 |
+
streamlit
|
6 |
+
pandas
|
7 |
+
matplotlib
|