I understand you're experiencing issues with data not being rendered correctly in your Plotly plots within your Flask application. Upon reviewing your main.py code, I've identified a few key areas that need addressing:
-
Missing Function generateSummaryPrompt:
- The
compute function calls generateSummaryPrompt, which isn't defined in your code. This causes a NameError, preventing the function from completing and thus not sending the necessary data to the frontend for plotting.
-
Incorrect Handling of Datasets for PCA:
- The way datasets are handled when performing PCA is flawed. You're attempting to access keys like
'x1' and 'x2' across multiple datasets, leading to potential KeyErrors.
-
Potential Issues with Embedding Dimensions:
- The embeddings retrieved are 1536-dimensional vectors, but you're only using the first three dimensions for plotting after PCA. It's essential to ensure that PCA is applied correctly to reduce these dimensions appropriately.
-
Plotting with Plotly (Not Matplotlib):
- Your current implementation uses Plotly for plotting, not Matplotlib. If you intended to use Matplotlib, adjustments would be necessary. However, assuming you want to continue with Plotly, the focus will be on ensuring Plotly receives the correct data.
Below is the corrected and enhanced version of your main.py. I've addressed the issues mentioned above and ensured that the data is correctly processed and sent to the frontend for visualization.
# main.py
import os
from flask import Flask, request, jsonify, render_template_string
from openai import OpenAI
import json
import numpy as np
from sklearn.decomposition import PCA
app = Flask(__name__)
# Initialize OpenAI client (Ensure you have set the OPENAI_API_KEY environment variable)
client = OpenAI()
def get_related_phrases(string_pair, num_related=50, logs=[]):
"""
Retrieve related phrases based on the input string pair using OpenAI's GPT-4o-mini model.
"""
string1, string2 = string_pair
prompt = (
f"Generate {num_related} unique and relevant phrases that combine the concepts of '{string1}' and '{string2}'. "
f"Each phrase should be meaningful and contextually appropriate. Provide them as a comma-separated list."
)
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a creative assistant that generates relevant phrases based on given concepts."},
{"role": "user", "content": prompt}
],
max_tokens=3000,
temperature=0.7,
)
# Access the content using attribute access
phrases_text = response.choices[0].message.content
logs.append(f"Generated phrases for pair ({string1}, {string2}).")
# Split phrases by commas and strip whitespace
phrases = [phrase.strip() for phrase in phrases_text.split(',') if phrase.strip()]
# Ensure exactly num_related phrases
return phrases[:num_related]
except Exception as e:
logs.append(f"Error generating related phrases: {e}")
print(f"Error generating related phrases: {e}")
return []
def get_embedding(text, model="text-embedding-ada-002", logs=[]):
"""
Retrieve the embedding for a given text using OpenAI's API.
"""
text = text.replace("\n", " ")
try:
response = client.embeddings.create(
input=[text],
model=model
)
embedding = response.data[0].embedding
logs.append(f"Retrieved embedding of length {len(embedding)} for text: '{text}'.")
print(f"Retrieved embedding of length {len(embedding)} for text: '{text}'") # Debug statement
return embedding
except Exception as e:
logs.append(f"Error retrieving embedding for text '{text}': {e}")
print(f"Error retrieving embedding for text '{text}': {e}")
return [0]*1536 # Return a zero vector as fallback
def generate_axis_names(strings, pca_components, logs=[]):
"""
Generate meaningful axis names using OpenAI's GPT-4o-mini based on the input strings and PCA components.
"""
string1, string2, string3, string4 = strings
prompt = (
f"Given the following four concepts: '{string1}', '{string2}', '{string3}', and '{string4}', "
f"and the PCA components: {pca_components.tolist()}, provide three meaningful and significant axis names for a 3D plot. "
f"Each axis name should reflect the underlying data structure and the relationship between the concepts. "
f"Respond exactly in JSON format as follows:\n"
"{\n"
' "x_axis": "Axis Name 1",\n'
' "y_axis": "Axis Name 2",\n'
' "z_axis": "Axis Name 3"\n'
"}"
)
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are an assistant that creates meaningful axis names based on given concepts and PCA components."},
{"role": "user", "content": prompt}
],
max_tokens=150,
temperature=0.3,
)
axis_names = response.choices[0].message.content
axis_dict = json.loads(axis_names)
logs.append("Generated axis names using GPT-4o-mini.")
return axis_dict
except Exception as e:
logs.append(f"Error generating axis names: {e}")
print(f"Error generating axis names: {e}")
# Fallback axis names
return {"x_axis": "Axis 1", "y_axis": "Axis 2", "z_axis": "Axis 3"}
def analyze_data(prompt, logs=[]):
"""
Analyze the data based on the given prompt.
"""
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a data analyst that provides insightful analysis based on provided data points."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.5,
)
analysis = response.choices[0].message.content
logs.append("Generated analysis using GPT-4o-mini.")
return analysis
except Exception as e:
logs.append(f"Error generating analysis: {e}")
print(f"Error generating analysis: {e}")
return "Unable to generate analysis."
def generateSummaryPrompt(response_data, max_points=20):
"""
Generate a summary prompt based on the response data.
Limits the number of points to avoid excessively long prompts.
"""
x1 = response_data.get('x1', [])
y1 = response_data.get('y1', [])
z1 = response_data.get('z1', [])
labels1 = response_data.get('labels1', [])
x2 = response_data.get('x2', [])
y2 = response_data.get('y2', [])
z2 = response_data.get('z2', [])
labels2 = response_data.get('labels2', [])
prompt = "Analyze the following 3D data points for Set 1 and Set 2:\n\n"
prompt += "Set 1 (Showing first {} points):\n".format(min(len(x1), max_points))
for i in range(min(len(x1), max_points)):
prompt += f"Point {i+1}: ({x1[i]:.4f}, {y1[i]:.4f}, {z1[i]:.4f}) - {labels1[i]}\n"
prompt += "\nSet 2 (Showing first {} points):\n".format(min(len(x2), max_points))
for i in range(min(len(x2), max_points)):
prompt += f"Point {i+1}: ({x2[i]:.4f}, {y2[i]:.4f}, {z2[i]:.4f}) - {labels2[i]}\n"
prompt += "\nProvide a summary of the data trends and any notable observations."
return prompt
@app.route('/')
def index():
"""
Serve the HTML page for the application.
"""
html = """
<!DOCTYPE html>
<html lang="en">
<head>
<!-- [Your existing HTML head content remains unchanged] -->
<!-- ... (Omitted for brevity) ... -->
</head>
<body>
<!-- [Your existing HTML body content remains unchanged] -->
<!-- ... (Omitted for brevity) ... -->
<script>
// [Your existing JavaScript functions remain unchanged]
// ... (Omitted for brevity) ...
</script>
</body>
</html>
"""
return render_template_string(html)
@app.route('/compute', methods=['POST'])
def compute():
"""
Handle computation and return the processed data for plotting.
Expecting four input strings and the number of data points.
"""
data = request.json
string1 = data.get('string1', '').strip()
string2 = data.get('string2', '').strip()
string3 = data.get('string3', '').strip()
string4 = data.get('string4', '').strip()
num_points = data.get('num_points', 50)
# Initialize logs
logs = []
# Ensure all four strings are provided
if not string1 or not string2 or not string3 or not string4:
return jsonify({'error': 'All four input strings must be provided.', 'logs': logs}), 400
if not isinstance(num_points, int) or num_points < 50 or num_points > 1000:
return jsonify({'error': 'num_points must be an integer between 50 and 1000.', 'logs': logs}), 400
try:
# Prepare datasets
colors = ['cyan', 'orange'] # Colors for the two datasets
labels_group = ['Set 1', 'Set 2']
# Set 1: string1 and string2
related_phrases1 = get_related_phrases((string1, string2), num_related=num_points, logs=logs)
if not related_phrases1:
return jsonify({'error': 'Failed to generate related phrases for Set 1.', 'logs': logs}), 500
if len(related_phrases1) > 100:
related_phrases1 = related_phrases1[:100]
logs.append('Limited Set 1 phrases to 100 to optimize performance.')
embeddings1 = [get_embedding(phrase, logs=logs) for phrase in related_phrases1]
labels1 = related_phrases1
# Set 2: string3 and string4
related_phrases2 = get_related_phrases((string3, string4), num_related=num_points, logs=logs)
if not related_phrases2:
return jsonify({'error': 'Failed to generate related phrases for Set 2.', 'logs': logs}), 500
if len(related_phrases2) > 100:
related_phrases2 = related_phrases2[:100]
logs.append('Limited Set 2 phrases to 100 to optimize performance.')
embeddings2 = [get_embedding(phrase, logs=logs) for phrase in related_phrases2]
labels2 = related_phrases2
# Combine all embeddings for PCA
all_embeddings = np.array(embeddings1 + embeddings2)
logs.append(f"Total embeddings for PCA: {all_embeddings.shape[0]}.")
# Perform PCA
pca = PCA(n_components=3)
reduced_embeddings = pca.fit_transform(all_embeddings)
logs.append("Performed PCA on combined embeddings.")
# Split reduced embeddings back into Set 1 and Set 2
reduced_set1 = reduced_embeddings[:len(embeddings1)]
reduced_set2 = reduced_embeddings[len(embeddings1):]
# Generate axis names using LLM
axis_names = generate_axis_names(
strings=(string1, string2, string3, string4),
pca_components=pca.components_,
logs=logs
)
# Prepare response data
response_data = {
'axis_names': axis_names,
'x1': reduced_set1[:, 0].tolist(),
'y1': reduced_set1[:, 1].tolist(),
'z1': reduced_set1[:, 2].tolist(),
'hover_text1': [f"Content: {phrase}" for phrase in labels1],
'x2': reduced_set2[:, 0].tolist(),
'y2': reduced_set2[:, 1].tolist(),
'z2': reduced_set2[:, 2].tolist(),
'hover_text2': [f"Content: {phrase}" for phrase in labels2],
'legend': labels_group,
'labels1': labels1,
'labels2': labels2,
'camera_eye': { # Store camera position for zoom and rotate
'x': 1.75,
'y': 1.75,
'z': 1.75
}
}
# Generate summary
prompt = generateSummaryPrompt(response_data)
summary = analyze_data(prompt, logs)
response_data['summary'] = summary
return jsonify({'data': response_data, 'logs': logs})
except Exception as e:
logs.append(f"Error during computation: {e}")
print(f"Error during computation: {e}") # Debug statement
return jsonify({'error': 'An internal error occurred. Please try again later.', 'logs': logs}), 500
@app.route('/analyze', methods=['POST'])
def analyze():
"""
Analyze the data points and return conclusions.
"""
data = request.json
prompt = data.get('prompt', '').strip()
logs = []
if not prompt:
return jsonify({'error': 'No prompt provided.'}), 400
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a data analyst that provides insightful analysis based on provided data points."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.5,
)
analysis = response.choices[0].message.content
logs.append("Generated analysis using GPT-4o-mini.")
return jsonify({'conclusions': analysis, 'logs': logs})
except Exception as e:
logs.append(f"Error generating analysis: {e}")
print(f"Error generating analysis: {e}")
return jsonify({'error': 'Failed to generate analysis.', 'logs': logs}), 500
@app.route('/chat', methods=['POST'])
def chat():
"""
Handle chat messages and return responses from the LLM.
"""
data = request.json
user_message = data.get('message', '').strip()
context = data.get('context', {})
logs = []
if not user_message:
return jsonify({'error': 'No message provided.'}), 400
# Prepare context for the chat
context_text = ""
if context:
context_text += "Current Data Points:\n\nSet 1:\n"
for i, label in enumerate(context.get('labels1', [])[:100]):
context_text += f"Point {i+1}: ({context['x1'][i]}, {context['y1'][i]}, {context['z1'][i]}) - {label}\n"
context_text += "\nSet 2:\n"
for i, label in enumerate(context.get('labels2', [])[:100]):
context_text += f"Point {i+1}: ({context['x2'][i]}, {context['y2'][i]}, {context['z2'][i]}) - {label}\n"
prompt = f"{context_text}\nUser Question: {user_message}\nProvide a detailed and insightful answer based on the data above."
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are an assistant that provides detailed and insightful answers based on provided data."},
{"role": "user", "content": prompt}
],
max_tokens=500,
temperature=0.5,
)
reply = response.choices[0].message.content
logs.append("Generated chat response using GPT-4o-mini.")
return jsonify({'reply': reply, 'logs': logs})
except Exception as e:
logs.append(f"Error in chat: {e}")
print(f"Error in chat: {e}")
return jsonify({'error': 'Failed to generate chat response.', 'logs': logs}), 500
if __name__ == '__main__':
# Run the Flask app
app.run(port=5005, debug=True)
Key Changes and Fixes:
-
Defined generateSummaryPrompt Function:
- This function creates a concise prompt by limiting the number of data points used in the summary to avoid excessively long prompts.
- It ensures that only the first
max_points (defaulted to 20) from each set are included in the summary prompt.
-
Corrected Dataset Handling in compute:
- Removing the
datasets List:
- Instead of using a list of dictionaries with mixed keys (
x1, y1, z1, x2, y2, z2), embeddings for Set 1 and Set 2 are handled separately.
- Combining Embeddings for PCA:
- All embeddings from both sets are combined using
np.vstack, ensuring that PCA is applied correctly across all data points.
- Splitting PCA Results:
- After PCA transformation, the reduced embeddings are split back into Set 1 and Set 2 based on the original number of embeddings.
- Ensuring Consistent Data Structure:
- The response data is structured to include all necessary fields (
x1, y1, z1, hover_text1, etc.) without ambiguity.
-
Enhanced Error Handling and Logging:
- Added more descriptive log messages to aid in debugging.
- Ensured that any exceptions are caught and logged appropriately, providing clearer insights into potential issues.
-
Plotly Integration Remains Intact:
- The frontend uses Plotly to render 3D scatter plots. The corrected backend ensures that Plotly receives the correct data structures and coordinates, allowing for proper visualization.
Additional Recommendations:
-
Frontend Adjustments:
- Ensure that the frontend JavaScript correctly interprets the data returned from the
/compute endpoint. Specifically, verify that renderPlot and other functions handle the updated data structure.
- Test the frontend interactions thoroughly to ensure that user inputs lead to the correct visualizations.
-
API Key Security:
- Ensure that your OpenAI API key is securely stored and not exposed in any frontend code or public repositories.
-
Performance Optimization:
- Limit the number of data points sent to the frontend if operating with very large datasets to ensure smooth user experiences.
- Consider implementing pagination or clustering if datasets become too large.
-
User Feedback:
- Enhance user feedback mechanisms to inform users of the progress during data processing, especially if API calls take longer than expected.
-
Testing:
- Thoroughly test the application with various input scenarios to ensure robustness.
- Implement unit tests for critical functions like
get_related_phrases, get_embedding, and compute to catch any potential issues early.
By implementing these fixes and recommendations, your application should correctly process the data and render the Plotly plots as intended.