-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathclient.py
More file actions
2936 lines (2393 loc) · 122 KB
/
client.py
File metadata and controls
2936 lines (2393 loc) · 122 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 ..types.agent_call_response import AgentCallResponse
from ..types.agent_call_stream_response import AgentCallStreamResponse
from ..types.agent_continue_call_response import AgentContinueCallResponse
from ..types.agent_continue_call_stream_response import AgentContinueCallStreamResponse
from ..types.agent_kernel_request import AgentKernelRequest
from ..types.agent_log_response import AgentLogResponse
from ..types.agent_response import AgentResponse
from ..types.create_agent_log_response import CreateAgentLogResponse
from ..types.file_environment_response import FileEnvironmentResponse
from ..types.file_sort_by import FileSortBy
from ..types.list_agents import ListAgents
from ..types.log_status import LogStatus
from ..types.model_endpoints import ModelEndpoints
from ..types.model_providers import ModelProviders
from ..types.sort_order import SortOrder
from ..types.template_language import TemplateLanguage
from .raw_client import AsyncRawAgentsClient, RawAgentsClient
from .requests.agent_log_request_agent import AgentLogRequestAgentParams
from .requests.agent_log_request_tool_choice import AgentLogRequestToolChoiceParams
from .requests.agent_request_reasoning_effort import AgentRequestReasoningEffortParams
from .requests.agent_request_stop import AgentRequestStopParams
from .requests.agent_request_template import AgentRequestTemplateParams
from .requests.agent_request_tools_item import AgentRequestToolsItemParams
from .requests.agents_call_request_agent import AgentsCallRequestAgentParams
from .requests.agents_call_request_tool_choice import AgentsCallRequestToolChoiceParams
from .requests.agents_call_stream_request_agent import AgentsCallStreamRequestAgentParams
from .requests.agents_call_stream_request_tool_choice import AgentsCallStreamRequestToolChoiceParams
# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)
class AgentsClient:
def __init__(self, *, client_wrapper: SyncClientWrapper):
self._raw_client = RawAgentsClient(client_wrapper=client_wrapper)
@property
def with_raw_response(self) -> RawAgentsClient:
"""
Retrieves a raw implementation of this client that returns raw responses.
Returns
-------
RawAgentsClient
"""
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[AgentLogRequestToolChoiceParams] = OMIT,
agent: typing.Optional[AgentLogRequestAgentParams] = 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,
agent_log_request_environment: typing.Optional[str] = OMIT,
save: typing.Optional[bool] = OMIT,
log_id: typing.Optional[str] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> CreateAgentLogResponse:
"""
Create an Agent Log.
You can use query parameters `version_id`, or `environment`, to target
an existing version of the Agent. Otherwise, the default deployed version will be chosen.
If you create the Agent Log with a `log_status` of `incomplete`, you should later update it to `complete`
in order to trigger Evaluators.
Parameters
----------
version_id : typing.Optional[str]
A specific Version ID of the Agent 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 Agent, including the name. This locates the Agent 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 Agent.
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[AgentLogRequestToolChoiceParams]
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.
agent : typing.Optional[AgentLogRequestAgentParams]
The Agent configuration to use. Two formats are supported:
- An object representing the details of the Agent configuration
- A string representing the raw contents of a .agent file
A new Agent 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.
agent_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
-------
CreateAgentLogResponse
Successful Response
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
client.agents.log(path='Banking/Teller Agent', agent={'provider': "anthropic", 'endpoint': "chat", 'model': 'claude-3-7-sonnet-latest', 'reasoning_effort': 1024, 'template': [{'role': "system", 'content': 'You are a helpful digital assistant, helping users navigate our digital banking platform.'}], 'max_iterations': 3, 'tools': [{'type': 'file', 'link': {'file_id': 'pr_1234567890', 'version_id': 'prv_1234567890'}, 'on_agent_call': "continue"}, {'type': 'inline', 'json_schema': {'name': 'stop', 'description': 'Call this tool when you have finished your task.', 'parameters': {'type': 'object'
, 'properties': {'output': {'type': 'string', 'description': 'The final output to return to the user.'}}
, 'additionalProperties': False
, 'required': ['output']
}, 'strict': True}, 'on_agent_call': "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,
agent=agent,
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,
agent_log_request_environment=agent_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,
*,
messages: typing.Optional[typing.Sequence[ChatMessageParams]] = OMIT,
output_message: typing.Optional[ChatMessageParams] = OMIT,
inputs: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
output: typing.Optional[str] = OMIT,
error: typing.Optional[str] = OMIT,
log_status: typing.Optional[LogStatus] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> AgentLogResponse:
"""
Update a Log.
Update the details of a Log with the given ID.
Parameters
----------
id : str
Unique identifier for Agent.
log_id : str
Unique identifier for the Log.
messages : typing.Optional[typing.Sequence[ChatMessageParams]]
List of chat messages that were used as an input to the Flow.
output_message : typing.Optional[ChatMessageParams]
The output message returned by this Flow.
inputs : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
The inputs passed to the Flow Log.
output : typing.Optional[str]
The output of the Flow Log. Provide None to unset existing `output` value. Provide either this, `output_message` or `error`.
error : typing.Optional[str]
The error message of the Flow Log. Provide None to unset existing `error` value. Provide either this, `output_message` or `output`.
log_status : typing.Optional[LogStatus]
Status of the Flow Log. When a Flow Log is updated to `complete`, no more Logs can be added to it. You cannot update a Flow Log's status from `complete` to `incomplete`.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
AgentLogResponse
Successful Response
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
client.agents.update_log(id='ag_1234567890', log_id='log_1234567890', messages=[{'role': "user", 'content': 'I need to withdraw $1000'}, {'role': "assistant", 'content': 'Of course! Would you like to use your savings or checking account?'}], output_message={'role': "assistant", 'content': "I'm sorry, I can't help with that."}, log_status="complete", )
"""
_response = self._raw_client.update_log(
id,
log_id,
messages=messages,
output_message=output_message,
inputs=inputs,
output=output,
error=error,
log_status=log_status,
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[AgentsCallStreamRequestToolChoiceParams] = OMIT,
agent: typing.Optional[AgentsCallStreamRequestAgentParams] = 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,
agents_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,
return_inputs: typing.Optional[bool] = OMIT,
include_trace_children: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.Iterator[AgentCallStreamResponse]:
"""
Call an Agent. The Agent will run on the Humanloop runtime and return a completed Agent Log.
If the Agent requires a tool call that cannot be ran by Humanloop, execution will halt. To continue,
pass the ID of the incomplete Log and the required tool call to the /agents/continue endpoint.
The agent will run for the maximum number of iterations, or until it encounters a stop condition,
according to its configuration.
You can use query parameters `version_id`, or `environment`, to target
an existing version of the Agent. Otherwise the default deployed version will be chosen.
Instead of targeting an existing version explicitly, you can instead pass in
Agent details in the request body. A new version is created if it does not match
any existing ones. This is helpful in the case where you are storing or deriving
your Agent details in code.
Parameters
----------
version_id : typing.Optional[str]
A specific Version ID of the Agent 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 Agent, including the name. This locates the Agent 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 Agent.
messages : typing.Optional[typing.Sequence[ChatMessageParams]]
The messages passed to the to provider chat endpoint.
tool_choice : typing.Optional[AgentsCallStreamRequestToolChoiceParams]
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.
agent : typing.Optional[AgentsCallStreamRequestAgentParams]
The Agent configuration to use. Two formats are supported:
- An object representing the details of the Agent configuration
- A string representing the raw contents of a .agent file
<<<<<<< HEAD
=======
>>>>>>> 190233f (Merge branch 'master' into flow-complete-dx)
A new Agent 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.
agents_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.
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.
include_trace_children : typing.Optional[bool]
If true, populate `trace_children` for the returned Agent Log. Only applies when not streaming. Defaults to false.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Yields
------
typing.Iterator[AgentCallStreamResponse]
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
response = client.agents.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,
agent=agent,
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,
agents_call_stream_request_environment=agents_call_stream_request_environment,
save=save,
log_id=log_id,
provider_api_keys=provider_api_keys,
return_inputs=return_inputs,
include_trace_children=include_trace_children,
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[AgentsCallRequestToolChoiceParams] = OMIT,
agent: typing.Optional[AgentsCallRequestAgentParams] = 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,
agents_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,
return_inputs: typing.Optional[bool] = OMIT,
include_trace_children: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> AgentCallResponse:
"""
Call an Agent. The Agent will run on the Humanloop runtime and return a completed Agent Log.
If the Agent requires a tool call that cannot be ran by Humanloop, execution will halt. To continue,
pass the ID of the incomplete Log and the required tool call to the /agents/continue endpoint.
The agent will run for the maximum number of iterations, or until it encounters a stop condition,
according to its configuration.
You can use query parameters `version_id`, or `environment`, to target
an existing version of the Agent. Otherwise the default deployed version will be chosen.
Instead of targeting an existing version explicitly, you can instead pass in
Agent details in the request body. A new version is created if it does not match
any existing ones. This is helpful in the case where you are storing or deriving
your Agent details in code.
Parameters
----------
version_id : typing.Optional[str]
A specific Version ID of the Agent 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 Agent, including the name. This locates the Agent 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 Agent.
messages : typing.Optional[typing.Sequence[ChatMessageParams]]
The messages passed to the to provider chat endpoint.
tool_choice : typing.Optional[AgentsCallRequestToolChoiceParams]
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.
agent : typing.Optional[AgentsCallRequestAgentParams]
The Agent configuration to use. Two formats are supported:
- An object representing the details of the Agent configuration
- A string representing the raw contents of a .agent file
<<<<<<< HEAD
=======
>>>>>>> 190233f (Merge branch 'master' into flow-complete-dx)
A new Agent 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.
agents_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.
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.
include_trace_children : typing.Optional[bool]
If true, populate `trace_children` for the returned Agent Log. Only applies when not streaming. Defaults to false.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
AgentCallResponse
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
client.agents.call(path='Banking/Teller Agent', messages=[{'role': "user", 'content': "I'd like to deposit $1000 to my savings account from my checking account."}], )
"""
_response = self._raw_client.call(
version_id=version_id,
environment=environment,
path=path,
id=id,
messages=messages,
tool_choice=tool_choice,
agent=agent,
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,
agents_call_request_environment=agents_call_request_environment,
save=save,
log_id=log_id,
provider_api_keys=provider_api_keys,
return_inputs=return_inputs,
include_trace_children=include_trace_children,
request_options=request_options,
)
return _response.data
def continue_call_stream(
self,
*,
log_id: str,
messages: typing.Sequence[ChatMessageParams],
provider_api_keys: typing.Optional[ProviderApiKeysParams] = OMIT,
include_trace_children: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> typing.Iterator[AgentContinueCallStreamResponse]:
"""
Continue an incomplete Agent call.
This endpoint allows continuing an existing incomplete Agent call, by passing the tool call
requested by the Agent. The Agent will resume processing from where it left off.
The messages in the request will be appended to the original messages in the Log. You do not
have to provide the previous conversation history.
The original log must be in an incomplete state to be continued.
Parameters
----------
log_id : str
This identifies the Agent Log to continue.
messages : typing.Sequence[ChatMessageParams]
The additional messages with which to continue the Agent Log. Often, these should start with the Tool messages with results for the previous Assistant message's tool calls.
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.
include_trace_children : typing.Optional[bool]
If true, populate `trace_children` for the returned Agent Log. Defaults to false.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Yields
------
typing.Iterator[AgentContinueCallStreamResponse]
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
response = client.agents.continue_call_stream(log_id='log_id', messages=[{'role': "user"}], )
for chunk in response:
yield chunk
"""
with self._raw_client.continue_call_stream(
log_id=log_id,
messages=messages,
provider_api_keys=provider_api_keys,
include_trace_children=include_trace_children,
request_options=request_options,
) as r:
yield from r.data
def continue_call(
self,
*,
log_id: str,
messages: typing.Sequence[ChatMessageParams],
provider_api_keys: typing.Optional[ProviderApiKeysParams] = OMIT,
include_trace_children: typing.Optional[bool] = OMIT,
request_options: typing.Optional[RequestOptions] = None,
) -> AgentContinueCallResponse:
"""
Continue an incomplete Agent call.
This endpoint allows continuing an existing incomplete Agent call, by passing the tool call
requested by the Agent. The Agent will resume processing from where it left off.
The messages in the request will be appended to the original messages in the Log. You do not
have to provide the previous conversation history.
The original log must be in an incomplete state to be continued.
Parameters
----------
log_id : str
This identifies the Agent Log to continue.
messages : typing.Sequence[ChatMessageParams]
The additional messages with which to continue the Agent Log. Often, these should start with the Tool messages with results for the previous Assistant message's tool calls.
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.
include_trace_children : typing.Optional[bool]
If true, populate `trace_children` for the returned Agent Log. Defaults to false.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
AgentContinueCallResponse
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
client.agents.continue_call(log_id='log_1234567890', messages=[{'role': "tool", 'content': '{"type": "checking", "balance": 5200}', 'tool_call_id': 'tc_1234567890'}], )
"""
_response = self._raw_client.continue_call(
log_id=log_id,
messages=messages,
provider_api_keys=provider_api_keys,
include_trace_children=include_trace_children,
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[AgentResponse]:
"""
Get a list of all Agents.
Parameters
----------
page : typing.Optional[int]
Page number for pagination.
size : typing.Optional[int]
Page size for pagination. Number of Agents to fetch.
name : typing.Optional[str]
Case-insensitive filter for Agent name.
user_filter : typing.Optional[str]
Case-insensitive filter for users in the Agent. This filter matches against both email address and name of users.
sort_by : typing.Optional[FileSortBy]
Field to sort Agents by
order : typing.Optional[SortOrder]
Direction to sort by.
request_options : typing.Optional[RequestOptions]
Request-specific configuration.
Returns
-------
SyncPager[AgentResponse]
Successful Response
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
response = client.agents.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[AgentRequestTemplateParams] = 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[AgentRequestStopParams] = 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[AgentRequestReasoningEffortParams] = OMIT,
tools: typing.Optional[typing.Sequence[AgentRequestToolsItemParams]] = OMIT,
attributes: typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]] = OMIT,
max_iterations: typing.Optional[int] = 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,
) -> AgentResponse:
"""
Create an Agent or update it with a new version if it already exists.
Agents are identified by the `ID` or their `path`. The parameters (i.e. the template, temperature, model etc.) and
tools determine the versions of the Agent.
You can provide `version_name` and `version_description` to identify and describe your versions.
Version names must be unique within an Agent - 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 Agent, including the name. This locates the Agent 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 Agent.
endpoint : typing.Optional[ModelEndpoints]
The provider model endpoint used.
template : typing.Optional[AgentRequestTemplateParams]
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[AgentRequestStopParams]
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[AgentRequestReasoningEffortParams]
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[AgentRequestToolsItemParams]]
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.
max_iterations : typing.Optional[int]
The maximum number of iterations the Agent can run. This is used to limit the number of times the Agent model is called.
version_name : typing.Optional[str]
Unique name for the Prompt version. Each Prompt can only have one version with a given name.
version_description : typing.Optional[str]
Description of the 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
-------
AgentResponse
Successful Response
Examples
--------
from humanloop import Humanloop
client = Humanloop(api_key="YOUR_API_KEY", )
client.agents.upsert(path='Banking/Teller Agent', provider="anthropic", endpoint="chat", model='claude-3-7-sonnet-latest', reasoning_effort=1024, template=[{'role': "system", 'content': 'You are a helpful digital assistant, helping users navigate our digital banking platform.'}], max_iterations=3, tools=[{'type': 'inline', 'json_schema': {'name': 'stop', 'description': 'Call this tool when you have finished your task.', 'parameters': {'type': 'object'
, 'properties': {'output': {'type': 'string', 'description': 'The final output to return to the user.'}}
, 'additionalProperties': False
, 'required': ['output']
}, 'strict': True}, 'on_agent_call': "stop"}], version_name='teller-agent-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,