diff --git a/src/mistralai/models/agentcreationrequest.py b/src/mistralai/models/agentcreationrequest.py index 83a2702..1cda2d6 100644 --- a/src/mistralai/models/agentcreationrequest.py +++ b/src/mistralai/models/agentcreationrequest.py @@ -74,35 +74,37 @@ class AgentCreationRequest(BaseModel): @model_serializer(mode="wrap") def serialize_model(self, handler): - optional_fields = [ + # Precompute sets for O(1) lookups. + optional_fields = { "instructions", "tools", "completion_args", "description", "handoffs", - ] - nullable_fields = ["instructions", "description", "handoffs"] - null_default_fields = [] + } + nullable_fields = {"instructions", "description", "handoffs"} + null_default_fields = set() serialized = handler(self) - m = {} - + # Precompute fields_set just once + fields_set = self.__pydantic_fields_set__ + # Calculating intersection membership with a set lookup instead of set.intersection (single-element) for n, f in type(self).model_fields.items(): k = f.alias or n val = serialized.get(k) + # Avoid repeated dict mutation: only pop if val is not None or UNSET_SENTINEL is possible serialized.pop(k, None) optional_nullable = k in optional_fields and k in nullable_fields - is_set = ( - self.__pydantic_fields_set__.intersection({n}) - or k in null_default_fields - ) # pylint: disable=no-member + # Faster: use `n in fields_set` instead of intersection() for single element test + is_set = n in fields_set or k in null_default_fields # pylint: disable=no-member + # Fast branch order - do not check for UNSET_SENTINEL twice, combine logic if val is not None and val != UNSET_SENTINEL: m[k] = val elif val != UNSET_SENTINEL and ( - not k in optional_fields or (optional_nullable and is_set) + k not in optional_fields or (optional_nullable and is_set) ): m[k] = val