-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.py
1779 lines (1456 loc) · 60.8 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from flask import (
Flask,
request,
jsonify,
render_template,
session,
Response,
redirect,
url_for,
flash,
send_from_directory,
stream_with_context,
send_file,
)
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from werkzeug.security import generate_password_hash, check_password_hash
import requests
from bs4 import BeautifulSoup
from openai import OpenAI
import os
import json
from dotenv import load_dotenv
import logging
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
from flask_cors import CORS
import uuid
import re
from datetime import datetime, timedelta
import time
from alembic import op
import sqlalchemy as sa
from functools import wraps
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
import numpy as np
from sqlalchemy import func
from apscheduler.schedulers.background import BackgroundScheduler
from flask import jsonify, request
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import random
import shopify
import woocommerce
import sqlalchemy
from collections import defaultdict
from itsdangerous import URLSafeTimedSerializer
import httpx
import base64
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from woocommerce import API
from flask_caching import Cache
from werkzeug.utils import secure_filename
import stripe
from extensions import db
from wp import wp_blueprint
from sqlalchemy.orm.attributes import flag_modified
import psycopg2
# Import models
from models import User, APIKey, CustomPrompt, Analytics, AIModel, ModelReview, FineTuneJob, ChatInteraction, Conversation, EcommerceIntegration, Team, TeamMember, WebsiteInfo, FAQ
# Load environment variables from .env file
load_dotenv()
# Get the API key from the environment variables
openai_api_key = os.getenv("OPENAI_API_KEY")
HUME_API_KEY = os.getenv('HUME_API_KEY')
HUME_SECRET_KEY = os.getenv('HUME_SECRET_KEY')
if not openai_api_key:
raise ValueError("No OpenAI API key set for OPENAI_API_KEY")
openai_client = OpenAI(api_key=openai_api_key)
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": "*"}}, supports_credentials=True)
# Add this after creating the Flask app
app.config['GITHUB_CLIENT_ID'] = os.getenv('GITHUB_CLIENT_ID')
# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Set up rate limiting
limiter = Limiter(
key_func=get_remote_address,
app=app,
default_limits=["2000 per day", "1000 per hour"],
)
# Configure SQLAlchemy
app.config["SECRET_KEY"] = os.getenv(
"SECRET_KEY", "fallback_secret_key_for_development"
)
app.config["SQLALCHEMY_DATABASE_URI"] = os.getenv("DATABASE_URL", "sqlite:///users.db")
db.init_app(app)
migrate = Migrate(app, db)
app.register_blueprint(wp_blueprint, url_prefix='/wp')
# Define the login_required decorator
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if "user_id" not in session:
return redirect(url_for("auth"))
return f(*args, **kwargs)
return decorated_function
def extract_text_from_url(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
return " ".join([p.text for p in soup.find_all("p")])
def generate_integration_code(api_key, design):
return f"""
<!-- AI Chatbot Integration -->
<script src="https://infin8t.tech/chatbot.js?api_key={api_key}&open={design}"></script>
"""
@app.route("/chatbot.js", methods=["GET", "POST"])
def chatbot_script():
try:
api_key = request.args.get("api_key")
if not api_key:
app.logger.error("API key not provided in request")
return jsonify({"error": "API key is required"}), 400
api_key_obj = APIKey.query.filter_by(key=api_key).first()
if not api_key_obj:
return jsonify({"error": "Invalid API key"}), 400
design = api_key_obj.design or "0" # Default to "0" if not set
# Determine which design file to use
if design == "1":
design_file = "design/design1.txt"
elif design == "2":
design_file = "design/design2.txt"
elif design == "3":
design_file = "design/design3.txt"
else:
design_file = "design/design.txt"
# Read the script from the appropriate design file
script_path = os.path.join(app.root_path, design_file)
with open(script_path, "r") as file:
script = file.read()
# Replace placeholders with actual API key
script = script.replace("{api_key}", api_key)
return Response(script, mimetype="application/javascript")
except Exception as e:
app.logger.error(f"Error in chatbot_script: {str(e)}")
return (
jsonify({"error": "An error occurred while generating the chatbot script"}),
500,
)
@app.route("/test_db")
def test_db():
try:
db.session.query(func.now()).scalar()
return "Database connection successful"
except Exception as e:
app.logger.error(f"Database connection error: {str(e)}")
return f"Database connection failed: {str(e)}"
@app.route("/")
def home():
return render_template("home.html")
@app.route("/about")
def about():
return render_template("about.html")
@app.route("/documentation")
def docs():
return render_template("documentation.html")
@app.route("/project")
def projects():
return render_template("products.html")
@app.route("/contact")
def contact():
return render_template("contact.html")
@app.route("/privacy")
def privacy():
return render_template("privacy.html")
@app.route("/auth")
@app.route("/login")
def auth():
app.logger.info("Auth route accessed")
return render_template('auth.html')
# SMTP configuration
SMTP_SERVER = os.getenv("SMTP_SERVER")
SMTP_PORT = int(os.getenv("SMTP_PORT"))
SMTP_USERNAME = os.getenv("SMTP_USERNAME")
SMTP_PASSWORD = os.getenv("SMTP_PASSWORD")
# Store OTPs temporarily (in a real application, use a database)
otps = {}
def send_otp(email):
otp = ''.join([str(random.randint(0, 9)) for _ in range(6)])
otps[email] = otp
message = MIMEMultipart()
message["From"] = SMTP_USERNAME
message["To"] = email
message["Subject"] = "Your OTP for Chatcat Registration"
html_body = f"""
<html>
<body>
<h2>Welcome to Chatcat!</h2>
<p>Thank you for registering with us. To complete your registration, please use the following One-Time Password (OTP):</p>
<h1 style="color: #4CAF50; font-size: 40px;">{otp}</h1>
<p>This OTP is valid for 10 minutes. If you didn't request this, please ignore this email.</p>
<p>Best regards,<br>The Cartonify Team</p>
<hr>
<footer style="font-size: 12px; color: #666;">
<p>
<a href="https://chatcat.com/terms">Terms and Conditions</a> |
<a href="https://chatcat.com/privacy">Privacy Policy</a> |
<a href="https://chatcat.com/docs">Documentation</a>
</p>
</footer>
</body>
</html>
"""
message.attach(MIMEText(html_body, "html"))
with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
server.login(SMTP_USERNAME, SMTP_PASSWORD)
server.send_message(message)
@app.route('/send-otp', methods=['POST'])
def send_otp_route():
email = request.json.get('email')
if not email:
return jsonify({"error": "Email is required"}), 400
try:
send_otp(email)
return jsonify({"message": "OTP sent successfully"}), 200
except Exception as e:
app.logger.error(f"Error sending OTP: {str(e)}")
return jsonify({"error": "Failed to send OTP"}), 500
@app.route("/register", methods=["POST"])
def register():
email = request.json.get("email")
password = request.json.get("password")
otp = request.json.get("otp")
if not email or not password or not otp:
return jsonify({"error": "Email, password, and OTP are required"}), 400
if otps.get(email) != otp:
return jsonify({"error": "Invalid OTP"}), 400
if User.query.filter_by(email=email).first():
return jsonify({"error": "Email already registered"}), 400
hashed_password = generate_password_hash(password)
new_user = User(email=email, password=hashed_password)
db.session.add(new_user)
db.session.commit()
# Clear the OTP after successful registration
del otps[email]
return jsonify({"message": "Registration successful"}), 201
@app.route("/login", methods=["POST"])
def login():
data = request.json
email = data.get("email")
password = data.get("password")
user = User.query.filter_by(email=email).first()
if user and check_password_hash(user.password, password):
session["user_id"] = user.id
return jsonify({"message": "Logged in successfully", "redirect": "/dashboard/home"}), 200
return jsonify({"error": "Invalid credentials"}), 401
@app.route("/logout", methods=["POST"])
def logout():
session.pop("user_id", None)
return jsonify({"message": "Logged out successfully", "redirect": "/auth"}), 200
@app.route("/dashboard/home/process_url", methods=["POST"])
@limiter.limit("50 per minute")
def process_url():
if "user_id" not in session:
return jsonify({"error": "User not logged in"}), 401
url = request.json.get("url")
llm = request.json.get("llm")
design = request.json.get("design", "0")
name = request.json.get("name") # Get the name from the request
if not url or not llm:
return jsonify({"error": "URL and LLM choice are required"}), 400
try:
extracted_text = extract_text_from_url(url)
api_key = f"user_{uuid.uuid4().hex}"
# Use the provided name or generate a default name if not provided
api_name = name if name else f"API for {url[:30]}..."
new_api_key = APIKey(
key=api_key,
name=api_name,
llm=llm,
extracted_text=extracted_text,
user_id=session["user_id"],
design=design
)
db.session.add(new_api_key)
db.session.commit()
integration_code = generate_integration_code(api_key, design)
return jsonify(
{
"message": "Processing complete",
"api_key": api_key,
"name": api_name,
"llm": llm,
"integration_code": integration_code,
}
)
except Exception as e:
app.logger.error(f"Error in process_url: {str(e)}", exc_info=True)
return jsonify({"error": str(e)}), 500
def process_ecommerce_response(response):
# Try to extract product information using regex
product_info = re.search(
r"Product: (.*?)\nPrice: (.*?)\nDescription: (.*?)\nImage: (.*?)\nURL: (.*?)(\n|$)",
response,
)
if product_info:
# If product information is found, structure it
product_data = {
"name": product_info.group(1),
"price": product_info.group(2),
"description": product_info.group(3),
"image_url": product_info.group(4),
"product_url": product_info.group(5),
}
return {"response": response, "product_data": product_data}
else:
# If no product information is found, return the response as is
return {"response": response}
def generate_suggested_queries(context, conversation_history, num_suggestions=3):
full_text = context + ' ' + ' '.join([msg['content'] for msg in conversation_history])
prompt = f"""Based on the following context and recent conversation, generate {num_suggestions} very short follow-up questions:
Context: {context[:100]}... # Truncate context for brevity
Conversation History:
{' '.join([f"{msg['role']}: {msg['content']}" for msg in conversation_history])}
Generate {num_suggestions} short questions:"""
try:
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
max_tokens=50, # Reduce token count for faster response
n=1,
temperature=0.7,
)
generated_text = response.choices[0].message.content.strip()
questions = generated_text.split('\n')
# Ensure questions are very short
questions = [q.split('. ', 1)[-1].strip()[:30] for q in questions if q.strip()]
return questions[:num_suggestions]
except Exception as e:
app.logger.error(f"Error generating suggested queries: {str(e)}")
return []
@app.route("/chat", methods=["POST", "OPTIONS"])
@limiter.limit("50 per minute")
def chat():
if request.method == "OPTIONS":
return jsonify({}), 200
start_time = time.time()
try:
user_input = request.json.get("input")
api_key = request.json.get("api_key")
if not user_input or not api_key:
return jsonify({"error": "Input and API key are required"}), 400
api_key_data = APIKey.query.filter_by(key=api_key).first()
if not api_key_data:
return jsonify({"error": "Invalid API key"}), 400
# Fetch or create conversation
conversation = Conversation.query.filter_by(user_id=api_key_data.user_id, api_key_id=api_key_data.id).order_by(Conversation.updated_at.desc()).first()
if not conversation or (datetime.utcnow() - conversation.created_at) > timedelta(hours=24):
conversation = Conversation(user_id=api_key_data.user_id, api_key_id=api_key_data.id, messages=[])
db.session.add(conversation)
# Append user input to conversation history
conversation.messages.append({"role": "user", "content": user_input})
# Fetch the extracted text associated with this API key
context = api_key_data.extracted_text
# Fetch custom prompts for the user
custom_prompts = CustomPrompt.query.filter_by(user_id=api_key_data.user_id).all()
# Prepare messages for AI, including conversation history and custom prompts
messages = [
{
"role": "system",
"content": f"""You are a concise AI assistant for this website. Provide brief, relevant responses. Context: {context[:200]}...
Key guidelines:
1. Provide friendly, personalized responses based on your deep understanding of the website and company.
2. Use a conversational tone that reflects the brand's personality.
3. Enthusiastically share details about products, services, and what makes the company unique.
4. Suggest complementary items or services when it would benefit the customer.
5. Anticipate and address potential questions or concerns proactively.
6. Incorporate industry terms naturally, as an expert would.
7. Keep responses concise but informative. Elaborate if the customer seems interested.
8. Engage customers by asking relevant follow-up questions or suggesting next steps.
9. Draw on the context of the entire conversation to provide cohesive assistance.
For e-commerce inquiries:
- Access the order tracking system to provide real-time order status updates.
- Consult the product database for accurate information on names, pricing, and inventory.
- Share current processing times based on the latest operations reports.
- If specific e-commerce details are unavailable, offer to personally look into it and get back to the customer.
Key points:
1. Be friendly and personalized.
2. Use conversational tone.
3. Be enthusiastic about products/services.
4. Keep responses under 50 words.
5. If unsure, ask for clarification.
Custom information:
{' '.join([f'- {prompt.prompt}: {prompt.response}' for prompt in custom_prompts])}
Custom info: {' '.join([f'{prompt.prompt}: {prompt.response[:20]}...' for prompt in custom_prompts[:3]])}"""
}
] + conversation.messages[-5:] # Include last 5 messages for context
logger.info(f"Sending request to AI service with input: {user_input}")
def generate_ai_response():
try:
accumulated_message = ""
for chunk in get_ai_response_stream(api_key_data.llm, messages):
accumulated_message = json.loads(chunk)["response"]
yield f"data: {chunk}"
# Generate suggested queries based on context and conversation
suggested_queries = generate_suggested_queries(context, conversation.messages)
# Add suggested queries to the response
final_response = {
"response": accumulated_message,
"suggested_queries": suggested_queries
}
yield f"data: {json.dumps(final_response)}\n\n"
# Append AI response to conversation history
conversation.messages.append({"role": "assistant", "content": json.dumps(final_response)})
conversation.updated_at = datetime.utcnow()
flag_modified(conversation, "messages")
db.session.commit()
# Record analytics
analytics = Analytics(
user_id=api_key_data.user_id,
api_key=api_key,
endpoint="/chat",
response_time=time.time() - start_time,
status_code=200,
)
db.session.add(analytics)
db.session.commit()
app.logger.info(f"Analytics recorded for user_id: {api_key_data.user_id}, api_key: {api_key}")
# Update the stored conversation with the AI's response
conversation = loadConversation()
conversation.push({ sender: 'AI', message: final_response })
saveConversation(conversation)
except Exception as e:
app.logger.error(f"Error in chat route: {str(e)}", exc_info=True)
yield f"data: {json.dumps({'error': str(e)})}\n\n"
# Record analytics for error case
analytics = Analytics(
user_id=api_key_data.user_id,
api_key=api_key,
endpoint="/chat",
response_time=time.time() - start_time,
status_code=500,
)
db.session.add(analytics)
db.session.commit()
return Response(stream_with_context(generate_ai_response()), content_type='text/event-stream')
except Exception as e:
app.logger.error(f"Error in chat route: {str(e)}", exc_info=True)
return jsonify({"error": f"Unexpected error: {str(e)}"}), 500
def get_ai_response_stream(llm_type, messages):
response = openai_client.chat.completions.create(
model="gpt-3.5-turbo", # Use a faster model
messages=messages,
max_tokens=50, # Reduce token count for faster, more concise responses
temperature=0.7,
stream=True
)
accumulated_message = ""
for chunk in response:
if chunk.choices[0].delta.content is not None:
accumulated_message += chunk.choices[0].delta.content
yield json.dumps({"response": accumulated_message}) + "\n\n"
return accumulated_message
def get_ai_response(llm_type, messages):
user_id = session.get("user_id")
if user_id:
# Fetch website-specific information
website_info = WebsiteInfo.query.filter_by(user_id=user_id).first()
faq_items = FAQ.query.filter_by(user_id=user_id).order_by(FAQ.order).all()
# Add website-specific context to the system message
website_context = f"""
You are an AI assistant for {website_info.name}.
Website description: {website_info.description}
Key features: {website_info.features}
FAQ:
{' '.join([f'Q: {faq.question} A: {faq.answer}' for faq in faq_items])}
Always respond as if you are the official assistant for this specific website.
Provide direct and accurate information based on the website details and FAQ.
Do not use phrases like 'I don't have information' or 'I can't access specific details'.
If you're unsure about a specific detail, refer to the general information provided.
"""
# Update the system message with website-specific context
messages[0]['content'] = website_context + messages[0]['content']
# Use OpenAI's GPT-4 for all requests
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
max_tokens=100,
temperature=0.7
)
raw_response = response.choices[0].message.content
# Ensure raw_response is a string
if not isinstance(raw_response, str):
raw_response = str(raw_response)
structured_response = process_raw_response(raw_response)
return structured_response
def process_raw_response(raw_response):
# Split the response into sentences
sentences = re.split(r'(?<=[.!?])\s+', raw_response)
# Initialize structured response
structured_response = {
"introduction": "",
"steps": [],
"conclusion": ""
}
# Process sentences
for sentence in sentences:
if sentence.startswith(("With", "Using")):
structured_response["introduction"] = sentence
elif re.match(r'^\d+\.', sentence):
# This is a numbered step
step = re.sub(r'^\d+\.\s*', '', sentence)
structured_response["steps"].append(step)
elif sentence.startswith(("Finally", "In conclusion")):
structured_response["conclusion"] = sentence
else:
# If it doesn't fit elsewhere, add it to the last step
if structured_response["steps"]:
structured_response["steps"][-1] += " " + sentence
else:
structured_response["introduction"] += " " + sentence
return structured_response
def process_ecommerce_response(response):
if isinstance(response, dict):
# This is our new structured response
return response
# If it's not a dict, assume it's a string (old format)
# Try to extract product information using regex
product_info = re.search(
r"Product: (.*?)\nPrice: (.*?)\nDescription: (.*?)\nImage: (.*?)\nURL: (.*?)(\n|$)",
response,
)
if product_info:
# If product information is found, structure it
product_data = {
"name": product_info.group(1),
"price": product_info.group(2),
"description": product_info.group(3),
"image_url": product_info.group(4),
"product_url": product_info.group(5),
}
return {"response": response, "product_data": product_data}
else:
# If no product information is found, return the response as is
return {"response": response}
@app.route("/dashboard/home/user/api_keys", methods=["GET"])
@login_required
def get_user_api_keys():
user = User.query.get(session["user_id"])
api_keys = [{"id": key.id, "key": key.key, "name": key.name, "llm": key.llm, "design": key.design} for key in user.api_keys]
return jsonify({"api_keys": api_keys})
# Add this new route to retrieve analytics data
@app.route("/dashboard/home/api/analytics", methods=["GET"])
@login_required
def get_analytics():
try:
user_id = session["user_id"]
app.logger.info(f"Fetching analytics for user_id: {user_id}")
# Get all analytics data for the user
analytics = Analytics.query.filter_by(user_id=user_id).order_by(Analytics.timestamp.desc()).all()
app.logger.info(f"Found {len(analytics)} analytics entries for user_id: {user_id}")
if not analytics:
return jsonify({"message": "No analytics data available", "analytics": [], "graph_data": [], "total_calls": 0, "avg_response_time": 0}), 200
# Prepare data for charts
daily_usage = defaultdict(int)
response_times = []
for entry in analytics:
date = entry.timestamp.date()
daily_usage[date] += 1
response_times.append(entry.response_time)
graph_data = [
{"date": date.isoformat(), "count": count}
for date, count in sorted(daily_usage.items())
]
avg_response_time = sum(response_times) / len(response_times) if response_times else 0
analytics_data = [
{
"api_key": a.api_key,
"endpoint": a.endpoint,
"timestamp": a.timestamp.isoformat(),
"response_time": a.response_time,
"status_code": a.status_code,
}
for a in analytics[:100] # Limit to last 100 entries for the table
]
result = {
"analytics": analytics_data,
"graph_data": graph_data,
"avg_response_time": avg_response_time,
"total_calls": len(analytics)
}
app.logger.info(f"Returning analytics data: {result}")
return jsonify(result)
except Exception as e:
app.logger.error(f"Error in get_analytics: {str(e)}", exc_info=True)
return jsonify({"error": "An error occurred while fetching analytics data"}), 500
@app.route("/test_apis")
def test_apis():
openai_result = "Failed"
try:
response = openai_client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello"}],
max_tokens=5,
)
openai_result = "Success"
except Exception as e:
logger.error(f"OpenAI API connection error: {str(e)}")
return f"OpenAI API: {openai_result}"
@app.route("/dashboard/home/api/update_profile", methods=["POST"])
@login_required
def update_profile():
user = User.query.get(session["user_id"])
new_email = request.form.get("email")
new_password = request.form.get("new_password")
confirm_password = request.form.get("confirm_password")
if new_email and new_email != user.email:
if User.query.filter_by(email=new_email).first():
flash("Email already in use", "error")
else:
user.email = new_email
flash("Email updated successfully", "success")
if new_password:
if new_password == confirm_password:
user.password = generate_password_hash(new_password)
flash("Password updated successfully", "success")
else:
flash("Passwords do not match", "error")
db.session.commit()
return redirect(url_for("dashboard"))
@app.route("/dashboard")
@app.route("/dashboard/<section>")
@login_required
def dashboard_section(section=None):
user = User.query.get(session["user_id"])
custom_prompts = CustomPrompt.query.filter_by(user_id=user.id).all()
website_info = WebsiteInfo.query.filter_by(user_id=user.id).first()
faq_items = FAQ.query.filter_by(user_id=user.id).order_by(FAQ.order).all()
return render_template("dashboard.html", user=user, active_section=section or "home", custom_prompts=custom_prompts, website_info=website_info, faq_items=faq_items)
@app.route('/subscription')
def subscription_page():
subscription_plans = {
'basic': {'price': 99900, 'api_calls': 1000},
'pro': {'price': 199900, 'api_calls': 5000},
'enterprise': {'price': 499900, 'api_calls': 20000}
}
return render_template('subscription.html', subscription_plans=subscription_plans, user=current_user)
@app.route("/profile", methods=["GET", "POST"])
@login_required
def profile():
user = User.query.get(session["user_id"])
if request.method == "POST":
new_email = request.form.get("email")
new_password = request.form.get("new_password")
confirm_password = request.form.get("confirm_password")
if new_email:
user.email = new_email
if new_password and new_password == confirm_password:
user.password = generate_password_hash(new_password)
elif new_password and new_password != confirm_password:
flash("Passwords do not match", "error")
return redirect(url_for("profile"))
db.session.commit()
flash("Profile updated successfully", "success")
return redirect(url_for("profile"))
return render_template("profile.html", user=user)
@app.route("/dashboard/home/delete_api_key", methods=["POST"])
@login_required
def delete_api_key():
api_key_id = request.json.get('api_key_id')
if not api_key_id:
return jsonify({"error": "API key ID is required"}), 400
api_key = APIKey.query.get(api_key_id)
if not api_key or api_key.user_id != session["user_id"]:
return jsonify({"error": "Invalid API key or you don't have permission to delete it"}), 404
try:
db.session.delete(api_key)
db.session.commit()
return jsonify({"message": "API key and associated conversations deleted successfully"}), 200
except Exception as e:
db.session.rollback()
app.logger.error(f"Error deleting API key: {str(e)}")
return jsonify({"error": "An error occurred while deleting the API key"}), 500
@app.route("/add_custom_prompt", methods=["POST"])
@login_required
def add_custom_prompt():
prompt = request.form.get("prompt")
response = request.form.get("response")
if prompt and response:
new_prompt = CustomPrompt(
user_id=session["user_id"], prompt=prompt, response=response
)
db.session.add(new_prompt)
db.session.commit()
flash("Custom prompt added successfully", "success")
else:
flash("Prompt and response are required", "error")
return redirect(url_for("dashboard_section", section="custom-prompts"))
@app.route("/change_password", methods=["POST"])
@login_required
def change_password():
current_password = request.form.get("current_password")
new_password = request.form.get("new_password")
user = User.query.get(session["user_id"])
if user and check_password_hash(user.password, current_password):
user.password = generate_password_hash(new_password)
db.session.commit()
flash("Password changed successfully", "success")
else:
flash("Current password is incorrect", "error")
return redirect(url_for("dashboard"))
@app.route("/test_api_key", methods=["POST"])
@login_required
def test_api_key():
api_key = request.json.get("api_key")
test_input = request.json.get("input", "Hello, this is a test message.")
api_key_data = APIKey.query.filter_by(key=api_key).first()
if not api_key_data:
return jsonify({"error": "Invalid API key"}), 400
try:
response = requests.post(
"https://infin8t.tech/chat",
json={"input": test_input, "api_key": api_key},
timeout=10,
) # Add a timeout
response.raise_for_status() # Raises an HTTPError for bad responses
return (
jsonify(
{
"status_code": response.status_code,
"headers": dict(response.headers),
"response": response.json(),
}
),
200,
)
except requests.exceptions.RequestException as e:
app.logger.error(f"API test failed: {str(e)}")
return jsonify({"error": f"API test failed: {str(e)}"}), 500
except ValueError as e: # This will catch json decode errors
app.logger.error(f"Error decoding JSON response: {str(e)}")
return jsonify({"error": f"Error decoding response: {str(e)}"}), 500
except Exception as e:
app.logger.error(f"Unexpected error in API test: {str(e)}")
return jsonify({"error": f"Unexpected error: {str(e)}"}), 500
# New routes
@app.route("/ai_models", methods=["GET"])
def get_ai_models():
models = AIModel.query.all()
return jsonify(
[
{
"id": model.id,
"name": model.name,
"description": model.description,
"provider": model.provider,
"documentation_url": model.documentation_url,
"average_rating": get_average_rating(model.id),
}
for model in models
]
)
@app.route("/ai_models/<int:model_id>", methods=["GET"])
def get_ai_model(model_id):
model = AIModel.query.get_or_404(model_id)
reviews = ModelReview.query.filter_by(model_id=model_id).all()
return jsonify(
{
"id": model.id,
"name": model.name,
"description": model.description,
"provider": model.provider,
"documentation_url": model.documentation_url,
"average_rating": get_average_rating(model.id),
"reviews": [
{
"user_id": review.user_id,
"rating": review.rating,
"review_text": review.review_text,
"created_at": review.created_at,
}
for review in reviews
],
}
)
@app.route('/resend-otp', methods=['POST'])
def resend_otp_route():
email = request.json.get('email')
if not email:
return jsonify({"error": "Email is required"}), 400
try:
send_otp(email)
return jsonify({"message": "OTP resent successfully"}), 200
except Exception as e:
app.logger.error(f"Error resending OTP: {str(e)}")
return jsonify({"error": "Failed to resend OTP"}), 500
@app.route("/ai_models/<int:model_id>/review", methods=["POST"])
def add_model_review(model_id):
if "user_id" not in session:
return jsonify({"error": "User not logged in"}), 401
data = request.json
new_review = ModelReview(
user_id=session["user_id"],
model_id=model_id,
rating=data["rating"],
review_text=data.get("review_text", ""),
)
db.session.add(new_review)
db.session.commit()
return jsonify({"message": "Review added successfully"}), 201
def get_average_rating(model_id):
reviews = ModelReview.query.filter_by(model_id=model_id).all()
if not reviews:
return 0
return sum(review.rating for review in reviews) / len(reviews)
@app.route('/slack/oauth_callback')
@login_required
def slack_oauth_callback():
code = request.args.get('code')
client_id = os.getenv('SLACK_CLIENT_ID')
client_secret = os.getenv('SLACK_CLIENT_SECRET')
redirect_uri = url_for('slack_oauth_callback', _external=True)
# Exchange the code for an access token
response = requests.post('https://slack.com/api/oauth.v2.access', data={
'client_id': client_id,
'client_secret': client_secret,