dash-chat-api / main.py
rairo's picture
Update main.py
26d0fc1 verified
raw
history blame
5.48 kB
from langchain_google_genai import ChatGoogleGenerativeAI
import pandas as pd
import os
import io
from flask import Flask, request, jsonify
from flask_cors import CORS, cross_origin
import logging
from dotenv import load_dotenv
from pandasai import SmartDatalake
from pandasai import SmartDataframe
from pandasai.responses.response_parser import ResponseParser
from langchain.prompts import PromptTemplate
from langchain.chains import LLMChain
from datetime import datetime
import matplotlib.pyplot as plt
import google.generativeai as genai
load_dotenv()
app = Flask(__name__)
cors = CORS(app)
class FlaskResponse(ResponseParser):
def __init__(self, context):
super().__init__(context)
def format_dataframe(self, result):
return result['value'].to_html()
def format_plot(self, result):
# Here we assume that result['value'] is a matplotlib Figure.
try:
fig = result['value']
buf = io.BytesIO()
fig.savefig(buf, format="png")
buf.seek(0)
image_base64 = base64.b64encode(buf.read()).decode("utf-8")
# Return a data URL that can be rendered in an <img> tag.
return f"data:image/png;base64,{image_base64}"
except Exception as e:
print("Error processing plot:", e)
return str(result['value'])
def format_other(self, result):
return str(result['value'])
gemini_api_key = os.getenv('Gemini')
llm = ChatGoogleGenerativeAI(api_key=gemini_api_key, model='gemini-2.0-flash-thinking-exp', temperature=0.1)
gemini_api_key = os.environ['Gemini']
genai.configure(api_key=gemini_api_key)
generation_config = {
"temperature": 0.2,
"top_p": 0.95,
"max_output_tokens": 5000,
}
model = genai.GenerativeModel(
model_name="gemini-2.0-flash-thinking-exp",
generation_config=generation_config,
)
# Endpoint for chat
@app.route("/chat", methods=["POST"])
@cross_origin()
def bot():
# Retrieve parameters from the request
json_table = request.json.get("json_table")
user_question = request.json.get("user_question")
print("User question:", user_question)
# Convert the table data into a dataframe
data = eval(str(json_table))
df = pd.DataFrame(data)
print("Columns in dataframe:", list(df.columns))
# Create a SmartDataframe instance using your configuration.
pandas_agent = SmartDataframe(
df,
config={
"llm": llm,
"response_parser": FlaskResponse,
"custom_whitelisted_dependencies": [
"os",
"io",
"sys",
"chr",
"glob",
"b64decoder",
"collections",
"geopy",
"geopandas",
"wordcloud",
"builtins"
],
"security": "none"
}
)
# Get the answer from the agent
answer = pandas_agent.chat(user_question)
# Process the answer based on its type
formatted_answer = None
if isinstance(answer, pd.DataFrame):
formatted_answer = answer.to_html()
elif isinstance(answer, plt.Figure):
buf = io.BytesIO()
answer.savefig(buf, format="png")
buf.seek(0)
image_base64 = base64.b64encode(buf.read()).decode("utf-8")
formatted_answer = f"data:image/png;base64,{image_base64}"
elif isinstance(answer, (int, float)):
formatted_answer = str(answer)
else:
formatted_answer = str(answer)
# Return the formatted answer as JSON.
return jsonify({"answer": formatted_answer})
# Reports endpoint
@app.route("/report", methods=["POST"])
@cross_origin()
def busines_report():
json_data = request.json.get("json_data")
prompt = """
You are an expert business analyst. Analyze the following data and generate a comprehensive and insightful business report, including appropriate key perfomance indicators and recommendations.
data:
""" + str(json_data)
response = model.generate_content(prompt)
report = response.text
return jsonify(str(report))
# MArketing
@app.route("/marketing", methods=["POST"])
@cross_origin()
def marketing():
json_data = request.json.get("json_data")
prompt = """
You are an expert MArketing Strategist. Analyze the following data and generate a comprehensive marketing strategy, be very creative:
""" + str(json_data)
response = model.generate_content(prompt)
report = response.text
return jsonify(str(report))
# Business Plan
@app.route("/bplan", methods=["POST"])
@cross_origin()
def business_plan():
json_data = request.json.get("json_data")
prompt = """
You are an expert business analyst. Analyze the following data and generate a comprehensive business plan to help the business look for funding and support:
""" + str(json_data)
response = model.generate_content(prompt)
report = response.text
return jsonify(str(report))
#Notificatiions
@app.route("/notify", methods=["POST"])
@cross_origin()
def notifications():
json_data = request.json.get("json_data")
prompt = """
You are a business analyst. Write a very brief analysis and marketing tips using this business data
""" + str(json_data)
response = model.generate_content(prompt)
report = response.text
return jsonify(str(report))
if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=7860)