-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathmodels.py
2142 lines (1754 loc) · 84.4 KB
/
models.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
import secrets
from django.db import transaction
import traceback
import logging
import os
import uuid
from django.conf import settings
from django.db import models
from django.db.models import Index
from datetime import datetime
from django.core.exceptions import ValidationError
from urllib.parse import urlparse
from django.core.validators import URLValidator, MaxValueValidator
from accounts.models import User
logger = logging.getLogger(__name__)
def get_datasource_upload_path(instance, filename):
"""
Generate dynamic upload path for DataSource files.
Path format: data_sources/<guru_type_slug>/<filename>
"""
guru_type_slug = instance.guru_type.slug.lower()
return f'data_sources/{guru_type_slug}/{filename}'
class Question(models.Model):
class Source(models.TextChoices):
USER = "USER"
RAW_QUESTION = "RAW_QUESTION"
REDDIT = "REDDIT"
SUMMARY_QUESTION = "SUMMARY QUESTION"
WIDGET_QUESTION = "WIDGET QUESTION"
API = "API"
DISCORD = "DISCORD"
SLACK = "SLACK"
GITHUB = "GITHUB"
slug = models.SlugField(max_length=1500)
question = models.TextField()
old_question = models.TextField(default='', blank=True, null=True) # For tracking changes
user_question = models.TextField(default='', blank=True, null=True)
og_image_url = models.URLField(max_length=2000, default='', blank=True, null=True)
content = models.TextField()
is_helpful = models.BooleanField(null=True, blank=True)
description = models.TextField()
change_count = models.IntegerField(default=0)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
add_to_sitemap = models.BooleanField(default=False)
sitemap_reason = models.TextField(default='', blank=True, null=True)
sitemap_date = models.DateTimeField(null=True, blank=True)
similar_questions = models.JSONField(default=dict, blank=True, null=False)
context_distances = models.JSONField(default=list, blank=True, null=False)
reranked_scores = models.JSONField(default=list, blank=True, null=False)
default_question = models.BooleanField(default=False)
guru_type = models.ForeignKey(
"GuruType", on_delete=models.SET_NULL, null=True, blank=True
)
cost_dollars = models.FloatField(default=0, blank=True, null=True)
completion_tokens = models.PositiveIntegerField(default=0, blank=True, null=True)
prompt_tokens = models.PositiveIntegerField(default=0, blank=True, null=True)
cached_prompt_tokens = models.PositiveIntegerField(
default=0, blank=True, null=True) # Already included in prompt_tokens
latency_sec = models.FloatField(default=0, blank=True, null=True)
source = models.CharField(
max_length=50,
choices=[(tag.value, tag.value) for tag in Source],
default=Source.USER.value,
)
references = models.JSONField(default=dict, blank=True, null=True)
prompt = models.TextField(default="", blank=True, null=True)
english = models.BooleanField(default=True)
title_processed = models.BooleanField(default=False)
llm_eval = models.BooleanField(default=False)
similarity_written_to_milvus = models.BooleanField(default=False)
parent = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True, related_name="parent_question")
follow_up_questions = models.JSONField(default=list, blank=True, null=False)
binge = models.ForeignKey("Binge", on_delete=models.SET_NULL, null=True, blank=True, default=None)
cache_request_count = models.IntegerField(default=0)
# Avg context relevance of the contexts passing the minimum threshold. Between 0 and 1.
trust_score = models.FloatField(default=0, blank=True, null=True)
processed_ctx_relevances = models.JSONField(default=dict, blank=True, null=False)
llm_usages = models.JSONField(default=dict, blank=True, null=False)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
times = models.JSONField(default=dict, blank=True, null=False)
enhanced_question = models.TextField(default='', blank=True, null=True)
@property
def frontend_url(self):
"""Returns the frontend URL for this question."""
from core.utils import get_base_url
if not self.guru_type:
return ""
if self.binge:
root_slug = self.binge.root_question.slug if self.binge.root_question else self.slug
return f"{get_base_url()}/g/{self.guru_type.slug}/{root_slug}/binge/{self.binge.id}?question_slug={self.slug}"
return f"{get_base_url()}/g/{self.guru_type.slug}/{self.slug}"
def __str__(self):
return f"{self.id} - {self.slug}"
def save(self, *args, **kwargs):
# Validate source
if not self.source or self.source not in [tag.value for tag in self.Source]:
self.source = self.Source.USER.value
if not self.binge:
# Check uniqueness for non-binge questions
existing_by_slug = Question.objects.filter(
slug=self.slug,
guru_type=self.guru_type,
binge__isnull=True
).exclude(pk=self.pk).exists()
if existing_by_slug:
raise ValidationError("A question with this slug and guru type already exists")
else:
# Check uniqueness for binge questions
existing_binge = Question.objects.filter(
binge=self.binge,
slug=self.slug,
guru_type=self.guru_type
).exclude(pk=self.pk).exists()
if existing_binge:
raise ValidationError("A question with this slug and guru type already exists in this binge")
total_cost_dollars = 0
for prices in self.llm_usages.values():
total_cost_dollars += prices['cost_dollars']
self.cost_dollars = total_cost_dollars
if not self.user_question:
self.user_question = self.question
if self.llm_eval and self.binge:
raise ValidationError("LLM eval is not allowed for binge questions")
super().save(*args, **kwargs)
class Meta:
indexes = [
Index(fields=["add_to_sitemap"]),
Index(fields=["guru_type"]),
Index(fields=["date_created"]),
Index(fields=["source"]),
Index(fields=["guru_type", "date_created"]),
Index(fields=["guru_type", "source"]),
]
@property
def total_tokens(self):
return self.prompt_tokens + self.completion_tokens
def is_on_sitemap(self):
from core.utils import get_default_settings, get_most_similar_questions
add_to_sitemap = True
sitemap_reason = None
if self.parent:
add_to_sitemap = False
sitemap_reason = "Is a follow up question"
return add_to_sitemap, sitemap_reason
# If not belonging to a custom guru, return False
# if not self.guru_type.custom:
# add_to_sitemap = False
# sitemap_reason = "Not belonging to a custom guru"
# return add_to_sitemap, sitemap_reason
if self.source not in [Question.Source.SUMMARY_QUESTION.value, Question.Source.RAW_QUESTION.value]:
add_to_sitemap = False
sitemap_reason = "Not a summary or raw question"
return add_to_sitemap, sitemap_reason
if not self.english:
add_to_sitemap = False
sitemap_reason = "Not English"
return add_to_sitemap, sitemap_reason
default_settings = get_default_settings()
reranked_scores = self.reranked_scores
avg_score = sum(map(lambda x: x['score'], reranked_scores)) / len(reranked_scores) if reranked_scores else 0
if avg_score < default_settings.rerank_threshold:
add_to_sitemap = False
sitemap_reason = f"Rerank avg score too low: {avg_score} < {default_settings.rerank_threshold}"
return add_to_sitemap, sitemap_reason
# If there is another question with the same title, do not add to sitemap
questions_with_same_title = Question.objects.filter(
question=self.question, add_to_sitemap=True).exclude(id=self.id)
if questions_with_same_title.exists():
add_to_sitemap = False
sitemap_reason = f"Same title with ID: {questions_with_same_title.first().id}"
logger.info(
f"Question {self.id} has another question with the same title. Not adding to sitemap.", exc_info=True)
return add_to_sitemap, sitemap_reason
# Get the closest first question
similar_questions = get_most_similar_questions(
self.slug, self.content, self.guru_type.slug, column='content', top_k=1, sitemap_constraint=True)
if len(similar_questions) == 0:
add_to_sitemap = True
else:
distance = similar_questions[0]['distance']
if distance > settings.VECTOR_DISTANCE_THRESHOLD:
add_to_sitemap = True
else:
add_to_sitemap = False
# DO NOT CHANGE THE REASON TEXT. It's used in the signal: delete_question_similarities
sitemap_reason = f"Similar to question ID: ({similar_questions[0]['id']}) - ({similar_questions[0]['title']}) with content distance: {distance}"
# Check also Context Relevance score to check if the threshold is greater than 0.5
if self.trust_score < settings.SITEMAP_ADD_CONTEXT_RELEVANCE_THRESHOLD:
add_to_sitemap = False
sitemap_reason = f"Trust score is low: {self.trust_score} < {settings.SITEMAP_ADD_CONTEXT_RELEVANCE_THRESHOLD}"
return add_to_sitemap, sitemap_reason
class RawQuestion(models.Model):
question = models.TextField()
category = models.TextField(default='')
guru_type = models.ForeignKey("GuruType", on_delete=models.SET_NULL, null=True, blank=True)
raw_question_generation = models.ForeignKey(
"RawQuestionGeneration", on_delete=models.SET_NULL, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
processed = models.BooleanField(default=False)
def __str__(self):
return str(self.id)
class RawQuestionGeneration(models.Model):
guru_type = models.ForeignKey(
"GuruType", on_delete=models.SET_NULL, null=True, blank=True
)
sort = models.TextField(null=False, blank=False)
page_num = models.IntegerField(null=False, blank=False)
page_size = models.IntegerField(null=False, blank=False)
generate_count = models.IntegerField(null=False, blank=False)
model = models.TextField(null=False, blank=False)
cost_dollars = models.FloatField(default=0, blank=True, null=True)
prompts = models.JSONField(default=list, blank=True, null=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return str(self.id)
class ContentPageStatistics(models.Model):
question = models.OneToOneField(
Question, on_delete=models.CASCADE, related_name="statistics"
)
view_count = models.PositiveIntegerField(default=0)
upvotes = models.PositiveIntegerField(default=0)
downvotes = models.PositiveIntegerField(default=0)
def __str__(self):
return f"Statistics for {self.question.slug}"
class QuestionValidityCheckPricing(models.Model):
slug = models.SlugField(max_length=1500)
cost_dollars = models.FloatField(default=0, blank=True, null=True)
completion_tokens = models.PositiveIntegerField(default=0, blank=True, null=True)
prompt_tokens = models.PositiveIntegerField(default=0, blank=True, null=True)
cached_prompt_tokens = models.PositiveIntegerField(
default=0, blank=True, null=True) # Already included in prompt_tokens
def __str__(self):
return str(self.id)
@property
def total_tokens(self):
return self.prompt_tokens + self.completion_tokens
class GuruType(models.Model):
class EmbeddingModel(models.TextChoices):
IN_HOUSE = "IN_HOUSE", "In-house embedding model"
GEMINI_EMBEDDING_001 = "GEMINI_EMBEDDING_001", "Gemini - embedding-001"
GEMINI_TEXT_EMBEDDING_004 = "GEMINI_TEXT_EMBEDDING_004", "Gemini - text-embedding-004"
OPENAI_TEXT_EMBEDDING_3_SMALL = "OPENAI_TEXT_EMBEDDING_3_SMALL", "OpenAI - text-embedding-3-small"
OPENAI_TEXT_EMBEDDING_3_LARGE = "OPENAI_TEXT_EMBEDDING_3_LARGE", "OpenAI - text-embedding-3-large"
OPENAI_TEXT_EMBEDDING_ADA_002 = "OPENAI_TEXT_EMBEDDING_ADA_002", "OpenAI - text-embedding-ada-002"
class Language(models.TextChoices):
ENGLISH = "ENGLISH", "English"
TURKISH = "TURKISH", "Turkish"
# Language code mapping
LANGUAGE_CODES = {
'ENGLISH': 'en',
'TURKISH': 'tr',
}
# Get language code helper method
def get_language_code(self):
"""Returns the ISO language code for the selected language"""
return self.LANGUAGE_CODES.get(self.language, 'en')
slug = models.CharField(max_length=50, unique=True)
name = models.CharField(max_length=50, blank=True, null=True)
maintainers = models.ManyToManyField(User, blank=True, related_name='maintained_guru_types')
stackoverflow_tag = models.CharField(max_length=100, blank=True, null=True)
github_repos = models.JSONField(default=list, blank=True)
github_details = models.JSONField(default=dict, blank=True, null=False)
github_details_updated_date = models.DateTimeField(null=True, blank=True)
colors = models.JSONField(default=dict, blank=True, null=False)
icon_url = models.CharField(max_length=2000, default="", blank=True, null=True)
ogimage_url = models.URLField(max_length=2000, default="", blank=True, null=True) # question
ogimage_base_url = models.URLField(max_length=2000, default="", blank=True, null=True)
stackoverflow_source = models.BooleanField(default=True) # Set this to false for custom guru types
active = models.BooleanField(default=False)
intro_text = models.TextField(default='', blank=True, null=True)
custom = models.BooleanField(default=True)
milvus_collection_name = models.CharField(max_length=100, blank=True, null=True)
typesense_collection_name = models.CharField(max_length=100, blank=True, null=True)
domain_knowledge = models.TextField(default='', blank=True, null=True)
custom_instruction_prompt = models.TextField(default='', blank=True, null=True)
custom_follow_up_prompt = models.TextField(default='', blank=True, null=True)
has_sitemap_added_questions = models.BooleanField(default=False)
index_repo = models.BooleanField(default=True)
# GitHub repository limits
github_repo_count_limit = models.IntegerField(default=1)
github_file_count_limit_per_repo_soft = models.IntegerField(default=1000) # Warning threshold
github_file_count_limit_per_repo_hard = models.IntegerField(default=1500) # Absolute maximum
github_repo_size_limit_mb = models.IntegerField(default=100)
# Data source limits
website_count_limit = models.IntegerField(default=1500)
youtube_count_limit = models.IntegerField(default=100)
pdf_size_limit_mb = models.IntegerField(default=100)
jira_count_limit = models.IntegerField(default=100)
zendesk_count_limit = models.IntegerField(default=100)
confluence_count_limit = models.IntegerField(default=100)
text_embedding_model = models.CharField(
max_length=100,
choices=EmbeddingModel.choices,
default=None, # Will be set in save()
null=True,
blank=True
)
code_embedding_model = models.CharField(
max_length=100,
choices=EmbeddingModel.choices,
default=None, # Will be set in save()
null=True,
blank=True
)
send_notification = models.BooleanField(default=False)
private = models.BooleanField(default=False)
language = models.CharField(
max_length=100,
choices=Language.choices,
default=Language.ENGLISH
)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.slug
def save(self, *args, **kwargs):
from core.utils import validate_slug
from core.guru_types import generate_milvus_collection_name, generate_typesense_collection_name
# Set default embedding models if not set
if not self.text_embedding_model:
self.text_embedding_model = Settings.get_default_embedding_model()
if not self.code_embedding_model:
self.code_embedding_model = Settings.get_default_embedding_model()
if 'domain_knowledge' not in self.prompt_map:
raise ValidationError({'msg': 'Domain knowledge field is required'})
domain_knowledge = self.prompt_map['domain_knowledge']
if len(domain_knowledge) > 200:
raise ValidationError({'msg': f'Domain knowledge must be 200 characters or less. Got: {domain_knowledge}'})
if not self.id: # If it is a new object
if not self.slug:
self.slug = validate_slug(self.name)
self.milvus_collection_name = generate_milvus_collection_name(self.slug)
self.typesense_collection_name = generate_typesense_collection_name(self.slug)
if ' ' in self.slug:
raise ValidationError({'msg': 'Guru type name must not contain spaces'})
if self.slug == '':
raise ValidationError({'msg': 'Guru type name cannot be empty'})
unique_github_repos = set(self.github_repos)
if settings.ENV != 'selfhosted' and len(unique_github_repos) > self.github_repo_count_limit:
raise ValidationError({'msg': f'You have reached the maximum number ({self.github_repo_count_limit}) of GitHub repositories for this guru type.'})
if settings.ENV == 'selfhosted':
if self.text_embedding_model == GuruType.EmbeddingModel.IN_HOUSE:
raise ValidationError({'msg': 'In-house embedding model is not allowed in selfhosted environment.'})
if self.code_embedding_model == GuruType.EmbeddingModel.IN_HOUSE:
raise ValidationError({'msg': 'In-house embedding model is not allowed in selfhosted environment.'})
self.github_repos = list(unique_github_repos)
super().save(*args, **kwargs)
def generate_widget_id(self, domain_url):
"""
Generates a new widget ID for this guru type and domain.
If an active key exists for the domain, raises ValidationError.
Validates that the domain URL is properly formatted.
Supports the following domain URL formats:
- Standard URLs: 'https://example.com', 'http://subdomain.example.com'
- Wildcard patterns:
- '*': Match any domain (universal wildcard)
- 'http://localhost:*': Match localhost with any port
- 'https://*.example.com': Match any subdomain of example.com
Examples:
- '*' → Allow from any domain
- 'http://localhost:*' → Allow from localhost with any port (localhost:3000, localhost:8080, etc.)
- 'https://*.example.com' → Allow from any subdomain of example.com (app.example.com, api.example.com, etc.)
- 'https://example.com' → Allow only from exact domain example.com
"""
if domain_url:
# Normalize domain_url
domain_url = domain_url.rstrip('/')
# Check if this is a wildcard pattern
is_wildcard = '*' in domain_url
# For non-wildcard URLs, perform standard validation
if not is_wildcard:
# Standard URL validation
url_validator = URLValidator()
try:
url_validator(domain_url)
except ValidationError:
raise ValidationError({'msg': 'Invalid URL format'})
# Additional domain validation
parsed_url = urlparse(domain_url)
if not parsed_url.netloc:
raise ValidationError({'msg': 'Invalid domain URL'})
# Ensure URL has valid scheme
if parsed_url.scheme not in ['http', 'https']:
raise ValidationError({'msg': 'URL must start with http:// or https://'})
# Check for existing widget for this domain/guru type combination
existing_key = WidgetId.objects.filter(
guru_type=self,
domain_url=domain_url,
).first()
if existing_key:
raise ValidationError({'msg': 'This domain url already has a widget ID'})
# Generate new key
key = secrets.token_urlsafe(32)
WidgetId.objects.create(
guru_type=self,
key=key,
domain_url=domain_url,
is_wildcard=is_wildcard if domain_url else False
)
return key
@property
def prompt_map(self):
return {
"guru_type": self.name,
"domain_knowledge": self.domain_knowledge,
"custom_instruction_prompt": self.custom_instruction_prompt,
"custom_follow_up_prompt": self.custom_follow_up_prompt,
"language": self.language
}
@property
def ready(self):
# Check if all its data sources are processed
non_processed_count = DataSource.objects.filter(guru_type=self, status=DataSource.Status.NOT_PROCESSED).count()
non_written_count = DataSource.objects.filter(
guru_type=self, status=DataSource.Status.SUCCESS, in_milvus=False).count()
return non_processed_count == 0 and non_written_count == 0
def check_datasource_limits(self, user, file=None, website_urls_count=0, youtube_urls_count=0, github_urls_count=0, jira_urls_count=0, zendesk_urls_count=0, confluence_urls_count=0):
"""
Checks if adding a new datasource would exceed the limits for this guru type.
Returns (bool, str) tuple - (is_allowed, error_message)
"""
if settings.ENV != 'selfhosted':
# Check if user is maintainer
if not self.maintainers.filter(id=user.id).exists():
if user.is_admin:
# If user is admin, only check the limits
pass
else:
return False, "You don't have permission to add data sources to this guru type"
if settings.ENV == 'selfhosted':
# Selfhosted users bypass all limits
return True, None
# Get current counts
website_count = DataSource.objects.filter(
guru_type=self,
type=DataSource.Type.WEBSITE
).count()
youtube_count = DataSource.objects.filter(
guru_type=self,
type=DataSource.Type.YOUTUBE
).count()
github_count = DataSource.objects.filter(
guru_type=self,
type=DataSource.Type.GITHUB_REPO
).count()
jira_count = DataSource.objects.filter(
guru_type=self,
type=DataSource.Type.JIRA
).count()
zendesk_count = DataSource.objects.filter(
guru_type=self,
type=DataSource.Type.ZENDESK
).count()
confluence_count = DataSource.objects.filter(
guru_type=self,
type=DataSource.Type.CONFLUENCE
).count()
# Get total PDF size in MB
pdf_sources = DataSource.objects.filter(
guru_type=self,
type=DataSource.Type.PDF
)
total_pdf_mb = 0
for source in pdf_sources:
if source.file:
total_pdf_mb += source.file.size / (1024 * 1024) # Convert bytes to MB
# Check website limit
if (website_count + website_urls_count) > self.website_count_limit:
return False, f"Website limit ({self.website_count_limit}) reached"
# Check YouTube limit
if (youtube_count + youtube_urls_count) > self.youtube_count_limit:
return False, f"YouTube video limit ({self.youtube_count_limit}) reached"
# Check GitHub repo limit
if (github_count + github_urls_count) > self.github_repo_count_limit:
return False, f"GitHub repository limit ({self.github_repo_count_limit}) reached"
# Check Jira issue limit
if (jira_count + jira_urls_count) > self.jira_count_limit:
return False, f"Jira issue limit ({self.jira_count_limit}) reached"
# Check Zendesk ticket limit
if (zendesk_count + zendesk_urls_count) > self.zendesk_count_limit:
return False, f"Zendesk ticket limit ({self.zendesk_count_limit}) reached"
# Check Confluence page limit
if (confluence_count + confluence_urls_count) > self.confluence_count_limit:
return False, f"Confluence page limit ({self.confluence_count_limit}) reached"
# Check PDF size limit if file provided
if file:
file_size_mb = file.size / (1024 * 1024)
if total_pdf_mb + file_size_mb > self.pdf_size_limit_mb:
return False, f"Total PDF size limit ({self.pdf_size_limit_mb}MB) would be exceeded"
return True, None
class LLMEval(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='llm_evals')
model = models.TextField()
version = models.IntegerField(default=1)
# relevance = models.FloatField(default=0, blank=True, null=True)
# relevance_cot = models.TextField(default='', blank=True, null=True)
# sentiment = models.FloatField(default=0, blank=True, null=True)
# sentiment_cot = models.TextField(default='', blank=True, null=True)
# conciseness = models.FloatField(default=0, blank=True, null=True)
# conciseness_cot = models.TextField(default='', blank=True, null=True)
# correctness = models.FloatField(default=0, blank=True, null=True)
# correctness_cot = models.TextField(default='', blank=True, null=True)
# coherence = models.FloatField(default=0, blank=True, null=True)
# coherence_cot = models.TextField(default='', blank=True, null=True)
context_relevance = models.FloatField(default=0, blank=True, null=True)
context_relevance_cot = models.TextField(default='', blank=True, null=True)
context_relevance_prompt = models.TextField(default='', blank=True, null=True)
context_relevance_user_prompt = models.TextField(default='', blank=True, null=True)
groundedness = models.FloatField(default=0, blank=True, null=True)
groundedness_cot = models.TextField(default='', blank=True, null=True)
groundedness_prompt = models.TextField(default='', blank=True, null=True)
answer_relevance = models.FloatField(default=0, blank=True, null=True)
answer_relevance_cot = models.TextField(default='', blank=True, null=True)
answer_relevance_prompt = models.TextField(default='', blank=True, null=True)
answer = models.TextField(default='', blank=True, null=True)
reranked_scores = models.JSONField(default=list, blank=True, null=False)
cost_dollars = models.FloatField(default=0, blank=True, null=True)
prompt_tokens = models.PositiveIntegerField(default=0, blank=True, null=True)
completion_tokens = models.PositiveIntegerField(default=0, blank=True, null=True)
cached_prompt_tokens = models.PositiveIntegerField(
default=0, blank=True, null=True) # Already included in prompt_tokens
prompt = models.TextField(default='', blank=True, null=True)
contexts = models.JSONField(default=list, blank=True, null=False)
settings = models.JSONField(default=dict, blank=True, null=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
processed_ctx_relevances = models.JSONField(default=dict, blank=True, null=False)
def __str__(self):
return f"{self.id}"
@property
def total_tokens(self):
return self.prompt_tokens + self.completion_tokens
class DataSource(models.Model):
class Type(models.TextChoices):
PDF = "PDF"
WEBSITE = "WEBSITE"
YOUTUBE = "YOUTUBE"
GITHUB_REPO = "GITHUB_REPO"
JIRA = "JIRA"
ZENDESK = "ZENDESK"
CONFLUENCE = "CONFLUENCE"
class Status(models.TextChoices):
NOT_PROCESSED = "NOT_PROCESSED"
SUCCESS = "SUCCESS"
FAIL = "FAIL"
type = models.CharField(
max_length=50,
choices=[(tag.value, tag.value) for tag in Type],
default=Type.PDF.value,
)
url = models.URLField(max_length=2000, null=True, blank=True) # If website or youtube
guru_type = models.ForeignKey(
GuruType, on_delete=models.CASCADE, null=True, blank=True
)
title = models.TextField(null=True, blank=True)
file = models.FileField(
upload_to=get_datasource_upload_path,
blank=True,
null=True
)
content = models.TextField(null=True, blank=True)
in_milvus = models.BooleanField(default=False)
doc_ids = models.JSONField(
default=list, blank=True, null=True
) # If written to milvus
status = models.CharField(
max_length=50,
choices=[(tag.value, tag.value) for tag in Status],
default=Status.NOT_PROCESSED.value,
)
error = models.TextField(default='', blank=True, null=False)
user_error = models.TextField(default='', blank=True, null=False)
content_rewritten = models.BooleanField(default=False)
original_content = models.TextField(null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
initial_summarizations_created = models.BooleanField(default=False)
final_summarization_created = models.BooleanField(default=False)
default_branch = models.CharField(max_length=100, null=True, blank=True) # Only used for Github Repos
private = models.BooleanField(default=False)
last_reindex_date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
reindex_count = models.IntegerField(default=0)
scrape_tool = models.CharField(max_length=100, null=True, blank=True)
last_successful_index_date = models.DateTimeField(null=True, blank=True)
github_glob_include = models.BooleanField(default=True)
github_glob_pattern = models.CharField(max_length=100, null=True, blank=True)
class Meta:
unique_together = ["url", "guru_type"]
def __str__(self):
return f"{self.id} - {self.title}"
def get_file_path(self):
# Only used once while writing, after that, it is written to url
guru_type = self.guru_type.slug.lower()
file_name = os.path.basename(self.file.name)
name, ext = os.path.splitext(file_name)
random_key = uuid.uuid4().hex[:30]
if self.guru_type.custom:
return f'./{settings.ENV}/custom_gurus/{guru_type}/{name}-{random_key}{ext}'
return f'./{settings.ENV}/default_gurus/{guru_type}/{name}-{random_key}{ext}'
def get_file_path_local(self):
return os.path.join(settings.MEDIA_ROOT, 'data_sources', self.guru_type.slug, self.file.name)
def get_url_prefix(self):
return f'https://storage.googleapis.com/{settings.GS_DATA_SOURCES_BUCKET_NAME}'
def get_metadata(self):
if self.type == DataSource.Type.PDF:
return {
'title': self.title,
}
return {
'link': self.url,
'title': self.title,
}
def save(self, *args, **kwargs):
# If it is already created
if self.id:
super().save(*args, **kwargs)
return
# Check for existence. Return if it exists
if self.type == DataSource.Type.PDF:
self.title = self.file.name.split('/')[-1]
existing_data_source = DataSource.objects.filter(
type=self.type,
guru_type=self.guru_type,
title=self.title).first()
else:
existing_data_source = DataSource.objects.filter(
type=self.type,
guru_type=self.guru_type,
url=self.url).first()
if existing_data_source:
raise DataSourceExists({'id': existing_data_source.id, 'title': existing_data_source.title})
if self.type == DataSource.Type.PDF:
if self.file:
if settings.STORAGE_TYPE == 'gcloud':
from core.gcp import DATA_SOURCES_GCP
expected_path = self.get_file_path()
path, success = DATA_SOURCES_GCP.upload_file(self.file, expected_path)
if not success:
raise Exception("Failed to upload file")
self.url = f'{self.get_url_prefix()}/{expected_path.lstrip("./")}'
else:
self.url = self.get_file_path_local()
else:
raise Exception("File is required")
else:
# Check if url format is valid
if not self.url.startswith(('http://', 'https://')):
raise ValidationError({'msg': 'Invalid URL format'})
if self.type == DataSource.Type.GITHUB_REPO:
if settings.ENV != 'selfhosted' and DataSource.objects.filter(type=self.type, guru_type=self.guru_type).count() > self.guru_type.github_repo_count_limit:
raise ValidationError({'msg': f"You have reached the maximum number ({self.guru_type.github_repo_count_limit}) of GitHub repositories for this guru type."})
super().save(*args, **kwargs)
def write_to_milvus(self, overridden_model=None):
# Model override is added to reinsert code context after changing the embedding model
from core.utils import embed_texts_with_model, split_text, map_extension_to_language, split_code, get_embedding_model_config, get_default_settings
from core.milvus_utils import insert_vectors
from django.conf import settings
if self.in_milvus:
return
if overridden_model:
model = overridden_model
else:
if self.type == DataSource.Type.GITHUB_REPO:
model = self.guru_type.code_embedding_model
else:
model = self.guru_type.text_embedding_model
if self.type == DataSource.Type.GITHUB_REPO:
collection_name, dimension = get_embedding_model_config(model)
else:
_, dimension = get_embedding_model_config(model)
collection_name = self.guru_type.milvus_collection_name
default_settings = get_default_settings()
split_size = default_settings.split_size
split_min_length = default_settings.split_min_length
split_overlap = default_settings.split_overlap
if self.type == DataSource.Type.GITHUB_REPO:
github_files = GithubFile.objects.filter(data_source=self, in_milvus=False)
logger.info(f"Writing {len(github_files)} GitHub files to Milvus. Repository: {self.url}")
doc_ids = self.doc_ids
# Process files in batches
batch_size = settings.GITHUB_FILE_BATCH_SIZE
for i in range(0, len(github_files), batch_size):
batch = github_files[i:i + batch_size]
logger.info(f"Processing batch {i//batch_size + 1} of {(len(github_files) + batch_size - 1)//batch_size}. Repository: {self.url}")
# Prepare all texts and metadata for the batch
all_texts = []
all_metadata = []
file_text_counts = [] # Keep track of how many text chunks each file has
for file in batch:
# Split the content into chunks
extension = file.path.split('/')[-1].split('.')[-1]
language = map_extension_to_language(extension)
if language:
splitted = split_code(
file.content,
split_size,
split_min_length,
split_overlap,
language
)
else:
splitted = split_text(
file.content,
split_size,
split_min_length,
split_overlap,
separators=["\n\n", "\n", ".", "?", "!", " ", ""]
)
metadata = {
"type": file.data_source.type,
"repo_link": file.repository_link,
"link": file.link, # Now we can safely use file.link as it's been updated
"repo_title": file.repo_title,
"title": file.title,
"file_path": file.path
}
# Add texts and metadata
all_texts.extend(splitted)
all_metadata.extend([metadata] * len(splitted))
file_text_counts.append(len(splitted)) # Store count of chunks for this file
# Batch embed all texts using the configured model
try:
embeddings = embed_texts_with_model(all_texts, model)
except Exception as e:
logger.error(f"Error embedding texts in batch: {traceback.format_exc()}")
continue
if embeddings is None:
logger.error("Embeddings is None for batch")
continue
# Prepare documents for Milvus
docs = []
split_num = 0
guru_slug = self.guru_type.slug
for i, (text, metadata, embedding) in enumerate(zip(all_texts, all_metadata, embeddings)):
split_num += 1
docs.append({
"metadata": {**metadata, "split_num": split_num},
"text": text,
"vector": embedding,
"guru_slug": guru_slug,
})
# Write batch to Milvus with the correct collection name and dimension
try:
batch_ids = list(insert_vectors(collection_name, docs, code=True, dimension=dimension))
if len(batch_ids) != len(docs):
logger.error(f"Error writing batch to Milvus: {len(batch_ids)} != {len(docs)}")
continue
# Distribute IDs back to files based on chunk counts and prepare for bulk update
start_idx = 0
files_to_update = []
for file, chunk_count in zip(batch, file_text_counts):
end_idx = start_idx + chunk_count
file_ids = batch_ids[start_idx:end_idx]
file.doc_ids = file_ids
file.in_milvus = True
files_to_update.append(file)
start_idx = end_idx
doc_ids.extend(file_ids)
# Bulk update all files in this batch
GithubFile.objects.bulk_update(files_to_update, ['doc_ids', 'in_milvus'])
except Exception as e:
logger.error(f"Error writing batch to Milvus: {str(e)}")
continue
self.doc_ids = doc_ids
else:
splitted = split_text(
self.content,
split_size,
split_min_length,
split_overlap,
separators=["\n\n", "\n", ".", "?", "!", " ", ""]
)
type = self.type
link = self.url
title = self.title
# Embed the texts using the configured model
try:
embeddings = embed_texts_with_model(splitted, model)
except Exception as e:
logger.error(f"Error embedding texts: {traceback.format_exc()}")
self.status = DataSource.Status.FAIL
self.save()
raise e
if embeddings is None:
logger.error(f"Embeddings is None. {traceback.format_exc()}")
raise Exception("Embeddings is None")
# Prepare the metadata
docs = []
split_num = 0
for i, split in enumerate(splitted):
split_num += 1
docs.append(
{
"metadata": {
"type": type,
"link": link,
"split_num": split_num,
"title": title,
},
"text": split,
"vector": embeddings[i],
}
)
# Write to milvus with the correct collection name and dimension
ids = insert_vectors(collection_name, docs, dimension=dimension)
# Update the model
if self.doc_ids is None:
self.doc_ids = []
self.doc_ids += ids
self.in_milvus = True
self.save()
def delete_from_milvus(self, overridden_model=None):
from core.milvus_utils import delete_vectors
from core.utils import get_embedding_model_config
if not self.in_milvus:
return
if overridden_model:
model = overridden_model
else:
if self.type == DataSource.Type.GITHUB_REPO:
model = self.guru_type.code_embedding_model
else:
model = self.guru_type.text_embedding_model
ids = self.doc_ids
if self.type == DataSource.Type.GITHUB_REPO:
collection_name, dimension = get_embedding_model_config(model, sync=False)
else: