diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/_channel_id_field_mixin.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/_channel_id_field_mixin.py index 38101b87..f510fa16 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/_channel_id_field_mixin.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/_channel_id_field_mixin.py @@ -4,7 +4,7 @@ from __future__ import annotations import logging -from typing import Optional, Any +from typing import Any from pydantic import ( ModelWrapValidatorHandler, @@ -25,12 +25,12 @@ class _ChannelIdFieldMixin: """A mixin to add a computed field channel_id of type ChannelId to a Pydantic model.""" - _channel_id: Optional[ChannelId] = None + _channel_id: ChannelId | None = None # required to define the setter below - @computed_field(return_type=Optional[ChannelId], alias="channelId") + @computed_field(return_type=ChannelId | None, alias="channelId") @property - def channel_id(self) -> Optional[ChannelId]: + def channel_id(self) -> ChannelId | None: """Gets the _channel_id field""" return self._channel_id diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/activity.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/activity.py index b146a459..c6fec56b 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/activity.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/activity.py @@ -6,7 +6,7 @@ import logging from copy import copy from datetime import datetime, timezone -from typing import Optional, Any +from typing import Any, cast from pydantic import ( Field, @@ -15,7 +15,6 @@ model_validator, SerializerFunctionWrapHandler, ModelWrapValidatorHandler, - computed_field, ValidationError, ) @@ -152,7 +151,7 @@ class Activity(AgentsModel, _ChannelIdFieldMixin): """ type: NonEmptyString - id: Optional[NonEmptyString] = None + id: NonEmptyString | None = None timestamp: datetime = None local_timestamp: datetime = None local_timezone: NonEmptyString = None @@ -497,7 +496,7 @@ def create_message_activity(): """ return Activity(type=ActivityTypes.message) - def create_reply(self, text: str = None, locale: str = None): + def create_reply(self, text: str | None = None, locale: str | None = None): """ Creates a new message activity as a response to this activity. @@ -539,7 +538,11 @@ def create_reply(self, text: str = None, locale: str = None): ) def create_trace( - self, name: str, value: object = None, value_type: str = None, label: str = None + self, + name: str, + value: object | None = None, + value_type: str | None = None, + label: str | None = None, ): """ Creates a new trace activity based on this activity. @@ -551,41 +554,47 @@ def create_trace( :returns: The new trace activity. """ - if not value_type and value: + if not value_type and value is not None: value_type = type(value).__name__ - return pick_model( + return cast( Activity, - type=ActivityTypes.trace, - timestamp=datetime.now(timezone.utc), - from_property=SkipNone( - ChannelAccount.pick_properties(self.recipient, ["id", "name"]) - ), - recipient=SkipNone( - ChannelAccount.pick_properties(self.from_property, ["id", "name"]) - ), - reply_to_id=( - SkipNone(self.id) # preserve unset - if type != ActivityTypes.conversation_update - or self.channel_id not in ["directline", "webchat"] - else None - ), - service_url=self.service_url, - channel_id=self.channel_id, - conversation=SkipNone( - ConversationAccount.pick_properties( - self.conversation, ["is_group", "id", "name"] - ) + pick_model( + Activity, + type=ActivityTypes.trace, + timestamp=datetime.now(timezone.utc), + from_property=SkipNone( + ChannelAccount.pick_properties(self.recipient, ["id", "name"]) + ), + recipient=SkipNone( + ChannelAccount.pick_properties(self.from_property, ["id", "name"]) + ), + reply_to_id=( + SkipNone(self.id) # preserve unset + if type != ActivityTypes.conversation_update + or self.channel_id not in ["directline", "webchat"] + else None + ), + service_url=self.service_url, + channel_id=self.channel_id, + conversation=SkipNone( + ConversationAccount.pick_properties( + self.conversation, ["is_group", "id", "name"] + ) + ), + name=SkipNone(name), + label=SkipNone(label), + value_type=SkipNone(value_type), + value=SkipNone(value), ), - name=SkipNone(name), - label=SkipNone(label), - value_type=SkipNone(value_type), - value=SkipNone(value), ).as_trace_activity() @staticmethod def create_trace_activity( - name: str, value: object = None, value_type: str = None, label: str = None + name: str, + value: object | None = None, + value_type: str | None = None, + label: str | None = None, ): """ Creates an instance of the :class:`Activity` class as a TraceActivity object. @@ -597,7 +606,7 @@ def create_trace_activity( :returns: The new trace activity. """ - if not value_type and value: + if not value_type and value is not None: value_type = type(value).__name__ return pick_model( @@ -624,23 +633,26 @@ def get_conversation_reference(self) -> ConversationReference: :returns: A conversation reference for the conversation that contains this activity. """ - return pick_model( + return cast( ConversationReference, - activity_id=( - SkipNone(self.id) - if self.type != ActivityTypes.conversation_update - or self.channel_id not in ["directline", "webchat"] - else None + pick_model( + ConversationReference, + activity_id=( + SkipNone(self.id) + if self.type != ActivityTypes.conversation_update + or self.channel_id not in ["directline", "webchat"] + else None + ), + user=copy(self.from_property), + agent=copy(self.recipient), + conversation=copy(self.conversation), + channel_id=self.channel_id, + locale=self.locale, + service_url=self.service_url, ), - user=copy(self.from_property), - agent=copy(self.recipient), - conversation=copy(self.conversation), - channel_id=self.channel_id, - locale=self.locale, - service_url=self.service_url, ) - def get_product_info_entity(self) -> Optional[ProductInfo]: + def get_product_info_entity(self) -> ProductInfo | None: if not self.entities: return None target = EntityTypes.PRODUCT_INFO.lower() @@ -741,8 +753,8 @@ def __is_activity(self, activity_type: str) -> bool: def add_ai_metadata( self, - citations: Optional[list[ClientCitation]] = None, - usage_info: Optional[SensitivityUsageInfo] = None, + citations: list[ClientCitation] | None = None, + usage_info: SensitivityUsageInfo | None = None, ) -> None: """ Adds AI entity to an activity to indicate AI-generated content. @@ -771,19 +783,19 @@ def is_agentic_request(self) -> bool: RoleTypes.agentic_user, ] - def get_agentic_instance_id(self) -> Optional[str]: + def get_agentic_instance_id(self) -> str | None: """Gets the agent instance ID from the context if it's an agentic request.""" if not self.is_agentic_request() or not self.recipient: return None return self.recipient.agentic_app_id - def get_agentic_user(self) -> Optional[str]: + def get_agentic_user(self) -> str | None: """Gets the agentic user (agenticUserId) from the context if it's an agentic request.""" if not self.is_agentic_request() or not self.recipient: return None return self.recipient.agentic_user_id - def get_agentic_tenant_id(self) -> Optional[str]: + def get_agentic_tenant_id(self) -> str | None: """Gets the agentic tenant ID from the context if it's an agentic request.""" if self.is_agentic_request(): if self.recipient and self.recipient.tenant_id: diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/card_action.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/card_action.py index ec736745..7cf709ac 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/card_action.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/card_action.py @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional from .agents_model import AgentsModel from ._type_aliases import NonEmptyString @@ -38,5 +37,5 @@ class CardAction(AgentsModel): text: str = None display_text: str = None value: object = None - channel_data: Optional[object] = None + channel_data: object | None = None image_alt_text: str = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_account.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_account.py index cb0b7055..c663f7d5 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_account.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_account.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Any, Optional +from typing import Any from pydantic import ConfigDict from .agents_model import AgentsModel @@ -27,11 +27,11 @@ class ChannelAccount(AgentsModel): id: NonEmptyString = None name: str = None - aad_object_id: Optional[NonEmptyString] = None - role: Optional[NonEmptyString] = None - agentic_user_id: Optional[NonEmptyString] = None - agentic_app_id: Optional[NonEmptyString] = None - tenant_id: Optional[NonEmptyString] = None + aad_object_id: NonEmptyString | None = None + role: NonEmptyString | None = None + agentic_user_id: NonEmptyString | None = None + agentic_app_id: NonEmptyString | None = None + tenant_id: NonEmptyString | None = None @property def properties(self) -> dict[str, Any]: diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_adapter_protocol.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_adapter_protocol.py index ce07f248..132cbc6c 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_adapter_protocol.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_adapter_protocol.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. from abc import abstractmethod -from typing import Protocol, List, Callable, Awaitable, Optional +from typing import Protocol, Callable, Awaitable from .turn_context_protocol import TurnContextProtocol from microsoft_agents.activity import ( @@ -14,12 +14,12 @@ class ChannelAdapterProtocol(Protocol): - on_turn_error: Optional[Callable[[TurnContextProtocol, Exception], Awaitable]] + on_turn_error: Callable[[TurnContextProtocol, Exception], Awaitable] | None @abstractmethod async def send_activities( - self, context: TurnContextProtocol, activities: List[Activity] - ) -> List[ResourceResponse]: + self, context: TurnContextProtocol, activities: list[Activity] + ) -> list[ResourceResponse]: pass @abstractmethod @@ -54,7 +54,7 @@ async def continue_conversation_with_claims( claims_identity: dict, continuation_activity: Activity, callback: Callable[[TurnContextProtocol], Awaitable], - audience: str = None, + audience: str | None = None, ): pass diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_id.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_id.py index e8192d6c..0681124e 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_id.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/channel_id.py @@ -3,7 +3,7 @@ from __future__ import annotations -from typing import Optional, Any +from typing import Any from pydantic_core import CoreSchema, core_schema from pydantic import GetCoreSchemaHandler @@ -16,10 +16,10 @@ class ChannelId(str): def __init__( self, - value: Optional[str] = None, + value: str | None = None, *, - channel: Optional[str] = None, - sub_channel: Optional[str] = None, + channel: str | None = None, + sub_channel: str | None = None, ) -> None: """Initialize a ChannelId instance. @@ -39,10 +39,10 @@ def __init__( def __new__( cls, - value: Optional[str] = None, + value: str | None = None, *, - channel: Optional[str] = None, - sub_channel: Optional[str] = None, + channel: str | None = None, + sub_channel: str | None = None, ) -> ChannelId: """Create a new ChannelId instance. @@ -83,7 +83,7 @@ def channel(self) -> str: return self._channel # type: ignore[return-value] @property - def sub_channel(self) -> Optional[str]: + def sub_channel(self) -> str | None: """The sub-channel, e.g. 'work' in 'email:work'. May be None.""" return self._sub_channel diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/conversation_account.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/conversation_account.py index ee62906c..2bb82428 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/conversation_account.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/conversation_account.py @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional from .agents_model import AgentsModel from ._type_aliases import NonEmptyString @@ -31,11 +30,11 @@ class ConversationAccount(AgentsModel): :type properties: object """ - is_group: Optional[bool] = None - conversation_type: Optional[NonEmptyString] = None + is_group: bool | None = None + conversation_type: NonEmptyString | None = None id: NonEmptyString - name: Optional[NonEmptyString] = None - aad_object_id: Optional[NonEmptyString] = None - role: Optional[NonEmptyString] = None - tenant_id: Optional[NonEmptyString] = None + name: NonEmptyString | None = None + aad_object_id: NonEmptyString | None = None + role: NonEmptyString | None = None + tenant_id: NonEmptyString | None = None properties: object = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/conversation_reference.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/conversation_reference.py index 4ec1b4a8..a8405855 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/conversation_reference.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/conversation_reference.py @@ -4,7 +4,6 @@ from __future__ import annotations from uuid import uuid4 as uuid -from typing import Optional import logging from pydantic import Field @@ -46,11 +45,11 @@ class ConversationReference(AgentsModel, _ChannelIdFieldMixin): """ # optionals here are due to webchat - activity_id: Optional[NonEmptyString] = None - user: Optional[ChannelAccount] = None + activity_id: NonEmptyString | None = None + user: ChannelAccount | None = None agent: ChannelAccount = Field(None, alias="bot") conversation: ConversationAccount - locale: Optional[NonEmptyString] = None + locale: NonEmptyString | None = None service_url: NonEmptyString = None def get_continuation_activity(self) -> "Activity": # type: ignore diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/entity/ai_entity.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/entity/ai_entity.py index 68f1a6bf..007eab50 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/entity/ai_entity.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/entity/ai_entity.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. from enum import Enum -from typing import List, Optional, Literal +from typing import Literal from pydantic import Field from ..agents_model import AgentsModel @@ -62,10 +62,10 @@ class SensitivityUsageInfo(AgentsModel, _SchemaMixin): type: str = "https://schema.org/Message" at_type: Literal["CreativeWork"] = "CreativeWork" - description: Optional[str] = None + description: str | None = None name: str = "" - position: Optional[int] = None - pattern: Optional[SensitivityPattern] = None + position: int | None = None + pattern: SensitivityPattern | None = None class ClientCitationAppearance(AgentsModel, _SchemaMixin): @@ -74,13 +74,13 @@ class ClientCitationAppearance(AgentsModel, _SchemaMixin): at_type: Literal["DigitalDocument"] = "DigitalDocument" name: str = "" - text: Optional[str] = None - url: Optional[str] = None + text: str | None = None + url: str | None = None abstract: str = "" - encoding_format: Optional[str] = None - image: Optional[ClientCitationImage] = None - keywords: Optional[List[str]] = None - usage_info: Optional[SensitivityUsageInfo] = None + encoding_format: str | None = None + image: ClientCitationImage | None = None + keywords: list[str] | None = None + usage_info: SensitivityUsageInfo | None = None class ClientCitation(AgentsModel, _SchemaMixin): @@ -107,6 +107,6 @@ class AIEntity(Entity): type: str = "https://schema.org/Message" id: str = "" - additional_type: List[str] = Field(default_factory=lambda: ["AIGeneratedContent"]) - citation: Optional[List[ClientCitation]] = None - usage_info: Optional[SensitivityUsageInfo] = None + additional_type: list[str] = Field(default_factory=lambda: ["AIGeneratedContent"]) + citation: list[ClientCitation] | None = None + usage_info: SensitivityUsageInfo | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/oauth_card.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/oauth_card.py index a59ecf84..106de7fd 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/oauth_card.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/oauth_card.py @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional from .card_action import CardAction from .agents_model import AgentsModel from .token_exchange_resource import TokenExchangeResource @@ -23,5 +22,5 @@ class OAuthCard(AgentsModel): text: str = None connection_name: NonEmptyString = None buttons: list[CardAction] = None - token_exchange_resource: Optional[TokenExchangeResource] = None + token_exchange_resource: TokenExchangeResource | None = None token_post_resource: TokenPostResource = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/app_based_link_query.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/app_based_link_query.py index 703cadc2..065b997e 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/app_based_link_query.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/app_based_link_query.py @@ -2,17 +2,16 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class AppBasedLinkQuery(AgentsModel): """Invoke request body type for app-based link query. :param url: Url queried by user - :type url: Optional[str] + :type url: str | None :param state: The magic code for OAuth Flow - :type state: Optional[str] + :type state: str | None """ - url: Optional[str] - state: Optional[str] + url: str | None + state: str | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/batch_operation_state_response.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/batch_operation_state_response.py index ddb0fff1..37ba0b2d 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/batch_operation_state_response.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/batch_operation_state_response.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from datetime import datetime -from typing import Optional from ..agents_model import AgentsModel @@ -20,5 +19,5 @@ class BatchOperationStateResponse(AgentsModel): state: str = None status_map: dict[int, int] = None - retry_after: Optional[datetime] = None + retry_after: datetime | None = None total_entries_count: int = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/cache_info.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/cache_info.py index af6ec7b4..b155071e 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/cache_info.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/cache_info.py @@ -2,17 +2,16 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class CacheInfo(AgentsModel): """A cache info object which notifies Teams how long an object should be cached for. :param cache_type: Type of Cache Info - :type cache_type: Optional[str] + :type cache_type: str | None :param cache_duration: Duration of the Cached Info. - :type cache_duration: Optional[int] + :type cache_duration: int | None """ - cache_type: Optional[str] - cache_duration: Optional[int] + cache_type: str | None + cache_duration: int | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/channel_info.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/channel_info.py index 3bd5c4ee..61460465 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/channel_info.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/channel_info.py @@ -2,20 +2,19 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class ChannelInfo(AgentsModel): """A channel info object which describes the channel. :param id: Unique identifier representing a channel - :type id: Optional[str] + :type id: str | None :param name: Name of the channel - :type name: Optional[str] + :type name: str | None :param type: The channel type - :type type: Optional[str] + :type type: str | None """ - id: Optional[str] = None - name: Optional[str] = None - type: Optional[str] = None + id: str | None = None + name: str | None = None + type: str | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/conversation_list.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/conversation_list.py index 52ddadf5..f417fa6b 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/conversation_list.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/conversation_list.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List from .channel_info import ChannelInfo @@ -11,7 +10,7 @@ class ConversationList(AgentsModel): """List of channels under a team. :param conversations: List of ChannelInfo objects. - :type conversations: List[ChannelInfo] + :type conversations: list[ChannelInfo] """ - conversations: List[ChannelInfo] + conversations: list[ChannelInfo] diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_consent_card.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_consent_card.py index dc5d9513..47071070 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_consent_card.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_consent_card.py @@ -1,8 +1,9 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +from typing import Any + from ..agents_model import AgentsModel -from typing import Any, Optional class FileConsentCard(AgentsModel): @@ -11,7 +12,7 @@ class FileConsentCard(AgentsModel): :param description: File description. :type description: str :param size_in_bytes: Size of the file to be uploaded in Bytes. - :type size_in_bytes: Optional[int] + :type size_in_bytes: int | None :param accept_context: Context sent back to the Bot if user consented to upload. :type accept_context: Any :param decline_context: Context sent back to the Bot if user declined. @@ -19,6 +20,6 @@ class FileConsentCard(AgentsModel): """ description: str - size_in_bytes: Optional[int] + size_in_bytes: int | None accept_context: Any decline_context: Any diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_consent_card_response.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_consent_card_response.py index 2a1f1804..4160eb57 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_consent_card_response.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_consent_card_response.py @@ -1,21 +1,22 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +from typing import Any + from ..agents_model import AgentsModel -from typing import Any, Optional class FileConsentCardResponse(AgentsModel): """Represents the value of the invoke activity sent when the user acts on a file consent card. :param action: The action the user took. Possible values include: 'accept', 'decline' - :type action: Optional[str] + :type action: str | None :param context: The context associated with the action. - :type context: Optional[Any] + :type context: Any | None :param upload_info: If the user accepted the file, contains information about the file to be uploaded. - :type upload_info: Optional[Any] + :type upload_info: Any | None """ - action: Optional[str] - context: Optional[Any] - upload_info: Optional[Any] + action: str | None + context: Any | None + upload_info: Any | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_download_info.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_download_info.py index 609ab0ae..113ae04e 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_download_info.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_download_info.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class FileDownloadInfo(AgentsModel): @@ -15,10 +14,10 @@ class FileDownloadInfo(AgentsModel): :param file_type: Type of file. :type file_type: str :param etag: ETag for the file. - :type etag: Optional[str] + :type etag: str | None """ download_url: str unique_id: str file_type: str - etag: Optional[str] + etag: str | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_info_card.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_info_card.py index c858b1e8..77e5d1b2 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_info_card.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/file_info_card.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class FileInfoCard(AgentsModel): @@ -13,9 +12,9 @@ class FileInfoCard(AgentsModel): :param file_type: Type of file. :type file_type: str :param etag: ETag for the file. - :type etag: Optional[str] + :type etag: str | None """ unique_id: str file_type: str - etag: Optional[str] + etag: str | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_end_event_details.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_end_event_details.py index 740c3646..1bafe7e6 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_end_event_details.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_end_event_details.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class MeetingEndEventDetails(AgentsModel): diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_event_details.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_event_details.py index fd604a68..29dc13f3 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_event_details.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_event_details.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class MeetingEventDetails(AgentsModel): diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_notification_channel_data.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_notification_channel_data.py index b7aaee69..1dd3ced6 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_notification_channel_data.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_notification_channel_data.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List from .on_behalf_of import OnBehalfOf @@ -13,4 +12,4 @@ class MeetingNotificationChannelData(AgentsModel): :type on_behalf_of_list: list[OnBehalfOf] """ - on_behalf_of_list: List[OnBehalfOf] = None + on_behalf_of_list: list[OnBehalfOf] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_notification_response.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_notification_response.py index d08dd55e..3b8b779e 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_notification_response.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_notification_response.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List from .meeting_notification_recipient_failure_info import ( MeetingNotificationRecipientFailureInfo, ) @@ -17,4 +16,4 @@ class MeetingNotificationResponse(AgentsModel): :type recipients_failure_info: list[MeetingNotificationRecipientFailureInfo] """ - recipients_failure_info: List[MeetingNotificationRecipientFailureInfo] = None + recipients_failure_info: list[MeetingNotificationRecipientFailureInfo] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_participant_info.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_participant_info.py index edc00a73..d6ec6221 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_participant_info.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_participant_info.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class MeetingParticipantInfo(AgentsModel): diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_participants_event_details.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_participants_event_details.py index 6d55f14f..e946252a 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_participants_event_details.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_participants_event_details.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List from .teams_meeting_member import TeamsMeetingMember @@ -13,4 +12,4 @@ class MeetingParticipantsEventDetails(AgentsModel): :type members: list[TeamsMeetingMember] """ - members: List[TeamsMeetingMember] = None + members: list[TeamsMeetingMember] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_start_event_details.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_start_event_details.py index 825fefcd..10f3bce0 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_start_event_details.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/meeting_start_event_details.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class MeetingStartEventDetails(AgentsModel): diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload.py index e0a07db5..ab45b415 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload.py @@ -3,7 +3,7 @@ from pydantic import Field from ..agents_model import AgentsModel -from typing import Annotated, List +from typing import Annotated from .message_actions_payload_from import MessageActionsPayloadFrom from .message_actions_payload_body import MessageActionsPayloadBody @@ -44,11 +44,11 @@ class MessageActionsPayload(AgentsModel): :param attachment_layout: How the attachment(s) are displayed in the message. :type attachment_layout: str :param attachments: Attachments in the message - card, image, file, etc. - :type attachments: List[MessageActionsPayloadAttachment] + :type attachments: list[MessageActionsPayloadAttachment] :param mentions: List of entities mentioned in the message. - :type mentions: List[MessageActionsPayloadMention] + :type mentions: list[MessageActionsPayloadMention] :param reactions: Reactions for the message. - :type reactions: List[MessageActionsPayloadReaction] + :type reactions: list[MessageActionsPayloadReaction] """ id: str = None @@ -65,6 +65,6 @@ class MessageActionsPayload(AgentsModel): from_property: MessageActionsPayloadFrom = None body: MessageActionsPayloadBody = None attachment_layout: str = None - attachments: List[MessageActionsPayloadAttachment] = None - mentions: List[MessageActionsPayloadMention] = None - reactions: List[MessageActionsPayloadReaction] = None + attachments: list[MessageActionsPayloadAttachment] = None + mentions: list[MessageActionsPayloadMention] = None + reactions: list[MessageActionsPayloadReaction] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_app.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_app.py index 6768a01b..c405fd64 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_app.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_app.py @@ -1,29 +1,31 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +from typing import Annotated + from pydantic import Field from ..agents_model import AgentsModel -from typing import Annotated, Optional class MessageActionsPayloadApp(AgentsModel): """Represents an application entity. :param application_identity_type: The type of application. Possible values include: 'aadApplication', 'bot', 'tenantBot', 'office365Connector', 'webhook' - :type application_identity_type: Optional[str] + :type application_identity_type: str | None :param id: The id of the application. - :type id: Optional[str] + :type id: str | None :param display_name: The plaintext display name of the application. - :type display_name: Optional[str] + :type display_name: str | None """ - application_identity_type: Optional[ + application_identity_type: ( Annotated[ str, Field( pattern=r"^(aadApplication|bot|tenantBot|office365Connector|webhook)$" ), ] - ] - id: Optional[str] - display_name: Optional[str] + | None + ) + id: str | None + display_name: str | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_attachment.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_attachment.py index 7b87d72e..2805c0e2 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_attachment.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_attachment.py @@ -1,30 +1,31 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +from typing import Any + from ..agents_model import AgentsModel -from typing import Any, Optional class MessageActionsPayloadAttachment(AgentsModel): """Represents the attachment in a message. :param id: The id of the attachment. - :type id: Optional[str] + :type id: str | None :param content_type: The type of the attachment. - :type content_type: Optional[str] + :type content_type: str | None :param content_url: The url of the attachment, in case of an external link. - :type content_url: Optional[str] + :type content_url: str | None :param content: The content of the attachment, in case of a code snippet, email, or file. - :type content: Optional[Any] + :type content: Any | None :param name: The plaintext display name of the attachment. - :type name: Optional[str] + :type name: str | None :param thumbnail_url: The url of a thumbnail image that might be embedded in the attachment, in case of a card. - :type thumbnail_url: Optional[str] + :type thumbnail_url: str | None """ - id: Optional[str] - content_type: Optional[str] - content_url: Optional[str] - content: Optional[Any] - name: Optional[str] - thumbnail_url: Optional[str] + id: str | None + content_type: str | None + content_url: str | None + content: Any | None + name: str | None + thumbnail_url: str | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_from.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_from.py index cd4f033f..6553b552 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_from.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_from.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional from .message_actions_payload_user import MessageActionsPayloadUser from .message_actions_payload_app import MessageActionsPayloadApp @@ -13,13 +12,13 @@ class MessageActionsPayloadFrom(AgentsModel): """Represents a user, application, or conversation type that either sent or was referenced in a message. :param user: Represents details of the user. - :type user: Optional["MessageActionsPayloadUser"] + :type user: MessageActionsPayloadUser | None :param application: Represents details of the app. - :type application: Optional["MessageActionsPayloadApp"] + :type application: MessageActionsPayloadApp | None :param conversation: Represents details of the conversation. - :type conversation: Optional["MessageActionsPayloadConversation"] + :type conversation: MessageActionsPayloadConversation | None """ - user: Optional[MessageActionsPayloadUser] - application: Optional[MessageActionsPayloadApp] - conversation: Optional[MessageActionsPayloadConversation] + user: MessageActionsPayloadUser | None + application: MessageActionsPayloadApp | None + conversation: MessageActionsPayloadConversation | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_mention.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_mention.py index 1c72c1da..a5d6aedf 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_mention.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_mention.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional from .message_actions_payload_from import MessageActionsPayloadFrom @@ -11,13 +10,13 @@ class MessageActionsPayloadMention(AgentsModel): """Represents the entity that was mentioned in the message. :param id: The id of the mentioned entity. - :type id: Optional[int] + :type id: int | None :param mention_text: The plaintext display name of the mentioned entity. - :type mention_text: Optional[str] + :type mention_text: str | None :param mentioned: Provides more details on the mentioned entity. - :type mentioned: Optional["MessageActionsPayloadFrom"] + :type mentioned: MessageActionsPayloadFrom | None """ - id: Optional[int] - mention_text: Optional[str] - mentioned: Optional[MessageActionsPayloadFrom] + id: int | None + mention_text: str | None + mentioned: MessageActionsPayloadFrom | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_reaction.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_reaction.py index d24a0020..306e4767 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_reaction.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_reaction.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional from .message_actions_payload_from import MessageActionsPayloadFrom @@ -11,13 +10,13 @@ class MessageActionsPayloadReaction(AgentsModel): """Represents the reaction of a user to a message. :param reaction_type: The type of reaction given to the message. Possible values include: 'like', 'heart', 'laugh', 'surprised', 'sad', 'angry' - :type reaction_type: Optional[str] + :type reaction_type: str | None :param created_date_time: Timestamp of when the user reacted to the message. - :type created_date_time: Optional[str] + :type created_date_time: str | None :param user: The user with which the reaction is associated. - :type user: Optional["MessageActionsPayloadFrom"] + :type user: MessageActionsPayloadFrom | None """ - reaction_type: Optional[str] - created_date_time: Optional[str] - user: Optional[MessageActionsPayloadFrom] + reaction_type: str | None + created_date_time: str | None + user: MessageActionsPayloadFrom | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_user.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_user.py index 17c5f1e6..a9fcea6b 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_user.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/message_actions_payload_user.py @@ -1,27 +1,29 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +from typing import Annotated + from pydantic import Field from ..agents_model import AgentsModel -from typing import Annotated, Optional class MessageActionsPayloadUser(AgentsModel): """Represents a user entity. :param user_identity_type: The identity type of the user. Possible values include: 'aadUser', 'onPremiseAadUser', 'anonymousGuest', 'federatedUser' - :type user_identity_type: Optional[str] + :type user_identity_type: str | None :param id: The id of the user. - :type id: Optional[str] + :type id: str | None :param display_name: The plaintext display name of the user. - :type display_name: Optional[str] + :type display_name: str | None """ - user_identity_type: Optional[ + user_identity_type: ( Annotated[ str, Field(pattern=r"^(aadUser|onPremiseAadUser|anonymousGuest|federatedUser)$"), ] - ] - id: Optional[str] - display_name: Optional[str] + | None + ) + id: str | None + display_name: str | None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_action.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_action.py index 2e47c7d3..dbd82860 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_action.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_action.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Any, List from .task_module_request_context import TaskModuleRequestContext from .message_actions_payload import MessageActionsPayload @@ -23,7 +22,7 @@ class MessagingExtensionAction(AgentsModel): :param bot_message_preview_action: Bot message preview action taken by user. Possible values include: 'edit', 'send' :type bot_message_preview_action: str :param bot_activity_preview: List of bot activity previews. - :type bot_activity_preview: List[Activity] + :type bot_activity_preview: list[Activity] :param message_payload: Message content sent as part of the command request. :type message_payload: MessageActionsPayload """ @@ -33,5 +32,5 @@ class MessagingExtensionAction(AgentsModel): command_id: str = None command_context: str = None bot_message_preview_action: str = None - bot_activity_preview: List[Activity] = None + bot_activity_preview: list[Activity] = None message_payload: MessageActionsPayload = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_attachment.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_attachment.py index 649dc838..652fe92c 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_attachment.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_attachment.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional from ..attachment import Attachment @@ -27,6 +26,6 @@ class MessagingExtensionAttachment(AgentsModel): content_type: str content_url: str content: object = None - name: Optional[str] = None - thumbnail_url: Optional[str] = None + name: str | None = None + thumbnail_url: str | None = None preview: Attachment = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_query.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_query.py index c784ec9c..be3782f1 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_query.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_query.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List, Optional from .messaging_extension_parameter import MessagingExtensionParameter from .messaging_extension_query_options import MessagingExtensionQueryOptions @@ -14,14 +13,14 @@ class MessagingExtensionQuery(AgentsModel): :param command_id: Id of the command assigned by Bot :type command_id: str :param parameters: Parameters for the query - :type parameters: List["MessagingExtensionParameter"] + :type parameters: list[MessagingExtensionParameter] :param query_options: Query options for the extension - :type query_options: Optional["MessagingExtensionQueryOptions"] + :type query_options: MessagingExtensionQueryOptions | None :param state: State parameter passed back to the bot after authentication/configuration flow :type state: str """ command_id: str = None - parameters: List[MessagingExtensionParameter] = None - query_options: Optional[MessagingExtensionQueryOptions] = None + parameters: list[MessagingExtensionParameter] = None + query_options: MessagingExtensionQueryOptions | None = None state: str = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_response.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_response.py index 86e1464e..a8416c08 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_response.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_response.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional from .messaging_extension_result import MessagingExtensionResult from .cache_info import CacheInfo @@ -12,10 +11,10 @@ class MessagingExtensionResponse(AgentsModel): """Messaging extension response. :param compose_extension: The compose extension result. - :type compose_extension: Optional["MessagingExtensionResult"] + :type compose_extension: MessagingExtensionResult | None :param cache_info: CacheInfo for this MessagingExtensionResponse. - :type cache_info: Optional["CacheInfo"] + :type cache_info: CacheInfo | None """ - compose_extension: Optional[MessagingExtensionResult] = None - cache_info: Optional[CacheInfo] = None + compose_extension: MessagingExtensionResult | None = None + cache_info: CacheInfo | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_result.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_result.py index 24f4d856..6f5e6abe 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_result.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_result.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List, Optional from .messaging_extension_attachment import MessagingExtensionAttachment from .messaging_extension_suggested_action import MessagingExtensionSuggestedAction @@ -17,18 +16,18 @@ class MessagingExtensionResult(AgentsModel): :param type: The type of the result. Possible values include: 'result', 'auth', 'config', 'message', 'botMessagePreview' :type type: str :param attachments: (Only when type is result) Attachments - :type attachments: List["MessagingExtensionAttachment"] + :type attachments: list[MessagingExtensionAttachment] :param suggested_actions: Suggested actions for the result. - :type suggested_actions: Optional["MessagingExtensionSuggestedAction"] + :type suggested_actions: MessagingExtensionSuggestedAction | None :param text: (Only when type is message) Text - :type text: Optional[str] + :type text: str | None :param activity_preview: (Only when type is botMessagePreview) Message activity to preview - :type activity_preview: Optional["Activity"] + :type activity_preview: Activity | None """ attachment_layout: str = None type: str = None - attachments: List[MessagingExtensionAttachment] = None - suggested_actions: Optional[MessagingExtensionSuggestedAction] = None - text: Optional[str] = None - activity_preview: Optional["Activity"] = None + attachments: list[MessagingExtensionAttachment] = None + suggested_actions: MessagingExtensionSuggestedAction | None = None + text: str | None = None + activity_preview: Activity | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_suggested_action.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_suggested_action.py index 6829cccc..fac981fa 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_suggested_action.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/messaging_extension_suggested_action.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List from ..card_action import CardAction @@ -11,7 +10,7 @@ class MessagingExtensionSuggestedAction(AgentsModel): """Messaging extension suggested actions. :param actions: List of suggested actions. - :type actions: List["CardAction"] + :type actions: list["CardAction"] """ - actions: List[CardAction] = None + actions: list[CardAction] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/notification_info.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/notification_info.py index 5d8767de..fbc84a6c 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/notification_info.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/notification_info.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class NotificationInfo(AgentsModel): @@ -11,11 +10,11 @@ class NotificationInfo(AgentsModel): :param alert: True if notification is to be sent to the user, false otherwise. :type alert: bool :param alert_in_meeting: True if notification is to be sent in a meeting context. - :type alert_in_meeting: Optional[bool] + :type alert_in_meeting: bool | None :param external_resource_url: URL for external resources related to the notification. - :type external_resource_url: Optional[str] + :type external_resource_url: str | None """ alert: bool = None - alert_in_meeting: Optional[bool] = None - external_resource_url: Optional[str] = None + alert_in_meeting: bool | None = None + external_resource_url: str | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card.py index afa2ffed..96c8a1f8 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List, Optional from .o365_connector_card_section import O365ConnectorCardSection from .o365_connector_card_action_base import O365ConnectorCardActionBase @@ -13,20 +12,20 @@ class O365ConnectorCard(AgentsModel): :param title: Title of the item :type title: str :param text: Text for the card - :type text: Optional[str] + :type text: str | None :param summary: Summary for the card - :type summary: Optional[str] + :type summary: str | None :param theme_color: Theme color for the card - :type theme_color: Optional[str] + :type theme_color: str | None :param sections: Set of sections for the current card - :type sections: Optional[List["O365ConnectorCardSection"]] + :type sections: list[O365ConnectorCardSection] | None :param potential_action: Set of actions for the current card - :type potential_action: Optional[List["O365ConnectorCardActionBase"]] + :type potential_action: list[O365ConnectorCardActionBase] | None """ title: str = None - text: Optional[str] = None - summary: Optional[str] = None - theme_color: Optional[str] = None - sections: Optional[List[O365ConnectorCardSection]] = None - potential_action: Optional[List[O365ConnectorCardActionBase]] = None + text: str | None = None + summary: str | None = None + theme_color: str | None = None + sections: list[O365ConnectorCardSection] | None = None + potential_action: list[O365ConnectorCardActionBase] | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_action_card.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_action_card.py index a72528aa..de89c063 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_action_card.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_action_card.py @@ -3,7 +3,6 @@ from pydantic import Field from ..agents_model import AgentsModel -from typing import List from .o365_connector_card_input_base import O365ConnectorCardInputBase from .o365_connector_card_action_base import O365ConnectorCardActionBase @@ -18,13 +17,13 @@ class O365ConnectorCardActionCard(AgentsModel): :param id: Action Id :type id: str :param inputs: Set of inputs contained in this ActionCard - :type inputs: List["O365ConnectorCardInputBase"] + :type inputs: list[O365ConnectorCardInputBase] :param actions: Set of actions contained in this ActionCard - :type actions: List["O365ConnectorCardActionBase"] + :type actions: list[O365ConnectorCardActionBase] """ type: str = Field(None, alias="@type") name: str = None id: str = Field(None, alias="@id") - inputs: List[O365ConnectorCardInputBase] = None - actions: List[O365ConnectorCardActionBase] = None + inputs: list[O365ConnectorCardInputBase] = None + actions: list[O365ConnectorCardActionBase] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_http_post.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_http_post.py index 10c4a693..3609e3f2 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_http_post.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_http_post.py @@ -3,7 +3,6 @@ from pydantic import Field from ..agents_model import AgentsModel -from typing import Optional class O365ConnectorCardHttpPOST(AgentsModel): @@ -16,10 +15,10 @@ class O365ConnectorCardHttpPOST(AgentsModel): :param id: Id of the HttpPOST action. :type id: str :param body: Content of the HttpPOST action. - :type body: Optional[str] + :type body: str | None """ type: str = Field(None, alias="@type") name: str = None id: str = Field(None, alias="@id") - body: Optional[str] = None + body: str | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_image.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_image.py index 7f2bd6a6..069103de 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_image.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_image.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class O365ConnectorCardImage(AgentsModel): @@ -11,8 +10,8 @@ class O365ConnectorCardImage(AgentsModel): :param image: URL for the image. :type image: str :param title: Title of the image. - :type title: Optional[str] + :type title: str | None """ image: str = None - title: Optional[str] = None + title: str | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_input_base.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_input_base.py index f7b210f5..a68763c9 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_input_base.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_input_base.py @@ -3,7 +3,6 @@ from pydantic import Field from ..agents_model import AgentsModel -from typing import Optional class O365ConnectorCardInputBase(AgentsModel): @@ -14,15 +13,15 @@ class O365ConnectorCardInputBase(AgentsModel): :param id: Input Id. It must be unique per entire O365 connector card. :type id: str :param is_required: Define if this input is a required field. Default value is false. - :type is_required: Optional[bool] + :type is_required: bool | None :param title: Input title that will be shown as the placeholder - :type title: Optional[str] + :type title: str | None :param value: Default value for this input field - :type value: Optional[str] + :type value: str | None """ type: str = Field(None, alias="@type") id: str = None - is_required: Optional[bool] = None - title: Optional[str] = None - value: Optional[str] = None + is_required: bool | None = None + title: str | None = None + value: str | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_multichoice_input.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_multichoice_input.py index efb41ead..49f31bf5 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_multichoice_input.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_multichoice_input.py @@ -3,7 +3,6 @@ from pydantic import Field from ..agents_model import AgentsModel -from typing import List, Optional from .o365_connector_card_multichoice_input_choice import ( O365ConnectorCardMultichoiceInputChoice, ) @@ -17,24 +16,24 @@ class O365ConnectorCardMultichoiceInput(AgentsModel): :param id: Input Id. It must be unique per entire O365 connector card. :type id: str :param is_required: Define if this input is a required field. Default value is false. - :type is_required: Optional[bool] + :type is_required: bool | None :param title: Input title that will be shown as the placeholder - :type title: Optional[str] + :type title: str | None :param value: Default value for this input field - :type value: Optional[str] + :type value: str | None :param choices: Set of choices for this input field. - :type choices: List["O365ConnectorCardMultichoiceInputChoice"] + :type choices: list[O365ConnectorCardMultichoiceInputChoice] :param style: Choice style. Possible values include: 'compact', 'expanded' - :type style: Optional[str] + :type style: str | None :param is_multi_select: Define if this input field allows multiple selections. Default value is false. - :type is_multi_select: Optional[bool] + :type is_multi_select: bool | None """ type: str = Field(None, alias="@type") id: str = None - is_required: Optional[bool] = None - title: Optional[str] = None - value: Optional[str] = None - choices: List[O365ConnectorCardMultichoiceInputChoice] = None - style: Optional[str] = None - is_multi_select: Optional[bool] = None + is_required: bool | None = None + title: str | None = None + value: str | None = None + choices: list[O365ConnectorCardMultichoiceInputChoice] = None + style: str | None = None + is_multi_select: bool | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_open_uri.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_open_uri.py index 7d466a01..8e8a3e94 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_open_uri.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_open_uri.py @@ -3,7 +3,6 @@ from pydantic import Field from ..agents_model import AgentsModel -from typing import List from .o365_connector_card_open_uri_target import O365ConnectorCardOpenUriTarget @@ -17,10 +16,10 @@ class O365ConnectorCardOpenUri(AgentsModel): :param id: Id of the OpenUri action. :type id: str :param targets: List of targets for the OpenUri action. - :type targets: List["O365ConnectorCardOpenUriTarget"] + :type targets: list[O365ConnectorCardOpenUriTarget] """ type: str = Field(None, alias="@type") name: str = None id: str = Field(None, alias="@id") - targets: List[O365ConnectorCardOpenUriTarget] = None + targets: list[O365ConnectorCardOpenUriTarget] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_section.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_section.py index 6bb0d700..8ddd26d9 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_section.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_section.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List, Optional from .o365_connector_card_fact import O365ConnectorCardFact from .o365_connector_card_image import O365ConnectorCardImage from .o365_connector_card_action_base import O365ConnectorCardActionBase @@ -12,31 +11,31 @@ class O365ConnectorCardSection(AgentsModel): """O365 connector card section. :param title: Title of the section. - :type title: Optional[str] + :type title: str | None :param text: Text for the section. - :type text: Optional[str] + :type text: str | None :param activity_title: Activity title. - :type activity_title: Optional[str] + :type activity_title: str | None :param activity_subtitle: Activity subtitle. - :type activity_subtitle: Optional[str] + :type activity_subtitle: str | None :param activity_image: Activity image URL. - :type activity_image: Optional[str] + :type activity_image: str | None :param activity_text: Activity text. - :type activity_text: Optional[str] + :type activity_text: str | None :param facts: List of facts for the section. - :type facts: Optional[List["O365ConnectorCardFact"]] + :type facts: list[O365ConnectorCardFact] | None :param images: List of images for the section. - :type images: Optional[List["O365ConnectorCardImage"]] + :type images: list[O365ConnectorCardImage] | None :param potential_action: List of actions for the section. - :type potential_action: Optional[List["O365ConnectorCardActionBase"]] + :type potential_action: list[O365ConnectorCardActionBase] | None """ - title: Optional[str] = None - text: Optional[str] = None - activity_title: Optional[str] = None - activity_subtitle: Optional[str] = None - activity_image: Optional[str] = None - activity_text: Optional[str] = None - facts: Optional[List[O365ConnectorCardFact]] = None - images: Optional[List[O365ConnectorCardImage]] = None - potential_action: Optional[List[O365ConnectorCardActionBase]] = None + title: str | None = None + text: str | None = None + activity_title: str | None = None + activity_subtitle: str | None = None + activity_image: str | None = None + activity_text: str | None = None + facts: list[O365ConnectorCardFact] | None = None + images: list[O365ConnectorCardImage] | None = None + potential_action: list[O365ConnectorCardActionBase] | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_text_input.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_text_input.py index 613790fa..12dd749e 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_text_input.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_text_input.py @@ -3,7 +3,6 @@ from pydantic import Field from ..agents_model import AgentsModel -from typing import Optional class O365ConnectorCardTextInput(AgentsModel): @@ -14,18 +13,18 @@ class O365ConnectorCardTextInput(AgentsModel): :param id: Input Id. It must be unique per entire O365 connector card. :type id: str :param is_required: Define if this input is a required field. Default value is false. - :type is_required: Optional[bool] + :type is_required: bool | None :param title: Input title that will be shown as the placeholder - :type title: Optional[str] + :type title: str | None :param value: Default value for this input field - :type value: Optional[str] + :type value: str | None :param is_multiline: Define if this input field allows multiple lines of text. Default value is false. - :type is_multiline: Optional[bool] + :type is_multiline: bool | None """ type: str = Field(None, alias="@type") id: str = None - is_required: Optional[bool] = None - title: Optional[str] = None - value: Optional[str] = None - is_multiline: Optional[bool] = None + is_required: bool | None = None + title: str | None = None + value: str | None = None + is_multiline: bool | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_view_action.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_view_action.py index 484fd036..386163f8 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_view_action.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/o365_connector_card_view_action.py @@ -3,7 +3,6 @@ from pydantic import Field from ..agents_model import AgentsModel -from typing import Optional class O365ConnectorCardViewAction(AgentsModel): @@ -16,10 +15,10 @@ class O365ConnectorCardViewAction(AgentsModel): :param id: Id of the ViewAction action. :type id: str :param target: Target URL for the ViewAction action. - :type target: Optional[str] + :type target: str | None """ type: str = Field(None, alias="@type") name: str = None id: str = Field(None, alias="@id") - target: Optional[str] = None + target: str | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/tab_response_cards.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/tab_response_cards.py index e5afbbf1..8cdceb29 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/tab_response_cards.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/tab_response_cards.py @@ -2,7 +2,6 @@ # Licensed under the MIT License.from ..agents_model import AgentsModel from ..agents_model import AgentsModel -from typing import List from .tab_response_card import TabResponseCard @@ -14,4 +13,4 @@ class TabResponseCards(AgentsModel): :type cards: list[TabResponseCard] """ - cards: List[TabResponseCard] = None + cards: list[TabResponseCard] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/tab_suggested_actions.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/tab_suggested_actions.py index aa285a44..a631f541 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/tab_suggested_actions.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/tab_suggested_actions.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List from ..card_action import CardAction @@ -14,4 +13,4 @@ class TabSuggestedActions(AgentsModel): :type actions: list[CardAction] """ - actions: List[CardAction] = None + actions: list[CardAction] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/targeted_meeting_notification_value.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/targeted_meeting_notification_value.py index 0ba96d61..65be92eb 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/targeted_meeting_notification_value.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/targeted_meeting_notification_value.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List from .surface import Surface @@ -10,10 +9,10 @@ class TargetedMeetingNotificationValue(AgentsModel): """Specifies the value for targeted meeting notifications. :param recipients: List of recipient MRIs for the notification. - :type recipients: List[str] + :type recipients: list[str] :param message: The message content of the notification. :type message: str """ - recipients: List[str] = None - surfaces: List[Surface] = None + recipients: list[str] = None + surfaces: list[Surface] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_continue_response.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_continue_response.py index 76874ef6..0f190510 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_continue_response.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_continue_response.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional from .task_module_task_info import TaskModuleTaskInfo @@ -12,8 +11,8 @@ class TaskModuleContinueResponse(AgentsModel): :param type: The type of response. Default is 'continue'. :type type: str :param value: The task module task info. - :type value: Optional["TaskModuleTaskInfo"] + :type value: TaskModuleTaskInfo | None """ type: str = None - value: Optional[TaskModuleTaskInfo] = None + value: TaskModuleTaskInfo | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_message_response.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_message_response.py index 6169ced6..82ee51f4 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_message_response.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_message_response.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class TaskModuleMessageResponse(AgentsModel): @@ -11,8 +10,8 @@ class TaskModuleMessageResponse(AgentsModel): :param type: The type of response. Default is 'message'. :type type: str :param value: The message to display. - :type value: Optional[str] + :type value: str | None """ type: str = None - value: Optional[str] = None + value: str | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_request.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_request.py index 6d9f37df..d232e406 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_request.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_request.py @@ -1,9 +1,10 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. +from typing import Any + from pydantic import Field from ..agents_model import AgentsModel -from typing import Any, Optional from .task_module_request_context import TaskModuleRequestContext from .tab_entity_context import TabEntityContext @@ -13,13 +14,13 @@ class TaskModuleRequest(AgentsModel): """Task module invoke request value payload. :param data: User input data. Free payload with key-value pairs. - :type data: object + :type data: Any | None :param context: Current user context, i.e., the current theme - :type context: Optional[Any] + :type context: TaskModuleRequestContext | None :param tab_entity_context: Gets or sets current tab request context. - :type tab_entity_context: Optional[TabEntityContext] + :type tab_entity_context: TabEntityContext | None """ - data: Optional[Any] - context: Optional[TaskModuleRequestContext] - tab_entity_context: Optional[TabEntityContext] = Field(None, alias="tabContext") + data: Any | None + context: TaskModuleRequestContext | None + tab_entity_context: TabEntityContext | None = Field(None, alias="tabContext") diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_request_context.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_request_context.py index d3cde510..338dda00 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_request_context.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/task_module_request_context.py @@ -2,14 +2,13 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import Optional class TaskModuleRequestContext(AgentsModel): """Context for a task module request. :param theme: The current user's theme. - :type theme: Optional[str] + :type theme: str | None """ - theme: Optional[str] = None + theme: str | None = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/teams_channel_data.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/teams_channel_data.py index 14fb5cdc..16e8dffe 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/teams_channel_data.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/teams_channel_data.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List from .channel_info import ChannelInfo from .team_info import TeamInfo from .notification_info import NotificationInfo @@ -30,7 +29,7 @@ class TeamsChannelData(AgentsModel): :param settings: Information about the settings in which the message was sent :type settings: TeamsChannelDataSettings :param on_behalf_of: The OnBehalfOf list for user attribution - :type on_behalf_of: List[OnBehalfOf] + :type on_behalf_of: list[OnBehalfOf] """ channel: ChannelInfo = None @@ -40,4 +39,4 @@ class TeamsChannelData(AgentsModel): tenant: TenantInfo = None meeting: TeamsMeetingInfo = None settings: TeamsChannelDataSettings = None - on_behalf_of: List[OnBehalfOf] = None + on_behalf_of: list[OnBehalfOf] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/teams_paged_members_result.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/teams_paged_members_result.py index b523376a..1c4fed5a 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/teams_paged_members_result.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/teams/teams_paged_members_result.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. from ..agents_model import AgentsModel -from typing import List from .teams_channel_account import TeamsChannelAccount @@ -16,4 +15,4 @@ class TeamsPagedMembersResult(AgentsModel): """ continuation_token: str = None - members: List[TeamsChannelAccount] = None + members: list[TeamsChannelAccount] = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/token_exchange_state.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/token_exchange_state.py index f2a9b6d5..a58887ae 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/token_exchange_state.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/token_exchange_state.py @@ -3,7 +3,6 @@ import base64 import json -from typing import Optional from pydantic import Field from .conversation_reference import ConversationReference @@ -28,7 +27,7 @@ class TokenExchangeState(AgentsModel): connection_name: NonEmptyString = None conversation: ConversationReference = None - relates_to: Optional[ConversationReference] = None + relates_to: ConversationReference | None = None agent_url: NonEmptyString = Field(None, alias="bot_url") ms_app_id: NonEmptyString = None diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/token_response.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/token_response.py index fc4f49f9..9686c16e 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/token_response.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/token_response.py @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional import jwt from .agents_model import AgentsModel @@ -53,7 +52,7 @@ def is_exchangeable(self) -> bool: return False @staticmethod - def _get_app_id_from_token_payload(token_payload: dict) -> Optional[str]: + def _get_app_id_from_token_payload(token_payload: dict) -> str | None: """ Extracts the appId from the token's claims. diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/token_status.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/token_status.py index 3509715d..9f9945e2 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/token_status.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/token_status.py @@ -3,7 +3,6 @@ """Models for token status operations.""" -from typing import Optional from pydantic import Field from .agents_model import AgentsModel @@ -24,9 +23,9 @@ class TokenStatus(AgentsModel): :type service_provider_display_name: str """ - channel_id: Optional[NonEmptyString] = Field(None, alias="channelId") - connection_name: Optional[NonEmptyString] = Field(None, alias="connectionName") - has_token: Optional[bool] = Field(None, alias="hasToken") - service_provider_display_name: Optional[NonEmptyString] = Field( + channel_id: NonEmptyString | None = Field(None, alias="channelId") + connection_name: NonEmptyString | None = Field(None, alias="connectionName") + has_token: bool | None = Field(None, alias="hasToken") + service_provider_display_name: NonEmptyString | None = Field( None, alias="serviceProviderDisplayName" ) diff --git a/libraries/microsoft-agents-activity/microsoft_agents/activity/turn_context_protocol.py b/libraries/microsoft-agents-activity/microsoft_agents/activity/turn_context_protocol.py index 945cbc71..9e87cda9 100644 --- a/libraries/microsoft-agents-activity/microsoft_agents/activity/turn_context_protocol.py +++ b/libraries/microsoft-agents-activity/microsoft_agents/activity/turn_context_protocol.py @@ -3,7 +3,7 @@ from __future__ import annotations -from typing import Protocol, List, Callable, Optional, Generic, TypeVar +from typing import Protocol, Callable, Generic, TypeVar from abc import abstractmethod from microsoft_agents.activity import ( @@ -28,19 +28,19 @@ class TurnContextProtocol(Protocol, Generic[T]): async def send_activity( self, activity_or_text: Activity | str, - speak: Optional[str] = None, - input_hint: Optional[str] = None, - ) -> Optional[ResourceResponse]: + speak: str | None = None, + input_hint: str | None = None, + ) -> ResourceResponse | None: pass @abstractmethod async def send_activities( - self, activities: List[Activity] - ) -> List[ResourceResponse]: + self, activities: list[Activity] + ) -> list[ResourceResponse]: pass @abstractmethod - async def update_activity(self, activity: Activity) -> Optional[ResourceResponse]: + async def update_activity(self, activity: Activity) -> ResourceResponse | None: pass @abstractmethod @@ -63,6 +63,10 @@ def on_delete_activity(self, handler: Callable) -> "TurnContextProtocol": @abstractmethod async def send_trace_activity( - self, name: str, value: object = None, value_type: str = None, label: str = None + self, + name: str, + value: object | None = None, + value_type: str | None = None, + label: str | None = None, ) -> ResourceResponse: pass diff --git a/libraries/microsoft-agents-authentication-msal/microsoft_agents/authentication/msal/msal_auth.py b/libraries/microsoft-agents-authentication-msal/microsoft_agents/authentication/msal/msal_auth.py index b470ae48..8e837274 100644 --- a/libraries/microsoft-agents-authentication-msal/microsoft_agents/authentication/msal/msal_auth.py +++ b/libraries/microsoft-agents-authentication-msal/microsoft_agents/authentication/msal/msal_auth.py @@ -7,7 +7,6 @@ import asyncio import logging import jwt -from typing import Optional from urllib.parse import urlparse, ParseResult as URI from msal import ( ConfidentialClientApplication, @@ -275,7 +274,7 @@ def _get_client( return client @staticmethod - def _uri_validator(url_str: str) -> tuple[bool, Optional[URI]]: + def _uri_validator(url_str: str) -> tuple[bool, URI | None]: try: result = urlparse(url_str) return all([result.scheme, result.netloc]), result @@ -303,13 +302,13 @@ def _resolve_scopes_list(self, instance_url: URI, scopes=None) -> list[str]: # to avoid this async def get_agentic_application_token( self, tenant_id: str, agent_app_instance_id: str - ) -> Optional[str]: + ) -> str | None: """Gets the agentic application token for the given agent application instance ID. :param agent_app_instance_id: The agent application instance ID. :type agent_app_instance_id: str :return: The agentic application token, or None if not found. - :rtype: Optional[str] + :rtype: str | None """ if not agent_app_instance_id: @@ -428,7 +427,7 @@ async def get_agentic_user_token( agent_app_instance_id: str, agentic_user_id: str, scopes: list[str], - ) -> Optional[str]: + ) -> str | None: """Gets the agentic user token for the given agent application instance ID and agentic user Id and the scopes. :param agent_app_instance_id: The agent application instance ID. @@ -438,7 +437,7 @@ async def get_agentic_user_token( :param scopes: The scopes to request for the token. :type scopes: list[str] :return: The agentic user token, or None if not found. - :rtype: Optional[str] + :rtype: str | None """ if not agent_app_instance_id or not agentic_user_id: raise ValueError( diff --git a/libraries/microsoft-agents-authentication-msal/microsoft_agents/authentication/msal/msal_connection_manager.py b/libraries/microsoft-agents-authentication-msal/microsoft_agents/authentication/msal/msal_connection_manager.py index a1424014..242c40b9 100644 --- a/libraries/microsoft-agents-authentication-msal/microsoft_agents/authentication/msal/msal_connection_manager.py +++ b/libraries/microsoft-agents-authentication-msal/microsoft_agents/authentication/msal/msal_connection_manager.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. import re -from typing import Dict, List, Optional + from microsoft_agents.hosting.core import ( AgentAuthConfiguration, AccessTokenProviderBase, @@ -14,14 +14,14 @@ class MsalConnectionManager(Connections): - _connections: Dict[str, MsalAuth] - _connections_map: List[Dict[str, str]] + _connections: dict[str, MsalAuth] + _connections_map: list[dict[str, str]] _service_connection_configuration: AgentAuthConfiguration def __init__( self, - connections_configurations: Optional[Dict[str, AgentAuthConfiguration]] = None, - connections_map: Optional[List[Dict[str, str]]] = None, + connections_configurations: dict[str, AgentAuthConfiguration] | None = None, + connections_map: list[dict[str, str]] | None = None, **kwargs, ): """ @@ -34,7 +34,7 @@ def __init__( :raises ValueError: If no service connection configuration is provided. """ - self._connections: Dict[str, MsalAuth] = {} + self._connections: dict[str, MsalAuth] = {} self._connections_map = connections_map or kwargs.get("CONNECTIONSMAP", {}) self._config_map: dict[str, AgentAuthConfiguration] = {} @@ -46,7 +46,7 @@ def __init__( self._connections[connection_name] = MsalAuth(agent_auth_config) self._config_map[connection_name] = agent_auth_config else: - raw_configurations: Dict[str, Dict] = kwargs.get("CONNECTIONS", {}) + raw_configurations: dict[str, dict] = kwargs.get("CONNECTIONS", {}) for connection_name, connection_settings in raw_configurations.items(): parsed_configuration = AgentAuthConfiguration( **connection_settings.get("SETTINGS", {}) @@ -61,12 +61,12 @@ def __init__( if not self._connections.get("SERVICE_CONNECTION", None): raise ValueError("No service connection configuration provided.") - def get_connection(self, connection_name: Optional[str]) -> AccessTokenProviderBase: + def get_connection(self, connection_name: str | None) -> AccessTokenProviderBase: """ Get the OAuth connection for the agent. :arg connection_name: The name of the connection. - :type connection_name: Optional[str] + :type connection_name: str | None :return: The OAuth connection for the agent. :rtype: :class:`microsoft_agents.hosting.core.AccessTokenProviderBase` """ diff --git a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/connection_settings.py b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/connection_settings.py index 96909a10..cdacf63f 100644 --- a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/connection_settings.py +++ b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/connection_settings.py @@ -2,7 +2,8 @@ # Licensed under the MIT License. from os import environ -from typing import Dict, Optional, Any +from typing import Any + from .direct_to_engine_connection_settings_protocol import ( DirectToEngineConnectionSettingsProtocol, ) @@ -19,11 +20,11 @@ def __init__( self, environment_id: str, agent_identifier: str, - cloud: Optional[PowerPlatformCloud] = None, - copilot_agent_type: Optional[AgentType] = None, - custom_power_platform_cloud: Optional[str] = None, - client_session_settings: Optional[dict] = None, - direct_connect_url: Optional[str] = None, + cloud: PowerPlatformCloud | None = None, + copilot_agent_type: AgentType | None = None, + custom_power_platform_cloud: str | None = None, + client_session_settings: dict | None = None, + direct_connect_url: str | None = None, use_experimental_endpoint: bool = False, enable_diagnostics: bool = False, ) -> None: @@ -59,15 +60,15 @@ def __init__( @staticmethod def populate_from_environment( - environment_id: Optional[str] = None, - agent_identifier: Optional[str] = None, - cloud: Optional[PowerPlatformCloud] = None, - copilot_agent_type: Optional[AgentType] = None, - custom_power_platform_cloud: Optional[str] = None, - direct_connect_url: Optional[str] = None, - use_experimental_endpoint: Optional[bool] = None, - enable_diagnostics: Optional[bool] = None, - ) -> Dict[str, Any]: + environment_id: str | None = None, + agent_identifier: str | None = None, + cloud: PowerPlatformCloud | None = None, + copilot_agent_type: AgentType | None = None, + custom_power_platform_cloud: str | None = None, + direct_connect_url: str | None = None, + use_experimental_endpoint: bool | None = None, + enable_diagnostics: bool | None = None, + ) -> dict[str, Any]: """ Populate connection settings from environment variables. diff --git a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/copilot_client.py b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/copilot_client.py index 967b0061..9d5a234f 100644 --- a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/copilot_client.py +++ b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/copilot_client.py @@ -3,7 +3,7 @@ import aiohttp import logging -from typing import AsyncIterable, Callable, Optional +from typing import AsyncIterable, Callable from microsoft_agents.activity import Activity, ActivityTypes, ConversationAccount @@ -126,7 +126,7 @@ async def start_conversation( yield activity async def ask_question( - self, question: str, conversation_id: Optional[str] = None + self, question: str, conversation_id: str | None = None ) -> AsyncIterable[Activity]: """Ask a question in the specified conversation. @@ -236,7 +236,7 @@ async def execute( yield result_activity async def subscribe( - self, conversation_id: str, last_received_event_id: Optional[str] = None + self, conversation_id: str, last_received_event_id: str | None = None ) -> AsyncIterable[SubscribeEvent]: """Subscribe to conversation events. diff --git a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/copilot_client_protocol.py b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/copilot_client_protocol.py index 0aff6a41..c4ea6651 100644 --- a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/copilot_client_protocol.py +++ b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/copilot_client_protocol.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import AsyncIterable, Optional, Protocol +from typing import AsyncIterable, Protocol from microsoft_agents.activity import Activity from .subscribe_event import SubscribeEvent from .start_request import StartRequest @@ -35,7 +35,7 @@ async def start_conversation_with_request( ... async def ask_question( - self, question: str, conversation_id: Optional[str] = None + self, question: str, conversation_id: str | None = None ) -> AsyncIterable[Activity]: """ Ask a question in a conversation. @@ -79,7 +79,7 @@ async def execute( ... async def subscribe( - self, conversation_id: str, last_received_event_id: Optional[str] = None + self, conversation_id: str, last_received_event_id: str | None = None ) -> AsyncIterable[SubscribeEvent]: """ Subscribe to conversation events. diff --git a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/direct_to_engine_connection_settings_protocol.py b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/direct_to_engine_connection_settings_protocol.py index c6d35b7c..e5d5d1d9 100644 --- a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/direct_to_engine_connection_settings_protocol.py +++ b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/direct_to_engine_connection_settings_protocol.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Protocol, Optional +from typing import Protocol from .agent_type import AgentType from .power_platform_cloud import PowerPlatformCloud @@ -13,16 +13,16 @@ class DirectToEngineConnectionSettingsProtocol(Protocol): """ # Schema name for the Copilot Studio Hosted Copilot. - agent_identifier: Optional[str] + agent_identifier: str | None # if PowerPlatformCloud is set to Other, this is the url for the power platform API endpoint. - custom_power_platform_cloud: Optional[str] + custom_power_platform_cloud: str | None # Environment ID for the environment that hosts the agent - environment_id: Optional[str] + environment_id: str | None # Power Platform Cloud where the environment is hosted - cloud: Optional[PowerPlatformCloud] + cloud: PowerPlatformCloud | None # Type of Agent hosted in Copilot Studio - copilot_agent_type: Optional[AgentType] + copilot_agent_type: AgentType | None diff --git a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/power_platform_environment.py b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/power_platform_environment.py index a25321b1..94cc257a 100644 --- a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/power_platform_environment.py +++ b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/power_platform_environment.py @@ -3,7 +3,7 @@ from microsoft_agents.copilotstudio.client.errors import copilot_studio_errors from urllib.parse import urlparse, urlunparse -from typing import Optional + from .connection_settings import ConnectionSettings from .agent_type import AgentType from .power_platform_cloud import PowerPlatformCloud @@ -20,12 +20,12 @@ class PowerPlatformEnvironment: @staticmethod def get_copilot_studio_connection_url( settings: ConnectionSettings, - conversation_id: Optional[str] = None, + conversation_id: str | None = None, agent_type: AgentType = AgentType.PUBLISHED, cloud: PowerPlatformCloud = PowerPlatformCloud.PROD, create_subscribe_link: bool = False, - cloud_base_address: Optional[str] = None, - direct_connect_url: Optional[str] = None, + cloud_base_address: str | None = None, + direct_connect_url: str | None = None, ) -> str: """ Gets the Power Platform API connection URL for the given settings. @@ -97,10 +97,10 @@ def get_copilot_studio_connection_url( @staticmethod def get_token_audience( - settings: Optional[ConnectionSettings] = None, + settings: ConnectionSettings | None = None, cloud: PowerPlatformCloud = PowerPlatformCloud.UNKNOWN, - cloud_base_address: Optional[str] = None, - direct_connect_url: Optional[str] = None, + cloud_base_address: str | None = None, + direct_connect_url: str | None = None, ) -> str: """ Returns the Power Platform API Audience. @@ -183,7 +183,7 @@ def create_uri( agent_identifier: str, host: str, agent_type: AgentType, - conversation_id: Optional[str], + conversation_id: str | None, create_subscribe_link: bool = False, ) -> str: """ @@ -206,7 +206,7 @@ def _create_uri_standard( agent_identifier: str, host: str, agent_type: AgentType, - conversation_id: Optional[str], + conversation_id: str | None, create_subscribe_link: bool = False, ) -> str: """ @@ -243,7 +243,7 @@ def _create_uri_standard( @staticmethod def _create_uri_direct( base_address: str, - conversation_id: Optional[str], + conversation_id: str | None, create_subscribe_link: bool = False, ) -> str: """ @@ -317,7 +317,7 @@ def _decode_cloud_from_uri(uri: str) -> PowerPlatformCloud: def get_environment_endpoint( cloud: PowerPlatformCloud, environment_id: str, - cloud_base_address: Optional[str] = None, + cloud_base_address: str | None = None, ) -> str: if cloud == PowerPlatformCloud.OTHER and not cloud_base_address: raise ValueError(str(copilot_studio_errors.CloudBaseAddressRequired)) diff --git a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/start_request.py b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/start_request.py index 71edac8b..1bbaf068 100644 --- a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/start_request.py +++ b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/start_request.py @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional from microsoft_agents.activity import AgentsModel from pydantic import Field @@ -11,7 +10,7 @@ class StartRequest(AgentsModel): Request model for starting a conversation with Copilot Studio. """ - locale: Optional[str] = Field( + locale: str | None = Field( default=None, description="The locale to use as defined by the client" ) emit_start_conversation_event: bool = Field( @@ -19,7 +18,7 @@ class StartRequest(AgentsModel): alias="emitStartConversationEvent", description="Whether to emit a StartConversation event", ) - conversation_id: Optional[str] = Field( + conversation_id: str | None = Field( default=None, alias="conversationId", description="Conversation ID requested by the client", diff --git a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/subscribe_event.py b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/subscribe_event.py index 202a9686..8bce12ef 100644 --- a/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/subscribe_event.py +++ b/libraries/microsoft-agents-copilotstudio-client/microsoft_agents/copilotstudio/client/subscribe_event.py @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional from microsoft_agents.activity import Activity @@ -10,7 +9,7 @@ class SubscribeEvent: Represents a subscription event containing an activity and optional SSE event ID. """ - def __init__(self, activity: Activity, event_id: Optional[str] = None): + def __init__(self, activity: Activity, event_id: str | None = None): """ Initialize a SubscribeEvent. diff --git a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/_start_agent_process.py b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/_start_agent_process.py index bba42c8f..f00dd8b0 100644 --- a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/_start_agent_process.py +++ b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/_start_agent_process.py @@ -1,4 +1,3 @@ -from typing import Optional from aiohttp.web import Request, Response from microsoft_agents.hosting.core import error_resources from microsoft_agents.hosting.core.app import AgentApplication @@ -9,7 +8,7 @@ async def start_agent_process( request: Request, agent_application: AgentApplication, adapter: CloudAdapter, -) -> Optional[Response]: +) -> Response | None: """Starts the agent host with the provided adapter and agent application. Args: adapter (CloudAdapter): The adapter to use for the agent host. diff --git a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/agent_http_adapter.py b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/agent_http_adapter.py index a0351aa0..2776f4c2 100644 --- a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/agent_http_adapter.py +++ b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/agent_http_adapter.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. from abc import abstractmethod -from typing import Optional, Protocol +from typing import Protocol from aiohttp.web import ( Request, @@ -14,5 +14,5 @@ class AgentHttpAdapter(Protocol): @abstractmethod - async def process(self, request: Request, agent: Agent) -> Optional[Response]: + async def process(self, request: Request, agent: Agent) -> Response | None: raise NotImplementedError() diff --git a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py index 88373953..e1a0e601 100644 --- a/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py +++ b/libraries/microsoft-agents-hosting-aiohttp/microsoft_agents/hosting/aiohttp/cloud_adapter.py @@ -1,6 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional from aiohttp.web import Request, Response, json_response @@ -45,8 +44,8 @@ class CloudAdapter(HttpAdapterBase, AgentHttpAdapter): def __init__( self, *, - connection_manager: Connections = None, - channel_service_client_factory: ChannelServiceClientFactoryBase = None, + connection_manager: Connections | None = None, + channel_service_client_factory: ChannelServiceClientFactoryBase | None = None, ): """ Initializes a new instance of the CloudAdapter class. @@ -59,7 +58,7 @@ def __init__( channel_service_client_factory=channel_service_client_factory, ) - async def process(self, request: Request, agent: Agent) -> Optional[Response]: + async def process(self, request: Request, agent: Agent) -> Response | None: """Process an aiohttp request. Args: diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_flow_state.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_flow_state.py index cbbb77aa..318ea14e 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_flow_state.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_flow_state.py @@ -5,7 +5,6 @@ from datetime import datetime, timezone from enum import Enum -from typing import Optional from pydantic import BaseModel @@ -48,7 +47,7 @@ class _FlowState(BaseModel, StoreItem): auth_handler_id: str = "" expiration: float = 0 - continuation_activity: Optional[Activity] = None + continuation_activity: Activity | None = None attempts_remaining: int = 0 tag: _FlowStateTag = _FlowStateTag.NOT_STARTED diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_flow_storage_client.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_flow_storage_client.py index 867b3aa6..7785d33b 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_flow_storage_client.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_flow_storage_client.py @@ -1,8 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional - from ..storage import Storage from ._flow_state import _FlowState @@ -34,7 +32,7 @@ def __init__( channel_id: str, user_id: str, storage: Storage, - cache_class: Optional[type[Storage]] = None, + cache_class: type[Storage] | None = None, ): """ Args: @@ -65,7 +63,7 @@ def key(self, auth_handler_id: str) -> str: """Creates a storage key for a specific sign-in handler.""" return f"{self._base_key}{auth_handler_id}" - async def read(self, auth_handler_id: str) -> Optional[_FlowState]: + async def read(self, auth_handler_id: str) -> _FlowState | None: """Reads the flow state for a specific authentication handler.""" key: str = self.key(auth_handler_id) data = await self._cache.read([key], target_cls=_FlowState) diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_oauth_flow.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_oauth_flow.py index ce82f50f..5bdf27c4 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_oauth_flow.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/_oauth/_oauth_flow.py @@ -7,7 +7,6 @@ from pydantic import BaseModel from datetime import datetime, timezone -from typing import Optional from microsoft_agents.activity import ( Activity, @@ -28,8 +27,8 @@ class _FlowResponse(BaseModel): flow_state: _FlowState = _FlowState() flow_error_tag: _FlowErrorTag = _FlowErrorTag.NONE - token_response: Optional[TokenResponse] = None - sign_in_resource: Optional[SignInResource] = None + token_response: TokenResponse | None = None + sign_in_resource: SignInResource | None = None class _OAuthFlow: @@ -107,11 +106,11 @@ def __init__( def flow_state(self) -> _FlowState: return self._flow_state.model_copy() - async def get_user_token(self, magic_code: str = None) -> TokenResponse: + async def get_user_token(self, magic_code: str | None = None) -> TokenResponse: """Get the user token based on the context. Args: - magic_code (str, Optional): Defaults to None. The magic code for user authentication. + magic_code (str | None): Defaults to None. The magic code for user authentication. Returns: TokenResponse diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/activity_handler.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/activity_handler.py index 0b584f31..b8547e60 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/activity_handler.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/activity_handler.py @@ -480,7 +480,7 @@ async def on_invoke_activity( # pylint: disable=unused-argument :type turn_context: :class:`microsoft_agents.activity.TurnContextProtocol` :returns: A task that represents the work queued to execute - :rtype: Optional[:class:`microsoft_agents.activity.InvokeResponse`] + :rtype: :class:`microsoft_agents.activity.InvokeResponse` | None """ try: if ( @@ -539,7 +539,7 @@ async def on_adaptive_card_invoke( raise _InvokeResponseException(HTTPStatus.NOT_IMPLEMENTED) @staticmethod - def _create_invoke_response(body: BaseModel = None) -> InvokeResponse: + def _create_invoke_response(body: BaseModel | None = None) -> InvokeResponse: serialized_body = ( body.model_dump(mode="json", by_alias=True, exclude_none=True) if body diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/_routes/_route.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/_routes/_route.py index dfdd9719..8c64c462 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/_routes/_route.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/_routes/_route.py @@ -3,7 +3,7 @@ from __future__ import annotations -from typing import Generic, Optional, TypeVar +from typing import Generic, TypeVar from ...turn_context import TurnContext from .._type_defs import RouteHandler, RouteSelector @@ -35,7 +35,7 @@ def __init__( handler: RouteHandler[StateT], is_invoke: bool = False, rank: int = RouteRank.DEFAULT, - auth_handlers: Optional[list[str]] = None, + auth_handlers: list[str] | None = None, is_agentic: bool = False, **kwargs, ) -> None: diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/agent_application.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/agent_application.py index fbfdf8a2..9d17e4dc 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/agent_application.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/agent_application.py @@ -14,10 +14,8 @@ Awaitable, Callable, Generic, - Optional, Pattern, TypeVar, - Union, cast, ) @@ -68,32 +66,32 @@ class AgentApplication(Agent, Generic[StateT]): typing: TypingIndicator _options: ApplicationOptions - _adapter: Optional[ChannelServiceAdapter] = None - _auth: Optional[Authorization] = None - _proactive: Optional[Proactive] = None + _adapter: ChannelServiceAdapter | None = None + _auth: Authorization | None = None + _proactive: Proactive | None = None _internal_before_turn: list[Callable[[TurnContext, StateT], Awaitable[bool]]] = [] _internal_after_turn: list[Callable[[TurnContext, StateT], Awaitable[bool]]] = [] _route_list: _RouteList[StateT] = _RouteList[StateT]() - _error: Optional[Callable[[TurnContext, Exception], Awaitable[None]]] = None - _turn_state_factory: Optional[Callable[[TurnContext], StateT]] = None + _error: Callable[[TurnContext, Exception], Awaitable[None]] | None = None + _turn_state_factory: Callable[[TurnContext], StateT] | None = None def __init__( self, - options: Optional[ApplicationOptions] = None, + options: ApplicationOptions | None = None, *, - connection_manager: Optional[Connections] = None, - authorization: Optional[Authorization] = None, + connection_manager: Connections | None = None, + authorization: Authorization | None = None, **kwargs, ) -> None: """ Creates a new AgentApplication instance. :param options: Configuration options for the application. - :type options: Optional[:class:`microsoft_agents.hosting.core.app.app_options.ApplicationOptions`] + :type options: :class:`microsoft_agents.hosting.core.app.app_options.ApplicationOptions` | None :param connection_manager: OAuth connection manager. - :type connection_manager: Optional[:class:`microsoft_agents.hosting.core.authorization.Connections`] + :type connection_manager: :class:`microsoft_agents.hosting.core.authorization.Connections` | None :param authorization: Authorization manager for handling authentication flows. - :type authorization: Optional[:class:`microsoft_agents.hosting.core.app.oauth.Authorization`] + :type authorization: :class:`microsoft_agents.hosting.core.app.oauth.Authorization` | None :param kwargs: Additional configuration parameters. :type kwargs: Any """ @@ -251,7 +249,7 @@ def add_route( is_invoke: bool = False, is_agentic: bool = False, rank: RouteRank = RouteRank.DEFAULT, - auth_handlers: Optional[list[str]] = None, + auth_handlers: list[str] | None = None, ) -> None: """Adds a new route to the application. @@ -269,7 +267,7 @@ def add_route( :param rank: The rank of the route, defaults to RouteRank.DEFAULT :type rank: :class:`microsoft_agents.hosting.core.app._routes.route_rank.RouteRank`, Optional :param auth_handlers: A list of authentication handler IDs to use for this route, defaults to None - :type auth_handlers: Optional[list[str]], Optional + :type auth_handlers: list[str] | None :raises ApplicationError: If the selector or handler are not valid. """ if not selector or not handler: @@ -288,9 +286,9 @@ def add_route( def activity( self, - activity_type: Union[str, ActivityTypes, list[Union[str, ActivityTypes]]], + activity_type: str | ActivityTypes | list[str | ActivityTypes], *, - auth_handlers: Optional[list[str]] = None, + auth_handlers: list[str] | None = None, **kwargs, ) -> Callable[[RouteHandler[StateT]], RouteHandler[StateT]]: """ @@ -307,7 +305,7 @@ async def on_event(context: TurnContext, state: TurnState): :param activity_type: Activity type or collection of types that should trigger the handler. :type activity_type: Union[str, microsoft_agents.activity.ActivityTypes, list[Union[str, microsoft_agents.activity.ActivityTypes]]] :param auth_handlers: Optional list of authorization handler IDs for the route. - :type auth_handlers: Optional[list[str]] + :type auth_handlers: list[str] | None :param kwargs: Additional route configuration passed to :meth:`add_route`. """ @@ -325,9 +323,9 @@ def __call(func: RouteHandler[StateT]) -> RouteHandler[StateT]: def message( self, - select: Union[str, Pattern[str], list[Union[str, Pattern[str]]]], + select: str | Pattern[str] | list[str | Pattern[str]], *, - auth_handlers: Optional[list[str]] = None, + auth_handlers: list[str] | None = None, **kwargs, ) -> Callable[[RouteHandler[StateT]], RouteHandler[StateT]]: """ @@ -342,9 +340,9 @@ async def on_hi_message(context: TurnContext, state: TurnState): return True :param select: Literal text, compiled regex, or list of either used to match the incoming message. - :type select: Union[str, Pattern[str], list[Union[str, Pattern[str]]]] + :type select: str | Pattern[str] | list[str | Pattern[str]] :param auth_handlers: Optional list of authorization handler IDs for the route. - :type auth_handlers: Optional[list[str]] + :type auth_handlers: list[str] | None :param kwargs: Additional route configuration passed to :meth:`add_route`. """ @@ -372,7 +370,7 @@ def conversation_update( self, type: ConversationUpdateTypes, *, - auth_handlers: Optional[list[str]] = None, + auth_handlers: list[str] | None = None, **kwargs, ) -> Callable[[RouteHandler[StateT]], RouteHandler[StateT]]: """ @@ -389,7 +387,7 @@ async def on_channel_created(context: TurnContext, state: TurnState): :param type: Conversation update category that must match the incoming activity. :type type: microsoft_agents.activity.ConversationUpdateTypes :param auth_handlers: Optional list of authorization handler IDs for the route. - :type auth_handlers: Optional[list[str]] + :type auth_handlers: list[str] | None :param kwargs: Additional route configuration passed to :meth:`add_route`. """ @@ -426,7 +424,7 @@ def message_reaction( self, type: MessageReactionTypes, *, - auth_handlers: Optional[list[str]] = None, + auth_handlers: list[str] | None = None, **kwargs, ) -> Callable[[RouteHandler[StateT]], RouteHandler[StateT]]: """ @@ -443,7 +441,7 @@ async def on_reactions_added(context: TurnContext, state: TurnState): :param type: Reaction category that must match the incoming activity. :type type: microsoft_agents.activity.MessageReactionTypes :param auth_handlers: Optional list of authorization handler IDs for the route. - :type auth_handlers: Optional[list[str]] + :type auth_handlers: list[str] | None :param kwargs: Additional route configuration passed to :meth:`add_route`. """ @@ -476,7 +474,7 @@ def message_update( self, type: MessageUpdateTypes, *, - auth_handlers: Optional[list[str]] = None, + auth_handlers: list[str] | None = None, **kwargs, ) -> Callable[[RouteHandler[StateT]], RouteHandler[StateT]]: """ @@ -493,7 +491,7 @@ async def on_edit_message(context: TurnContext, state: TurnState): :param type: Message update category that must match the incoming activity. :type type: microsoft_agents.activity.MessageUpdateTypes :param auth_handlers: Optional list of authorization handler IDs for the route. - :type auth_handlers: Optional[list[str]] + :type auth_handlers: list[str] | None :param kwargs: Additional route configuration passed to :meth:`add_route`. """ @@ -535,9 +533,7 @@ def __call(func: RouteHandler[StateT]) -> RouteHandler[StateT]: return __call - def handoff( - self, *, auth_handlers: Optional[list[str]] = None, **kwargs - ) -> Callable[ + def handoff(self, *, auth_handlers: list[str] | None = None, **kwargs) -> Callable[ [Callable[[TurnContext, StateT, str], Awaitable[None]]], Callable[[TurnContext, StateT, str], Awaitable[None]], ]: @@ -552,7 +548,7 @@ async def on_handoff(context: TurnContext, state: TurnState, continuation: str): print(continuation) :param auth_handlers: Optional list of authorization handler IDs for the route. - :type auth_handlers: Optional[list[str]] + :type auth_handlers: list[str] | None :param kwargs: Additional route configuration passed to :meth:`add_route`. """ @@ -587,8 +583,8 @@ async def __handler(context: TurnContext, state: StateT): return __call def on_sign_in_success( - self, func: Callable[[TurnContext, StateT, Optional[str]], Awaitable[None]] - ) -> Callable[[TurnContext, StateT, Optional[str]], Awaitable[None]]: + self, func: Callable[[TurnContext, StateT, str | None], Awaitable[None]] + ) -> Callable[[TurnContext, StateT, str | None], Awaitable[None]]: """ Register a callback that executes when a user successfully signs in. @@ -600,7 +596,7 @@ async def sign_in_success(context: TurnContext, state: TurnState, connection_id: print("sign-in succeeded") :param func: Callable that handles the sign-in success event. - :type func: Callable[[TurnContext, StateT, Optional[str]], Awaitable[None]] + :type func: Callable[[TurnContext, StateT, str | None], Awaitable[None]] :raises ApplicationError: If authorization services are not configured. """ @@ -621,8 +617,8 @@ async def sign_in_success(context: TurnContext, state: TurnState, connection_id: return func def on_sign_in_failure( - self, func: Callable[[TurnContext, StateT, Optional[str]], Awaitable[None]] - ) -> Callable[[TurnContext, StateT, Optional[str]], Awaitable[None]]: + self, func: Callable[[TurnContext, StateT, str | None], Awaitable[None]] + ) -> Callable[[TurnContext, StateT, str | None], Awaitable[None]]: """ Register a callback that executes when a user fails to sign in. @@ -634,7 +630,7 @@ async def sign_in_failure(context: TurnContext, state: TurnState, connection_id: print("sign-in failed") :param func: Callable that handles the sign-in failure event. - :type func: Callable[[TurnContext, StateT, Optional[str]], Awaitable[None]] + :type func: Callable[[TurnContext, StateT, str | None], Awaitable[None]] :raises ApplicationError: If authorization services are not configured. """ diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/app_options.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/app_options.py index a66ca494..3393ddd6 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/app_options.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/app_options.py @@ -7,7 +7,7 @@ from dataclasses import dataclass, field from logging import Logger -from typing import Callable, List, Optional +from typing import Callable from microsoft_agents.hosting.core.app.oauth import AuthHandler from microsoft_agents.hosting.core.storage import Storage @@ -24,7 +24,7 @@ @dataclass class ApplicationOptions: - adapter: Optional[ChannelServiceAdapter] = None + adapter: ChannelServiceAdapter | None = None """ Optional. Options used to initialize your `BotAdapter` """ @@ -39,7 +39,7 @@ class ApplicationOptions: Optional. `AgentApplication` ID of the bot. """ - storage: Optional[Storage] = None + storage: Storage | None = None """ Optional. `Storage` provider to use for the application. """ @@ -73,25 +73,25 @@ class ApplicationOptions: will mark the bot's process as idle and shut it down. """ - file_downloaders: List[InputFileDownloader] = field(default_factory=list) + file_downloaders: list[InputFileDownloader] = field(default_factory=list) """ Optional. Array of input file download plugins to use. """ - turn_state_factory: Optional[Callable[[], TurnState]] = None + turn_state_factory: Callable[[], TurnState] | None = None """ Optional. Factory function to create the turn state. This should return an instance of `TurnState` or a subclass. If not provided, the default `TurnState` will be used. """ - authorization_handlers: Optional[dict[str, AuthHandler]] = None + authorization_handlers: dict[str, AuthHandler] | None = None """ Optional. Authorization handler for OAuth flows. If not provided, no OAuth flows will be supported. """ - proactive: Optional[ProactiveOptions] = None + proactive: ProactiveOptions | None = None """ Optional. Options for the proactive messaging subsystem. When set, :attr:`AgentApplication.proactive` is available for storing diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/input_file.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/input_file.py index 7039bb9c..a0026390 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/input_file.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/input_file.py @@ -7,7 +7,6 @@ from abc import ABC, abstractmethod from dataclasses import dataclass -from typing import List, Optional from microsoft_agents.hosting.core import TurnContext @@ -21,12 +20,12 @@ class InputFile: :param content_type: The content type of the file. :type content_type: str :param content_url: Optional. URL to the content of the file. - :type content_url: Optional[str] + :type content_url: str | None """ content: bytes content_type: str - content_url: Optional[str] + content_url: str | None class InputFileDownloader(ABC): @@ -38,7 +37,7 @@ class InputFileDownloader(ABC): """ @abstractmethod - async def download_files(self, context: TurnContext) -> List[InputFile]: + async def download_files(self, context: TurnContext) -> list[InputFile]: """ Download any files referenced by the incoming activity for the current turn. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/_authorization_handler.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/_authorization_handler.py index 542b74cb..83afa4e0 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/_authorization_handler.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/_authorization_handler.py @@ -4,7 +4,6 @@ """ from abc import ABC -from typing import Optional import logging from microsoft_agents.activity import TokenResponse @@ -29,10 +28,10 @@ def __init__( self, storage: Storage, connection_manager: Connections, - auth_handler: Optional[AuthHandler] = None, + auth_handler: AuthHandler | None = None, *, - auth_handler_id: Optional[str] = None, - auth_handler_settings: Optional[dict] = None, + auth_handler_id: str | None = None, + auth_handler_settings: dict | None = None, **kwargs, ) -> None: """ @@ -68,14 +67,14 @@ def __init__( ) async def _sign_in( - self, context: TurnContext, scopes: Optional[list[str]] = None + self, context: TurnContext, scopes: list[str] | None = None ) -> _SignInResponse: """Initiate or continue the sign-in process for the user with the given auth handler. :param context: The turn context for the current turn of conversation. :type context: TurnContext :param scopes: Optional list of scopes to request during sign-in. If None, default scopes will be used. - :type scopes: Optional[list[str]], Optional + :type scopes: list[str] | None :return: A SignInResponse indicating the result of the sign-in attempt. :rtype: SignInResponse """ @@ -84,17 +83,17 @@ async def _sign_in( async def get_refreshed_token( self, context: TurnContext, - exchange_connection: Optional[str] = None, - exchange_scopes: Optional[list[str]] = None, + exchange_connection: str | None = None, + exchange_scopes: list[str] | None = None, ) -> TokenResponse: """Attempts to get a refreshed token for the user with the given scopes :param context: The turn context for the current turn of conversation. :type context: TurnContext :param exchange_connection: Optional name of the connection to use for token exchange. If None, default connection will be used. - :type exchange_connection: Optional[str], Optional + :type exchange_connection: str | None :param exchange_scopes: Optional list of scopes to request during token exchange. If None, default scopes will be used. - :type exchange_scopes: Optional[list[str]], Optional + :type exchange_scopes: list[str] | None """ raise NotImplementedError() @@ -104,6 +103,6 @@ async def _sign_out(self, context: TurnContext) -> None: :param context: The turn context for the current turn of conversation. :type context: TurnContext :param auth_handler_id: The ID of the auth handler to sign out from. If None, sign out from all handlers. - :type auth_handler_id: Optional[str] + :type auth_handler_id: str | None """ raise NotImplementedError() diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/_user_authorization.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/_user_authorization.py index 81a02b83..cd8a8b00 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/_user_authorization.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/_user_authorization.py @@ -5,8 +5,6 @@ from __future__ import annotations import logging -import jwt -from typing import Optional from microsoft_agents.activity import ( Attachment, @@ -96,8 +94,8 @@ async def _handle_obo( self, context: TurnContext, input_token_response: TokenResponse, - exchange_connection: Optional[str] = None, - exchange_scopes: Optional[list[str]] = None, + exchange_connection: str | None = None, + exchange_scopes: list[str] | None = None, ) -> TokenResponse: """ Exchanges a token for another token with different scopes. @@ -205,8 +203,8 @@ async def _handle_flow_response( async def _sign_in( self, context: TurnContext, - exchange_connection: Optional[str] = None, - exchange_scopes: Optional[list[str]] = None, + exchange_connection: str | None = None, + exchange_scopes: list[str] | None = None, ) -> _SignInResponse: """Begins or continues an OAuth flow. @@ -257,17 +255,17 @@ async def _sign_in( async def get_refreshed_token( self, context: TurnContext, - exchange_connection: Optional[str] = None, - exchange_scopes: Optional[list[str]] = None, + exchange_connection: str | None = None, + exchange_scopes: list[str] | None = None, ) -> TokenResponse: """Attempts to get a refreshed token for the user with the given scopes :param context: The turn context for the current turn of conversation. :type context: TurnContext :param exchange_connection: Optional name of the connection to use for token exchange. If None, default connection will be used. - :type exchange_connection: Optional[str], Optional + :type exchange_connection: str | None :param exchange_scopes: Optional list of scopes to request during token exchange. If None, default scopes will be used. - :type exchange_scopes: Optional[list[str]], Optional + :type exchange_scopes: list[str] | None """ flow, _ = await self._load_flow(context) input_token_response = await flow.get_user_token() diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/agentic_user_authorization.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/agentic_user_authorization.py index 548edaab..8427d571 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/agentic_user_authorization.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/agentic_user_authorization.py @@ -5,8 +5,6 @@ import logging -from typing import Optional - from microsoft_agents.activity import TokenResponse from ....turn_context import TurnContext @@ -28,10 +26,10 @@ def __init__( self, storage: Storage, connection_manager: Connections, - auth_handler: Optional[AuthHandler] = None, + auth_handler: AuthHandler | None = None, *, - auth_handler_id: Optional[str] = None, - auth_handler_settings: Optional[dict] = None, + auth_handler_id: str | None = None, + auth_handler_settings: dict | None = None, **kwargs, ) -> None: """ @@ -63,7 +61,7 @@ async def get_agentic_instance_token(self, context: TurnContext) -> TokenRespons :param context: The context object for the current turn. :type context: TurnContext :return: The agentic instance token, or None if not an agentic request. - :rtype: Optional[str] + :rtype: str | None """ if not context.activity.is_agentic_request(): @@ -92,7 +90,7 @@ async def get_agentic_user_token( :param scopes: The scopes to request for the token. :type scopes: list[str] :return: The agentic user token, or None if not an agentic request or no user. - :rtype: Optional[str] + :rtype: str | None """ logger.info("Retrieving agentic user token for scopes: %s", scopes) @@ -142,8 +140,8 @@ async def get_agentic_user_token( async def _sign_in( self, context: TurnContext, - exchange_connection: Optional[str] = None, - exchange_scopes: Optional[list[str]] = None, + exchange_connection: str | None = None, + exchange_scopes: list[str] | None = None, ) -> _SignInResponse: """Retrieves the agentic user token if available. @@ -152,7 +150,7 @@ async def _sign_in( :param connection_name: The name of the connection to use for sign-in. :type connection_name: str :param scopes: The scopes to request for the token. - :type scopes: Optional[list[str]] + :type scopes: list[str] | None :return: A _SignInResponse containing the token response and flow state tag. :rtype: _SignInResponse """ @@ -168,17 +166,17 @@ async def _sign_in( async def get_refreshed_token( self, context: TurnContext, - exchange_connection: Optional[str] = None, - exchange_scopes: Optional[list[str]] = None, + exchange_connection: str | None = None, + exchange_scopes: list[str] | None = None, ) -> TokenResponse: """Attempts to get a refreshed token for the user with the given scopes :param context: The turn context for the current turn of conversation. :type context: TurnContext :param exchange_connection: Optional name of the connection to use for token exchange. If None, default connection will be used. - :type exchange_connection: Optional[str], Optional + :type exchange_connection: str | None :param exchange_scopes: Optional list of scopes to request during token exchange. If None, default scopes will be used. - :type exchange_scopes: Optional[list[str]], Optional + :type exchange_scopes: list[str] | None """ with spans.AgenticToken( auth_handler_id=self._id, @@ -190,6 +188,6 @@ async def get_refreshed_token( return await self.get_agentic_user_token(context, exchange_scopes) async def sign_out( - self, context: TurnContext, auth_handler_id: Optional[str] = None + self, context: TurnContext, auth_handler_id: str | None = None ) -> None: """Nothing to do for agentic sign out.""" diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/connector_user_authorization.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/connector_user_authorization.py index 61f838f7..53c93b45 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/connector_user_authorization.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_handlers/connector_user_authorization.py @@ -6,7 +6,6 @@ import logging import jwt from datetime import datetime, timezone -from typing import Optional from microsoft_agents.activity import TokenResponse from microsoft_agents.hosting.core.errors import ErrorResources @@ -32,10 +31,10 @@ def __init__( self, storage: Storage, connection_manager: Connections, - auth_handler: Optional[AuthHandler] = None, + auth_handler: AuthHandler | None = None, *, - auth_handler_id: Optional[str] = None, - auth_handler_settings: Optional[dict] = None, + auth_handler_id: str | None = None, + auth_handler_settings: dict | None = None, **kwargs, ) -> None: """ @@ -64,8 +63,8 @@ def __init__( async def _sign_in( self, context: TurnContext, - exchange_connection: Optional[str] = None, - exchange_scopes: Optional[list[str]] = None, + exchange_connection: str | None = None, + exchange_scopes: list[str] | None = None, ) -> _SignInResponse: """ For connector requests, there is no separate sign-in flow. @@ -74,9 +73,9 @@ async def _sign_in( :param context: The turn context for the current turn of conversation. :type context: TurnContext :param exchange_connection: Optional connection name for token exchange. - :type exchange_connection: Optional[str] + :type exchange_connection: str | None :param exchange_scopes: Optional list of scopes (unused for connector auth). - :type exchange_scopes: Optional[list[str]] + :type exchange_scopes: list[str] | None :return: A SignInResponse with the extracted token. :rtype: _SignInResponse """ @@ -89,8 +88,8 @@ async def _sign_in( async def get_refreshed_token( self, context: TurnContext, - exchange_connection: Optional[str] = None, - exchange_scopes: Optional[list[str]] = None, + exchange_connection: str | None = None, + exchange_scopes: list[str] | None = None, ) -> TokenResponse: """ Gets the connector user token and optionally exchanges it via OBO. @@ -98,9 +97,9 @@ async def get_refreshed_token( :param context: The turn context for the current turn of conversation. :type context: TurnContext :param exchange_connection: Optional name of the connection to use for token exchange. - :type exchange_connection: Optional[str], Optional + :type exchange_connection: str | None, Optional :param exchange_scopes: Optional list of scopes to request during token exchange. - :type exchange_scopes: Optional[list[str]], Optional + :type exchange_scopes: list[str] | None, Optional :return: The token response, potentially after OBO exchange. :rtype: TokenResponse """ @@ -146,8 +145,8 @@ async def _handle_obo( self, context: TurnContext, input_token_response: TokenResponse, - exchange_connection: Optional[str] = None, - exchange_scopes: Optional[list[str]] = None, + exchange_connection: str | None = None, + exchange_scopes: list[str] | None = None, ) -> TokenResponse: """ Exchanges a token for another token with different scopes via OBO flow. @@ -157,9 +156,9 @@ async def _handle_obo( :param input_token_response: The input token to exchange. :type input_token_response: TokenResponse :param exchange_connection: Optional connection name for exchange. - :type exchange_connection: Optional[str] + :type exchange_connection: str | None :param exchange_scopes: Optional scopes for the exchanged token. - :type exchange_scopes: Optional[list[str]] + :type exchange_scopes: list[str] | None :return: The token response after exchange, or the original if exchange not configured. :rtype: TokenResponse """ diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_sign_in_response.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_sign_in_response.py index 0c756697..ddae270b 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_sign_in_response.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_sign_in_response.py @@ -2,8 +2,6 @@ # Licensed under the MIT License. -from typing import Optional - from microsoft_agents.activity import TokenResponse from ..._oauth import _FlowStateTag @@ -17,7 +15,7 @@ class _SignInResponse: def __init__( self, - token_response: Optional[TokenResponse] = None, + token_response: TokenResponse | None = None, tag: _FlowStateTag = _FlowStateTag.FAILURE, ) -> None: self.token_response = token_response or TokenResponse() diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_sign_in_state.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_sign_in_state.py index bd16530a..233af643 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_sign_in_state.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/_sign_in_state.py @@ -5,8 +5,6 @@ from __future__ import annotations -from typing import Optional - from pydantic import BaseModel from microsoft_agents.activity import Activity @@ -23,7 +21,7 @@ class _SignInState(BaseModel, StoreItem): """ active_handler_id: str - continuation_activity: Optional[Activity] = None + continuation_activity: Activity | None = None def store_item_to_json(self) -> JSON: return self.model_dump(mode="json", exclude_unset=True, by_alias=True) diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/auth_handler.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/auth_handler.py index 4d11b212..1d3c7a3a 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/auth_handler.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/auth_handler.py @@ -4,7 +4,6 @@ """ import logging -from typing import Optional logger = logging.getLogger(__name__) @@ -32,7 +31,7 @@ def __init__( abs_oauth_connection_name: str = "", obo_connection_name: str = "", auth_type: str = "", - scopes: Optional[list[str]] = None, + scopes: list[str] | None = None, **kwargs, ): """ diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/authorization.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/authorization.py index 267c3b89..873da5b2 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/authorization.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/oauth/authorization.py @@ -3,10 +3,8 @@ Licensed under the MIT License. """ -from datetime import datetime import logging -from typing import TypeVar, Optional, Callable, Awaitable, Generic, cast -import jwt +from typing import Callable, Awaitable, cast from microsoft_agents.activity import Activity, TokenResponse @@ -45,7 +43,7 @@ def __init__( self, storage: Storage, connection_manager: Connections, - auth_handlers: Optional[dict[str, AuthHandler]] = None, + auth_handlers: dict[str, AuthHandler] | None = None, auto_sign_in: bool = False, use_cache: bool = False, **kwargs, @@ -61,7 +59,7 @@ def __init__( :param connection_manager: The connection manager for OAuth providers. :type connection_manager: :class:`microsoft_agents.hosting.core.authorization.Connections` :param auth_handlers: Configuration for OAuth providers. - :type auth_handlers: dict[str, :class:`microsoft_agents.hosting.core.app.oauth.auth_handler.AuthHandler`], Optional + :type auth_handlers: dict[str, :class:`microsoft_agents.hosting.core.app.oauth.auth_handler.AuthHandler`] | None :raises ValueError: When storage is None or no auth handlers provided. """ if not storage: @@ -70,12 +68,12 @@ def __init__( self._storage = storage self._connection_manager = connection_manager - self._sign_in_success_handler: Optional[ - Callable[[TurnContext, TurnState, Optional[str]], Awaitable[None]] - ] = None - self._sign_in_failure_handler: Optional[ - Callable[[TurnContext, TurnState, Optional[str]], Awaitable[None]] - ] = None + self._sign_in_success_handler: ( + Callable[[TurnContext, TurnState, str | None], Awaitable[None]] | None + ) = None + self._sign_in_failure_handler: ( + Callable[[TurnContext, TurnState, str | None], Awaitable[None]] | None + ) = None self._handlers = {} @@ -139,13 +137,13 @@ def _sign_in_state_key(context: TurnContext) -> str: """ return f"auth:_SignInState:{context.activity.channel_id}:{context.activity.from_property.id}" - async def _load_sign_in_state(self, context: TurnContext) -> Optional[_SignInState]: + async def _load_sign_in_state(self, context: TurnContext) -> _SignInState | None: """Load the sign-in state from storage for the given context. :param context: The turn context for the current turn of conversation. :type context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext` :return: The sign-in state if found, None otherwise. - :rtype: Optional[:class:`microsoft_agents.hosting.core.app.oauth._sign_in_state._SignInState`] + :rtype: :class:`microsoft_agents.hosting.core.app.oauth._sign_in_state._SignInState` | None """ key = self._sign_in_state_key(context) return (await self._storage.read([key], target_cls=_SignInState)).get(key) @@ -179,9 +177,9 @@ def _cache_key(context: TurnContext, handler_id: str) -> str: @staticmethod def _get_cached_token( context: TurnContext, handler_id: str - ) -> Optional[TokenResponse]: + ) -> TokenResponse | None: key = Authorization._cache_key(context, handler_id) - return cast(Optional[TokenResponse], context.turn_state.get(key)) + return cast(TokenResponse | None, context.turn_state.get(key)) @staticmethod def _cache_token( @@ -215,7 +213,7 @@ async def _start_or_continue_sign_in( self, context: TurnContext, state: TurnState, - auth_handler_id: Optional[str] = None, + auth_handler_id: str | None = None, ) -> _SignInResponse: """Start or continue the sign-in process for the user with the given auth handler. @@ -268,14 +266,14 @@ async def _start_or_continue_sign_in( return sign_in_response async def sign_out( - self, context: TurnContext, auth_handler_id: Optional[str] = None + self, context: TurnContext, auth_handler_id: str | None = None ) -> None: """Attempts to sign out the user from a specified auth handler or the default handler. :param context: The turn context for the current turn of conversation. :type context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext` :param auth_handler_id: The ID of the auth handler to sign out from. If None, sign out from all handlers. - :type auth_handler_id: Optional[str] + :type auth_handler_id: str | None :return: None """ auth_handler_id = auth_handler_id or self._default_handler_id @@ -286,7 +284,7 @@ async def sign_out( async def _on_turn_auth_intercept( self, context: TurnContext, state: TurnState - ) -> tuple[bool, Optional[Activity]]: + ) -> tuple[bool, Activity | None]: """Intercepts the turn to check for active authentication flows. Returns true if the rest of the turn should be skipped because auth did not finish. @@ -299,7 +297,7 @@ async def _on_turn_auth_intercept( :param state: The turn state for the current turn. :type state: :class:`microsoft_agents.hosting.core.app.state.turn_state.TurnState` :return: A tuple indicating whether the turn should be skipped and the continuation activity if applicable. - :rtype: tuple[bool, Optional[:class:`microsoft_agents.activity.Activity`]] + :rtype: tuple[bool, :class:`microsoft_agents.activity.Activity` | None] """ sign_in_state = await self._load_sign_in_state(context) @@ -325,7 +323,7 @@ async def _on_turn_auth_intercept( return False, None async def get_token( - self, context: TurnContext, auth_handler_id: Optional[str] = None + self, context: TurnContext, auth_handler_id: str | None = None ) -> TokenResponse: """Gets the token for a specific auth handler or the default handler. @@ -343,9 +341,9 @@ async def get_token( async def exchange_token( self, context: TurnContext, - scopes: Optional[list[str]] = None, - auth_handler_id: Optional[str] = None, - exchange_connection: Optional[str] = None, + scopes: list[str] | None = None, + auth_handler_id: str | None = None, + exchange_connection: str | None = None, ) -> TokenResponse: """Exchanges or refreshes the token for a specific auth handler or the default handler. @@ -353,13 +351,13 @@ async def exchange_token( :type context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext` :param scopes: The scopes to request during the token exchange or refresh. Defaults to the list given in the AuthHandler configuration if None. - :type scopes: Optional[list[str]] + :type scopes: list[str] | None :param auth_handler_id: The ID of the auth handler to exchange or refresh the token for. If None, the default handler will be used. - :type auth_handler_id: Optional[str] + :type auth_handler_id: str | None :param exchange_connection: The name of the connection to use for token exchange. If None, the connection defined in the AuthHandler configuration will be used. - :type exchange_connection: Optional[str] + :type exchange_connection: str | None :return: The token response from the OAuth provider. :rtype: :class:`microsoft_agents.activity.TokenResponse` :raises ValueError: If the specified auth handler ID is not recognized or not configured. @@ -396,24 +394,24 @@ async def exchange_token( def on_sign_in_success( self, - handler: Callable[[TurnContext, TurnState, Optional[str]], Awaitable[None]], + handler: Callable[[TurnContext, TurnState, str | None], Awaitable[None]], ) -> None: """ Sets a handler to be called when sign-in is successfully completed. :param handler: The handler function to call on successful sign-in. - :type handler: Callable[[:class:`microsoft_agents.hosting.core.turn_context.TurnContext`, :class:`microsoft_agents.hosting.core.app.state.turn_state.TurnState`, Optional[str]], Awaitable[None]] + :type handler: Callable[[:class:`microsoft_agents.hosting.core.turn_context.TurnContext`, :class:`microsoft_agents.hosting.core.app.state.turn_state.TurnState`, str | None], Awaitable[None]] """ self._sign_in_success_handler = handler def on_sign_in_failure( self, - handler: Callable[[TurnContext, TurnState, Optional[str]], Awaitable[None]], + handler: Callable[[TurnContext, TurnState, str | None], Awaitable[None]], ) -> None: """ Sets a handler to be called when sign-in fails. :param handler: The handler function to call on sign-in failure. - :type handler: Callable[[:class:`microsoft_agents.hosting.core.turn_context.TurnContext`, :class:`microsoft_agents.hosting.core.app.state.turn_state.TurnState`, Optional[str]], Awaitable[None]] + :type handler: Callable[[:class:`microsoft_agents.hosting.core.turn_context.TurnContext`, :class:`microsoft_agents.hosting.core.app.state.turn_state.TurnState`, str | None], Awaitable[None]] """ self._sign_in_failure_handler = handler diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation.py index d75b3be1..b9c397dc 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation.py @@ -5,7 +5,7 @@ from __future__ import annotations -from typing import Optional, TYPE_CHECKING +from typing import TYPE_CHECKING from microsoft_agents.activity import ConversationReference from microsoft_agents.hosting.core.authorization import ClaimsIdentity @@ -67,7 +67,7 @@ def from_turn_context(cls, context: "TurnContext") -> "Conversation": """ from microsoft_agents.hosting.core.channel_adapter import ChannelAdapter - identity: Optional[ClaimsIdentity] = context.turn_state.get( + identity: ClaimsIdentity | None = context.turn_state.get( ChannelAdapter.AGENT_IDENTITY_KEY ) reference = context.activity.get_conversation_reference() diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation_builder.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation_builder.py index 6c800bed..7e71c0cb 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation_builder.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation_builder.py @@ -5,8 +5,6 @@ from __future__ import annotations -from typing import Optional - from microsoft_agents.activity import ( ChannelAccount, Channels, @@ -45,16 +43,16 @@ class ConversationBuilder: def __init__(self) -> None: self._claims: dict[str, str] = {} - self._channel_id: Optional[str] = None - self._service_url: Optional[str] = None - self._agent_id: Optional[str] = None - self._agent_name: Optional[str] = None - self._user_id: Optional[str] = None - self._user_name: Optional[str] = None - self._conversation_id: Optional[str] = None - self._conversation_name: Optional[str] = None - self._tenant_id: Optional[str] = None - self._activity_id: Optional[str] = None + self._channel_id: str | None = None + self._service_url: str | None = None + self._agent_id: str | None = None + self._agent_name: str | None = None + self._user_id: str | None = None + self._user_name: str | None = None + self._conversation_id: str | None = None + self._conversation_name: str | None = None + self._tenant_id: str | None = None + self._activity_id: str | None = None # ------------------------------------------------------------------ # Entry-point factories @@ -65,8 +63,8 @@ def create( cls, agent_client_id: str, channel_id: str, - service_url: Optional[str] = None, - requestor_id: Optional[str] = None, + service_url: str | None = None, + requestor_id: str | None = None, ) -> "ConversationBuilder": """ Start building a :class:`~microsoft_agents.hosting.core.app.proactive.conversation.Conversation` @@ -79,10 +77,10 @@ def create( :type channel_id: str :param service_url: Override the service URL. Defaults to the canonical URL for *channel_id*. - :type service_url: Optional[str] + :type service_url: str | None :param requestor_id: If provided, stored as the ``appid`` claim (useful when the requestor differs from the audience). - :type requestor_id: Optional[str] + :type requestor_id: str | None :return: A builder pre-populated with the supplied claims. :rtype: :class:`ConversationBuilder` """ @@ -106,7 +104,7 @@ def create_from_identity( cls, identity: ClaimsIdentity, channel_id: str, - service_url: Optional[str] = None, + service_url: str | None = None, ) -> "ConversationBuilder": """ Start building a :class:`~microsoft_agents.hosting.core.app.proactive.conversation.Conversation` @@ -117,7 +115,7 @@ def create_from_identity( :param channel_id: The channel identifier. :type channel_id: str :param service_url: Override the service URL. - :type service_url: Optional[str] + :type service_url: str | None :return: A builder pre-populated with the identity's claims. :rtype: :class:`ConversationBuilder` """ @@ -142,7 +140,7 @@ def create_from_identity( def with_user( self, user_id: str, - user_name: Optional[str] = None, + user_name: str | None = None, ) -> "ConversationBuilder": """ Set the user account. @@ -150,7 +148,7 @@ def with_user( :param user_id: The user's channel account ID. :type user_id: str :param user_name: Optional display name. - :type user_name: Optional[str] + :type user_name: str | None :return: ``self`` for chaining. :rtype: :class:`ConversationBuilder` """ @@ -161,8 +159,8 @@ def with_user( def with_conversation( self, conversation_id: str, - conversation_name: Optional[str] = None, - tenant_id: Optional[str] = None, + conversation_name: str | None = None, + tenant_id: str | None = None, ) -> "ConversationBuilder": """ Set the conversation account details. @@ -170,9 +168,9 @@ def with_conversation( :param conversation_id: The conversation ID. :type conversation_id: str :param conversation_name: Optional conversation name. - :type conversation_name: Optional[str] + :type conversation_name: str | None :param tenant_id: Optional tenant ID. - :type tenant_id: Optional[str] + :type tenant_id: str | None :return: ``self`` for chaining. :rtype: :class:`ConversationBuilder` """ diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation_reference_builder.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation_reference_builder.py index 05189da3..e1e514ee 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation_reference_builder.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/conversation_reference_builder.py @@ -5,8 +5,6 @@ from __future__ import annotations -from typing import Optional - from microsoft_agents.activity import ( ChannelAccount, Channels, @@ -45,15 +43,15 @@ class ConversationReferenceBuilder: """ def __init__(self) -> None: - self._channel_id: Optional[str] = None - self._conversation_id: Optional[str] = None - self._service_url: Optional[str] = None - self._agent_id: Optional[str] = None - self._agent_name: Optional[str] = None - self._user_id: Optional[str] = None - self._user_name: Optional[str] = None - self._activity_id: Optional[str] = None - self._locale: Optional[str] = None + self._channel_id: str | None = None + self._conversation_id: str | None = None + self._service_url: str | None = None + self._agent_id: str | None = None + self._agent_name: str | None = None + self._user_id: str | None = None + self._user_name: str | None = None + self._activity_id: str | None = None + self._locale: str | None = None # ------------------------------------------------------------------ # Entry-point factories @@ -86,7 +84,7 @@ def create_for_agent( cls, agent_client_id: str, channel_id: str, - service_url: Optional[str] = None, + service_url: str | None = None, ) -> "ConversationReferenceBuilder": """ Start building a :class:`~microsoft_agents.activity.ConversationReference` @@ -101,7 +99,7 @@ def create_for_agent( :type channel_id: str :param service_url: Override the service URL. When ``None`` the default URL for the channel is used. - :type service_url: Optional[str] + :type service_url: str | None :return: A builder pre-populated for the agent. :rtype: :class:`ConversationReferenceBuilder` """ @@ -124,7 +122,7 @@ def create_for_agent( def with_agent( self, agent_id: str, - agent_name: Optional[str] = None, + agent_name: str | None = None, ) -> "ConversationReferenceBuilder": """ Set the agent (bot) account on the reference. @@ -132,7 +130,7 @@ def with_agent( :param agent_id: The agent's channel account ID. :type agent_id: str :param agent_name: Optional display name. - :type agent_name: Optional[str] + :type agent_name: str | None :return: ``self`` for chaining. :rtype: :class:`ConversationReferenceBuilder` """ @@ -143,7 +141,7 @@ def with_agent( def with_user( self, user_id: str, - user_name: Optional[str] = None, + user_name: str | None = None, ) -> "ConversationReferenceBuilder": """ Set the user account on the reference. @@ -151,7 +149,7 @@ def with_user( :param user_id: The user's channel account ID. :type user_id: str :param user_name: Optional display name. - :type user_name: Optional[str] + :type user_name: str | None :return: ``self`` for chaining. :rtype: :class:`ConversationReferenceBuilder` """ diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/create_conversation_options.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/create_conversation_options.py index f144c9e5..d4e58b31 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/create_conversation_options.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/create_conversation_options.py @@ -6,7 +6,6 @@ from __future__ import annotations from dataclasses import dataclass, field -from typing import Optional from microsoft_agents.activity import ConversationParameters from microsoft_agents.hosting.core.authorization import ClaimsIdentity @@ -26,10 +25,10 @@ class CreateConversationOptions: passed to the channel when creating the conversation. :type parameters: :class:`~microsoft_agents.activity.ConversationParameters` :param service_url: Optional override for the channel service URL. - :type service_url: Optional[str] + :type service_url: str | None :param audience: Optional OAuth audience override. When ``None`` the audience is derived from *identity*. - :type audience: Optional[str] + :type audience: str | None :param store_conversation: When ``True`` the newly created conversation is automatically stored via :meth:`~microsoft_agents.hosting.core.app.proactive.proactive.Proactive.store_conversation` @@ -39,9 +38,9 @@ class CreateConversationOptions: identity: ClaimsIdentity = field(default=None) channel_id: str = field(default="") - parameters: Optional[ConversationParameters] = field(default=None) - service_url: Optional[str] = field(default=None) - audience: Optional[str] = field(default=None) + parameters: ConversationParameters | None = field(default=None) + service_url: str | None = field(default=None) + audience: str | None = field(default=None) store_conversation: bool = field(default=False) def validate(self) -> None: diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/proactive.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/proactive.py index 68776d1b..6bf4b274 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/proactive.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/proactive.py @@ -6,7 +6,7 @@ from __future__ import annotations import logging -from typing import Awaitable, Callable, Generic, Optional, TypeVar, TYPE_CHECKING +from typing import Awaitable, Callable, Generic, TypeVar, TYPE_CHECKING from microsoft_agents.activity import Activity, ResourceResponse @@ -125,7 +125,7 @@ async def store_conversation( logger.debug("Storing conversation with key: %s", key) await self._storage.write({key: conversation}) - async def get_conversation(self, conversation_id: str) -> Optional[Conversation]: + async def get_conversation(self, conversation_id: str) -> Conversation | None: """ Retrieve a previously stored :class:`~microsoft_agents.hosting.core.app.proactive.conversation.Conversation`. @@ -134,7 +134,7 @@ async def get_conversation(self, conversation_id: str) -> Optional[Conversation] :type conversation_id: str :return: The stored :class:`~microsoft_agents.hosting.core.app.proactive.conversation.Conversation`, or ``None`` if not found. - :rtype: Optional[:class:`~microsoft_agents.hosting.core.app.proactive.conversation.Conversation`] + :rtype: :class:`~microsoft_agents.hosting.core.app.proactive.conversation.Conversation` | None """ key = self._storage_key(conversation_id) results = await self._storage.read([key], target_cls=Conversation) @@ -160,7 +160,7 @@ async def send_activity( adapter: "ChannelServiceAdapter", conversation_id_or_conversation: "str | Conversation", activity: Activity, - ) -> Optional[ResourceResponse]: + ) -> ResourceResponse | None: """ Send a single activity into an existing conversation. @@ -176,7 +176,7 @@ async def send_activity( :type activity: :class:`~microsoft_agents.activity.Activity` :return: The :class:`~microsoft_agents.activity.ResourceResponse` from the channel, or ``None``. - :rtype: Optional[:class:`~microsoft_agents.activity.ResourceResponse`] + :rtype: :class:`~microsoft_agents.activity.ResourceResponse` | None :raises KeyError: If *conversation_id_or_conversation* is a string and the conversation is not found in storage. """ @@ -188,9 +188,9 @@ async def _send_activity_impl( adapter: "ChannelServiceAdapter", conversation: Conversation, activity: Activity, - ) -> Optional[ResourceResponse]: - result: Optional[ResourceResponse] = None - captured_exc: Optional[BaseException] = None + ) -> ResourceResponse | None: + result: ResourceResponse | None = None + captured_exc: BaseException | None = None claims = Conversation.identity_from_claims(conversation.claims) continuation = conversation.conversation_reference.get_continuation_activity() @@ -218,8 +218,8 @@ async def continue_conversation( conversation_id_or_conversation: "str | Conversation", handler: RouteHandler, *, - continuation_activity: Optional[Activity] = None, - token_handlers: Optional[list[str]] = None, + continuation_activity: Activity | None = None, + token_handlers: list[str] | None = None, ) -> None: """ Continue an existing conversation by invoking *handler* inside a full @@ -240,12 +240,12 @@ async def continue_conversation( :meth:`~microsoft_agents.activity.ConversationReference.get_continuation_activity` is used. Supply a custom activity to carry additional payload (e.g. the original message) into the proactive turn via ``context.activity.value``. - :type continuation_activity: Optional[:class:`~microsoft_agents.activity.Activity`] + :type continuation_activity: :class:`~microsoft_agents.activity.Activity` | None :param token_handlers: Optional list of OAuth connection names whose tokens must be available before *handler* is invoked. When :attr:`~ProactiveOptions.fail_on_unsigned_in_connections` is ``True`` (the default) and a token is missing a :exc:`RuntimeError` is raised. - :type token_handlers: Optional[list[str]] + :type token_handlers: list[str] | None :raises KeyError: If *conversation_id_or_conversation* is a string and the conversation is not found in storage. :raises RuntimeError: If a required OAuth token is not available and @@ -253,7 +253,7 @@ async def continue_conversation( """ conversation = await self._resolve_conversation(conversation_id_or_conversation) - captured_exc: Optional[BaseException] = None + captured_exc: BaseException | None = None claims = Conversation.identity_from_claims(conversation.claims) continuation = ( continuation_activity @@ -280,7 +280,7 @@ async def create_conversation( self, adapter: "ChannelServiceAdapter", options: CreateConversationOptions, - handler: Optional[RouteHandler] = None, + handler: RouteHandler | None = None, ) -> Conversation: """ Create a brand-new conversation with a user and optionally run *handler*. @@ -292,7 +292,7 @@ async def create_conversation( :type options: :class:`~microsoft_agents.hosting.core.app.proactive.create_conversation_options.CreateConversationOptions` :param handler: Optional async callable invoked inside the new conversation's first turn. - :type handler: Optional[Callable] + :type handler: Callable | None :return: A :class:`~microsoft_agents.hosting.core.app.proactive.conversation.Conversation` representing the newly created conversation. :rtype: :class:`~microsoft_agents.hosting.core.app.proactive.conversation.Conversation` @@ -300,8 +300,8 @@ async def create_conversation( """ options.validate() - new_conversation: Optional[Conversation] = None - captured_exc: Optional[BaseException] = None + new_conversation: Conversation | None = None + captured_exc: BaseException | None = None audience = options.audience or options.identity.get_token_audience() @@ -346,7 +346,7 @@ async def _on_turn( self, context: "TurnContext", handler: RouteHandler, - token_handlers: Optional[list[str]] = None, + token_handlers: list[str] | None = None, ) -> None: """Run a proactive turn: load state → optional OAuth check → handler → save state.""" state = await self._load_state(context) diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/proactive_options.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/proactive_options.py index 2ff0c0b3..e100c04a 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/proactive_options.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/proactive/proactive_options.py @@ -6,8 +6,6 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Optional - from microsoft_agents.hosting.core.storage import Storage @@ -17,7 +15,7 @@ class ProactiveOptions: Options for the Proactive messaging subsystem. :param storage: The storage instance used to persist and retrieve conversations. - :type storage: Optional[:class:`microsoft_agents.hosting.core.storage.Storage`] + :type storage: :class:`microsoft_agents.hosting.core.storage.Storage` | None :param fail_on_unsigned_in_connections: If ``True`` (the default), a :exc:`RuntimeError` is raised when a required OAuth token is not available during a proactive continuation. Set to ``False`` to silently skip the @@ -25,7 +23,7 @@ class ProactiveOptions: :type fail_on_unsigned_in_connections: bool """ - storage: Optional[Storage] = None + storage: Storage | None = None """Storage used to persist Conversation objects.""" fail_on_unsigned_in_connections: bool = True diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/state.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/state.py index ce4c7064..14aff573 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/state.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/state.py @@ -9,7 +9,7 @@ import json from abc import ABC, abstractmethod from copy import deepcopy -from typing import Any, Callable, List, Optional, Type, TypeVar, Union, overload +from typing import Any, Callable, Type, TypeVar, overload from microsoft_agents.hosting.core.state.state_property_accessor import ( StatePropertyAccessor as _StatePropertyAccessor, @@ -31,8 +31,8 @@ def state(_cls: Type[T]) -> Type[T]: ... def state( - _cls: Optional[Type[T]] = None, -) -> Union[Callable[[Type[T]], Type[T]], Type[T]]: + _cls: Type[T] | None = None, +) -> Callable[[Type[T]], Type[T]] | Type[T]: """ @state\n class Example(State): @@ -71,7 +71,7 @@ class State(dict[str, StoreItem], ABC): The Storage Key """ - __deleted__: List[str] + __deleted__: list[str] """ Deleted Keys """ @@ -91,16 +91,14 @@ def __init__(self, *args, **kwargs) -> None: # pylint: disable=unused-argument for key, value in kwargs.items(): self[key] = value - async def save( - self, _context: TurnContext, storage: Optional[Storage] = None - ) -> None: + async def save(self, _context: TurnContext, storage: Storage | None = None) -> None: """ Saves The State to Storage :param _context: the turn context. :type _context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext` :param storage: storage to save to. - :type storage: Optional[:class:`microsoft_agents.hosting.core.storage.Storage`] + :type storage: :class:`microsoft_agents.hosting.core.storage.Storage` | None """ if not storage or self.__key__ == "": @@ -122,7 +120,7 @@ async def save( @classmethod @abstractmethod async def load( - cls, context: TurnContext, storage: Optional[Storage] = None + cls, context: TurnContext, storage: Storage | None = None ) -> "State": """ Loads The State from Storage @@ -130,7 +128,7 @@ async def load( :param context: the turn context. :type context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext` :param storage: storage to read from. - :type storage: Optional[:class:`microsoft_agents.hosting.core.storage.Storage`] + :type storage: :class:`microsoft_agents.hosting.core.storage.Storage` | None :return: The loaded state instance. :rtype: :class:`microsoft_agents.hosting.core.app.state.state.State` """ @@ -206,19 +204,17 @@ def __init__(self, state: State, name: str) -> None: async def get( self, turn_context: TurnContext, - default_value_or_factory: Optional[ - Union[Any, Callable[[], Optional[Any]]] - ] = None, - ) -> Optional[Any]: + default_value_or_factory: Any | Callable[[], Any | None] = None, + ) -> Any | None: """ Get the property value from the state. :param turn_context: The turn context. :type turn_context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext` :param default_value_or_factory: Default value or factory function to use if property doesn't exist. - :type default_value_or_factory: Optional[Union[Any, Callable[[], Optional[Any]]]] + :type default_value_or_factory: Any | Callable[[], Any | None] | None :return: The property value or default value if not found. - :rtype: Optional[Any] + :rtype: Any | None """ value = self._state[self._name] if self._name in self._state else None diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/temp_state.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/temp_state.py index cb954c72..96906921 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/temp_state.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/temp_state.py @@ -5,7 +5,7 @@ from __future__ import annotations -from typing import Dict, List, Optional, TypeVar, Callable, Any, Generic +from typing import TypeVar, Callable, Any, Generic from microsoft_agents.hosting.core.storage import Storage @@ -32,7 +32,7 @@ class TempState(AgentState): def __init__(self): super().__init__(None, context_service_key=self.SCOPE_NAME) - self._state: Dict[str, Any] = {} + self._state: dict[str, Any] = {} @property def name(self) -> str: @@ -40,12 +40,12 @@ def name(self) -> str: return self.SCOPE_NAME @property - def input_files(self) -> List[InputFile]: + def input_files(self) -> list[InputFile]: """Downloaded files included in the Activity""" return self.get_value(self.INPUT_FILES_KEY, lambda: []) @input_files.setter - def input_files(self, value: List[InputFile]) -> None: + def input_files(self, value: list[InputFile]) -> None: self.set_value(self.INPUT_FILES_KEY, value) def clear(self, turn_context: TurnContext) -> None: @@ -66,7 +66,7 @@ def delete_value(self, name: str) -> None: del self._state[name] def get_value( - self, name: str, default_value_factory: Optional[Callable[[], T]] = None + self, name: str, default_value_factory: Callable[[], T] | None = None ) -> T: """Gets a value from the state with the given name, using a factory for default values if not found""" if name not in self._state and default_value_factory is not None: diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/turn_state.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/turn_state.py index be1f8339..19c56d89 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/turn_state.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/state/turn_state.py @@ -6,7 +6,7 @@ from __future__ import annotations import logging -from typing import Any, Dict, Optional, Type, TypeVar, cast, Callable, Awaitable +from typing import Any, Dict, Type, TypeVar, Callable import asyncio from microsoft_agents.hosting.core.storage import Storage @@ -113,9 +113,9 @@ def has_value(self, path: str) -> bool: def get_value( self, name: str, - default_value_factory: Optional[Callable[[], T]] = None, + default_value_factory: Callable[[], T] | None = None, *, - target_cls: Type[T] = None, + target_cls: Type[T] | None = None, ) -> T: """ Gets a value from state. @@ -195,7 +195,7 @@ def get_scope(self, scope_type: Type[T]) -> T: return scope_obj raise ValueError(f"Scope '{scope_type.__name__}' not found") - def _try_get_scope(self, scope_type: Type[T]) -> tuple[bool, Optional[T]]: + def _try_get_scope(self, scope_type: Type[T]) -> tuple[bool, T | None]: """ Tries to get a scope by type. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/citation.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/citation.py index f643639a..dc55ae1e 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/citation.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/citation.py @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional from dataclasses import dataclass @@ -12,11 +11,11 @@ class Citation: content: str """The content of the citation.""" - title: Optional[str] = None + title: str | None = None """The title of the citation.""" - url: Optional[str] = None + url: str | None = None """The URL of the citation.""" - filepath: Optional[str] = None + filepath: str | None = None """The filepath of the document.""" diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/citation_util.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/citation_util.py index 1ec923dc..266d8717 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/citation_util.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/citation_util.py @@ -2,7 +2,6 @@ # Licensed under the MIT License. import re -from typing import List, Optional from microsoft_agents.activity import ClientCitation @@ -45,8 +44,8 @@ def format_citations_response(text: str) -> str: @staticmethod def get_used_citations( - text: str, citations: List[ClientCitation] - ) -> Optional[List[ClientCitation]]: + text: str, citations: list[ClientCitation] + ) -> list[ClientCitation] | None: """ Get the citations used in the text. This will remove any citations that are included in the citations array from the response but not referenced in the text. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/streaming_response.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/streaming_response.py index f5229d3d..47fa79ec 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/streaming_response.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/streaming/streaming_response.py @@ -4,7 +4,7 @@ import uuid import asyncio import logging -from typing import List, Optional, Callable, Literal, cast +from typing import Callable, Literal, cast from microsoft_agents.activity import ( Activity, @@ -49,20 +49,20 @@ def __init__(self, context: "TurnContext"): """ self._context = context self._sequence_number = 1 - self._stream_id: Optional[str] = None + self._stream_id: str | None = None self._message = "" - self._queue: List[Callable[[], Activity | None]] = [] - self._queue_sync: Optional[asyncio.Task] = None + self._queue: list[Callable[[], Activity | None]] = [] + self._queue_sync: asyncio.Task | None = None self._chunk_queued = False self._ended = False self._cancelled = False self._is_streaming_channel = False self._interval = 0.1 - self._attachments: Optional[List[Attachment]] = None - self._citations: List[ClientCitation] = [] - self._sensitivity_label: Optional[SensitivityUsageInfo] = None + self._attachments: list[Attachment] | None = None + self._citations: list[ClientCitation] = [] + self._sensitivity_label: SensitivityUsageInfo | None = None self._enable_feedback_loop = False - self._feedback_loop_type: Optional[Literal["default", "custom"]] = None + self._feedback_loop_type: Literal["default", "custom"] | None = None self._enable_generated_by_ai_label = False # Set defaults based on channel @@ -102,7 +102,7 @@ def create_activity(): self._queue_activity(create_activity) def queue_text_chunk( - self, text: str, citations: Optional[List[Citation]] = None + self, text: str, citations: list[Citation] | None = None ) -> None: """ Queues a chunk of partial message text to be sent to the client. @@ -142,7 +142,7 @@ async def end_stream(self) -> None: # Wait for the queue to drain await self.wait_for_queue() - def set_attachments(self, attachments: List[Attachment]) -> None: + def set_attachments(self, attachments: list[Attachment]) -> None: """ Sets the attachments to attach to the final chunk. @@ -160,7 +160,7 @@ def set_sensitivity_label(self, sensitivity_label: SensitivityUsageInfo) -> None """ self._sensitivity_label = sensitivity_label - def set_citations(self, citations: List[Citation]) -> None: + def set_citations(self, citations: list[Citation]) -> None: """ Sets the citations for the full message. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/typing_indicator.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/typing_indicator.py index e3841e85..aec7f744 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/typing_indicator.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/app/typing_indicator.py @@ -7,7 +7,6 @@ import asyncio import logging -from typing import Optional from microsoft_agents.hosting.core import TurnContext from microsoft_agents.activity import Activity, ActivityTypes @@ -32,7 +31,7 @@ def __init__(self, context: TurnContext, interval_seconds: float = 10.0) -> None raise ValueError("interval_seconds must be greater than 0") self._context: TurnContext = context self._interval: float = interval_seconds - self._task: Optional[asyncio.Task[None]] = None + self._task: asyncio.Task[None] | None = None async def _run(self) -> None: """Sends typing indicators at regular intervals.""" diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/access_token_provider_base.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/access_token_provider_base.py index 26c748a1..25241033 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/access_token_provider_base.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/access_token_provider_base.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Protocol, Optional +from typing import Protocol from abc import abstractmethod @@ -34,7 +34,7 @@ async def acquire_token_on_behalf_of( async def get_agentic_application_token( self, tenant_id: str, agent_app_instance_id: str - ) -> Optional[str]: + ) -> str | None: raise NotImplementedError() async def get_agentic_instance_token( @@ -48,5 +48,5 @@ async def get_agentic_user_token( agent_app_instance_id: str, agentic_user_id: str, scopes: list[str], - ) -> Optional[str]: + ) -> str | None: raise NotImplementedError() diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/anonymous_token_provider.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/anonymous_token_provider.py index 722b3945..16ef56ea 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/anonymous_token_provider.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/anonymous_token_provider.py @@ -1,8 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional - from .access_token_provider_base import AccessTokenProviderBase @@ -24,7 +22,7 @@ async def acquire_token_on_behalf_of( async def get_agentic_application_token( self, tenant_id: str, agent_app_instance_id: str - ) -> Optional[str]: + ) -> str | None: return "" async def get_agentic_instance_token( @@ -38,5 +36,5 @@ async def get_agentic_user_token( agent_app_instance_id: str, agentic_user_id: str, scopes: list[str], - ) -> Optional[str]: + ) -> str | None: return "" diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/claims_identity.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/claims_identity.py index dff15a25..de520970 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/claims_identity.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/authorization/claims_identity.py @@ -1,6 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional from .authentication_constants import AuthenticationConstants @@ -10,18 +9,18 @@ def __init__( self, claims: dict[str, str], is_authenticated: bool, - authentication_type: Optional[str] = None, - security_token: Optional[str] = None, + authentication_type: str | None = None, + security_token: str | None = None, ): self.claims = claims self.is_authenticated = is_authenticated self.authentication_type = authentication_type self.security_token = security_token - def get_claim_value(self, claim_type: str) -> Optional[str]: + def get_claim_value(self, claim_type: str) -> str | None: return self.claims.get(claim_type) - def get_app_id(self) -> Optional[str]: + def get_app_id(self) -> str | None: """ Gets the AppId from the current ClaimsIdentity. @@ -32,7 +31,7 @@ def get_app_id(self) -> Optional[str]: AuthenticationConstants.AUDIENCE_CLAIM, None ) or self.claims.get(AuthenticationConstants.APP_ID_CLAIM, None) - def get_outgoing_app_id(self) -> Optional[str]: + def get_outgoing_app_id(self) -> str | None: """ Gets the outgoing AppId from current claims. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_adapter.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_adapter.py index 2592d958..b79c8a46 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_adapter.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_adapter.py @@ -3,7 +3,7 @@ from abc import ABC, abstractmethod from collections.abc import Callable -from typing import List, Awaitable +from typing import Awaitable from microsoft_agents.hosting.core.authorization import ClaimsIdentity from microsoft_agents.activity import ChannelAdapterProtocol from microsoft_agents.activity import ( @@ -34,8 +34,8 @@ def __init__(self): @abstractmethod async def send_activities( - self, context: TurnContext, activities: List[Activity] - ) -> List[ResourceResponse]: + self, context: TurnContext, activities: list[Activity] + ) -> list[ResourceResponse]: """ Sends a set of activities to the user. An array of responses from the server will be returned. @@ -119,7 +119,7 @@ async def continue_conversation_with_claims( claims_identity: ClaimsIdentity, continuation_activity: Activity, callback: Callable[[TurnContext], Awaitable], - audience: str = None, + audience: str | None = None, ): """ Sends a proactive message to a conversation. Call this method to proactively send a message to a conversation. @@ -221,7 +221,9 @@ async def create_conversation( return await self.run_pipeline(context, callback) async def run_pipeline( - self, context: TurnContext, callback: Callable[[TurnContext], Awaitable] = None + self, + context: TurnContext, + callback: Callable[[TurnContext], Awaitable] | None = None, ): """ Called by the parent class to run the adapters middleware set and calls the passed in `callback()` handler at diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_api_handler_protocol.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_api_handler_protocol.py index 82ce7740..e50905d8 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_api_handler_protocol.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_api_handler_protocol.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. from abc import abstractmethod -from typing import Protocol, Optional +from typing import Protocol from microsoft_agents.activity import ( Activity, @@ -25,7 +25,7 @@ async def on_get_conversations( self, claims_identity: ClaimsIdentity, conversation_id: str, - continuation_token: Optional[str] = None, + continuation_token: str | None = None, ) -> ConversationsResult: """ List the Conversations in which this agent has participated. @@ -123,8 +123,8 @@ async def on_get_conversation_paged_members( self, claims_identity: ClaimsIdentity, conversation_id: str, - page_size: Optional[int] = None, - continuation_token: Optional[str] = None, + page_size: int | None = None, + continuation_token: str | None = None, ) -> PagedMembersResult: """ Enumerate the members of a conversation one page at a time. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_service_adapter.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_service_adapter.py index c81457c5..8d0e6f5c 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_service_adapter.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_service_adapter.py @@ -3,11 +3,10 @@ from __future__ import annotations -from asyncio import sleep from abc import ABC from copy import Error from http import HTTPStatus -from typing import Awaitable, Callable, cast, Optional +from typing import Awaitable, Callable, cast from uuid import uuid4 from microsoft_agents.activity import ( @@ -27,7 +26,6 @@ ) from microsoft_agents.hosting.core.connector import ( ConnectorClientBase, - UserTokenClientBase, ConnectorClient, UserTokenClient, ) @@ -239,7 +237,7 @@ async def continue_conversation_with_claims( :param callback: The method to call for the resulting agent turn. :type callback: Callable[[:class:`microsoft_agents.hosting.core.turn_context.TurnContext`], Awaitable] :param audience: The audience for the conversation. - :type audience: Optional[str] + :type audience: str | None """ with spans.AdapterContinueConversation(continuation_activity): return await self.process_proactive( @@ -382,7 +380,7 @@ async def process_activity( :type callback: Callable[[:class:`microsoft_agents.hosting.core.turn_context.TurnContext`], Awaitable] :return: A task that represents the work queued to execute. - :rtype: Optional[:class:`microsoft_agents.activity.InvokeResponse`] + :rtype: :class:`microsoft_agents.activity.InvokeResponse` | None .. note:: This class processes an activity received by the agents web server. This includes any messages @@ -425,7 +423,7 @@ async def process_activity( context.turn_state[self.USER_TOKEN_CLIENT_KEY] = user_token_client # Create the connector client to use for outbound requests. - connector_client: Optional[ConnectorClient] = None + connector_client: ConnectorClient | None = None if self._resolve_if_connector_client_is_needed(activity): connector_client = ( await self._channel_service_client_factory.create_connector_client( @@ -507,7 +505,7 @@ def _create_turn_context( claims_identity: ClaimsIdentity, oauth_scope: str, callback: Callable[[TurnContext], Awaitable], - activity: Optional[Activity] = None, + activity: Activity | None = None, ) -> TurnContext: context = TurnContext(self, activity, claims_identity) @@ -520,13 +518,13 @@ def _create_turn_context( return context - def _process_turn_results(self, context: TurnContext) -> Optional[InvokeResponse]: + def _process_turn_results(self, context: TurnContext) -> InvokeResponse | None: """Process the results of a turn and return the appropriate response. :param context: The turn context :type context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext` :return: The invoke response, if applicable - :rtype: Optional[:class:`microsoft_agents.activity.InvokeResponse`] + :rtype: :class:`microsoft_agents.activity.InvokeResponse` | None """ # Handle ExpectedReplies scenarios where all activities have been # buffered and sent back at once in an invoke response. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_service_client_factory_base.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_service_client_factory_base.py index b7a6b68b..dc3c9fd6 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_service_client_factory_base.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/channel_service_client_factory_base.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Protocol, Optional +from typing import Protocol from abc import abstractmethod from microsoft_agents.hosting.core.authorization import ClaimsIdentity @@ -20,7 +20,7 @@ async def create_connector_client( claims_identity: ClaimsIdentity, service_url: str, audience: str, - scopes: Optional[list[str]] = None, + scopes: list[str] | None = None, use_anonymous: bool = False, ) -> ConnectorClientBase: """ diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/channel_protocol.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/channel_protocol.py index a5855af0..c045b3d0 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/channel_protocol.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/channel_protocol.py @@ -16,7 +16,7 @@ async def post_activity( conversation_id: str, activity: Activity, *, - response_body_type: type[AgentsModel] = None, + response_body_type: type[AgentsModel] | None = None, **kwargs, ) -> InvokeResponse: raise NotImplementedError() diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/channels_configuration.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/channels_configuration.py index 935611a9..03547f23 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/channels_configuration.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/channels_configuration.py @@ -10,12 +10,12 @@ class ChannelInfo(ChannelInfoProtocol): def __init__( self, - id: str = None, - app_id: str = None, - resource_url: str = None, - token_provider: str = None, - channel_factory: str = None, - endpoint: str = None, + id: str | None = None, + app_id: str | None = None, + resource_url: str | None = None, + token_provider: str | None = None, + channel_factory: str | None = None, + endpoint: str | None = None, **kwargs ): self.id = id diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/http_agent_channel.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/http_agent_channel.py index ecc1cbbe..b7895baf 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/http_agent_channel.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/client/http_agent_channel.py @@ -31,7 +31,7 @@ async def post_activity( conversation_id: str, activity: Activity, *, - response_body_type: type[AgentsModel] = None, + response_body_type: type[AgentsModel] | None = None, **kwargs, ) -> InvokeResponse: if not endpoint: diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/attachments_base.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/attachments_base.py index ea9d2b9c..c962686f 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/attachments_base.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/attachments_base.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. from abc import abstractmethod -from typing import AsyncIterator, Optional, Protocol +from typing import AsyncIterator, Protocol from microsoft_agents.activity import AttachmentInfo @@ -13,5 +13,5 @@ async def get_attachment_info(self, attachment_id: str) -> AttachmentInfo: raise NotImplementedError() @abstractmethod - async def get_attachment(self) -> Optional[AsyncIterator[bytes]]: + async def get_attachment(self) -> AsyncIterator[bytes] | None: pass diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/client/connector_client.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/client/connector_client.py index 777c685a..d132b937 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/client/connector_client.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/client/connector_client.py @@ -4,7 +4,7 @@ """Connector Client for Microsoft Agents.""" import logging -from typing import Any, Optional +from typing import Any from aiohttp import ClientSession from io import BytesIO @@ -142,7 +142,7 @@ def _normalize_conversation_id(self, conversation_id: str) -> str: return conversation_id[: self._max_conversation_id_length] async def get_conversations( - self, continuation_token: Optional[str] = None + self, continuation_token: str | None = None ) -> ConversationsResult: """ Retrieves a list of conversations. @@ -586,8 +586,8 @@ async def get_activity_members( async def get_conversation_paged_members( self, conversation_id: str, - page_size: Optional[int] = None, - continuation_token: Optional[str] = None, + page_size: int | None = None, + continuation_token: str | None = None, ) -> PagedMembersResult: """ Gets the members of a conversation with pagination. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/client/user_token_client.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/client/user_token_client.py index 22759895..9dea01a2 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/client/user_token_client.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/client/user_token_client.py @@ -4,7 +4,6 @@ """User Token Client for Microsoft Agents.""" import logging -from typing import Optional from aiohttp import ClientSession from microsoft_agents.hosting.core.connector import UserTokenClientBase @@ -31,9 +30,9 @@ def __init__(self, client: ClientSession): async def get_sign_in_url( self, state: str, - code_challenge: Optional[str] = None, - emulator_url: Optional[str] = None, - final_redirect: Optional[str] = None, + code_challenge: str | None = None, + emulator_url: str | None = None, + final_redirect: str | None = None, ) -> str: """ Get sign-in URL. @@ -68,9 +67,9 @@ async def get_sign_in_url( async def get_sign_in_resource( self, state: str, - code_challenge: Optional[str] = None, - emulator_url: Optional[str] = None, - final_redirect: Optional[str] = None, + code_challenge: str | None = None, + emulator_url: str | None = None, + final_redirect: str | None = None, ) -> SignInResource: """ Get sign-in resource. @@ -116,8 +115,8 @@ async def get_token( self, user_id: str, connection_name: str, - channel_id: Optional[str] = None, - code: Optional[str] = None, + channel_id: str | None = None, + code: str | None = None, ) -> TokenResponse: with spans.GetUserToken( @@ -187,8 +186,8 @@ async def get_aad_tokens( self, user_id: str, connection_name: str, - channel_id: Optional[str] = None, - body: Optional[dict] = None, + channel_id: str | None = None, + body: dict | None = None, ) -> dict[str, TokenResponse]: """Get AAD tokens for a user.""" @@ -216,8 +215,8 @@ async def get_aad_tokens( async def sign_out( self, user_id: str, - connection_name: Optional[str] = None, - channel_id: Optional[str] = None, + connection_name: str | None = None, + channel_id: str | None = None, ) -> None: """Sign out user from a connection.""" @@ -244,8 +243,8 @@ async def sign_out( async def get_token_status( self, user_id: str, - channel_id: Optional[str] = None, - include: Optional[str] = None, + channel_id: str | None = None, + include: str | None = None, ) -> list[TokenStatus]: """Get token status for a user.""" @@ -277,7 +276,7 @@ async def exchange_token( user_id: str, connection_name: str, channel_id: str, - body: Optional[dict] = None, + body: dict | None = None, ) -> TokenResponse: """Exchange token for a user.""" diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/conversations_base.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/conversations_base.py index 1c71ca98..83be1500 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/conversations_base.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/conversations_base.py @@ -2,10 +2,9 @@ # Licensed under the MIT License. from abc import abstractmethod -from typing import Protocol, Optional +from typing import Protocol from microsoft_agents.activity import ( - AttachmentInfo, ConversationResourceResponse, ConversationsResult, ConversationParameters, @@ -21,7 +20,7 @@ class ConversationsBase(Protocol): @abstractmethod async def get_conversations( - self, continuation_token: Optional[str] = None + self, continuation_token: str | None = None ) -> ConversationsResult: """ List the Conversations in which this agent has participated. @@ -102,8 +101,8 @@ async def get_conversation_member( async def get_conversation_paged_members( self, conversation_id: str, - page_size: Optional[int] = None, - continuation_token: Optional[str] = None, + page_size: int | None = None, + continuation_token: str | None = None, ) -> PagedMembersResult: """ Enumerate the members of a conversation one page at a time. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/mcs/mcs_connector_client.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/mcs/mcs_connector_client.py index fb2d60ea..033eef69 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/mcs/mcs_connector_client.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/mcs/mcs_connector_client.py @@ -4,7 +4,6 @@ """MCS Connector Client for Microsoft Copilot Studio via Power Apps Connector.""" import logging -from typing import Optional from aiohttp import ClientSession from microsoft_agents.activity import Activity, ResourceResponse @@ -156,7 +155,7 @@ async def create_conversation(self, parameters: dict, **kwargs) -> dict: ) async def get_conversations( - self, continuation_token: Optional[str] = None, **kwargs + self, continuation_token: str | None = None, **kwargs ) -> dict: """Not supported for MCS Connector.""" raise NotImplementedError( @@ -166,8 +165,8 @@ async def get_conversations( async def get_conversation_paged_members( self, conversation_id: str, - page_size: Optional[int] = None, - continuation_token: Optional[str] = None, + page_size: int | None = None, + continuation_token: str | None = None, **kwargs, ) -> dict: """Not supported for MCS Connector.""" @@ -205,7 +204,7 @@ class MCSConnectorClient(ConnectorClientBase): All other operations will raise NotImplementedError. """ - def __init__(self, endpoint: str, client: Optional[ClientSession] = None): + def __init__(self, endpoint: str, client: ClientSession | None = None): """ Initialize the MCS Connector Client. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/user_token_base.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/user_token_base.py index 32c21abe..81323598 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/user_token_base.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/connector/user_token_base.py @@ -19,8 +19,8 @@ async def get_token( self, user_id: str, connection_name: str, - channel_id: str = None, - code: str = None, + channel_id: str | None = None, + code: str | None = None, ) -> TokenResponse: """ Get sign-in URL. @@ -63,8 +63,8 @@ async def get_aad_tokens( self, user_id: str, connection_name: str, - channel_id: str = None, - body: dict = None, + channel_id: str | None = None, + body: dict | None = None, ) -> dict[str, TokenResponse]: """ Gets Azure Active Directory tokens for a user and connection. @@ -79,7 +79,10 @@ async def get_aad_tokens( @abstractmethod async def sign_out( - self, user_id: str, connection_name: str = None, channel_id: str = None + self, + user_id: str, + connection_name: str | None = None, + channel_id: str | None = None, ) -> None: """ Signs the user out from the specified connection. @@ -92,7 +95,7 @@ async def sign_out( @abstractmethod async def get_token_status( - self, user_id: str, channel_id: str = None, include: str = None + self, user_id: str, channel_id: str | None = None, include: str | None = None ) -> list[TokenStatus]: """ Gets token status for the user. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_channel_service_routes.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_channel_service_routes.py index 16adf381..3c7e5bcb 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_channel_service_routes.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_channel_service_routes.py @@ -3,7 +3,7 @@ """Channel service route definitions (framework-agnostic logic).""" -from typing import Type, List, Union +from typing import Type from microsoft_agents.activity import ( AgentsModel, @@ -47,7 +47,7 @@ async def deserialize_from_body( return target_model.model_validate(body) @staticmethod - def serialize_model(model_or_list: Union[AgentsModel, List[AgentsModel]]) -> dict: + def serialize_model(model_or_list: AgentsModel | list[AgentsModel]) -> dict: """Serialize model or list of models to JSON-compatible dict.""" if isinstance(model_or_list, AgentsModel): return model_or_list.model_dump( diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_adapter_base.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_adapter_base.py index b2fea448..4ea5438b 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_adapter_base.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_adapter_base.py @@ -32,8 +32,8 @@ class HttpAdapterBase(ChannelServiceAdapter, ABC): def __init__( self, *, - connection_manager: Connections = None, - channel_service_client_factory: ChannelServiceClientFactoryBase = None, + connection_manager: Connections | None = None, + channel_service_client_factory: ChannelServiceClientFactoryBase | None = None, ): """Initialize the HTTP adapter. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_request_protocol.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_request_protocol.py index f99dc1d8..cbb8ba1e 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_request_protocol.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_request_protocol.py @@ -3,7 +3,7 @@ """Protocol for abstracting HTTP request objects across frameworks.""" -from typing import Protocol, Dict, Any, Optional +from typing import Protocol, Any class HttpRequestProtocol(Protocol): @@ -19,15 +19,15 @@ def method(self) -> str: ... @property - def headers(self) -> Dict[str, str]: + def headers(self) -> dict[str, str]: """Request headers.""" ... - async def json(self) -> Dict[str, Any]: + async def json(self) -> dict[str, Any]: """Parse request body as JSON.""" ... - def get_claims_identity(self) -> Optional[Any]: + def get_claims_identity(self) -> Any | None: """Get claims identity attached by auth middleware.""" ... diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_response.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_response.py index d593cdee..064d108b 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_response.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/http/_http_response.py @@ -3,7 +3,7 @@ """HTTP response abstraction.""" -from typing import Any, Optional, Dict +from typing import Any from dataclasses import dataclass @@ -12,9 +12,9 @@ class HttpResponse: """Framework-agnostic HTTP response.""" status_code: int - body: Optional[Any] = None - headers: Optional[Dict[str, str]] = None - content_type: Optional[str] = "application/json" + body: Any | None = None + headers: dict[str, str] | None = None + content_type: str | None = "application/json" class HttpResponseFactory: diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/message_factory.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/message_factory.py index 424a4024..15cb14b5 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/message_factory.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/message_factory.py @@ -17,8 +17,8 @@ def attachment_activity( attachment_layout: AttachmentLayoutTypes, attachments: list[Attachment], - text: str = None, - speak: str = None, + text: str | None = None, + speak: str | None = None, input_hint: InputHints | str = InputHints.accepting_input, ) -> Activity: message = Activity( @@ -44,7 +44,7 @@ class MessageFactory: @staticmethod def text( text: str, - speak: str = None, + speak: str | None = None, input_hint: InputHints | str = InputHints.accepting_input, ) -> Activity: """ @@ -68,8 +68,8 @@ def text( @staticmethod def suggested_actions( actions: list[CardAction], - text: str = None, - speak: str = None, + text: str | None = None, + speak: str | None = None, input_hint: InputHints | str = InputHints.accepting_input, ) -> Activity: """ @@ -101,9 +101,9 @@ def suggested_actions( @staticmethod def attachment( attachment: Attachment, - text: str = None, - speak: str = None, - input_hint: InputHints | str = None, + text: str | None = None, + speak: str | None = None, + input_hint: InputHints | str | None = None, ): """ Returns a single message activity containing an attachment. @@ -129,9 +129,9 @@ def attachment( @staticmethod def list( attachments: list[Attachment], - text: str = None, - speak: str = None, - input_hint: InputHints | str = None, + text: str | None = None, + speak: str | None = None, + input_hint: InputHints | str | None = None, ) -> Activity: """ Returns a message that will display a set of attachments in list form. @@ -161,9 +161,9 @@ def list( @staticmethod def carousel( attachments: list[Attachment], - text: str = None, - speak: str = None, - input_hint: InputHints | str = None, + text: str | None = None, + speak: str | None = None, + input_hint: InputHints | str | None = None, ) -> Activity: """ Returns a message that will display a set of attachments using a carousel layout. @@ -194,10 +194,10 @@ def carousel( def content_url( url: str, content_type: str, - name: str = None, - text: str = None, - speak: str = None, - input_hint: InputHints | str = None, + name: str | None = None, + text: str | None = None, + speak: str | None = None, + input_hint: InputHints | str | None = None, ): """ Returns a message that will display a single image or video to a user. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/rest_channel_service_client_factory.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/rest_channel_service_client_factory.py index 1b9b3dc5..7ed44d3a 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/rest_channel_service_client_factory.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/rest_channel_service_client_factory.py @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional import logging from microsoft_agents.activity import RoleTypes @@ -92,7 +91,7 @@ async def create_connector_client( claims_identity: ClaimsIdentity, service_url: str, audience: str, - scopes: Optional[list[str]] = None, + scopes: list[str] | None = None, use_anonymous: bool = False, ) -> ConnectorClientBase: if not claims_identity: diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/state/agent_state.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/state/agent_state.py index 02df1a6c..419b352c 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/state/agent_state.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/state/agent_state.py @@ -5,7 +5,7 @@ from abc import abstractmethod from copy import deepcopy -from typing import Callable, Dict, Union, Type +from typing import Callable, Type from microsoft_agents.hosting.core.storage import Storage, StoreItem @@ -18,7 +18,7 @@ class CachedAgentState(StoreItem): Internal cached Agent state. """ - def __init__(self, state: Dict[str, StoreItem | dict] = None): + def __init__(self, state: dict[str, StoreItem | dict] = None): if state: self.state = state self.hash = self.compute_hash() @@ -85,7 +85,7 @@ def __init__(self, storage: Storage, context_service_key: str): self.state_key = "state" self._storage = storage self._context_service_key = context_service_key - self._cached_state: CachedAgentState = None + self._cached_state: CachedAgentState | None = None def get_cached_state(self, turn_context: TurnContext) -> CachedAgentState: """ @@ -113,7 +113,7 @@ def create_property(self, name: str) -> StatePropertyAccessor: ) return BotStatePropertyAccessor(self, name) - def get(self, turn_context: TurnContext) -> Dict[str, StoreItem]: + def get(self, turn_context: TurnContext) -> dict[str, StoreItem]: cached = self.get_cached_state(turn_context) return getattr(cached, "state", None) @@ -148,7 +148,7 @@ async def save(self, turn_context: TurnContext, force: bool = False) -> None: if force or (self._cached_state is not None and self._cached_state.is_changed): storage_key = self.get_storage_key(turn_context) - changes: Dict[str, StoreItem] = {storage_key: self._cached_state} + changes: dict[str, StoreItem] = {storage_key: self._cached_state} await self._storage.write(changes) self._cached_state.hash = self._cached_state.compute_hash() @@ -185,16 +185,16 @@ async def delete(self, turn_context: TurnContext) -> None: @abstractmethod def get_storage_key( - self, turn_context: TurnContext, *, target_cls: Type[StoreItem] = None + self, turn_context: TurnContext, *, target_cls: Type[StoreItem] | None = None ) -> str: raise NotImplementedError() def get_value( self, property_name: str, - default_value_factory: Callable[[], StoreItem] = None, + default_value_factory: Callable[[], StoreItem] | None = None, *, - target_cls: Type[StoreItem] = None, + target_cls: Type[StoreItem] | None = None, ) -> StoreItem: """ Gets the value of the specified property in the turn context. @@ -312,9 +312,9 @@ async def delete(self, turn_context: TurnContext) -> None: async def get( self, turn_context: TurnContext, - default_value_or_factory: Union[Callable, StoreItem] = None, + default_value_or_factory: Callable | StoreItem | None = None, *, - target_cls: Type[StoreItem] = None, + target_cls: Type[StoreItem] | None = None, ) -> StoreItem: """ Gets the property value. diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/state/state_property_accessor.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/state/state_property_accessor.py index 4ad56489..145d26f9 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/state/state_property_accessor.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/state/state_property_accessor.py @@ -3,7 +3,7 @@ from abc import abstractmethod from collections.abc import Callable -from typing import Protocol, Type, Union +from typing import Protocol, Type from microsoft_agents.hosting.core.storage import StoreItem @@ -15,9 +15,9 @@ class StatePropertyAccessor(Protocol): async def get( self, turn_context: TurnContext, - default_value_or_factory: Union[Callable, StoreItem] = None, + default_value_or_factory: Callable | StoreItem | None = None, *, - target_cls: Type[StoreItem] = None + target_cls: Type[StoreItem] | None = None ) -> object: """ Get the property value from the source diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/memory_storage.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/memory_storage.py index 31560b27..2f05f716 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/memory_storage.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/memory_storage.py @@ -17,7 +17,7 @@ def __init__(self, state: dict[str, JSON] = None): self._lock = Lock() async def read( - self, keys: list[str], *, target_cls: StoreItemT = None, **kwargs + self, keys: list[str], *, target_cls: StoreItemT | None = None, **kwargs ) -> dict[str, StoreItemT]: if not keys: diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/storage.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/storage.py index 1e9ddd86..380def13 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/storage.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/storage.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Protocol, TypeVar, Type, Union +from typing import Protocol, TypeVar, Type from abc import abstractmethod from asyncio import gather @@ -13,7 +13,7 @@ class Storage(Protocol): async def read( - self, keys: list[str], *, target_cls: Type[StoreItemT] = None, **kwargs + self, keys: list[str], *, target_cls: Type[StoreItemT] | None = None, **kwargs ) -> dict[str, StoreItemT]: """Reads multiple items from storage. @@ -53,8 +53,8 @@ async def initialize(self) -> None: @abstractmethod async def _read_item( - self, key: str, *, target_cls: Type[StoreItemT] = None, **kwargs - ) -> tuple[Union[str, None], Union[StoreItemT, None]]: + self, key: str, *, target_cls: Type[StoreItemT] | None = None, **kwargs + ) -> tuple[str | None, StoreItemT | None]: """Reads a single item from storage by key. Returns a tuple of (key, StoreItem) if found, or (None, None) if not found. @@ -62,7 +62,7 @@ async def _read_item( pass async def read( - self, keys: list[str], *, target_cls: Type[StoreItemT] = None, **kwargs + self, keys: list[str], *, target_cls: Type[StoreItemT] | None = None, **kwargs ) -> dict[str, StoreItemT]: if not keys: raise ValueError("Storage.read(): Keys are required when reading.") @@ -72,13 +72,8 @@ async def read( with spans.StorageRead(len(keys)): await self.initialize() - items: list[tuple[Union[str, None], Union[StoreItemT, None]]] = ( - await gather( - *[ - self._read_item(key, target_cls=target_cls, **kwargs) - for key in keys - ] - ) + items: list[tuple[str | None, StoreItemT | None]] = await gather( + *[self._read_item(key, target_cls=target_cls, **kwargs) for key in keys] ) return {key: value for key, value in items if key is not None} diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_file_store.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_file_store.py index d40bf092..9e4c9752 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_file_store.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_file_store.py @@ -10,7 +10,7 @@ from datetime import datetime, timezone from pathlib import Path -from typing import Any, Dict, Iterable, List, Optional, Tuple, Union +from typing import Any from .transcript_logger import TranscriptLogger from .transcript_logger import PagedResult @@ -41,7 +41,7 @@ class FileTranscriptStore(TranscriptLogger): - Microsoft.Agents.Storage.Transcript namespace overview [AGENTS] """ - def __init__(self, root_folder: Union[str, Path]) -> None: + def __init__(self, root_folder: str | Path) -> None: self._root = Path(root_folder).expanduser().resolve() self._root.mkdir(parents=True, exist_ok=True) @@ -87,10 +87,10 @@ async def list_transcripts(self, channel_id: str) -> PagedResult[TranscriptInfo] :param channel_id: The channel ID to list transcripts for.""" channel_dir = self._channel_dir(channel_id) - def _list() -> List[TranscriptInfo]: + def _list() -> list[TranscriptInfo]: if not channel_dir.exists(): return [] - results: List[TranscriptInfo] = [] + results: list[TranscriptInfo] = [] for p in channel_dir.glob("*.transcript"): # mtime is a reasonable proxy for 'created/updated' created = datetime.fromtimestamp(p.stat().st_mtime, tz=timezone.utc) @@ -112,8 +112,8 @@ async def get_transcript_activities( self, channel_id: str, conversation_id: str, - continuation_token: Optional[str] = None, - start_date: Optional[datetime] = None, + continuation_token: str | None = None, + start_date: datetime | None = None, page_bytes: int = 512 * 1024, ) -> PagedResult[Activity]: """ @@ -127,12 +127,12 @@ async def get_transcript_activities( """ file_path = self._file_path(channel_id, conversation_id) - def _read_page() -> Tuple[List[Activity], Optional[str]]: + def _read_page() -> tuple[list[Activity], str | None]: if not file_path.exists(): return [], None offset = int(continuation_token) if continuation_token else 0 - results: List[Activity] = [] + results: list[Activity] = [] with open(file_path, "rb") as f: f.seek(0, os.SEEK_END) @@ -215,9 +215,9 @@ def _sanitize(pattern: re.Pattern[str], value: str) -> str: return value or "unknown" -def _get_ids(activity: Activity) -> Tuple[str, str]: +def _get_ids(activity: Activity) -> tuple[str, str]: # Works with both dict-like and object-like Activity - def _get(obj: Any, *path: str) -> Optional[Any]: + def _get(obj: Any, *path: str) -> Any: cur = obj for key in path: if cur is None: @@ -235,7 +235,7 @@ def _get(obj: Any, *path: str) -> Optional[Any]: return str(channel_id), str(conversation_id) -def _to_plain_dict(activity: Activity) -> Dict[str, Any]: +def _to_plain_dict(activity: Activity) -> dict[str, Any]: if isinstance(activity, dict): return activity diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_logger.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_logger.py index 41df1ffd..fa21e60e 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_logger.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_logger.py @@ -5,11 +5,10 @@ import string import json -from typing import Any, Optional from abc import ABC, abstractmethod from datetime import datetime, timezone from queue import Queue -from typing import Awaitable, Callable, List, Optional +from typing import Awaitable, Callable from dataclasses import dataclass from microsoft_agents.activity import Activity, ChannelAccount @@ -24,8 +23,8 @@ @dataclass class PagedResult(Generic[T]): - items: List[T] - continuation_token: Optional[str] = None + items: list[T] + continuation_token: str | None = None class TranscriptLogger(ABC): @@ -64,7 +63,7 @@ class FileTranscriptLogger(TranscriptLogger): and log tailing. """ - def __init__(self, file_path: str, encoding: Optional[str] = "utf-8"): + def __init__(self, file_path: str, encoding: str | None = "utf-8"): """ Initializes the FileTranscriptLogger and opens the file for appending. @@ -139,7 +138,7 @@ async def on_turn( # pylint: disable=unused-argument async def send_activities_handler( ctx: TurnContext, - activities: List[Activity], + activities: list[Activity], next_send: Callable[[], Awaitable[None]], ): # Run full pipeline diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_memory_store.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_memory_store.py index 6bc170f1..0753b3a5 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_memory_store.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_memory_store.py @@ -3,7 +3,6 @@ from threading import Lock from datetime import datetime, timezone -from typing import List from .transcript_logger import TranscriptLogger, PagedResult from .transcript_info import TranscriptInfo from microsoft_agents.activity import Activity @@ -50,7 +49,7 @@ async def get_transcript_activities( self, channel_id: str, conversation_id: str, - continuation_token: str = None, + continuation_token: str | None = None, start_date: datetime = datetime.min.replace(tzinfo=timezone.utc), ) -> PagedResult[Activity]: """ diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_store.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_store.py index 8e660bf8..edc09730 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_store.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/storage/transcript_store.py @@ -14,7 +14,7 @@ async def get_transcript_activities( self, channel_id: str, conversation_id: str, - continuation_token: str = None, + continuation_token: str | None = None, start_date: datetime = datetime.min.replace(tzinfo=timezone.utc), ) -> tuple[list[Activity], str]: """ diff --git a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/turn_context.py b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/turn_context.py index 46eeba4a..ba52da89 100644 --- a/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/turn_context.py +++ b/libraries/microsoft-agents-hosting-core/microsoft_agents/hosting/core/turn_context.py @@ -3,8 +3,6 @@ from __future__ import annotations import re -from typing import Optional - from copy import copy, deepcopy from collections.abc import Callable from datetime import datetime, timezone @@ -30,8 +28,8 @@ class TurnContext(TurnContextProtocol): def __init__( self, adapter_or_context, - request: Activity = None, - identity: ClaimsIdentity = None, + request: Activity | None = None, + identity: ClaimsIdentity | None = None, ): """ Creates a new TurnContext instance. @@ -149,7 +147,7 @@ def streaming_response(self): return self._streaming_response @property - def identity(self) -> Optional[ClaimsIdentity]: + def identity(self) -> ClaimsIdentity | None: return self._identity def get(self, key: str) -> object: @@ -185,8 +183,8 @@ def set(self, key: str, value: object) -> None: async def send_activity( self, activity_or_text: Activity | str, - speak: str = None, - input_hint: str = None, + speak: str | None = None, + input_hint: str | None = None, ) -> ResourceResponse | None: """ Sends a single activity or message to the user. @@ -338,7 +336,11 @@ async def next_handler(): return await logic async def send_trace_activity( - self, name: str, value: object = None, value_type: str = None, label: str = None + self, + name: str, + value: object | None = None, + value_type: str | None = None, + label: str | None = None, ) -> ResourceResponse: trace_activity = Activity( type=ActivityTypes.trace, diff --git a/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/_start_agent_process.py b/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/_start_agent_process.py index ebaf2e43..c72afb9f 100644 --- a/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/_start_agent_process.py +++ b/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/_start_agent_process.py @@ -1,4 +1,3 @@ -from typing import Optional from fastapi import Request, Response from microsoft_agents.hosting.core import error_resources from microsoft_agents.hosting.core.app import AgentApplication @@ -9,7 +8,7 @@ async def start_agent_process( request: Request, agent_application: AgentApplication, adapter: CloudAdapter, -) -> Optional[Response]: +) -> Response | None: """Starts the agent host with the provided adapter and agent application. Args: adapter (CloudAdapter): The adapter to use for the agent host. diff --git a/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/agent_http_adapter.py b/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/agent_http_adapter.py index 2584b272..db56d17a 100644 --- a/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/agent_http_adapter.py +++ b/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/agent_http_adapter.py @@ -2,7 +2,7 @@ # Licensed under the MIT License. from abc import abstractmethod -from typing import Optional, Protocol +from typing import Protocol from fastapi import Request, Response @@ -11,5 +11,5 @@ class AgentHttpAdapter(Protocol): @abstractmethod - async def process(self, request: Request, agent: Agent) -> Optional[Response]: + async def process(self, request: Request, agent: Agent) -> Response | None: raise NotImplementedError() diff --git a/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/cloud_adapter.py b/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/cloud_adapter.py index a94f81df..2b031e2a 100644 --- a/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/cloud_adapter.py +++ b/libraries/microsoft-agents-hosting-fastapi/microsoft_agents/hosting/fastapi/cloud_adapter.py @@ -1,6 +1,5 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import Optional from fastapi import Request, Response from fastapi.responses import JSONResponse @@ -46,8 +45,8 @@ class CloudAdapter(HttpAdapterBase, AgentHttpAdapter): def __init__( self, *, - connection_manager: Connections = None, - channel_service_client_factory: ChannelServiceClientFactoryBase = None, + connection_manager: Connections | None = None, + channel_service_client_factory: ChannelServiceClientFactoryBase | None = None, ): """ Initializes a new instance of the CloudAdapter class. @@ -60,7 +59,7 @@ def __init__( channel_service_client_factory=channel_service_client_factory, ) - async def process(self, request: Request, agent: Agent) -> Optional[Response]: + async def process(self, request: Request, agent: Agent) -> Response | None: """Process a FastAPI request. Args: diff --git a/libraries/microsoft-agents-hosting-teams/microsoft_agents/hosting/teams/teams_activity_handler.py b/libraries/microsoft-agents-hosting-teams/microsoft_agents/hosting/teams/teams_activity_handler.py index ba753bb2..c0511e2d 100644 --- a/libraries/microsoft-agents-hosting-teams/microsoft_agents/hosting/teams/teams_activity_handler.py +++ b/libraries/microsoft-agents-hosting-teams/microsoft_agents/hosting/teams/teams_activity_handler.py @@ -4,7 +4,7 @@ """ from http import HTTPStatus -from typing import Any, List +from typing import Any from microsoft_agents.hosting.core import ActivityHandler, TurnContext from microsoft_agents.hosting.teams.errors import teams_errors @@ -621,7 +621,7 @@ async def on_teams_message_soft_delete(self, turn_context: TurnContext) -> None: async def on_teams_members_added_dispatch( self, - members_added: List[ChannelAccount], + members_added: list[ChannelAccount], team_info: TeamInfo, turn_context: TurnContext, ) -> None: @@ -672,7 +672,7 @@ async def on_teams_members_added_dispatch( async def on_teams_members_added( self, - teams_members_added: List[TeamsChannelAccount], + teams_members_added: list[TeamsChannelAccount], team_info: TeamInfo, turn_context: TurnContext, ) -> None: @@ -686,7 +686,7 @@ async def on_teams_members_added( async def on_teams_members_removed_dispatch( self, - members_removed: List[ChannelAccount], + members_removed: list[ChannelAccount], team_info: TeamInfo, turn_context: TurnContext, ) -> None: @@ -706,7 +706,7 @@ async def on_teams_members_removed_dispatch( async def on_teams_members_removed( self, - teams_members_removed: List[TeamsChannelAccount], + teams_members_removed: list[TeamsChannelAccount], team_info: TeamInfo, turn_context: TurnContext, ) -> None: diff --git a/libraries/microsoft-agents-hosting-teams/microsoft_agents/hosting/teams/teams_info.py b/libraries/microsoft-agents-hosting-teams/microsoft_agents/hosting/teams/teams_info.py index 05cb1ab3..782e4bb1 100644 --- a/libraries/microsoft-agents-hosting-teams/microsoft_agents/hosting/teams/teams_info.py +++ b/libraries/microsoft-agents-hosting-teams/microsoft_agents/hosting/teams/teams_info.py @@ -3,7 +3,7 @@ """Teams information utilities for Microsoft Agents.""" -from typing import Optional, Tuple, Dict, Any, List +from typing import Any from microsoft_agents.activity import Activity, Channels, ConversationParameters @@ -37,9 +37,9 @@ class TeamsInfo: @staticmethod async def get_meeting_participant( context: TurnContext, - meeting_id: Optional[str] = None, - participant_id: Optional[str] = None, - tenant_id: Optional[str] = None, + meeting_id: str | None = None, + participant_id: str | None = None, + tenant_id: str | None = None, ) -> TeamsMeetingParticipant: """ Gets the meeting participant information. @@ -85,7 +85,7 @@ async def get_meeting_participant( @staticmethod async def get_meeting_info( - context: TurnContext, meeting_id: Optional[str] = None + context: TurnContext, meeting_id: str | None = None ) -> MeetingInfo: """ Gets the meeting information. @@ -113,7 +113,7 @@ async def get_meeting_info( @staticmethod async def get_team_details( - context: TurnContext, team_id: Optional[str] = None + context: TurnContext, team_id: str | None = None ) -> TeamDetails: """ Gets the team details. @@ -144,8 +144,8 @@ async def send_message_to_teams_channel( context: TurnContext, activity: Activity, teams_channel_id: str, - app_id: Optional[str] = None, - ) -> Tuple[Dict[str, Any], str]: + app_id: str | None = None, + ) -> tuple[dict[str, Any], str]: """ Sends a message to a Teams channel. @@ -224,8 +224,8 @@ async def _conversation_callback( @staticmethod async def get_team_channels( - context: TurnContext, team_id: Optional[str] = None - ) -> List[ChannelInfo]: + context: TurnContext, team_id: str | None = None + ) -> list[ChannelInfo]: """ Gets the channels of a team. @@ -252,8 +252,8 @@ async def get_team_channels( @staticmethod async def get_paged_members( context: TurnContext, - page_size: Optional[int] = None, - continuation_token: Optional[str] = None, + page_size: int | None = None, + continuation_token: str | None = None, ) -> TeamsPagedMembersResult: """ Gets the paged members of a team or conversation. @@ -326,9 +326,9 @@ async def get_member(context: TurnContext, user_id: str) -> TeamsChannelAccount: @staticmethod async def get_paged_team_members( context: TurnContext, - team_id: Optional[str] = None, - page_size: Optional[int] = None, - continuation_token: Optional[str] = None, + team_id: str | None = None, + page_size: int | None = None, + continuation_token: str | None = None, ) -> TeamsPagedMembersResult: """ Gets the paged members of a team. @@ -392,7 +392,7 @@ async def get_team_member( async def send_meeting_notification( context: TurnContext, notification: MeetingNotification, - meeting_id: Optional[str] = None, + meeting_id: str | None = None, ) -> MeetingNotificationResponse: """ Sends a meeting notification. @@ -425,7 +425,7 @@ async def send_message_to_list_of_users( context: TurnContext, activity: Activity, tenant_id: str, - members: List[TeamsMember], + members: list[TeamsMember], ) -> TeamsBatchOperationResponse: """ Sends a message to a list of users. @@ -524,7 +524,7 @@ async def send_message_to_list_of_channels( context: TurnContext, activity: Activity, tenant_id: str, - members: List[TeamsMember], + members: list[TeamsMember], ) -> TeamsBatchOperationResponse: """ Sends a message to a list of channels. diff --git a/libraries/microsoft-agents-storage-blob/microsoft_agents/storage/blob/blob_storage.py b/libraries/microsoft-agents-storage-blob/microsoft_agents/storage/blob/blob_storage.py index 595c62fd..a88c6078 100644 --- a/libraries/microsoft-agents-storage-blob/microsoft_agents/storage/blob/blob_storage.py +++ b/libraries/microsoft-agents-storage-blob/microsoft_agents/storage/blob/blob_storage.py @@ -1,5 +1,5 @@ import json -from typing import TypeVar, Union +from typing import TypeVar from io import BytesIO from azure.storage.blob.aio import ( @@ -63,8 +63,8 @@ async def initialize(self) -> None: self._initialized = True async def _read_item( - self, key: str, *, target_cls: StoreItemT = None, **kwargs - ) -> tuple[Union[str, None], Union[StoreItemT, None]]: + self, key: str, *, target_cls: StoreItemT | None = None, **kwargs + ) -> tuple[str | None, StoreItemT | None]: item = await ignore_error( self._container_client.download_blob(blob=key, timeout=5), is_status_code_error(404), diff --git a/libraries/microsoft-agents-storage-blob/microsoft_agents/storage/blob/blob_storage_config.py b/libraries/microsoft-agents-storage-blob/microsoft_agents/storage/blob/blob_storage_config.py index dec5e206..bbf9a905 100644 --- a/libraries/microsoft-agents-storage-blob/microsoft_agents/storage/blob/blob_storage_config.py +++ b/libraries/microsoft-agents-storage-blob/microsoft_agents/storage/blob/blob_storage_config.py @@ -1,5 +1,3 @@ -from typing import Union - from azure.core.credentials_async import AsyncTokenCredential @@ -11,7 +9,7 @@ def __init__( container_name: str, connection_string: str = "", url: str = "", - credential: Union[AsyncTokenCredential, None] = None, + credential: AsyncTokenCredential | None = None, ): """Configuration settings for BlobStorage. @@ -25,4 +23,4 @@ def __init__( self.container_name: str = container_name self.connection_string: str = connection_string self.url: str = url - self.credential: Union[AsyncTokenCredential, None] = credential + self.credential: AsyncTokenCredential | None = credential diff --git a/libraries/microsoft-agents-storage-cosmos/microsoft_agents/storage/cosmos/cosmos_db_storage.py b/libraries/microsoft-agents-storage-cosmos/microsoft_agents/storage/cosmos/cosmos_db_storage.py index 96df0352..c40d30bf 100644 --- a/libraries/microsoft-agents-storage-cosmos/microsoft_agents/storage/cosmos/cosmos_db_storage.py +++ b/libraries/microsoft-agents-storage-cosmos/microsoft_agents/storage/cosmos/cosmos_db_storage.py @@ -1,7 +1,7 @@ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. -from typing import TypeVar, Union +from typing import TypeVar import asyncio from azure.cosmos import ( @@ -88,8 +88,8 @@ def _sanitize(self, key: str) -> str: ) async def _read_item( - self, key: str, *, target_cls: StoreItemT = None, **kwargs - ) -> tuple[Union[str, None], Union[StoreItemT, None]]: + self, key: str, *, target_cls: StoreItemT | None = None, **kwargs + ) -> tuple[str | None, StoreItemT | None]: if key == "": raise ValueError(str(storage_errors.CosmosDbKeyCannotBeEmpty)) diff --git a/libraries/microsoft-agents-storage-cosmos/microsoft_agents/storage/cosmos/cosmos_db_storage_config.py b/libraries/microsoft-agents-storage-cosmos/microsoft_agents/storage/cosmos/cosmos_db_storage_config.py index 4e0e15ac..596a1036 100644 --- a/libraries/microsoft-agents-storage-cosmos/microsoft_agents/storage/cosmos/cosmos_db_storage_config.py +++ b/libraries/microsoft-agents-storage-cosmos/microsoft_agents/storage/cosmos/cosmos_db_storage_config.py @@ -1,5 +1,4 @@ import json -from typing import Union from azure.core.credentials_async import AsyncTokenCredential from microsoft_agents.storage.cosmos.errors import storage_errors @@ -16,12 +15,12 @@ def __init__( auth_key: str = "", database_id: str = "", container_id: str = "", - cosmos_client_options: dict = None, + cosmos_client_options: dict | None = None, container_throughput: int | None = None, key_suffix: str = "", compatibility_mode: bool = False, url: str = "", - credential: Union[AsyncTokenCredential, None] = None, + credential: AsyncTokenCredential | None = None, **kwargs, ): """Create the Config object. @@ -62,7 +61,7 @@ def __init__( "compatibility_mode", False ) self.url = url or kwargs.get("url", "") - self.credential: Union[AsyncTokenCredential, None] = credential + self.credential: AsyncTokenCredential | None = credential @staticmethod def validate_cosmos_db_config(config: "CosmosDBStorageConfig") -> None: