-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathtest_prompt.py
More file actions
1549 lines (1216 loc) · 48.6 KB
/
test_prompt.py
File metadata and controls
1549 lines (1216 loc) · 48.6 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 time import sleep
from unittest.mock import Mock, patch
import openai
import pytest
from langfuse._client.client import Langfuse
from langfuse._utils.prompt_cache import (
DEFAULT_PROMPT_CACHE_TTL_SECONDS,
PromptCache,
PromptCacheItem,
)
from langfuse.api.resources.commons.errors.not_found_error import NotFoundError
from langfuse.api.resources.prompts import Prompt_Chat, Prompt_Text
from langfuse.model import ChatPromptClient, TextPromptClient
from tests.utils import create_uuid, get_api
def test_create_prompt():
langfuse = Langfuse()
prompt_name = create_uuid()
prompt_client = langfuse.create_prompt(
name=prompt_name,
prompt="test prompt",
labels=["production"],
commit_message="initial commit",
)
second_prompt_client = langfuse.get_prompt(prompt_name)
assert prompt_client.name == second_prompt_client.name
assert prompt_client.version == second_prompt_client.version
assert prompt_client.prompt == second_prompt_client.prompt
assert prompt_client.config == second_prompt_client.config
assert prompt_client.commit_message == second_prompt_client.commit_message
assert prompt_client.config == {}
def test_create_prompt_with_special_chars_in_name():
langfuse = Langfuse()
prompt_name = create_uuid() + "special chars !@#$%^&*() +"
prompt_client = langfuse.create_prompt(
name=prompt_name,
prompt="test prompt",
labels=["production"],
tags=["test"],
)
second_prompt_client = langfuse.get_prompt(prompt_name)
assert prompt_client.name == second_prompt_client.name
assert prompt_client.version == second_prompt_client.version
assert prompt_client.prompt == second_prompt_client.prompt
assert prompt_client.tags == second_prompt_client.tags
assert prompt_client.config == second_prompt_client.config
assert prompt_client.config == {}
def test_create_chat_prompt():
langfuse = Langfuse()
prompt_name = create_uuid()
prompt_client = langfuse.create_prompt(
name=prompt_name,
prompt=[
{"role": "system", "content": "test prompt 1 with {{animal}}"},
{"role": "user", "content": "test prompt 2 with {{occupation}}"},
],
labels=["production"],
tags=["test"],
type="chat",
commit_message="initial commit",
)
second_prompt_client = langfuse.get_prompt(prompt_name, type="chat")
# Create a test generation
completion = openai.OpenAI().chat.completions.create(
model="gpt-4",
messages=prompt_client.compile(animal="dog", occupation="doctor"),
)
assert len(completion.choices) > 0
assert prompt_client.name == second_prompt_client.name
assert prompt_client.version == second_prompt_client.version
assert prompt_client.prompt == second_prompt_client.prompt
assert prompt_client.config == second_prompt_client.config
assert prompt_client.labels == ["production", "latest"]
assert prompt_client.tags == second_prompt_client.tags
assert prompt_client.commit_message == second_prompt_client.commit_message
assert prompt_client.config == {}
def test_create_chat_prompt_with_placeholders():
langfuse = Langfuse()
prompt_name = create_uuid()
prompt_client = langfuse.create_prompt(
name=prompt_name,
prompt=[
{"role": "system", "content": "You are a {{role}} assistant"},
{"type": "placeholder", "name": "history"},
{"role": "user", "content": "Help me with {{task}}"},
],
labels=["production"],
tags=["test"],
type="chat",
commit_message="initial commit",
)
second_prompt_client = langfuse.get_prompt(prompt_name, type="chat")
messages = second_prompt_client.compile(
role="helpful",
task="coding",
history=[
{"role": "user", "content": "Example: {{task}}"},
{"role": "assistant", "content": "Example response"},
],
)
# Create a test generation using compiled messages
completion = openai.OpenAI().chat.completions.create(
model="gpt-4",
messages=messages,
)
assert len(completion.choices) > 0
assert len(messages) == 4
assert messages[0]["content"] == "You are a helpful assistant"
assert messages[1]["content"] == "Example: coding"
assert messages[2]["content"] == "Example response"
assert messages[3]["content"] == "Help me with coding"
assert prompt_client.name == second_prompt_client.name
assert prompt_client.version == second_prompt_client.version
assert prompt_client.config == second_prompt_client.config
assert prompt_client.labels == ["production", "latest"]
assert prompt_client.tags == second_prompt_client.tags
assert prompt_client.commit_message == second_prompt_client.commit_message
assert prompt_client.config == {}
def test_create_prompt_with_placeholders():
"""Test creating a prompt with placeholder messages."""
langfuse = Langfuse()
prompt_name = create_uuid()
prompt_client = langfuse.create_prompt(
name=prompt_name,
prompt=[
{"role": "system", "content": "System message"},
{"type": "placeholder", "name": "context"},
{"role": "user", "content": "User message"},
],
type="chat",
)
# Verify the full prompt structure with placeholders
assert len(prompt_client.prompt) == 3
# First message - system
assert prompt_client.prompt[0]["type"] == "message"
assert prompt_client.prompt[0]["role"] == "system"
assert prompt_client.prompt[0]["content"] == "System message"
# Placeholder
assert prompt_client.prompt[1]["type"] == "placeholder"
assert prompt_client.prompt[1]["name"] == "context"
# Third message - user
assert prompt_client.prompt[2]["type"] == "message"
assert prompt_client.prompt[2]["role"] == "user"
assert prompt_client.prompt[2]["content"] == "User message"
def test_get_prompt_with_placeholders():
"""Test retrieving a prompt with placeholders."""
langfuse = Langfuse()
prompt_name = create_uuid()
langfuse.create_prompt(
name=prompt_name,
prompt=[
{"role": "system", "content": "You are {{name}}"},
{"type": "placeholder", "name": "history"},
{"role": "user", "content": "{{question}}"},
],
type="chat",
)
prompt_client = langfuse.get_prompt(prompt_name, type="chat", version=1)
# Verify placeholder structure is preserved
assert len(prompt_client.prompt) == 3
# First message - system with variable
assert prompt_client.prompt[0]["type"] == "message"
assert prompt_client.prompt[0]["role"] == "system"
assert prompt_client.prompt[0]["content"] == "You are {{name}}"
# Placeholder
assert prompt_client.prompt[1]["type"] == "placeholder"
assert prompt_client.prompt[1]["name"] == "history"
# Third message - user with variable
assert prompt_client.prompt[2]["type"] == "message"
assert prompt_client.prompt[2]["role"] == "user"
assert prompt_client.prompt[2]["content"] == "{{question}}"
@pytest.mark.parametrize(
("variables", "placeholders", "expected_len", "expected_contents"),
[
# 0. Variables only, no placeholders. Unresolved placeholders kept in output
(
{"role": "helpful", "task": "coding"},
{},
3,
[
"You are a helpful assistant",
None,
"Help me with coding",
], # None = placeholder
),
# 1. No variables, no placeholders. Expect verbatim message+placeholder output
(
{},
{},
3,
["You are a {{role}} assistant", None, "Help me with {{task}}"],
), # None = placeholder
# 2. Placeholders only, empty variables. Expect output with placeholders filled in
(
{},
{
"examples": [
{"role": "user", "content": "Example question"},
{"role": "assistant", "content": "Example answer"},
],
},
4,
[
"You are a {{role}} assistant",
"Example question",
"Example answer",
"Help me with {{task}}",
],
),
# 3. Both variables and placeholders. Expect fully compiled output
(
{"role": "helpful", "task": "coding"},
{
"examples": [
{"role": "user", "content": "Show me {{task}}"},
{"role": "assistant", "content": "Here's {{task}}"},
],
},
4,
[
"You are a helpful assistant",
"Show me coding",
"Here's coding",
"Help me with coding",
],
),
# # Empty placeholder array
# This is expected to fail! If the user provides a placeholder, it should contain an array
# (
# {"role": "helpful", "task": "coding"},
# {"examples": []},
# 2,
# ["You are a helpful assistant", "Help me with coding"],
# ),
# 4. Unused placeholder fill ins. Unresolved placeholders kept in output
(
{"role": "helpful", "task": "coding"},
{"unused": [{"role": "user", "content": "Won't appear"}]},
3,
[
"You are a helpful assistant",
None,
"Help me with coding",
], # None = placeholder
),
# 5. Placeholder with non-list value (should log warning and append as string)
(
{"role": "helpful", "task": "coding"},
{"examples": "not a list"},
3,
[
"You are a helpful assistant",
"not a list", # String value appended directly
"Help me with coding",
],
),
# 6. Placeholder with invalid message structure (should log warning and include both)
(
{"role": "helpful", "task": "coding"},
{
"examples": [
"invalid message",
{"role": "user", "content": "valid message"},
]
},
4,
[
"You are a helpful assistant",
"['invalid message', {'role': 'user', 'content': 'valid message'}]", # Invalid structure becomes string
"valid message", # Valid message processed normally
"Help me with coding",
],
),
],
)
def test_compile_with_placeholders(
variables, placeholders, expected_len, expected_contents
) -> None:
"""Test compile_with_placeholders with different variable/placeholder combinations."""
from langfuse.api.resources.prompts import Prompt_Chat
from langfuse.model import ChatPromptClient
mock_prompt = Prompt_Chat(
name="test_prompt",
version=1,
type="chat",
config={},
tags=[],
labels=[],
prompt=[
{"role": "system", "content": "You are a {{role}} assistant"},
{"type": "placeholder", "name": "examples"},
{"role": "user", "content": "Help me with {{task}}"},
],
)
compile_kwargs = {**placeholders, **variables}
result = ChatPromptClient(mock_prompt).compile(**compile_kwargs)
assert len(result) == expected_len
for i, expected_content in enumerate(expected_contents):
if expected_content is None:
# This should be an unresolved placeholder
assert "type" in result[i] and result[i]["type"] == "placeholder"
elif isinstance(result[i], str):
# This is a string value from invalid placeholder
assert result[i] == expected_content
else:
# This should be a regular message
assert "content" in result[i]
assert result[i]["content"] == expected_content
def test_warning_on_unresolved_placeholders():
"""Test that a warning is emitted when compiling with unresolved placeholders."""
from unittest.mock import patch
langfuse = Langfuse()
prompt_name = create_uuid()
langfuse.create_prompt(
name=prompt_name,
prompt=[
{"role": "system", "content": "You are {{name}}"},
{"type": "placeholder", "name": "history"},
{"role": "user", "content": "{{question}}"},
],
type="chat",
)
prompt_client = langfuse.get_prompt(prompt_name, type="chat", version=1)
# Test that warning is emitted when compiling with unresolved placeholders
with patch("langfuse.logger.langfuse_logger.warning") as mock_warning:
# Compile without providing the 'history' placeholder
result = prompt_client.compile(name="Assistant", question="What is 2+2?")
# Verify the warning was called with the expected message
mock_warning.assert_called_once()
warning_message = mock_warning.call_args[0][0]
assert "Placeholders ['history'] have not been resolved" in warning_message
# Verify the result only contains the resolved messages
assert len(result) == 3
assert result[0]["content"] == "You are Assistant"
assert result[1]["name"] == "history"
assert result[2]["content"] == "What is 2+2?"
def test_compiling_chat_prompt():
langfuse = Langfuse()
prompt_name = create_uuid()
prompt_client = langfuse.create_prompt(
name=prompt_name,
prompt=[
{
"role": "system",
"content": "test prompt 1 with {{state}} {{target}} {{state}}",
},
{"role": "user", "content": "test prompt 2 with {{state}}"},
],
labels=["production"],
type="chat",
)
second_prompt_client = langfuse.get_prompt(prompt_name, type="chat")
assert prompt_client.name == second_prompt_client.name
assert prompt_client.version == second_prompt_client.version
assert prompt_client.prompt == second_prompt_client.prompt
assert prompt_client.labels == ["production", "latest"]
assert second_prompt_client.compile(target="world", state="great") == [
{"role": "system", "content": "test prompt 1 with great world great"},
{"role": "user", "content": "test prompt 2 with great"},
]
def test_compiling_prompt():
langfuse = Langfuse()
prompt_name = "test_compiling_prompt"
prompt_client = langfuse.create_prompt(
name=prompt_name,
prompt='Hello, {{target}}! I hope you are {{state}}. {{undefined_variable}}. And here is some JSON that should not be compiled: {{ "key": "value" }} \
Here is a custom var for users using str.format instead of the mustache-style double curly braces: {custom_var}',
labels=["production"],
)
second_prompt_client = langfuse.get_prompt(prompt_name)
assert prompt_client.name == second_prompt_client.name
assert prompt_client.version == second_prompt_client.version
assert prompt_client.prompt == second_prompt_client.prompt
assert prompt_client.labels == ["production", "latest"]
compiled = second_prompt_client.compile(target="world", state="great")
assert (
compiled
== 'Hello, world! I hope you are great. {{undefined_variable}}. And here is some JSON that should not be compiled: {{ "key": "value" }} \
Here is a custom var for users using str.format instead of the mustache-style double curly braces: {custom_var}'
)
def test_compiling_prompt_without_character_escaping():
langfuse = Langfuse()
prompt_name = "test_compiling_prompt_without_character_escaping"
prompt_client = langfuse.create_prompt(
name=prompt_name, prompt="Hello, {{ some_json }}", labels=["production"]
)
second_prompt_client = langfuse.get_prompt(prompt_name)
assert prompt_client.name == second_prompt_client.name
assert prompt_client.version == second_prompt_client.version
assert prompt_client.prompt == second_prompt_client.prompt
assert prompt_client.labels == ["production", "latest"]
some_json = '{"key": "value"}'
compiled = second_prompt_client.compile(some_json=some_json)
assert compiled == 'Hello, {"key": "value"}'
def test_compiling_prompt_with_content_as_variable_name():
langfuse = Langfuse()
prompt_name = "test_compiling_prompt_with_content_as_variable_name"
prompt_client = langfuse.create_prompt(
name=prompt_name,
prompt="Hello, {{ content }}!",
labels=["production"],
)
second_prompt_client = langfuse.get_prompt(prompt_name)
assert prompt_client.name == second_prompt_client.name
assert prompt_client.version == second_prompt_client.version
assert prompt_client.prompt == second_prompt_client.prompt
assert prompt_client.labels == ["production", "latest"]
compiled = second_prompt_client.compile(content="Jane")
assert compiled == "Hello, Jane!"
def test_create_prompt_with_null_config():
langfuse = Langfuse(debug=False)
langfuse.create_prompt(
name="test_null_config",
prompt="Hello, world! I hope you are great",
labels=["production"],
config=None,
)
prompt = langfuse.get_prompt("test_null_config")
assert prompt.config == {}
def test_create_prompt_with_tags():
langfuse = Langfuse(debug=False)
prompt_name = create_uuid()
langfuse.create_prompt(
name=prompt_name,
prompt="Hello, world! I hope you are great",
tags=["tag1", "tag2"],
)
prompt = langfuse.get_prompt(prompt_name, version=1)
assert prompt.tags == ["tag1", "tag2"]
def test_create_prompt_with_empty_tags():
langfuse = Langfuse(debug=False)
prompt_name = create_uuid()
langfuse.create_prompt(
name=prompt_name,
prompt="Hello, world! I hope you are great",
tags=[],
)
prompt = langfuse.get_prompt(prompt_name, version=1)
assert prompt.tags == []
def test_create_prompt_with_previous_tags():
langfuse = Langfuse(debug=False)
prompt_name = create_uuid()
langfuse.create_prompt(
name=prompt_name,
prompt="Hello, world! I hope you are great",
)
prompt = langfuse.get_prompt(prompt_name, version=1)
assert prompt.tags == []
langfuse.create_prompt(
name=prompt_name,
prompt="Hello, world! I hope you are great",
tags=["tag1", "tag2"],
)
prompt_v2 = langfuse.get_prompt(prompt_name, version=2)
assert prompt_v2.tags == ["tag1", "tag2"]
langfuse.create_prompt(
name=prompt_name,
prompt="Hello, world! I hope you are great",
)
prompt_v3 = langfuse.get_prompt(prompt_name, version=3)
assert prompt_v3.tags == ["tag1", "tag2"]
def test_remove_prompt_tags():
langfuse = Langfuse(debug=False)
prompt_name = create_uuid()
langfuse.create_prompt(
name=prompt_name,
prompt="Hello, world! I hope you are great",
tags=["tag1", "tag2"],
)
langfuse.create_prompt(
name=prompt_name,
prompt="Hello, world! I hope you are great",
tags=[],
)
prompt_v1 = langfuse.get_prompt(prompt_name, version=1)
prompt_v2 = langfuse.get_prompt(prompt_name, version=2)
assert prompt_v1.tags == []
assert prompt_v2.tags == []
def test_update_prompt_tags():
langfuse = Langfuse(debug=False)
prompt_name = create_uuid()
langfuse.create_prompt(
name=prompt_name,
prompt="Hello, world! I hope you are great",
tags=["tag1", "tag2"],
)
prompt_v1 = langfuse.get_prompt(prompt_name, version=1)
assert prompt_v1.tags == ["tag1", "tag2"]
langfuse.create_prompt(
name=prompt_name,
prompt="Hello, world! I hope you are great",
tags=["tag3", "tag4"],
)
prompt_v2 = langfuse.get_prompt(prompt_name, version=2)
assert prompt_v2.tags == ["tag3", "tag4"]
def test_get_prompt_by_version_or_label():
langfuse = Langfuse()
prompt_name = create_uuid()
for i in range(3):
langfuse.create_prompt(
name=prompt_name,
prompt="test prompt " + str(i + 1),
labels=["production"] if i == 1 else [],
)
default_prompt_client = langfuse.get_prompt(prompt_name)
assert default_prompt_client.version == 2
assert default_prompt_client.prompt == "test prompt 2"
assert default_prompt_client.labels == ["production"]
first_prompt_client = langfuse.get_prompt(prompt_name, version=1)
assert first_prompt_client.version == 1
assert first_prompt_client.prompt == "test prompt 1"
assert first_prompt_client.labels == []
second_prompt_client = langfuse.get_prompt(prompt_name, version=2)
assert second_prompt_client.version == 2
assert second_prompt_client.prompt == "test prompt 2"
assert second_prompt_client.labels == ["production"]
third_prompt_client = langfuse.get_prompt(prompt_name, label="latest")
assert third_prompt_client.version == 3
assert third_prompt_client.prompt == "test prompt 3"
assert third_prompt_client.labels == ["latest"]
def test_prompt_end_to_end():
langfuse = Langfuse(debug=False)
langfuse.create_prompt(
name="test",
prompt="Hello, {{target}}! I hope you are {{state}}.",
labels=["production"],
config={"temperature": 0.5},
)
prompt = langfuse.get_prompt("test")
prompt_str = prompt.compile(target="world", state="great")
assert prompt_str == "Hello, world! I hope you are great."
assert prompt.config == {"temperature": 0.5}
generation = langfuse.start_generation(
name="mygen", input=prompt_str, prompt=prompt
).end()
# to check that these do not error
generation.update(prompt=prompt)
langfuse.flush()
api = get_api()
trace = api.trace.get(generation.trace_id)
assert len(trace.observations) == 1
generation = trace.observations[0]
assert generation.prompt_id is not None
observation = api.observations.get(generation.id)
assert observation.prompt_id is not None
@pytest.fixture
def langfuse():
from langfuse._client.resource_manager import LangfuseResourceManager
langfuse_instance = Langfuse()
langfuse_instance.api = Mock()
if langfuse_instance._resources is None:
langfuse_instance._resources = Mock(spec=LangfuseResourceManager)
langfuse_instance._resources.prompt_cache = PromptCache()
return langfuse_instance
# Fetching a new prompt when nothing in cache
def test_get_fresh_prompt(langfuse):
prompt_name = "test_get_fresh_prompt"
prompt = Prompt_Text(
name=prompt_name,
version=1,
prompt="Make me laugh",
type="text",
labels=[],
config={},
tags=[],
)
mock_server_call = langfuse.api.prompts.get
mock_server_call.return_value = prompt
result = langfuse.get_prompt(prompt_name, fallback="fallback")
mock_server_call.assert_called_once_with(
prompt_name,
version=None,
label=None,
request_options=None,
)
assert result == TextPromptClient(prompt)
# Should throw an error if prompt name is unspecified
def test_throw_if_name_unspecified(langfuse):
prompt_name = ""
with pytest.raises(ValueError) as exc_info:
langfuse.get_prompt(prompt_name)
assert "Prompt name cannot be empty" in str(exc_info.value)
# Should throw an error if nothing in cache and fetch fails
def test_throw_when_failing_fetch_and_no_cache(langfuse):
prompt_name = "failing_fetch_and_no_cache"
mock_server_call = langfuse.api.prompts.get
mock_server_call.side_effect = Exception("Prompt not found")
with pytest.raises(Exception) as exc_info:
langfuse.get_prompt(prompt_name)
assert "Prompt not found" in str(exc_info.value)
def test_using_custom_prompt_timeouts(langfuse):
prompt_name = "test_using_custom_prompt_timeouts"
prompt = Prompt_Text(
name=prompt_name,
version=1,
prompt="Make me laugh",
type="text",
labels=[],
config={},
tags=[],
)
mock_server_call = langfuse.api.prompts.get
mock_server_call.return_value = prompt
result = langfuse.get_prompt(
prompt_name, fallback="fallback", fetch_timeout_seconds=1000
)
mock_server_call.assert_called_once_with(
prompt_name,
version=None,
label=None,
request_options={"timeout_in_seconds": 1000},
)
assert result == TextPromptClient(prompt)
# Should throw an error if cache_ttl_seconds is passed as positional rather than keyword argument
def test_throw_if_cache_ttl_seconds_positional_argument(langfuse):
prompt_name = "test ttl seconds in positional arg"
ttl_seconds = 20
with pytest.raises(TypeError) as exc_info:
langfuse.get_prompt(prompt_name, ttl_seconds)
assert "positional arguments" in str(exc_info.value)
# Should return cached prompt if not expired
def test_get_valid_cached_prompt(langfuse):
prompt_name = "test_get_valid_cached_prompt"
prompt = Prompt_Text(
name=prompt_name,
version=1,
prompt="Make me laugh",
type="text",
labels=[],
config={},
tags=[],
)
prompt_client = TextPromptClient(prompt)
mock_server_call = langfuse.api.prompts.get
mock_server_call.return_value = prompt
result_call_1 = langfuse.get_prompt(prompt_name, fallback="fallback")
assert mock_server_call.call_count == 1
assert result_call_1 == prompt_client
result_call_2 = langfuse.get_prompt(prompt_name)
assert mock_server_call.call_count == 1
assert result_call_2 == prompt_client
# Should return cached chat prompt if not expired when fetching by label
def test_get_valid_cached_chat_prompt_by_label(langfuse):
prompt_name = "test_get_valid_cached_chat_prompt_by_label"
prompt = Prompt_Chat(
name=prompt_name,
version=1,
prompt=[{"role": "system", "content": "Make me laugh"}],
labels=["test"],
type="chat",
config={},
tags=[],
)
prompt_client = ChatPromptClient(prompt)
mock_server_call = langfuse.api.prompts.get
mock_server_call.return_value = prompt
result_call_1 = langfuse.get_prompt(prompt_name, label="test")
assert mock_server_call.call_count == 1
assert result_call_1 == prompt_client
result_call_2 = langfuse.get_prompt(prompt_name, label="test")
assert mock_server_call.call_count == 1
assert result_call_2 == prompt_client
# Should return cached chat prompt if not expired when fetching by version
def test_get_valid_cached_chat_prompt_by_version(langfuse):
prompt_name = "test_get_valid_cached_chat_prompt_by_version"
prompt = Prompt_Chat(
name=prompt_name,
version=1,
prompt=[{"role": "system", "content": "Make me laugh"}],
labels=["test"],
type="chat",
config={},
tags=[],
)
prompt_client = ChatPromptClient(prompt)
mock_server_call = langfuse.api.prompts.get
mock_server_call.return_value = prompt
result_call_1 = langfuse.get_prompt(prompt_name, version=1)
assert mock_server_call.call_count == 1
assert result_call_1 == prompt_client
result_call_2 = langfuse.get_prompt(prompt_name, version=1)
assert mock_server_call.call_count == 1
assert result_call_2 == prompt_client
# Should return cached chat prompt if fetching the default prompt or the 'production' labeled one
def test_get_valid_cached_production_chat_prompt(langfuse):
prompt_name = "test_get_valid_cached_production_chat_prompt"
prompt = Prompt_Chat(
name=prompt_name,
version=1,
prompt=[{"role": "system", "content": "Make me laugh"}],
labels=["test"],
type="chat",
config={},
tags=[],
)
prompt_client = ChatPromptClient(prompt)
mock_server_call = langfuse.api.prompts.get
mock_server_call.return_value = prompt
result_call_1 = langfuse.get_prompt(prompt_name)
assert mock_server_call.call_count == 1
assert result_call_1 == prompt_client
result_call_2 = langfuse.get_prompt(prompt_name, label="production")
assert mock_server_call.call_count == 1
assert result_call_2 == prompt_client
# Should return cached chat prompt if not expired
def test_get_valid_cached_chat_prompt(langfuse):
prompt_name = "test_get_valid_cached_chat_prompt"
prompt = Prompt_Chat(
name=prompt_name,
version=1,
prompt=[{"role": "system", "content": "Make me laugh"}],
labels=[],
type="chat",
config={},
tags=[],
)
prompt_client = ChatPromptClient(prompt)
mock_server_call = langfuse.api.prompts.get
mock_server_call.return_value = prompt
result_call_1 = langfuse.get_prompt(prompt_name)
assert mock_server_call.call_count == 1
assert result_call_1 == prompt_client
result_call_2 = langfuse.get_prompt(prompt_name)
assert mock_server_call.call_count == 1
assert result_call_2 == prompt_client
# Should refetch and return new prompt if cached one is expired according to custom TTL
@patch.object(PromptCacheItem, "get_epoch_seconds")
def test_get_fresh_prompt_when_expired_cache_custom_ttl(mock_time, langfuse: Langfuse):
mock_time.return_value = 0
ttl_seconds = 20
prompt_name = "test_get_fresh_prompt_when_expired_cache_custom_ttl"
prompt = Prompt_Text(
name=prompt_name,
version=1,
prompt="Make me laugh",
config={"temperature": 0.9},
labels=[],
type="text",
tags=[],
)
prompt_client = TextPromptClient(prompt)
mock_server_call = langfuse.api.prompts.get
mock_server_call.return_value = prompt
result_call_1 = langfuse.get_prompt(prompt_name, cache_ttl_seconds=ttl_seconds)
assert mock_server_call.call_count == 1
assert result_call_1 == prompt_client
# Set time to just BEFORE cache expiry
mock_time.return_value = ttl_seconds - 1
result_call_2 = langfuse.get_prompt(prompt_name)
assert mock_server_call.call_count == 1 # No new call
assert result_call_2 == prompt_client
# Set time to just AFTER cache expiry
mock_time.return_value = ttl_seconds + 1
result_call_3 = langfuse.get_prompt(prompt_name)
while True:
if langfuse._resources.prompt_cache._task_manager.active_tasks() == 0:
break
sleep(0.1)
assert mock_server_call.call_count == 2 # New call
assert result_call_3 == prompt_client
# Should disable caching when cache_ttl_seconds is set to 0
@patch.object(PromptCacheItem, "get_epoch_seconds")
def test_disable_caching_when_ttl_zero(mock_time, langfuse: Langfuse):
mock_time.return_value = 0
prompt_name = "test_disable_caching_when_ttl_zero"
# Initial prompt
prompt1 = Prompt_Text(
name=prompt_name,
version=1,
prompt="Make me laugh",
labels=[],
type="text",
config={},
tags=[],
)
# Updated prompts
prompt2 = Prompt_Text(
name=prompt_name,
version=2,
prompt="Tell me a joke",
labels=[],
type="text",
config={},
tags=[],
)
prompt3 = Prompt_Text(
name=prompt_name,
version=3,
prompt="Share a funny story",
labels=[],
type="text",
config={},
tags=[],
)
mock_server_call = langfuse.api.prompts.get
mock_server_call.side_effect = [prompt1, prompt2, prompt3]