-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.py
More file actions
2969 lines (2424 loc) · 123 KB
/
client.py
File metadata and controls
2969 lines (2424 loc) · 123 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
# This file was auto-generated by Fern from our API Definition.
import datetime as dt
import typing
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.pagination import AsyncPager, SyncPager
from ..core.request_options import RequestOptions
from ..requests.chat_message import ChatMessageParams
from ..requests.evaluator_activation_deactivation_request_activate_item import (
EvaluatorActivationDeactivationRequestActivateItemParams,
)
from ..requests.evaluator_activation_deactivation_request_deactivate_item import (
EvaluatorActivationDeactivationRequestDeactivateItemParams,
)
from ..requests.provider_api_keys import ProviderApiKeysParams
from ..requests.response_format import ResponseFormatParams
from ..requests.tool_function import ToolFunctionParams
from ..types.create_prompt_log_response import CreatePromptLogResponse
from ..types.file_environment_response import FileEnvironmentResponse
from ..types.file_sort_by import FileSortBy
from ..types.list_prompts import ListPrompts
from ..types.log_response import LogResponse
from ..types.model_endpoints import ModelEndpoints
from ..types.model_providers import ModelProviders
from ..types.populate_template_response import PopulateTemplateResponse
from ..types.prompt_call_response import PromptCallResponse
from ..types.prompt_call_stream_response import PromptCallStreamResponse
from ..types.prompt_kernel_request import PromptKernelRequest
from ..types.prompt_response import PromptResponse
from ..types.sort_order import SortOrder
from ..types.template_language import TemplateLanguage
from .raw_client import AsyncRawPromptsClient, RawPromptsClient
from .requests.prompt_log_request_prompt import PromptLogRequestPromptParams
from .requests.prompt_log_request_tool_choice import PromptLogRequestToolChoiceParams
from .requests.prompt_log_update_request_tool_choice import PromptLogUpdateRequestToolChoiceParams
from .requests.prompt_request_reasoning_effort import PromptRequestReasoningEffortParams
from .requests.prompt_request_stop import PromptRequestStopParams
from .requests.prompt_request_template import PromptRequestTemplateParams
from .requests.prompts_call_request_prompt import PromptsCallRequestPromptParams
from .requests.prompts_call_request_tool_choice import PromptsCallRequestToolChoiceParams
from .requests.prompts_call_stream_request_prompt import PromptsCallStreamRequestPromptParams
from .requests.prompts_call_stream_request_tool_choice import PromptsCallStreamRequestToolChoiceParams
# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)
class PromptsClient:
def __init__(self, *, client_wrapper: SyncClientWrapper):
self._raw_client = RawPromptsClient(client_wrapper=client_wrapper)
@property
def with_raw_response(self) -> RawPromptsClient:
"""
Retrieves a raw implementation of this client that returns raw responses.
Returns
-------
RawPromptsClient
"""
return self._raw_client
def log(
self,
*,
version_id: typing.Optional[str] = None,
environment: typing.Optional[str] = None,
run_id: typing.Optional[str] = OMIT,
path: typing.Optional[str] = OMIT,
id: typing.Optional[str] = OMIT,
output_message: typing.Optional[ChatMessageParams] = OMIT,
prompt_tokens: typing.Optional[int] = OMIT,
reasoning_tokens: typing.Optional[int] = OMIT,
output_tokens: typing.Optional[int] = OMIT,
prompt_cost: typing.Optional[float] = OMIT,
output_cost: typing.Optional[float] = OMIT,
finish_reason: typing.Optional[str] = OMIT,
messages: typing.Optional[typing.Sequence[ChatMessageParams]] = OMIT,
tool_choice: typing.Optional[PromptLogRequestToolChoiceParams] = OMIT,
prompt: typing.Optional[PromptLogRequestPromptParams] = OMIT,
start_time: typing.Optional[dt.datetime] = OMIT,
end_time: typing.Optional[dt.datetime] = OMIT,
output: typing.Optional[str] = OMIT,
created_at: typing.Optional[dt.datetime] = OMIT,
error: typing.Optional[str] = OMIT,
provider_latency: typing.Optional[float] = OMIT,
stdout: typing.Optional[str] = OMIT,
provider_request: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
provider_response: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
inputs: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
source: typing.Optional[str] = OMIT,
metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
source_datapoint_id: typing.Optional[str] = OMIT,
trace_parent_id: typing.Optional[str] = OMIT,
user: typing.Optional[str] = OMIT,
prompt_log_request_environment: typing.Optional[str] = OMIT,
save: typing.Optional[bool] = OMIT,
log_id: typing.Optional[str] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> CreatePromptLogResponse:
"""
Log to a Prompt.
You can use query parameters `version_id`, or `environment`, to target
an existing version of the Prompt. Otherwise, the default deployed version will be chosen.
Instead of targeting an existing version explicitly, you can instead pass in
Prompt details in the request body. In this case, we will check if the details correspond
to an existing version of the Prompt. If they do not, we will create a new version. This is helpful
in the case where you are storing or deriving your Prompt details in code.
Parameters
----------
version_id : typing.Optional[str]
A specific Version ID of the Prompt to log to.
environment : typing.Optional[str]
Name of the Environment identifying a deployed version to log to.
run_id : typing.Optional[str]
Unique identifier for the Run to associate the Log to.
path : typing.Optional[str]
Path of the Prompt, including the name. This locates the Prompt in the Humanloop filesystem and is used as as a unique identifier. For example: `folder/name` or just `name`.
id : typing.Optional[str]
ID for an existing Prompt.
output_message : typing.Optional[ChatMessageParams]
The message returned by the provider.
prompt_tokens : typing.Optional[int]
Number of tokens in the prompt used to generate the output.
reasoning_tokens : typing.Optional[int]
Number of reasoning tokens used to generate the output.
output_tokens : typing.Optional[int]
Number of tokens in the output generated by the model.
prompt_cost : typing.Optional[float]
Cost in dollars associated to the tokens in the prompt.
output_cost : typing.Optional[float]
Cost in dollars associated to the tokens in the output.
finish_reason : typing.Optional[str]
Reason the generation finished.
messages : typing.Optional[typing.Sequence[ChatMessageParams]]
The messages passed to the to provider chat endpoint.
tool_choice : typing.Optional[PromptLogRequestToolChoiceParams]
Controls how the model uses tools. The following options are supported:
- `'none'` means the model will not call any tool and instead generates a message; this is the default when no tools are provided as part of the Prompt.
- `'auto'` means the model can decide to call one or more of the provided tools; this is the default when tools are provided as part of the Prompt.
- `'required'` means the model must call one or more of the provided tools.
- `{'type': 'function', 'function': {name': <TOOL_NAME>}}` forces the model to use the named function.
prompt : typing.Optional[PromptLogRequestPromptParams]
The Prompt configuration to use. Two formats are supported:
- An object representing the details of the Prompt configuration
- A string representing the raw contents of a .prompt file
A new Prompt version will be created if the provided details do not match any existing version.
start_time : typing.Optional[dt.datetime]
When the logged event started.
end_time : typing.Optional[dt.datetime]
When the logged event ended.
output : typing.Optional[str]
Generated output from your model for the provided inputs. Can be `None` if logging an error, or if creating a parent Log with the intention to populate it later.
created_at : typing.Optional[dt.datetime]
User defined timestamp for when the log was created.
error : typing.Optional[str]
Error message if the log is an error.
provider_latency : typing.Optional[float]
Duration of the logged event in seconds.
stdout : typing.Optional[str]
Captured log and debug statements.
provider_request : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Raw request sent to provider.
provider_response : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Raw response received the provider.
inputs : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
The inputs passed to the prompt template.
source : typing.Optional[str]
Identifies where the model was called from.
metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Any additional metadata to record.
source_datapoint_id : typing.Optional[str]
Unique identifier for the Datapoint that this Log is derived from. This can be used by Humanloop to associate Logs to Evaluations. If provided, Humanloop will automatically associate this Log to Evaluations that require a Log for this Datapoint-Version pair.
trace_parent_id : typing.Optional[str]
The ID of the parent Log to nest this Log under in a Trace.
user : typing.Optional[str]
End-user ID related to the Log.
prompt_log_request_environment : typing.Optional[str]
The name of the Environment the Log is associated to.
save : typing.Optional[bool]
Whether the request/response payloads will be stored on Humanloop.
log_id : typing.Optional[str]
This will identify a Log. If you don't provide a Log ID, Humanloop will generate one for you.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
CreatePromptLogResponse
Successful Response
Examples
--------
from humanloop import Humanloop
import datetime
client = Humanloop(api_key="YOUR_API_KEY", )
client.prompts.log(path='persona', prompt={'model': 'gpt-4', 'template': [{'role': "system", 'content': 'You are {{person}}. Answer questions as this person. Do not break character.'}]}, messages=[{'role': "user", 'content': 'What really happened at Roswell?'}], inputs={'person': 'Trump'
}, created_at=datetime.datetime.fromisoformat("2024-07-18 23:29:35.178000+00:00", ), provider_latency=6.5931549072265625, output_message={'content': "Well, you know, there is so much secrecy involved in government, folks, it's unbelievable. They don't want to tell you everything. They don't tell me everything! But about Roswell, it's a very popular question. I know, I just know, that something very, very peculiar happened there. Was it a weather balloon? Maybe. Was it something extraterrestrial? Could be. I'd love to go down and open up all the classified documents, believe me, I would. But they don't let that happen. The Deep State, folks, the Deep State. They're unbelievable. They want to keep everything a secret. But whatever the truth is, I can tell you this: it's something big, very very big. Tremendous, in fact.", 'role': "assistant"}, prompt_tokens=100, output_tokens=220, prompt_cost=1e-05, output_cost=0.0002, finish_reason='stop', )
"""
_response = self._raw_client.log(
version_id=version_id,
environment=environment,
run_id=run_id,
path=path,
id=id,
output_message=output_message,
prompt_tokens=prompt_tokens,
reasoning_tokens=reasoning_tokens,
output_tokens=output_tokens,
prompt_cost=prompt_cost,
output_cost=output_cost,
finish_reason=finish_reason,
messages=messages,
tool_choice=tool_choice,
prompt=prompt,
start_time=start_time,
end_time=end_time,
output=output,
created_at=created_at,
error=error,
provider_latency=provider_latency,
stdout=stdout,
provider_request=provider_request,
provider_response=provider_response,
inputs=inputs,
source=source,
metadata=metadata,
source_datapoint_id=source_datapoint_id,
trace_parent_id=trace_parent_id,
user=user,
prompt_log_request_environment=prompt_log_request_environment,
save=save,
log_id=log_id,
request_options=request_options,
)
return _response.data
def update_log(
self,
id: str,
log_id: str,
*,
output_message: typing.Optional[ChatMessageParams] = OMIT,
prompt_tokens: typing.Optional[int] = OMIT,
reasoning_tokens: typing.Optional[int] = OMIT,
output_tokens: typing.Optional[int] = OMIT,
prompt_cost: typing.Optional[float] = OMIT,
output_cost: typing.Optional[float] = OMIT,
finish_reason: typing.Optional[str] = OMIT,
messages: typing.Optional[typing.Sequence[ChatMessageParams]] = OMIT,
tool_choice: typing.Optional[PromptLogUpdateRequestToolChoiceParams] = OMIT,
output: typing.Optional[str] = OMIT,
created_at: typing.Optional[dt.datetime] = OMIT,
error: typing.Optional[str] = OMIT,
provider_latency: typing.Optional[float] = OMIT,
stdout: typing.Optional[str] = OMIT,
provider_request: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
provider_response: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
inputs: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
source: typing.Optional[str] = OMIT,
metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
start_time: typing.Optional[dt.datetime] = OMIT,
end_time: typing.Optional[dt.datetime] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> LogResponse:
"""
Update a Log.
Update the details of a Log with the given ID.
Parameters
----------
id : str
Unique identifier for Prompt.
log_id : str
Unique identifier for the Log.
output_message : typing.Optional[ChatMessageParams]
The message returned by the provider.
prompt_tokens : typing.Optional[int]
Number of tokens in the prompt used to generate the output.
reasoning_tokens : typing.Optional[int]
Number of reasoning tokens used to generate the output.
output_tokens : typing.Optional[int]
Number of tokens in the output generated by the model.
prompt_cost : typing.Optional[float]
Cost in dollars associated to the tokens in the prompt.
output_cost : typing.Optional[float]
Cost in dollars associated to the tokens in the output.
finish_reason : typing.Optional[str]
Reason the generation finished.
messages : typing.Optional[typing.Sequence[ChatMessageParams]]
The messages passed to the to provider chat endpoint.
tool_choice : typing.Optional[PromptLogUpdateRequestToolChoiceParams]
Controls how the model uses tools. The following options are supported:
- `'none'` means the model will not call any tool and instead generates a message; this is the default when no tools are provided as part of the Prompt.
- `'auto'` means the model can decide to call one or more of the provided tools; this is the default when tools are provided as part of the Prompt.
- `'required'` means the model must call one or more of the provided tools.
- `{'type': 'function', 'function': {name': <TOOL_NAME>}}` forces the model to use the named function.
output : typing.Optional[str]
Generated output from your model for the provided inputs. Can be `None` if logging an error, or if creating a parent Log with the intention to populate it later.
created_at : typing.Optional[dt.datetime]
User defined timestamp for when the log was created.
error : typing.Optional[str]
Error message if the log is an error.
provider_latency : typing.Optional[float]
Duration of the logged event in seconds.
stdout : typing.Optional[str]
Captured log and debug statements.
provider_request : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Raw request sent to provider.
provider_response : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Raw response received the provider.
inputs : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
The inputs passed to the prompt template.
source : typing.Optional[str]
Identifies where the model was called from.
metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Any additional metadata to record.
start_time : typing.Optional[dt.datetime]
When the logged event started.
end_time : typing.Optional[dt.datetime]
When the logged event ended.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
LogResponse
Successful Response
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
client.prompts.update_log(id='id', log_id='log_id', )
"""
_response = self._raw_client.update_log(
id,
log_id,
output_message=output_message,
prompt_tokens=prompt_tokens,
reasoning_tokens=reasoning_tokens,
output_tokens=output_tokens,
prompt_cost=prompt_cost,
output_cost=output_cost,
finish_reason=finish_reason,
messages=messages,
tool_choice=tool_choice,
output=output,
created_at=created_at,
error=error,
provider_latency=provider_latency,
stdout=stdout,
provider_request=provider_request,
provider_response=provider_response,
inputs=inputs,
source=source,
metadata=metadata,
start_time=start_time,
end_time=end_time,
request_options=request_options,
)
return _response.data
def call_stream(
self,
*,
version_id: typing.Optional[str] = None,
environment: typing.Optional[str] = None,
path: typing.Optional[str] = OMIT,
id: typing.Optional[str] = OMIT,
messages: typing.Optional[typing.Sequence[ChatMessageParams]] = OMIT,
tool_choice: typing.Optional[PromptsCallStreamRequestToolChoiceParams] = OMIT,
prompt: typing.Optional[PromptsCallStreamRequestPromptParams] = OMIT,
inputs: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
source: typing.Optional[str] = OMIT,
metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
start_time: typing.Optional[dt.datetime] = OMIT,
end_time: typing.Optional[dt.datetime] = OMIT,
source_datapoint_id: typing.Optional[str] = OMIT,
trace_parent_id: typing.Optional[str] = OMIT,
user: typing.Optional[str] = OMIT,
prompts_call_stream_request_environment: typing.Optional[str] = OMIT,
save: typing.Optional[bool] = OMIT,
log_id: typing.Optional[str] = OMIT,
provider_api_keys: typing.Optional[ProviderApiKeysParams] = OMIT,
num_samples: typing.Optional[int] = OMIT,
return_inputs: typing.Optional[bool] = OMIT,
logprobs: typing.Optional[int] = OMIT,
suffix: typing.Optional[str] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.Iterator[PromptCallStreamResponse]:
"""
Call a Prompt.
Calling a Prompt calls the model provider before logging
the request, responses and metadata to Humanloop.
You can use query parameters `version_id`, or `environment`, to target
an existing version of the Prompt. Otherwise the default deployed version will be chosen.
Instead of targeting an existing version explicitly, you can instead pass in
Prompt details in the request body. In this case, we will check if the details correspond
to an existing version of the Prompt. If they do not, we will create a new version. This is helpful
in the case where you are storing or deriving your Prompt details in code.
Parameters
----------
version_id : typing.Optional[str]
A specific Version ID of the Prompt to log to.
environment : typing.Optional[str]
Name of the Environment identifying a deployed version to log to.
path : typing.Optional[str]
Path of the Prompt, including the name. This locates the Prompt in the Humanloop filesystem and is used as as a unique identifier. For example: `folder/name` or just `name`.
id : typing.Optional[str]
ID for an existing Prompt.
messages : typing.Optional[typing.Sequence[ChatMessageParams]]
The messages passed to the to provider chat endpoint.
tool_choice : typing.Optional[PromptsCallStreamRequestToolChoiceParams]
Controls how the model uses tools. The following options are supported:
- `'none'` means the model will not call any tool and instead generates a message; this is the default when no tools are provided as part of the Prompt.
- `'auto'` means the model can decide to call one or more of the provided tools; this is the default when tools are provided as part of the Prompt.
- `'required'` means the model must call one or more of the provided tools.
- `{'type': 'function', 'function': {name': <TOOL_NAME>}}` forces the model to use the named function.
prompt : typing.Optional[PromptsCallStreamRequestPromptParams]
The Prompt configuration to use. Two formats are supported:
- An object representing the details of the Prompt configuration
- A string representing the raw contents of a .prompt file
<<<<<<< HEAD
=======
>>>>>>> 190233f (Merge branch 'master' into flow-complete-dx)
A new Prompt version will be created if the provided details do not match any existing version.
inputs : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
The inputs passed to the prompt template.
source : typing.Optional[str]
Identifies where the model was called from.
metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Any additional metadata to record.
start_time : typing.Optional[dt.datetime]
When the logged event started.
end_time : typing.Optional[dt.datetime]
When the logged event ended.
source_datapoint_id : typing.Optional[str]
Unique identifier for the Datapoint that this Log is derived from. This can be used by Humanloop to associate Logs to Evaluations. If provided, Humanloop will automatically associate this Log to Evaluations that require a Log for this Datapoint-Version pair.
trace_parent_id : typing.Optional[str]
The ID of the parent Log to nest this Log under in a Trace.
user : typing.Optional[str]
End-user ID related to the Log.
prompts_call_stream_request_environment : typing.Optional[str]
The name of the Environment the Log is associated to.
save : typing.Optional[bool]
Whether the request/response payloads will be stored on Humanloop.
log_id : typing.Optional[str]
This will identify a Log. If you don't provide a Log ID, Humanloop will generate one for you.
provider_api_keys : typing.Optional[ProviderApiKeysParams]
API keys required by each provider to make API calls. The API keys provided here are not stored by Humanloop. If not specified here, Humanloop will fall back to the key saved to your organization.
num_samples : typing.Optional[int]
The number of generations.
return_inputs : typing.Optional[bool]
Whether to return the inputs in the response. If false, the response will contain an empty dictionary under inputs. This is useful for reducing the size of the response. Defaults to true.
logprobs : typing.Optional[int]
Include the log probabilities of the top n tokens in the provider_response
suffix : typing.Optional[str]
The suffix that comes after a completion of inserted text. Useful for completions that act like inserts.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Yields
------
typing.Iterator[PromptCallStreamResponse]
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
response = client.prompts.call_stream()
for chunk in response:
yield chunk
"""
with self._raw_client.call_stream(
version_id=version_id,
environment=environment,
path=path,
id=id,
messages=messages,
tool_choice=tool_choice,
prompt=prompt,
inputs=inputs,
source=source,
metadata=metadata,
start_time=start_time,
end_time=end_time,
source_datapoint_id=source_datapoint_id,
trace_parent_id=trace_parent_id,
user=user,
prompts_call_stream_request_environment=prompts_call_stream_request_environment,
save=save,
log_id=log_id,
provider_api_keys=provider_api_keys,
num_samples=num_samples,
return_inputs=return_inputs,
logprobs=logprobs,
suffix=suffix,
request_options=request_options,
) as r:
yield from r.data
def call(
self,
*,
version_id: typing.Optional[str] = None,
environment: typing.Optional[str] = None,
path: typing.Optional[str] = OMIT,
id: typing.Optional[str] = OMIT,
messages: typing.Optional[typing.Sequence[ChatMessageParams]] = OMIT,
tool_choice: typing.Optional[PromptsCallRequestToolChoiceParams] = OMIT,
prompt: typing.Optional[PromptsCallRequestPromptParams] = OMIT,
inputs: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
source: typing.Optional[str] = OMIT,
metadata: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
start_time: typing.Optional[dt.datetime] = OMIT,
end_time: typing.Optional[dt.datetime] = OMIT,
source_datapoint_id: typing.Optional[str] = OMIT,
trace_parent_id: typing.Optional[str] = OMIT,
user: typing.Optional[str] = OMIT,
prompts_call_request_environment: typing.Optional[str] = OMIT,
save: typing.Optional[bool] = OMIT,
log_id: typing.Optional[str] = OMIT,
provider_api_keys: typing.Optional[ProviderApiKeysParams] = OMIT,
num_samples: typing.Optional[int] = OMIT,
return_inputs: typing.Optional[bool] = OMIT,
logprobs: typing.Optional[int] = OMIT,
suffix: typing.Optional[str] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> PromptCallResponse:
"""
Call a Prompt.
Calling a Prompt calls the model provider before logging
the request, responses and metadata to Humanloop.
You can use query parameters `version_id`, or `environment`, to target
an existing version of the Prompt. Otherwise the default deployed version will be chosen.
Instead of targeting an existing version explicitly, you can instead pass in
Prompt details in the request body. In this case, we will check if the details correspond
to an existing version of the Prompt. If they do not, we will create a new version. This is helpful
in the case where you are storing or deriving your Prompt details in code.
Parameters
----------
version_id : typing.Optional[str]
A specific Version ID of the Prompt to log to.
environment : typing.Optional[str]
Name of the Environment identifying a deployed version to log to.
path : typing.Optional[str]
Path of the Prompt, including the name. This locates the Prompt in the Humanloop filesystem and is used as as a unique identifier. For example: `folder/name` or just `name`.
id : typing.Optional[str]
ID for an existing Prompt.
messages : typing.Optional[typing.Sequence[ChatMessageParams]]
The messages passed to the to provider chat endpoint.
tool_choice : typing.Optional[PromptsCallRequestToolChoiceParams]
Controls how the model uses tools. The following options are supported:
- `'none'` means the model will not call any tool and instead generates a message; this is the default when no tools are provided as part of the Prompt.
- `'auto'` means the model can decide to call one or more of the provided tools; this is the default when tools are provided as part of the Prompt.
- `'required'` means the model must call one or more of the provided tools.
- `{'type': 'function', 'function': {name': <TOOL_NAME>}}` forces the model to use the named function.
prompt : typing.Optional[PromptsCallRequestPromptParams]
The Prompt configuration to use. Two formats are supported:
- An object representing the details of the Prompt configuration
- A string representing the raw contents of a .prompt file
<<<<<<< HEAD
=======
>>>>>>> 190233f (Merge branch 'master' into flow-complete-dx)
A new Prompt version will be created if the provided details do not match any existing version.
inputs : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
The inputs passed to the prompt template.
source : typing.Optional[str]
Identifies where the model was called from.
metadata : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Any additional metadata to record.
start_time : typing.Optional[dt.datetime]
When the logged event started.
end_time : typing.Optional[dt.datetime]
When the logged event ended.
source_datapoint_id : typing.Optional[str]
Unique identifier for the Datapoint that this Log is derived from. This can be used by Humanloop to associate Logs to Evaluations. If provided, Humanloop will automatically associate this Log to Evaluations that require a Log for this Datapoint-Version pair.
trace_parent_id : typing.Optional[str]
The ID of the parent Log to nest this Log under in a Trace.
user : typing.Optional[str]
End-user ID related to the Log.
prompts_call_request_environment : typing.Optional[str]
The name of the Environment the Log is associated to.
save : typing.Optional[bool]
Whether the request/response payloads will be stored on Humanloop.
log_id : typing.Optional[str]
This will identify a Log. If you don't provide a Log ID, Humanloop will generate one for you.
provider_api_keys : typing.Optional[ProviderApiKeysParams]
API keys required by each provider to make API calls. The API keys provided here are not stored by Humanloop. If not specified here, Humanloop will fall back to the key saved to your organization.
num_samples : typing.Optional[int]
The number of generations.
return_inputs : typing.Optional[bool]
Whether to return the inputs in the response. If false, the response will contain an empty dictionary under inputs. This is useful for reducing the size of the response. Defaults to true.
logprobs : typing.Optional[int]
Include the log probabilities of the top n tokens in the provider_response
suffix : typing.Optional[str]
The suffix that comes after a completion of inserted text. Useful for completions that act like inserts.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
PromptCallResponse
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
client.prompts.call(path='persona', prompt={'model': 'gpt-4', 'template': [{'role': "system", 'content': 'You are stockbot. Return latest prices.'}], 'tools': [{'name': 'get_stock_price', 'description': 'Get current stock price', 'parameters': {'type': 'object'
, 'properties': {'ticker_symbol': {'type': 'string', 'name': 'Ticker Symbol', 'description': 'Ticker symbol of the stock'}}
, 'required': []
}}]}, messages=[{'role': "user", 'content': 'latest apple'}], )
"""
_response = self._raw_client.call(
version_id=version_id,
environment=environment,
path=path,
id=id,
messages=messages,
tool_choice=tool_choice,
prompt=prompt,
inputs=inputs,
source=source,
metadata=metadata,
start_time=start_time,
end_time=end_time,
source_datapoint_id=source_datapoint_id,
trace_parent_id=trace_parent_id,
user=user,
prompts_call_request_environment=prompts_call_request_environment,
save=save,
log_id=log_id,
provider_api_keys=provider_api_keys,
num_samples=num_samples,
return_inputs=return_inputs,
logprobs=logprobs,
suffix=suffix,
request_options=request_options,
)
return _response.data
def list(
self,
*,
page: typing.Optional[int] = None,
size: typing.Optional[int] = None,
name: typing.Optional[str] = None,
user_filter: typing.Optional[str] = None,
sort_by: typing.Optional[FileSortBy] = None,
order: typing.Optional[SortOrder] = None,
request_options: typing.Optional[RequestOptions] = None,
) -> SyncPager[PromptResponse]:
"""
Get a list of all Prompts.
Parameters
----------
page : typing.Optional[int]
Page number for pagination.
size : typing.Optional[int]
Page size for pagination. Number of Prompts to fetch.
name : typing.Optional[str]
Case-insensitive filter for Prompt name.
user_filter : typing.Optional[str]
Case-insensitive filter for users in the Prompt. This filter matches against both email address and name of users.
sort_by : typing.Optional[FileSortBy]
Field to sort Prompts by
order : typing.Optional[SortOrder]
Direction to sort by.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
SyncPager[PromptResponse]
Successful Response
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
response = client.prompts.list(size=1, )
for item in response:
yield item
# alternatively, you can paginate page-by-page
for page in response.iter_pages():
yield page
"""
return self._raw_client.list(
page=page,
size=size,
name=name,
user_filter=user_filter,
sort_by=sort_by,
order=order,
request_options=request_options,
)
def upsert(
self,
*,
model: str,
path: typing.Optional[str] = OMIT,
id: typing.Optional[str] = OMIT,
endpoint: typing.Optional[ModelEndpoints] = OMIT,
template: typing.Optional[PromptRequestTemplateParams] = OMIT,
template_language: typing.Optional[TemplateLanguage] = OMIT,
provider: typing.Optional[ModelProviders] = OMIT,
max_tokens: typing.Optional[int] = OMIT,
temperature: typing.Optional[float] = OMIT,
top_p: typing.Optional[float] = OMIT,
stop: typing.Optional[PromptRequestStopParams] = OMIT,
presence_penalty: typing.Optional[float] = OMIT,
frequency_penalty: typing.Optional[float] = OMIT,
other: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
seed: typing.Optional[int] = OMIT,
response_format: typing.Optional[ResponseFormatParams] = OMIT,
reasoning_effort: typing.Optional[PromptRequestReasoningEffortParams] = OMIT,
tools: typing.Optional[typing.Sequence[ToolFunctionParams]] = OMIT,
linked_tools: typing.Optional[typing.Sequence[str]] = OMIT,
attributes: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
version_name: typing.Optional[str] = OMIT,
version_description: typing.Optional[str] = OMIT,
description: typing.Optional[str] = OMIT,
tags: typing.Optional[typing.Sequence[str]] = OMIT,
readme: typing.Optional[str] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> PromptResponse:
"""
Create a Prompt or update it with a new version if it already exists.
Prompts are identified by the `ID` or their `path`. The parameters (i.e. the prompt template, temperature, model etc.) determine the versions of the Prompt.
You can provide `version_name` and `version_description` to identify and describe your versions.
Version names must be unique within a Prompt - attempting to create a version with a name
that already exists will result in a 409 Conflict error.
Parameters
----------
model : str
The model instance used, e.g. `gpt-4`. See [supported models](https://humanloop.com/docs/reference/supported-models)
path : typing.Optional[str]
Path of the Prompt, including the name. This locates the Prompt in the Humanloop filesystem and is used as as a unique identifier. For example: `folder/name` or just `name`.
id : typing.Optional[str]
ID for an existing Prompt.
endpoint : typing.Optional[ModelEndpoints]
The provider model endpoint used.
template : typing.Optional[PromptRequestTemplateParams]
The template contains the main structure and instructions for the model, including input variables for dynamic values.
For chat models, provide the template as a ChatTemplate (a list of messages), e.g. a system message, followed by a user message with an input variable.
For completion models, provide a prompt template as a string.
Input variables should be specified with double curly bracket syntax: `{{input_name}}`.
template_language : typing.Optional[TemplateLanguage]
The template language to use for rendering the template.
provider : typing.Optional[ModelProviders]
The company providing the underlying model service.
max_tokens : typing.Optional[int]
The maximum number of tokens to generate. Provide max_tokens=-1 to dynamically calculate the maximum number of tokens to generate given the length of the prompt
temperature : typing.Optional[float]
What sampling temperature to use when making a generation. Higher values means the model will be more creative.
top_p : typing.Optional[float]
An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass.
stop : typing.Optional[PromptRequestStopParams]
The string (or list of strings) after which the model will stop generating. The returned text will not contain the stop sequence.
presence_penalty : typing.Optional[float]
Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the generation so far.
frequency_penalty : typing.Optional[float]
Number between -2.0 and 2.0. Positive values penalize new tokens based on how frequently they appear in the generation so far.
other : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Other parameter values to be passed to the provider call.
seed : typing.Optional[int]
If specified, model will make a best effort to sample deterministically, but it is not guaranteed.
response_format : typing.Optional[ResponseFormatParams]
The format of the response. Only `{"type": "json_object"}` is currently supported for chat.
reasoning_effort : typing.Optional[PromptRequestReasoningEffortParams]
Guidance on how many reasoning tokens it should generate before creating a response to the prompt. OpenAI reasoning models (o1, o3-mini) expect a OpenAIReasoningEffort enum. Anthropic reasoning models expect an integer, which signifies the maximum token budget.
tools : typing.Optional[typing.Sequence[ToolFunctionParams]]
The tool specification that the model can choose to call if Tool calling is supported.
linked_tools : typing.Optional[typing.Sequence[str]]
The IDs of the Tools in your organization that the model can choose to call if Tool calling is supported. The default deployed version of that tool is called.
attributes : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
Additional fields to describe the Prompt. Helpful to separate Prompt versions from each other with details on how they were created or used.
version_name : typing.Optional[str]
Unique name for the Prompt version. Version names must be unique for a given Prompt.
version_description : typing.Optional[str]
Description of the version, e.g., the changes made in this version.
description : typing.Optional[str]
Description of the Prompt.
tags : typing.Optional[typing.Sequence[str]]
List of tags associated with this prompt.
readme : typing.Optional[str]
Long description of the Prompt.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
PromptResponse
Successful Response
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
client.prompts.upsert(path='Personal Projects/Coding Assistant', model='gpt-4o', endpoint="chat", template=[{'content': 'You are a helpful coding assistant specialising in {{language}}', 'role': "system"}], provider="openai", max_tokens=-1, temperature=0.7, version_name='coding-assistant-v1', version_description='Initial version', )
"""
_response = self._raw_client.upsert(
model=model,
path=path,
id=id,
endpoint=endpoint,
template=template,
template_language=template_language,
provider=provider,
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
stop=stop,
presence_penalty=presence_penalty,
frequency_penalty=frequency_penalty,
other=other,
seed=seed,
response_format=response_format,
reasoning_effort=reasoning_effort,
tools=tools,
linked_tools=linked_tools,
attributes=attributes,
version_name=version_name,
version_description=version_description,
description=description,
tags=tags,
readme=readme,
request_options=request_options,
)
return _response.data
def get(
self,
id: str,
*,
version_id: typing.Optional[str] = None,
environment: typing.Optional[str] = None,
request_options: typing.Optional[RequestOptions] = None,
) -> PromptResponse:
"""
Retrieve the Prompt with the given ID.