forked from microsoft/agent-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_models.py
More file actions
1137 lines (985 loc) · 39.3 KB
/
_models.py
File metadata and controls
1137 lines (985 loc) · 39.3 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
# Copyright (c) Microsoft. All rights reserved.
from __future__ import annotations
import logging
import os
from collections.abc import MutableMapping
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any, Literal, TypeVar, Union, overload
from agent_framework._serialization import SerializationMixin
if TYPE_CHECKING:
from powerfx import Engine
_engine_initialized = False
_engine: Engine | None = None
def _get_engine() -> Engine | None:
"""Lazily initialize the PowerFx engine on first use."""
global _engine_initialized, _engine
if not _engine_initialized:
_engine_initialized = True
try:
from powerfx import Engine
_engine = Engine()
except (ImportError, RuntimeError):
# ImportError: powerfx package not installed
# RuntimeError: .NET runtime not available or misconfigured
pass
return _engine
logger = logging.getLogger("agent_framework.declarative")
# Context variable for safe_mode setting.
# When True (default), environment variables are NOT accessible in PowerFx expressions.
# When False, environment variables CAN be accessed via Env symbol in PowerFx.
_safe_mode_context: ContextVar[bool] = ContextVar("safe_mode", default=True)
@overload
def _try_powerfx_eval(value: None, log_value: bool = True) -> None: ...
@overload
def _try_powerfx_eval(value: str, log_value: bool = True) -> str: ...
def _try_powerfx_eval(value: str | None, log_value: bool = True) -> str | None:
"""Check if a value refers to a environment variable and parse it if so.
Args:
value: The value to check.
log_value: Whether to log additional context on error.
"""
if value is None:
return value
if not value.startswith("="):
return value
engine = _get_engine()
if engine is None:
logger.warning(
"PowerFx engine not available for evaluating values starting with '='. "
"Ensure you are on python 3.13 or less and have the powerfx package installed. "
"Otherwise replace all powerfx statements in your yaml with strings."
)
return value
try:
safe_mode = _safe_mode_context.get()
if safe_mode:
return engine.eval(value[1:])
return engine.eval(value[1:], symbols={"Env": dict(os.environ)})
except Exception as exc:
if log_value:
logger.debug("PowerFx evaluation failed for a value: %s", exc)
else:
logger.debug("PowerFx evaluation failed for a value (details redacted): %s", exc)
return value
class Binding(SerializationMixin):
"""Object representing a tool argument binding."""
def __init__(
self,
name: str | None = None,
input: str | None = None,
) -> None:
self.name = _try_powerfx_eval(name)
self.input = _try_powerfx_eval(input)
class Property(SerializationMixin):
"""Object representing a property in a schema."""
def __init__(
self,
name: str | None = None,
kind: str | None = None,
description: str | None = None,
required: bool | None = None,
default: Any | None = None,
example: Any | None = None,
enum: list[Any] | None = None,
) -> None:
self.name = _try_powerfx_eval(name)
self.kind = _try_powerfx_eval(kind)
self.description = _try_powerfx_eval(description)
self.required = required
self.default = default
self.example = example
self.enum = enum or []
@classmethod
def from_dict(
cls, value: MutableMapping[str, Any], /, *, dependencies: MutableMapping[str, Any] | None = None
) -> Property:
"""Create a Property instance from a dictionary, dispatching to the appropriate subclass."""
# Only dispatch if we're being called on the base Property class
if cls is not Property:
# We're being called on a subclass, use the normal from_dict
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
# The YAML spec uses 'type' for the data type, but Property stores it as 'kind'
if "type" in value:
if "kind" not in value:
value["kind"] = value.pop("type")
else:
value.pop("type")
kind = value.get("kind", "")
if kind == "array":
return ArrayProperty.from_dict(value, dependencies=dependencies)
if kind == "object":
return ObjectProperty.from_dict(value, dependencies=dependencies)
# Default to Property for kind="property" or empty
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
class ArrayProperty(Property):
"""Object representing an array property."""
def __init__(
self,
name: str | None = None,
kind: str = "array",
description: str | None = None,
required: bool | None = None,
default: Any | None = None,
example: Any | None = None,
enum: list[Any] | None = None,
items: Property | None = None,
) -> None:
super().__init__(
name=name,
kind=kind,
description=description,
required=required,
default=default,
example=example,
enum=enum,
)
if not isinstance(items, Property) and items is not None:
items = Property.from_dict(items)
self.items = items
class ObjectProperty(Property):
"""Object representing an object property."""
def __init__(
self,
name: str | None = None,
kind: str = "object",
description: str | None = None,
required: bool | None = None,
default: Any | None = None,
example: Any | None = None,
enum: list[Any] | None = None,
properties: list[Property] | dict[str, dict[str, Any]] | None = None,
) -> None:
super().__init__(
name=name,
kind=kind,
description=description,
required=required,
default=default,
example=example,
enum=enum,
)
converted_properties: list[Property] = []
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, Property):
prop = Property.from_dict(prop)
converted_properties.append(prop)
elif isinstance(properties, dict):
for k, v in properties.items():
temp_prop = {"name": k, **v}
prop = Property.from_dict(temp_prop)
converted_properties.append(prop)
self.properties = converted_properties
class PropertySchema(SerializationMixin):
"""Object representing a property schema."""
def __init__(
self,
examples: list[dict[str, Any]] | None = None,
strict: bool = False,
properties: list[Property] | dict[str, dict[str, Any]] | None = None,
) -> None:
self.examples = examples or []
self.strict = strict
converted_properties: list[Property] = []
if isinstance(properties, list):
for prop in properties:
if not isinstance(prop, Property):
prop = Property.from_dict(prop)
converted_properties.append(prop)
elif isinstance(properties, dict):
for k, v in properties.items():
temp_prop = {"name": k, **v}
prop = Property.from_dict(temp_prop)
converted_properties.append(prop)
self.properties = converted_properties
@classmethod
def from_dict(
cls, value: MutableMapping[str, Any], /, *, dependencies: MutableMapping[str, Any] | None = None
) -> PropertySchema:
"""Create a PropertySchema instance from a dictionary, filtering out 'kind' field."""
# Filter out 'kind', 'type', 'name', and 'description' fields that may appear in YAML
# but aren't PropertySchema params
kwargs = {k: v for k, v in value.items() if k not in ("type", "kind", "name", "description")}
return SerializationMixin.from_dict.__func__(cls, kwargs, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
def to_json_schema(self) -> dict[str, Any]:
"""Get a schema out of this PropertySchema to create pydantic models."""
json_schema = self.to_dict(exclude={"type"}, exclude_none=True)
new_props = {}
required_fields: list[str] = []
for prop in json_schema.get("properties", []):
prop_name = prop.pop("name")
prop["type"] = prop.pop("kind", None)
# Convert property-level 'required' boolean to a top-level 'required' array
if prop.pop("required", False):
required_fields.append(prop_name)
# Remove empty enum arrays
if not prop.get("enum"):
prop.pop("enum", None)
new_props[prop_name] = prop
json_schema["type"] = "object"
json_schema["properties"] = new_props
if required_fields:
json_schema["required"] = required_fields
return json_schema
ConnectionT = TypeVar("ConnectionT", bound="Connection")
class Connection(SerializationMixin):
"""Object representing a connection specification."""
def __init__(
self,
kind: Literal["reference", "remote", "key", "anonymous"],
authenticationMode: str | None = None,
usageDescription: str | None = None,
) -> None:
self.kind = kind
self.authenticationMode = _try_powerfx_eval(authenticationMode)
self.usageDescription = _try_powerfx_eval(usageDescription)
@classmethod
def from_dict(
cls: type[ConnectionT],
value: MutableMapping[str, Any],
/,
*,
dependencies: MutableMapping[str, Any] | None = None,
) -> ConnectionT:
"""Create a Connection instance from a dictionary, dispatching to the appropriate subclass."""
# Only dispatch if we're being called on the base Connection class
if cls is not Connection:
# We're being called on a subclass, use the normal from_dict
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
kind = value.get("kind", "").lower()
if kind == "reference":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
ReferenceConnection, value, dependencies=dependencies
)
if kind == "remote":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
RemoteConnection, value, dependencies=dependencies
)
if kind in ("key", "apikey"):
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
ApiKeyConnection, value, dependencies=dependencies
)
if kind == "anonymous":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
AnonymousConnection, value, dependencies=dependencies
)
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
class ReferenceConnection(Connection):
"""Object representing a reference connection."""
def __init__(
self,
kind: Literal["reference"] = "reference",
authenticationMode: str | None = None,
usageDescription: str | None = None,
name: str | None = None,
target: str | None = None,
) -> None:
super().__init__(
kind=kind,
authenticationMode=authenticationMode,
usageDescription=usageDescription,
)
self.name = _try_powerfx_eval(name)
self.target = _try_powerfx_eval(target)
class RemoteConnection(Connection):
"""Object representing a remote connection."""
def __init__(
self,
kind: Literal["remote"] = "remote",
authenticationMode: str | None = None,
usageDescription: str | None = None,
name: str | None = None,
endpoint: str | None = None,
) -> None:
super().__init__(
kind=kind,
authenticationMode=authenticationMode,
usageDescription=usageDescription,
)
self.name = _try_powerfx_eval(name)
self.endpoint = _try_powerfx_eval(endpoint)
class ApiKeyConnection(Connection):
"""Object representing an API key connection."""
def __init__(
self,
kind: Literal["key"] = "key",
authenticationMode: str | None = None,
usageDescription: str | None = None,
endpoint: str | None = None,
apiKey: str | None = None,
key: str | None = None,
) -> None:
super().__init__(
kind=kind,
authenticationMode=authenticationMode,
usageDescription=usageDescription,
)
self.endpoint = _try_powerfx_eval(endpoint)
# Support both 'apiKey' and 'key' fields, with 'key' taking precedence if both are provided
self.apiKey = _try_powerfx_eval(key if key else apiKey, False)
class AnonymousConnection(Connection):
"""Object representing an anonymous connection."""
def __init__(
self,
kind: Literal["anonymous"] = "anonymous",
authenticationMode: str | None = None,
usageDescription: str | None = None,
endpoint: str | None = None,
) -> None:
super().__init__(
kind=kind,
authenticationMode=authenticationMode,
usageDescription=usageDescription,
)
self.endpoint = _try_powerfx_eval(endpoint)
Connections = Union[
ReferenceConnection,
RemoteConnection,
ApiKeyConnection,
AnonymousConnection,
]
class ModelOptions(SerializationMixin):
"""Object representing model options."""
def __init__(
self,
frequencyPenalty: float | None = None,
maxOutputTokens: int | None = None,
presencePenalty: float | None = None,
seed: int | None = None,
temperature: float | None = None,
topK: int | None = None,
topP: float | None = None,
stopSequences: list[str] | None = None,
allowMultipleToolCalls: bool | None = None,
additionalProperties: dict[str, Any] | None = None,
**kwargs: Any,
) -> None:
self.frequencyPenalty = frequencyPenalty
self.maxOutputTokens = maxOutputTokens
self.presencePenalty = presencePenalty
self.seed = seed
self.temperature = temperature
self.topK = topK
self.topP = topP
self.stopSequences = stopSequences or []
self.allowMultipleToolCalls = allowMultipleToolCalls
# Merge any additional properties from kwargs into additionalProperties
self.additionalProperties = additionalProperties or {}
self.additionalProperties.update(kwargs)
class Model(SerializationMixin):
"""Object representing a model specification."""
def __init__(
self,
id: str | None = None,
provider: str | None = None,
apiType: str | None = None,
connection: Connections | None = None,
options: ModelOptions | None = None,
) -> None:
self.id = _try_powerfx_eval(id)
self.provider = _try_powerfx_eval(provider)
self.apiType = _try_powerfx_eval(apiType)
if not isinstance(connection, Connection) and connection is not None:
connection = Connection.from_dict(connection)
self.connection = connection
if not isinstance(options, ModelOptions) and options is not None:
options = ModelOptions.from_dict(options)
self.options = options
class Format(SerializationMixin):
"""Object representing template format."""
def __init__(
self,
kind: str | None = None,
strict: bool = False,
options: dict[str, Any] | None = None,
) -> None:
self.kind = _try_powerfx_eval(kind)
self.strict = strict
self.options = options or {}
class Parser(SerializationMixin):
"""Object representing template parser."""
def __init__(
self,
kind: str | None = None,
options: dict[str, Any] | None = None,
) -> None:
self.kind = _try_powerfx_eval(kind)
self.options = options or {}
class Template(SerializationMixin):
"""Object representing a template configuration."""
def __init__(
self,
format: Format | None = None,
parser: Parser | None = None,
) -> None:
if not isinstance(format, Format) and format is not None:
format = Format.from_dict(format)
self.format = format
if not isinstance(parser, Parser) and parser is not None:
parser = Parser.from_dict(parser)
self.parser = parser
class AgentDefinition(SerializationMixin):
"""Object representing a prompt specification."""
def __init__(
self,
kind: str | None = None,
name: str | None = None,
displayName: str | None = None,
description: str | None = None,
metadata: dict[str, Any] | None = None,
inputSchema: PropertySchema | None = None,
outputSchema: PropertySchema | None = None,
) -> None:
self.kind = _try_powerfx_eval(kind)
self.name = _try_powerfx_eval(name)
self.displayName = _try_powerfx_eval(displayName)
self.description = _try_powerfx_eval(description)
self.metadata = metadata
if not isinstance(inputSchema, PropertySchema) and inputSchema is not None:
inputSchema = PropertySchema.from_dict(inputSchema)
self.inputSchema = inputSchema
if not isinstance(outputSchema, PropertySchema) and outputSchema is not None:
outputSchema = PropertySchema.from_dict(outputSchema)
self.outputSchema = outputSchema
@classmethod
def from_dict(
cls, value: MutableMapping[str, Any], /, *, dependencies: MutableMapping[str, Any] | None = None
) -> AgentDefinition:
"""Create an AgentDefinition instance from a dictionary, dispatching to the appropriate subclass."""
# Only dispatch if we're being called on the base AgentDefinition class
if cls is not AgentDefinition:
# We're being called on a subclass, use the normal from_dict
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
kind = value.get("kind", "")
if kind == "Prompt" or kind == "Agent":
return PromptAgent.from_dict(value, dependencies=dependencies)
# Default to AgentDefinition
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
ToolT = TypeVar("ToolT", bound="Tool")
class Tool(SerializationMixin):
"""Base class for tools."""
def __init__(
self,
name: str | None = None,
kind: str | None = None,
description: str | None = None,
bindings: list[Binding] | dict[str, Any] | None = None,
) -> None:
self.name = _try_powerfx_eval(name)
self.kind = _try_powerfx_eval(kind)
self.description = _try_powerfx_eval(description)
converted_bindings: list[Binding] = []
if isinstance(bindings, list):
for binding in bindings:
if not isinstance(binding, Binding):
binding = Binding.from_dict(binding)
converted_bindings.append(binding)
elif isinstance(bindings, dict):
for k, v in bindings.items():
temp_binding = {"name": k, "input": v} if isinstance(v, str) else {"name": k, **v}
binding = Binding.from_dict(temp_binding)
converted_bindings.append(binding)
self.bindings = converted_bindings
@classmethod
def from_dict(
cls: type[ToolT], value: MutableMapping[str, Any], /, *, dependencies: MutableMapping[str, Any] | None = None
) -> ToolT:
"""Create a Tool instance from a dictionary, dispatching to the appropriate subclass."""
# Only dispatch if we're being called on the base Tool class
if cls is not Tool:
# We're being called on a subclass, use the normal from_dict
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
kind = value.get("kind", "")
if kind == "function":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
FunctionTool, value, dependencies=dependencies
)
if kind == "custom":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
CustomTool, value, dependencies=dependencies
)
if kind == "web_search":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
WebSearchTool, value, dependencies=dependencies
)
if kind == "file_search":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
FileSearchTool, value, dependencies=dependencies
)
if kind == "mcp":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
McpTool, value, dependencies=dependencies
)
if kind == "openapi":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
OpenApiTool, value, dependencies=dependencies
)
if kind == "code_interpreter":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
CodeInterpreterTool, value, dependencies=dependencies
)
# Default to base Tool class
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
class FunctionTool(Tool):
"""Object representing a function tool."""
def __init__(
self,
name: str | None = None,
kind: str = "function",
description: str | None = None,
bindings: list[Binding] | None = None,
parameters: PropertySchema | list[Property] | dict[str, Any] | None = None,
strict: bool = False,
) -> None:
super().__init__(
name=name,
kind=kind,
description=description,
bindings=bindings,
)
if isinstance(parameters, list):
# If parameters is a list, wrap it in a PropertySchema
parameters = PropertySchema(properties=parameters)
elif not isinstance(parameters, PropertySchema) and parameters is not None:
parameters = PropertySchema.from_dict(parameters)
self.parameters = parameters
self.strict = strict
class CustomTool(Tool):
"""Object representing a custom tool."""
def __init__(
self,
name: str | None = None,
kind: str = "custom",
description: str | None = None,
bindings: list[Binding] | None = None,
connection: Connection | None = None,
options: dict[str, Any] | None = None,
) -> None:
super().__init__(
name=name,
kind=kind,
description=description,
bindings=bindings,
)
if not isinstance(connection, Connection) and connection is not None:
connection = Connection.from_dict(connection)
self.connection = connection
self.options = options or {}
class WebSearchTool(Tool):
"""Object representing a web search tool."""
def __init__(
self,
name: str | None = None,
kind: str = "web_search",
description: str | None = None,
bindings: list[Binding] | None = None,
connection: Connection | None = None,
options: dict[str, Any] | None = None,
) -> None:
super().__init__(
name=name,
kind=kind,
description=description,
bindings=bindings,
)
if not isinstance(connection, Connection) and connection is not None:
connection = Connection.from_dict(connection)
self.connection = connection
self.options = options or {}
class FileSearchTool(Tool):
"""Object representing a file search tool."""
def __init__(
self,
name: str | None = None,
kind: str = "file_search",
description: str | None = None,
bindings: list[Binding] | None = None,
connection: Connection | None = None,
vectorStoreIds: list[str] | None = None,
maximumResultCount: int | None = None,
ranker: str | None = None,
scoreThreshold: float | None = None,
filters: dict[str, Any] | None = None,
) -> None:
super().__init__(
name=name,
kind=kind,
description=description,
bindings=bindings,
)
if not isinstance(connection, Connection) and connection is not None:
connection = Connection.from_dict(connection)
self.connection = connection
self.vectorStoreIds = vectorStoreIds or []
self.maximumResultCount = maximumResultCount
self.ranker = _try_powerfx_eval(ranker)
self.scoreThreshold = scoreThreshold
self.filters = filters or {}
class McpServerApprovalMode(SerializationMixin):
"""Base class for MCP server approval modes."""
def __init__(
self,
kind: str | None = None,
) -> None:
self.kind = _try_powerfx_eval(kind)
class McpServerToolAlwaysRequireApprovalMode(McpServerApprovalMode):
"""MCP server tool always require approval mode."""
def __init__(
self,
kind: str = "always",
) -> None:
super().__init__(kind=kind)
class McpServerToolNeverRequireApprovalMode(McpServerApprovalMode):
"""MCP server tool never require approval mode."""
def __init__(
self,
kind: str = "never",
) -> None:
super().__init__(kind=kind)
class McpServerToolSpecifyApprovalMode(McpServerApprovalMode):
"""MCP server tool specify approval mode."""
def __init__(
self,
kind: str = "specify",
alwaysRequireApprovalTools: list[str] | None = None,
neverRequireApprovalTools: list[str] | None = None,
) -> None:
super().__init__(kind=kind)
self.alwaysRequireApprovalTools = alwaysRequireApprovalTools
self.neverRequireApprovalTools = neverRequireApprovalTools
class McpTool(Tool):
"""Object representing an MCP tool."""
def __init__(
self,
name: str | None = None,
kind: str = "mcp",
description: str | None = None,
bindings: list[Binding] | None = None,
connection: Connection | None = None,
serverName: str | None = None,
serverDescription: str | None = None,
approvalMode: McpServerApprovalMode | None = None,
allowedTools: list[str] | None = None,
url: str | None = None,
) -> None:
super().__init__(
name=name,
kind=kind,
description=description,
bindings=bindings,
)
if not isinstance(connection, Connection) and connection is not None:
connection = Connection.from_dict(connection)
self.connection = connection
self.serverName = _try_powerfx_eval(serverName)
self.serverDescription = _try_powerfx_eval(serverDescription)
if not isinstance(approvalMode, McpServerApprovalMode) and approvalMode is not None:
# Handle simplified string format: "always" -> {"kind": "always"}
if isinstance(approvalMode, str):
approvalMode = McpServerApprovalMode.from_dict({"kind": approvalMode})
else:
approvalMode = McpServerApprovalMode.from_dict(approvalMode)
self.approvalMode = approvalMode
self.allowedTools = allowedTools or []
self.url = _try_powerfx_eval(url)
class OpenApiTool(Tool):
"""Object representing an OpenAPI tool."""
def __init__(
self,
name: str | None = None,
kind: str = "openapi",
description: str | None = None,
bindings: list[Binding] | None = None,
connection: Connection | None = None,
specification: str | None = None,
) -> None:
super().__init__(
name=name,
kind=kind,
description=description,
bindings=bindings,
)
if not isinstance(connection, Connection) and connection is not None:
connection = Connection.from_dict(connection)
self.connection = connection
self.specification = _try_powerfx_eval(specification)
class CodeInterpreterTool(Tool):
"""Object representing a code interpreter tool."""
def __init__(
self,
name: str | None = None,
kind: str = "code_interpreter",
description: str | None = None,
bindings: list[Binding] | None = None,
fileIds: list[str] | None = None,
) -> None:
super().__init__(
name=name,
kind=kind,
description=description,
bindings=bindings,
)
self.fileIds = fileIds or []
class PromptAgent(AgentDefinition):
"""Object representing a prompt agent specification."""
def __init__(
self,
kind: str = "Prompt",
name: str | None = None,
displayName: str | None = None,
description: str | None = None,
metadata: dict[str, Any] | None = None,
inputSchema: PropertySchema | None = None,
outputSchema: PropertySchema | None = None,
model: Model | dict[str, Any] | None = None,
tools: list[Tool] | None = None,
template: Template | dict[str, Any] | None = None,
instructions: str | None = None,
additionalInstructions: str | None = None,
) -> None:
super().__init__(
kind=kind,
name=name,
displayName=displayName,
description=description,
metadata=metadata,
inputSchema=inputSchema,
outputSchema=outputSchema,
)
if not isinstance(model, Model) and model is not None:
model = Model.from_dict(model)
self.model = model
converted_tools: list[Tool] = []
for tool in tools or []:
if not isinstance(tool, Tool):
tool = Tool.from_dict(tool)
converted_tools.append(tool)
self.tools = converted_tools
if not isinstance(template, Template) and template is not None:
template = Template.from_dict(template)
self.template = template
self.instructions = _try_powerfx_eval(instructions)
self.additionalInstructions = _try_powerfx_eval(additionalInstructions)
class Resource(SerializationMixin):
"""Object representing a resource."""
def __init__(
self,
name: str | None = None,
kind: str | None = None,
) -> None:
self.name = _try_powerfx_eval(name)
self.kind = _try_powerfx_eval(kind)
@classmethod
def from_dict(
cls, value: MutableMapping[str, Any], /, *, dependencies: MutableMapping[str, Any] | None = None
) -> Resource:
"""Create a Resource instance from a dictionary, dispatching to the appropriate subclass."""
# Only dispatch if we're being called on the base Resource class
if cls is not Resource:
# We're being called on a subclass, use the normal from_dict
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
kind = value.get("kind", "")
if kind == "model":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
ModelResource, value, dependencies=dependencies
)
if kind == "tool":
return SerializationMixin.from_dict.__func__( # type: ignore[attr-defined, no-any-return]
ToolResource, value, dependencies=dependencies
)
return SerializationMixin.from_dict.__func__(cls, value, dependencies=dependencies) # type: ignore[attr-defined, no-any-return]
class ModelResource(Resource):
"""Object representing a model resource."""
def __init__(
self,
kind: str = "model",
name: str | None = None,
id: str | None = None,
) -> None:
super().__init__(kind=kind, name=name)
self.id = _try_powerfx_eval(id)
class ToolResource(Resource):
"""Object representing a tool resource."""
def __init__(
self,
kind: str = "tool",
name: str | None = None,
id: str | None = None,
options: dict[str, Any] | None = None,
) -> None:
super().__init__(kind=kind, name=name)
self.id = _try_powerfx_eval(id)
self.options = options or {}
class ProtocolVersionRecord(SerializationMixin):
"""Object representing a protocol version record."""
def __init__(
self,
protocol: str | None = None,
version: str | None = None,
) -> None:
self.protocol = _try_powerfx_eval(protocol)
self.version = _try_powerfx_eval(version)
class EnvironmentVariable(SerializationMixin):
"""Object representing an environment variable."""
def __init__(
self,
name: str | None = None,
value: str | None = None,
) -> None:
self.name = _try_powerfx_eval(name)
self.value = _try_powerfx_eval(value)
class AgentManifest(SerializationMixin):
"""Object representing an agent manifest."""
def __init__(
self,
name: str | None = None,
displayName: str | None = None,
description: str | None = None,
metadata: dict[str, Any] | None = None,
template: AgentDefinition | None = None,
parameters: PropertySchema | None = None,
resources: list[Resource] | dict[str, Any] | None = None,
) -> None:
self.name = _try_powerfx_eval(name)
self.displayName = _try_powerfx_eval(displayName)
self.description = _try_powerfx_eval(description)
self.metadata = metadata or {}
if not isinstance(template, AgentDefinition) and template is not None:
template = AgentDefinition.from_dict(template)
self.template = template or AgentDefinition()
if not isinstance(parameters, PropertySchema) and parameters is not None:
parameters = PropertySchema.from_dict(parameters)
self.parameters = parameters or PropertySchema()
converted_resources: list[Resource] = []
if isinstance(resources, list):
for resource in resources:
if not isinstance(resource, Resource):
resource = Resource.from_dict(resource)
converted_resources.append(resource)
elif isinstance(resources, dict):
for k, v in resources.items():