-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathmodels.py
More file actions
1670 lines (1435 loc) · 66.5 KB
/
models.py
File metadata and controls
1670 lines (1435 loc) · 66.5 KB
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 __future__ import annotations
import base64
import json
import logging
import secrets
import uuid
from datetime import UTC, datetime
from functools import cached_property
from typing import Self, cast
from uuid import uuid4
import markdown
from django.conf import settings
from django.contrib.postgres.fields import ArrayField
from django.core.exceptions import ValidationError
from django.core.validators import MaxValueValidator, MinValueValidator, validate_email
from django.db import models, transaction
from django.db.models import (
BooleanField,
Case,
Count,
F,
OuterRef,
Prefetch,
Q,
Subquery,
When,
functions,
)
from django.template.loader import get_template
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import gettext
from django_cryptography.fields import encrypt
from field_audit import audit_fields
from field_audit.models import AuditAction, AuditingManager
from apps.annotations.models import CustomTaggedItem
from apps.chat.models import Chat, ChatMessage, ChatMessageType
from apps.experiments import model_audit_fields
from apps.experiments.versioning import VersionDetails, VersionField, VersionsMixin, VersionsObjectManagerMixin, differs
from apps.generics.chips import Chip
from apps.service_providers.tracing import TraceInfo, TracingService
from apps.service_providers.tracing.base import SpanNotificationConfig
from apps.teams.models import BaseTeamModel, Team
from apps.teams.utils import current_team, get_slug_for_team
from apps.trace.models import Trace, TraceStatus
from apps.utils.fields import SanitizedJSONField
from apps.utils.models import BaseModel
from apps.utils.time import seconds_to_human
from apps.web.dynamic_filters.datastructures import ColumnFilterData, FilterParams
from apps.web.meta import absolute_url
log = logging.getLogger("ocs.experiments")
class VersionFieldDisplayFormatters:
"""A collection of formatters that are used for displaying version fields"""
@staticmethod
def format_tools(tools: set) -> str:
return ", ".join([AgentTools(tool).label for tool in tools])
@staticmethod
def yes_no(value: bool) -> str:
return "Yes" if value else "No"
@staticmethod
def format_array_field(arr: list) -> str:
return ", ".join([entry for entry in arr])
@staticmethod
def format_trigger(triggers) -> str:
if isinstance(triggers, VersionField):
triggers = triggers.raw_value
if not isinstance(triggers, list):
triggers = [triggers]
result_strings = []
for field in triggers:
if isinstance(field, VersionField):
field = field.raw_value
static_trigger = getattr(field, "raw_value", field)
string = "If"
if static_trigger.trigger_type == "TimeoutTrigger":
seconds = seconds_to_human(static_trigger.delay)
string = f"{string} no response for {seconds}"
else:
string = f"{string} {static_trigger.get_type_display().lower()}"
trigger_action = static_trigger.action.get_action_type_display().lower()
result_strings.append(f"{string} then {trigger_action}")
return "; ".join(result_strings) if result_strings else "No triggers found"
@staticmethod
def format_pipeline(pipeline) -> str:
if not pipeline:
return ""
name = str(pipeline)
template = get_template("generic/chip.html")
url = pipeline.get_absolute_url()
return template.render({"chip": Chip(label=name, url=url)})
@staticmethod
def format_builtin_tools(tools: set) -> str:
"""code_interpreter, file_search -> Code Interpreter, File Search"""
return ", ".join([tool.replace("_", " ").capitalize() for tool in tools])
class PromptObjectManager(AuditingManager):
pass
class ExperimentObjectManager(VersionsObjectManagerMixin, AuditingManager):
def get_default_or_working(self, family_member: Experiment):
"""
Returns the default version of the family of experiments relating to `family_member` or if there is no default,
the working experiment.
"""
if family_member.is_default_version:
return family_member
working_version_id = family_member.working_version_id or family_member.id
experiment = self.filter(
working_version_id=working_version_id, is_default_version=True, team_id=family_member.team_id
).first()
return experiment if experiment else family_member
def get_version_names(self, team, working_version=None) -> list[str]:
qs = self.get_queryset().filter(team=team)
if working_version:
qs = qs.filter(working_version=working_version)
nums = qs.order_by("-version_number").values_list("version_number", flat=True).distinct()
return [f"v{working_version.version_number}"] + [f"v{n}" for n in nums]
# team-wide distinct version numbers (stable, sorted)
nums = qs.order_by("-version_number").values_list("version_number", flat=True).distinct()
return [f"v{n}" for n in nums]
class SourceMaterialObjectManager(VersionsObjectManagerMixin, AuditingManager):
pass
class ConsentFormObjectManager(VersionsObjectManagerMixin, AuditingManager):
pass
class SyntheticVoiceObjectManager(AuditingManager):
pass
class PromptBuilderHistory(BaseTeamModel):
"""
History entries for the prompt builder
"""
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
history = SanitizedJSONField()
def __str__(self) -> str:
return str(self.history)
@audit_fields(*model_audit_fields.SOURCE_MATERIAL_FIELDS, audit_special_queryset_writes=True)
class SourceMaterial(BaseTeamModel, VersionsMixin):
"""
Some Source Material on a particular topic.
"""
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
topic = models.CharField(max_length=50)
description = models.TextField(null=True, default="", verbose_name="A longer description of the source material.") # noqa DJ001
material = models.TextField()
working_version = models.ForeignKey(
"self",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="versions",
)
is_archived = models.BooleanField(default=False)
objects = SourceMaterialObjectManager()
class Meta:
ordering = ["topic"]
def __str__(self):
return self.topic
def get_absolute_url(self):
return reverse("experiments:source_material_edit", args=[get_slug_for_team(self.team_id), self.id])
@transaction.atomic()
def archive(self):
super().archive()
self.experiment_set.update(source_material=None, audit_action=AuditAction.AUDIT)
def _get_version_details(self) -> VersionDetails:
return VersionDetails(
instance=self,
fields=[
VersionField(name="topic", raw_value=self.topic),
VersionField(name="description", raw_value=self.description),
VersionField(name="material", raw_value=self.material),
],
)
class SurveyObjectManager(VersionsObjectManagerMixin, models.Manager):
def get_queryset(self) -> models.QuerySet:
return (
super()
.get_queryset()
.annotate(
is_version=Case(
When(working_version_id__isnull=False, then=True),
When(working_version_id__isnull=True, then=False),
output_field=BooleanField(),
)
)
)
class Survey(BaseTeamModel, VersionsMixin):
"""
A survey.
"""
name = models.CharField(max_length=128)
url = models.URLField(max_length=500)
confirmation_text = models.TextField(
null=False,
default=(
"Please complete the following survey by clicking on the survey link."
" When you have finished, respond with '1' to let us know that you've completed it."
" Survey link: {survey_link}"
),
)
working_version = models.ForeignKey(
"self",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="versions",
)
is_archived = models.BooleanField(default=False)
objects = SurveyObjectManager()
class Meta:
ordering = ["name"]
def __str__(self):
return self.name
def get_link(self, participant, experiment_session):
participant_public_id = participant.public_id if participant else "[anonymous]"
return self.url.format(
participant_id=participant_public_id,
session_id=experiment_session.external_id,
experiment_id=experiment_session.experiment.public_id,
)
def get_absolute_url(self):
return reverse("experiments:survey_edit", args=[get_slug_for_team(self.team_id), self.id])
@transaction.atomic()
def archive(self):
super().archive()
self.experiments_pre.update(pre_survey=None, audit_action=AuditAction.AUDIT)
self.experiments_post.update(post_survey=None, audit_action=AuditAction.AUDIT)
def _get_version_details(self) -> VersionDetails:
return VersionDetails(
instance=self,
fields=[
VersionField(name="name", raw_value=self.name),
VersionField(name="url", raw_value=self.url),
VersionField(name="confirmation_text", raw_value=self.confirmation_text),
],
)
@audit_fields(*model_audit_fields.CONSENT_FORM_FIELDS, audit_special_queryset_writes=True)
class ConsentForm(BaseTeamModel, VersionsMixin):
"""
Custom markdown consent form to be used by experiments.
"""
objects = ConsentFormObjectManager()
name = models.CharField(max_length=128)
consent_text = models.TextField(help_text="Custom markdown text")
capture_identifier = models.BooleanField(default=True)
identifier_label = models.CharField(max_length=200, default="Email Address")
identifier_type = models.CharField(choices=(("email", "Email"), ("text", "Text")), default="email", max_length=16)
is_default = models.BooleanField(default=False, editable=False)
confirmation_text = models.CharField(
null=False,
default="Respond with '1' if you agree",
help_text=("Use this text to tell the user to respond with '1' in order to give their consent"),
)
working_version = models.ForeignKey(
"self",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="versions",
)
is_archived = models.BooleanField(default=False)
class Meta:
ordering = ["name"]
constraints = [
models.UniqueConstraint(
fields=["team_id", "is_default"],
name="unique_default_consent_form_per_team",
condition=Q(is_default=True),
),
]
@classmethod
def get_default(cls, team):
return cls.objects.working_versions_queryset().get(team=team, is_default=True)
def __str__(self):
return self.name
def get_rendered_content(self):
return markdown.markdown(self.consent_text)
def get_absolute_url(self):
return reverse("experiments:consent_edit", args=[get_slug_for_team(self.team_id), self.id])
@transaction.atomic()
def archive(self):
super().archive()
consent_form_id = ConsentForm.objects.filter(team=self.team, is_default=True).values("id")[:1]
self.experiments.update(consent_form_id=Subquery(consent_form_id), audit_action=AuditAction.AUDIT)
def create_new_version(self, save=True): # ty: ignore[invalid-method-override]
new_version = super().create_new_version(save=False)
new_version.is_default = False
new_version.save()
return new_version
def get_fields_to_exclude(self):
return super().get_fields_to_exclude() + ["is_default"]
def _get_version_details(self) -> VersionDetails:
return VersionDetails(
instance=self,
fields=[
VersionField(name="name", raw_value=self.name),
VersionField(name="consent_text", raw_value=self.consent_text),
VersionField(name="capture_identifier", raw_value=self.capture_identifier),
VersionField(name="identifier_label", raw_value=self.identifier_label),
VersionField(name="identifier_type", raw_value=self.identifier_type),
VersionField(name="confirmation_text", raw_value=self.confirmation_text),
],
)
@audit_fields(*model_audit_fields.SYNTHETIC_VOICE_FIELDS, audit_special_queryset_writes=True)
class SyntheticVoice(BaseModel):
"""
A synthetic voice as per the service documentation. This is used when synthesizing responses for an experiment
See AWS' docs for all available voices
https://docs.aws.amazon.com/polly/latest/dg/voicelist.html
"""
GENDERS = (
("male", "Male"),
("female", "Female"),
("male (child)", "Male (Child)"),
("female (child)", "Female (Child)"),
)
AWS = "AWS"
Azure = "Azure"
OpenAI = "OpenAI"
OpenAIVoiceEngine = "OpenAIVoiceEngine"
SERVICES = (
("AWS", AWS),
("Azure", Azure),
("OpenAI", OpenAI),
("OpenAIVoiceEngine", OpenAIVoiceEngine),
)
TEAM_SCOPED_SERVICES = [OpenAIVoiceEngine]
objects = SyntheticVoiceObjectManager()
name = models.CharField(
max_length=128, help_text="The name of the synthetic voice, as per the documentation of the service"
)
neural = models.BooleanField(default=False, help_text="Indicates whether this voice is a neural voice")
language = models.CharField(null=False, blank=False, max_length=64, help_text="The language this voice is for")
language_code = models.CharField(
null=False, blank=False, max_length=32, help_text="The language code this voice is for"
)
gender = models.CharField(
null=False, blank=True, choices=GENDERS, max_length=14, help_text="The gender of this voice"
)
service = models.CharField(
null=False, blank=False, choices=SERVICES, max_length=17, help_text="The service this voice is from"
)
voice_provider = models.ForeignKey(
"service_providers.VoiceProvider", verbose_name=gettext("Team"), on_delete=models.CASCADE, null=True
)
file = models.ForeignKey("files.File", null=True, on_delete=models.SET_NULL)
class Meta:
ordering = ["name"]
unique_together = ("name", "language_code", "language", "gender", "neural", "service", "voice_provider")
def get_gender(self):
# This is a bit of a hack to display the gender on the admin screen. Directly calling gender doesn't work
return self.gender
def __str__(self):
prefix = "*" if self.neural else ""
display_str = f"{prefix}{self.name}"
if self.gender:
display_str = f"{self.gender}: {display_str}"
if self.language:
display_str = f"{self.language}, {display_str}"
return display_str
@staticmethod
def get_for_team(team: Team, exclude_services=None) -> list[SyntheticVoice]:
"""Returns a queryset for this team comprising of all general synthetic voice records and those exclusive
to this team. Any services specified by `exclude_services` will be excluded from the final result"""
exclude_services = exclude_services or []
general_services = ~Q(service__in=SyntheticVoice.TEAM_SCOPED_SERVICES) & Q(voice_provider__isnull=True)
team_services = Q(voice_provider__team=team)
return SyntheticVoice.objects.filter(general_services | team_services, ~Q(service__in=exclude_services))
class VoiceResponseBehaviours(models.TextChoices):
ALWAYS = "always", gettext("Always")
RECIPROCAL = "reciprocal", gettext("Reciprocal")
NEVER = "never", gettext("Never")
class BuiltInTools(models.TextChoices):
WEB_SEARCH = "web-search", gettext("Web Search")
CODE_EXECUTION = "code-execution", gettext("Code Execution")
@classmethod
def get_provider_specific_tools(cls):
return {
"openai": [cls.WEB_SEARCH, cls.CODE_EXECUTION],
"anthropic": [cls.WEB_SEARCH],
# "google": [cls.WEB_SEARCH, cls.CODE_EXECUTION], commenting it for now until tools work for gemini
}
@classmethod
def choices_for_provider(cls, provider_type: str):
tools = cls.get_provider_specific_tools().get(provider_type.lower(), [])
return [(tool, cls(tool).label) for tool in tools]
@classmethod
def get_tool_configs_by_provider(cls):
return {
"anthropic": {
cls.WEB_SEARCH: [
{
"name": "allowed_domains",
"type": "expandable_text",
"label": "Allowed Domains",
"helpText": (
"Only search these domains (e.g. example.com or example.com/blog). "
"Separate entries with newlines."
),
},
{
"name": "blocked_domains",
"type": "expandable_text",
"label": "Blocked Domains",
"helpText": "Exclude these domains from search. Separate entries with newlines.",
},
],
}
}
class AgentTools(models.TextChoices):
RECURRING_REMINDER = "recurring-reminder", gettext("Recurring Reminder")
ONE_OFF_REMINDER = "one-off-reminder", gettext("One-off Reminder")
DELETE_REMINDER = "delete-reminder", gettext("Delete Reminder")
MOVE_SCHEDULED_MESSAGE_DATE = "move-scheduled-message-date", gettext("Move Reminder Date")
UPDATE_PARTICIPANT_DATA = "update-user-data", gettext("Update Participant Data")
APPEND_TO_PARTICIPANT_DATA = "append-to-participant-data", gettext("Append to Participant Data")
INCREMENT_COUNTER = "increment-counter", gettext("Increment Counter")
ATTACH_MEDIA = "attach-media", gettext("Attach Media")
END_SESSION = "end-session", gettext("End Session")
SEARCH_INDEX = "file-search", gettext("File Search")
SEARCH_INDEX_BY_ID = "file-search-by-index", gettext("File Search by index ID")
SET_SESSION_STATE = "set-session-state", gettext("Set Session State")
GET_SESSION_STATE = "get-session-state", gettext("Get Session State")
CALCULATOR = "calculator", gettext("Calculator")
@classmethod
def reminder_tools(cls) -> list[Self]:
return cast(
list[Self],
[cls.RECURRING_REMINDER, cls.ONE_OFF_REMINDER, cls.DELETE_REMINDER, cls.MOVE_SCHEDULED_MESSAGE_DATE],
)
@staticmethod
def user_tool_choices(include_end_session: bool = True) -> list[tuple]:
"""Returns the set of tools that a user should be able to attach to the bot"""
excluded_tools = [AgentTools.ATTACH_MEDIA, AgentTools.SEARCH_INDEX, AgentTools.SEARCH_INDEX_BY_ID]
if not include_end_session:
excluded_tools.append(AgentTools.END_SESSION)
return [(tool.value, tool.label) for tool in AgentTools if tool not in excluded_tools]
@audit_fields(*model_audit_fields.EXPERIMENT_FIELDS, audit_special_queryset_writes=True)
class Experiment(BaseTeamModel, VersionsMixin):
"""
An experiment combines a chatbot prompt, a safety prompt, and source material.
Each experiment can be run as a chatbot.
"""
# 0 is a reserved version number, meaning the default version
DEFAULT_VERSION_NUMBER = 0
TREND_CACHE_KEY_TEMPLATE = "experiment_trend_data_{experiment_id}"
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=128)
description = models.TextField(null=True, default="", verbose_name="A longer description of the experiment.") # noqa DJ001
pipeline = models.ForeignKey(
"pipelines.Pipeline",
on_delete=models.SET_NULL,
null=True,
blank=True,
verbose_name="Pipeline",
)
temperature = models.FloatField(default=0.7, validators=[MinValueValidator(0), MaxValueValidator(1)])
prompt_text = models.TextField(blank=True, default="")
input_formatter = models.TextField(
blank=True,
default="",
help_text="Use the {input} variable somewhere to modify the user input before it reaches the bot. "
"E.g. 'Safe or unsafe? {input}'",
)
source_material = models.ForeignKey(
SourceMaterial,
on_delete=models.SET_NULL,
null=True,
blank=True,
help_text="If provided, the source material will be given to every bot in the chain.",
)
seed_message = models.TextField(
blank=True,
default="",
help_text="If set, send this message to the bot when the session starts, "
"and prompt the user with the initial response.",
)
pre_survey = models.ForeignKey(
Survey, null=True, blank=True, related_name="experiments_pre", on_delete=models.SET_NULL
)
post_survey = models.ForeignKey(
Survey, null=True, blank=True, related_name="experiments_post", on_delete=models.SET_NULL
)
public_id = models.UUIDField(default=uuid.uuid4, unique=True)
consent_form = models.ForeignKey(
ConsentForm,
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="experiments",
help_text="Consent form content to show to users before participation in experiments.",
)
voice_provider = models.ForeignKey(
"service_providers.VoiceProvider",
on_delete=models.SET_NULL,
null=True,
blank=True,
verbose_name="Voice Provider",
)
synthetic_voice = models.ForeignKey(
SyntheticVoice, null=True, blank=True, related_name="experiments", on_delete=models.SET_NULL
)
conversational_consent_enabled = models.BooleanField(
default=False,
help_text=(
"If enabled, the consent form will be sent at the start of a conversation for external channels. Note: "
"This requires the experiment to have a seed message."
),
)
voice_response_behaviour = models.CharField(
max_length=10,
choices=VoiceResponseBehaviours.choices,
default=VoiceResponseBehaviours.RECIPROCAL,
help_text="This tells the bot when to reply with voice messages",
)
tools = ArrayField(models.CharField(max_length=128), default=list, blank=True)
echo_transcript = models.BooleanField(
default=True,
help_text=("Whether or not the bot should tell the user what it heard when the user sends voice messages"),
)
trace_provider = models.ForeignKey(
"service_providers.TraceProvider", on_delete=models.SET_NULL, null=True, blank=True
)
use_processor_bot_voice = models.BooleanField(default=False)
participant_allowlist = ArrayField(models.CharField(max_length=128), default=list, blank=True)
# Versioning fields
working_version = models.ForeignKey(
"self",
on_delete=models.CASCADE,
null=True,
blank=True,
related_name="versions",
)
version_number = models.PositiveIntegerField(default=1)
is_default_version = models.BooleanField(default=False)
is_archived = models.BooleanField(default=False)
version_description = models.TextField(
blank=True,
default="",
)
debug_mode_enabled = models.BooleanField(default=False)
citations_enabled = models.BooleanField(default=True)
create_version_task_id = models.CharField(max_length=128, blank=True)
file_uploads_enabled = models.BooleanField(
default=False,
help_text="Enables file attachments in the web chat interface.",
)
objects = ExperimentObjectManager()
class Meta:
ordering = ["name"]
permissions = [
("invite_participants", "Invite experiment participants"),
("download_chats", "Download experiment chats"),
]
constraints = [
models.UniqueConstraint(
fields=["is_default_version", "working_version"],
condition=Q(is_default_version=True),
name="unique_default_version_per_experiment",
),
models.UniqueConstraint(
fields=["version_number", "working_version"],
condition=Q(working_version__isnull=False),
name="unique_version_number_per_experiment",
),
]
indexes = [
models.Index(fields=["team", "is_archived", "working_version"]),
]
def __str__(self):
if self.working_version_id is None:
return self.name
return f"{self.name} ({self.version_display})"
def save(self, *args, **kwargs):
if self.working_version_id is None and self.is_default_version is True:
raise ValueError("A working experiment cannot be a default version")
self._clear_version_cache()
return super().save(*args, **kwargs)
def get_absolute_url(self):
return reverse("chatbots:single_chatbot_home", args=[get_slug_for_team(self.team_id), self.id])
def get_version(self, version: int) -> Experiment:
"""
Returns the version of this experiment family matching `version`. If `version` is 0, the default version is
returned.
"""
working_version = self.get_working_version()
if version == self.DEFAULT_VERSION_NUMBER:
return working_version.default_version
elif working_version.version_number == version:
return working_version
return working_version.versions.get(version_number=version)
@property
def event_triggers(self):
return [*self.timeout_triggers.all(), *self.static_triggers.all()]
@property
def version_display(self) -> str:
if self.is_working_version:
return ""
return f"v{self.version_number}"
@property
def trends_cache_key(self) -> str:
return self.TREND_CACHE_KEY_TEMPLATE.format(experiment_id=self.id)
@cached_property
def default_version(self) -> Experiment:
"""Returns the default experiment, or if there is none, the working experiment"""
return Experiment.objects.get_default_or_working(self)
def as_chip(self) -> Chip:
label = self.name
if self.is_archived:
label = f"{label} (archived)"
return Chip(label=label, url=self.get_absolute_url())
def as_experiment_chip(self) -> Chip:
"""Returns a link to the (legacy) experiment home page"""
return self.as_chip()
def as_chatbot_chip(self) -> Chip:
"""Returns a link to the chatbot home page"""
label = self.name
if self.is_archived:
label = f"{label} (archived)"
url = reverse("chatbots:single_chatbot_home", args=[get_slug_for_team(self.team_id), self.id])
return Chip(label=label, url=url)
def get_trend_data(self) -> tuple[list, list]:
"""
Get the error/success trends across all versions in this experiment's version family.
Returns two lists: successes and errors, each containing the count of successful and error traces
for each hour in the last 24 hours.
"""
to_date = timezone.now()
from_date = to_date - timezone.timedelta(hours=24)
# Get error counts for each hour bucket
error_trend = {}
success_trend = {}
trace_counts = (
Trace.objects.filter(
Q(experiment__working_version_id=self.id) | Q(experiment_id=self.id),
timestamp__gte=from_date,
timestamp__lte=to_date,
)
.annotate(hour_bucket=functions.TruncHour("timestamp", tzinfo=UTC))
.values("hour_bucket")
.annotate(
error_count=Count(Case(When(status=TraceStatus.ERROR, then=1))),
success_count=Count(Case(When(status=TraceStatus.SUCCESS, then=1))),
)
)
for trace in trace_counts:
error_trend[trace["hour_bucket"]] = trace["error_count"]
success_trend[trace["hour_bucket"]] = trace["success_count"]
# Create ordered list with zero-filled gaps
hour_buckets = []
current = from_date.replace(minute=0, second=0, microsecond=0)
end = to_date.replace(minute=0, second=0, microsecond=0)
while current <= end:
hour_buckets.append(current)
current += timezone.timedelta(hours=1)
successes = [success_trend.get(bucket, 0) for bucket in hour_buckets]
errors = [error_trend.get(bucket, 0) for bucket in hour_buckets]
return successes, errors
@classmethod
def get_bulk_trend_data(cls, experiment_ids: list[int]) -> dict[int, tuple[list, list]]:
"""
Get error/success trends for multiple experiments in a single DB query.
Returns a dict mapping each experiment ID to (successes, errors) lists,
each containing the hourly counts for the last 24 hours.
"""
if not experiment_ids:
return {}
to_date = timezone.now()
from_date = to_date - timezone.timedelta(hours=24)
# Build ordered hour buckets for the 24-hour window (shared across all experiments)
hour_buckets = []
current = from_date.replace(minute=0, second=0, microsecond=0)
end = to_date.replace(minute=0, second=0, microsecond=0)
while current <= end:
hour_buckets.append(current)
current += timezone.timedelta(hours=1)
# Single query: annotate each trace with its root experiment ID, then group
trace_counts = (
Trace.objects.filter(
Q(experiment__working_version_id__in=experiment_ids) | Q(experiment_id__in=experiment_ids),
timestamp__gte=from_date,
timestamp__lte=to_date,
)
.annotate(
root_experiment_id=Case(
When(experiment__working_version_id__isnull=False, then=F("experiment__working_version_id")),
default=F("experiment_id"),
),
hour_bucket=functions.TruncHour("timestamp", tzinfo=UTC),
)
.values("root_experiment_id", "hour_bucket")
.annotate(
error_count=Count(Case(When(status=TraceStatus.ERROR, then=1))),
success_count=Count(Case(When(status=TraceStatus.SUCCESS, then=1))),
)
)
# Organize results per experiment
per_experiment: dict[int, dict] = {}
for row in trace_counts:
eid = row["root_experiment_id"]
if eid not in per_experiment:
per_experiment[eid] = {"error": {}, "success": {}}
per_experiment[eid]["error"][row["hour_bucket"]] = row["error_count"]
per_experiment[eid]["success"][row["hour_bucket"]] = row["success_count"]
result = {}
for eid in experiment_ids:
exp_data = per_experiment.get(eid, {})
error_trend = exp_data.get("error", {})
success_trend = exp_data.get("success", {})
result[eid] = (
[success_trend.get(bucket, 0) for bucket in hour_buckets],
[error_trend.get(bucket, 0) for bucket in hour_buckets],
)
return result
def traces_url(self) -> str:
"""
Returns a URL to the traces page, filtered to show only traces for this experiment.
"""
experiment_filter = ColumnFilterData(column="experiment", operator="any of", value=json.dumps([self.id]))
versions_to_include = [f"v{n}" for n in range(1, self.version_number + 1)]
versions_filter = ColumnFilterData(column="versions", operator="any of", value=json.dumps(versions_to_include))
filter_params = FilterParams(column_filters=[experiment_filter, versions_filter])
return (
reverse("trace:home", kwargs={"team_slug": get_slug_for_team(self.team_id)})
+ "?"
+ filter_params.to_query()
)
@property
def trace_service(self):
if self.trace_provider:
return self.trace_provider.get_service()
def get_api_url(self):
if self.is_working_version:
return absolute_url(reverse("api:openai-chat-completions", args=[self.public_id]))
else:
working_version = self.working_version
return absolute_url(
reverse("api:openai-chat-completions-versioned", args=[working_version.public_id, self.version_number])
)
@property
def api_url(self):
return self.get_api_url()
@transaction.atomic()
def create_new_version( # ty: ignore[invalid-method-override]
self,
version_description: str | None = None,
make_default: bool = False,
is_copy: bool = False,
name: str | None = None,
):
"""
Creates a copy of an experiment as a new version of the original experiment.
"""
if make_default and is_copy:
raise ValueError("Cannot make a copy of an experiment the default version")
version_number = self.version_number
if not is_copy:
self.version_number = version_number + 1
self.save(update_fields=["version_number"])
# Fetch a new instance so the previous instance reference isn't simply being updated. I am not 100% sure
# why simply chaing the pk, id and _state.adding wasn't enough.
new_version = super().create_new_version(save=False, is_copy=is_copy)
new_version.version_description = version_description or ""
new_version.public_id = uuid4()
new_version.version_number = version_number
if not is_copy and (new_version.version_number == 1 or make_default):
new_version.is_default_version = True
if make_default:
self.versions.filter(is_default_version=True).update(
is_default_version=False, audit_action=AuditAction.AUDIT
)
if is_copy:
new_version.name = name if name is not None else new_version.name + "_copy"
new_version.version_number = 1
new_version.save()
if not is_copy:
# nothing to do for copy - just reference the same object in the new copy
self._copy_attr_to_new_version("source_material", new_version)
self._copy_attr_to_new_version("consent_form", new_version)
self._copy_attr_to_new_version("pre_survey", new_version)
self._copy_attr_to_new_version("post_survey", new_version)
self._copy_trigger_to_new_version(
trigger_queryset=self.static_triggers, new_version=new_version, is_copy=is_copy
)
self._copy_trigger_to_new_version(
trigger_queryset=self.timeout_triggers, new_version=new_version, is_copy=is_copy
)
self._copy_pipeline_to_new_version(new_version, is_copy)
return new_version
def get_fields_to_exclude(self):
return super().get_fields_to_exclude() + ["is_default_version", "public_id", "version_description"]
@transaction.atomic()
def archive(self):
"""
Archive the experiment and all versions in the case where this is the working version. The linked assistant and
pipeline for the working version should not be archived.
"""
super().archive()
self.static_triggers.update(is_archived=True)
if self.is_working_version:
self.delete_experiment_channels()
self.versions.update(is_archived=True, audit_action=AuditAction.AUDIT)
self.scheduled_messages.all().delete()
else:
if self.pipeline:
self.pipeline.archive()
def delete_experiment_channels(self):
from apps.channels.models import (
ExperimentChannel, # noqa: PLC0415 - circular: channels.models imports experiments.models
)
for channel in ExperimentChannel.objects.filter(experiment_id=self.id):
channel.soft_delete()
def _copy_pipeline_to_new_version(self, new_version, is_copy: bool = False):
if not self.pipeline:
return
new_pipeline = self.pipeline.create_new_version(is_copy=is_copy)
if is_copy:
new_pipeline.name = new_version.name
new_pipeline.save(update_fields=["name"])
new_version.pipeline = new_pipeline
new_version.save(update_fields=["pipeline"])
def _copy_attr_to_new_version(self, attr_name, new_version: Experiment):
"""Copies the attribute `attr_name` to the new version by creating a new version of the related record and
linking that to `new_version`
If the related field's version matches the current value, link it to the new experiment version; otherwise,
create a new version of it.
Q: Why?
A: When a new experiment version is created, the a new version is also created for the related field. If no
new changes was made to this new version by the time we want to create another version of the experiment, it
would make sense to add the already versioned related field to the versioned experiment instead of creating yet
another version of it.
"""
attr_instance = getattr(self, attr_name)
if not attr_instance:
return
latest_attr_version = attr_instance.latest_version
if latest_attr_version and not differs(
attr_instance, latest_attr_version, exclude_model_fields=latest_attr_version.get_fields_to_exclude()
):
setattr(new_version, attr_name, latest_attr_version)
else:
setattr(new_version, attr_name, attr_instance.create_new_version())
def _copy_trigger_to_new_version(self, trigger_queryset, new_version, is_copy: bool = False):
for trigger in trigger_queryset.all():
trigger.create_new_version(new_experiment=new_version, is_copy=is_copy)
@property
def is_public(self) -> bool:
"""
Whether or not a bot is public depends on the `participant_allowlist`. If it's empty, the bot is public.
"""
return len(self.participant_allowlist) == 0
def is_participant_allowed(self, identifier: str):
return identifier in self.participant_allowlist or self.team.members.filter(email=identifier).exists()
def _get_version_details(self) -> VersionDetails:
"""
Returns a `Version` instance representing the experiment version.
"""
fields = [
VersionField(group_name="General", name="name", raw_value=self.name),
VersionField(group_name="General", name="description", raw_value=self.description),
VersionField(group_name="General", name="seed_message", raw_value=self.seed_message),