Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class SemanticAction(AgentsModel):
:param entities: Entities associated with this action
:type entities: dict[str, :class:`microsoft_agents.activity.entity.Entity`]
:param state: State of this action. Allowed values: `start`, `continue`, `done`
:type state: str or :class:`microsoft_agents.activity.semantic_action_states.SemanticActionStates`
:type state: str or :class:`microsoft_agents.activity.semantic_actions_states.SemanticActionsStates`
"""

id: NonEmptyString
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def __init__(
Initialize the MSAL connection manager.

:arg connections_configurations: A dictionary of connection configurations.
:type connections_configurations: Dict[str, AgentAuthConfiguration]
:type connections_configurations: Dict[str, :class:`microsoft_agents.hosting.core.AgentAuthConfiguration`]
:arg connections_map: A list of connection mappings.
:type connections_map: List[Dict[str, str]]
:raises ValueError: If no service connection configuration is provided.
Expand Down Expand Up @@ -64,16 +64,19 @@ def get_connection(self, connection_name: Optional[str]) -> AccessTokenProviderB
Get the OAuth connection for the agent.

:arg connection_name: The name of the connection.
:type connection_name: str
:type connection_name: Optional[str]
:return: The OAuth connection for the agent.
:rtype: AccessTokenProviderBase
:rtype: :class:`microsoft_agents.hosting.core.AccessTokenProviderBase`
"""
# should never be None
return self._connections.get(connection_name, None)

def get_default_connection(self) -> AccessTokenProviderBase:
"""
Get the default OAuth connection for the agent.

:return: The default OAuth connection for the agent.
:rtype: :class:`microsoft_agents.hosting.core.AccessTokenProviderBase`
"""
# should never be None
return self._connections.get("SERVICE_CONNECTION", None)
Expand All @@ -85,11 +88,11 @@ def get_token_provider(
Get the OAuth token provider for the agent.

:arg claims_identity: The claims identity of the bot.
:type claims_identity: ClaimsIdentity
:type claims_identity: :class:`microsoft_agents.hosting.core.ClaimsIdentity`
:arg service_url: The service URL of the bot.
:type service_url: str
:return: The OAuth token provider for the agent.
:rtype: AccessTokenProviderBase
:rtype: :class:`microsoft_agents.hosting.core.AccessTokenProviderBase`
:raises ValueError: If no connection is found for the given audience and service URL.
"""
if not claims_identity or not service_url:
Expand Down Expand Up @@ -130,5 +133,8 @@ def get_token_provider(
def get_default_connection_configuration(self) -> AgentAuthConfiguration:
"""
Get the default connection configuration for the agent.

:return: The default connection configuration for the agent.
:rtype: :class:`microsoft_agents.hosting.core.AgentAuthConfiguration`
"""
return self._service_connection_configuration
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ async def on_members_added_activity(

:param members_added: A list of all the members added to the conversation, as described by the
conversation update activity
:type members_added: list[ChannelAccount]
:type members_added: list[:class:`microsoft_agents.activity.ChannelAccount`]
:param turn_context: The context object for this turn
:type turn_context: :class:`microsoft_agents.activity.TurnContextProtocol`
:returns: A task that represents the work queued to execute
Expand All @@ -195,9 +195,9 @@ async def on_members_removed_activity(
Override this method in a derived class to provide logic for when members other than the agent leave
the conversation. You can add your agent's good-bye logic.

:param members_added: A list of all the members removed from the conversation, as described by the
:param members_removed: A list of all the members removed from the conversation, as described by the
conversation update activity
:type members_added: list[ChannelAccount]
:type members_removed: list[:class:`microsoft_agents.activity.ChannelAccount`]
:param turn_context: The context object for this turn
:type turn_context: :class:`microsoft_agents.activity.TurnContextProtocol`
:returns: A task that represents the work queued to execute
Expand Down Expand Up @@ -260,7 +260,7 @@ async def on_reactions_added( # pylint: disable=unused-argument
are added to the conversation.

:param message_reactions: The list of reactions added
:type message_reactions: list[MessageReaction]
:type message_reactions: list[:class:`microsoft_agents.activity.MessageReaction`]
:param turn_context: The context object for this turn
:type turn_context: :class:`microsoft_agents.activity.TurnContextProtocol`
:returns: A task that represents the work queued to execute
Expand All @@ -285,7 +285,7 @@ async def on_reactions_removed( # pylint: disable=unused-argument
are removed from the conversation.

:param message_reactions: The list of reactions removed
:type message_reactions: list[MessageReaction]
:type message_reactions: list[:class:`microsoft_agents.activity.MessageReaction`]
:param turn_context: The context object for this turn
:type turn_context: :class:`microsoft_agents.activity.TurnContextProtocol`

Expand Down Expand Up @@ -459,6 +459,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`]
"""
try:
if (
Expand Down Expand Up @@ -510,8 +511,9 @@ async def on_adaptive_card_invoke(
:param turn_context: A context object for this turn.
:type turn_context: :class:`microsoft_agents.activity.TurnContextProtocol`
:param invoke_value: A string-typed object from the incoming activity's value.
:type invoke_value: :class:`microsoft_agents.activity.adaptive_card_invoke_value.AdaptiveCardInvokeValue`
:type invoke_value: :class:`microsoft_agents.activity.AdaptiveCardInvokeValue`
:return: The HealthCheckResponse object
:rtype: :class:`microsoft_agents.activity.AdaptiveCardInvokeResponse`
"""
raise _InvokeResponseException(HTTPStatus.NOT_IMPLEMENTED)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,15 @@ def __init__(
) -> 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`]
:param connection_manager: OAuth connection manager.
:type connection_manager: Optional[:class:`microsoft_agents.hosting.core.authorization.Connections`]
:param authorization: Authorization manager for handling authentication flows.
:type authorization: Optional[:class:`microsoft_agents.hosting.core.app.oauth.Authorization`]
:param kwargs: Additional configuration parameters.
:type kwargs: Any
"""
self.typing = TypingIndicator()
self._route_list = _RouteList[StateT]()
Expand Down Expand Up @@ -161,6 +170,10 @@ def __init__(
def adapter(self) -> ChannelServiceAdapter:
"""
The bot's adapter.

:return: The channel service adapter for the bot.
:rtype: :class:`microsoft_agents.hosting.core.channel_service_adapter.ChannelServiceAdapter`
:raises ApplicationError: If the adapter is not configured.
"""

if not self._adapter:
Expand All @@ -181,6 +194,10 @@ def adapter(self) -> ChannelServiceAdapter:
def auth(self) -> Authorization:
"""
The application's authentication manager

:return: The authentication manager for handling OAuth flows.
:rtype: :class:`microsoft_agents.hosting.core.app.oauth.Authorization`
:raises ApplicationError: If authentication is not configured.
"""
if not self._auth:
logger.error(
Expand All @@ -200,6 +217,9 @@ def auth(self) -> Authorization:
def options(self) -> ApplicationOptions:
"""
The application's configured options.

:return: The configuration options for the application.
:rtype: :class:`microsoft_agents.hosting.core.app.app_options.ApplicationOptions`
"""
return self._options

Expand All @@ -217,16 +237,16 @@ def add_route(
Routes are ordered by: is_agentic, is_invoke, rank (lower is higher priority), in that order.

:param selector: A function that takes a TurnContext and returns a boolean indicating whether the route should be selected.
:type selector: RouteSelector
:type selector: :class:`microsoft_agents.hosting.core.app._type_defs.RouteSelector`
:param handler: A function that takes a TurnContext and a TurnState and returns an Awaitable.
:type handler: RouteHandler[StateT]
:type handler: :class:`microsoft_agents.hosting.core.app._type_defs.RouteHandler`[StateT]
:param is_invoke: Whether the route is for an invoke activity, defaults to False
:type is_invoke: bool, Optional
:param is_agentic: Whether the route is for an agentic request, defaults to False. For agentic requests
the selector will include a new check for `context.activity.is_agentic_request()`.
:type is_agentic: bool, Optional
:param rank: The rank of the route, defaults to RouteRank.DEFAULT
:type rank: RouteRank, Optional
:type rank: :class:`microsoft_agents.hosting.core.app._routes.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
:raises ApplicationError: If the selector or handler are not valid.
Expand Down Expand Up @@ -706,6 +726,11 @@ def _remove_mentions(self, context: TurnContext):
def parse_env_vars_configuration(vars: dict[str, Any]) -> dict:
"""
Parses environment variables and returns a dictionary with the relevant configuration.

:param vars: Dictionary of environment variable names and values.
:type vars: dict[str, Any]
:return: Parsed configuration dictionary with nested structure.
:rtype: dict
"""
result = {}
for key, value in vars.items():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ def __init__(
only if auth_handlers is empty or None.

:param storage: The storage system to use for state management.
:type storage: Storage
:type storage: :class:`microsoft_agents.hosting.core.storage.Storage`
:param connection_manager: The connection manager for OAuth providers.
:type connection_manager: Connections
:type connection_manager: :class:`microsoft_agents.hosting.core.authorization.Connections`
:param auth_handlers: Configuration for OAuth providers.
:type auth_handlers: dict[str, AuthHandler], Optional
:type auth_handlers: dict[str, :class:`microsoft_agents.hosting.core.app.oauth.auth_handler.AuthHandler`], Optional
:raises ValueError: When storage is None or no auth handlers provided.
"""
if not storage:
Expand Down Expand Up @@ -105,7 +105,7 @@ def _init_handlers(self) -> None:
it initializes an instance of each variant that is referenced.

:param auth_handlers: A dictionary of auth handler configurations.
:type auth_handlers: dict[str, AuthHandler]
:type auth_handlers: dict[str, :class:`microsoft_agents.hosting.core.app.oauth.auth_handler.AuthHandler`]
"""
for name, auth_handler in self._handler_settings.items():
auth_type = auth_handler.auth_type
Expand All @@ -126,26 +126,42 @@ def _sign_in_state_key(context: TurnContext) -> str:
can be used to inspect or manipulate the state directly if needed.

:param context: The turn context for the current turn of conversation.
:type context: TurnContext
:type context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext`
:return: A unique (across other values of channel_id and user_id) key for the sign-in state.
:rtype: 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]:
"""Load the sign-in state from storage for the given context."""
"""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`]
"""
key = self._sign_in_state_key(context)
return (await self._storage.read([key], target_cls=_SignInState)).get(key)

async def _save_sign_in_state(
self, context: TurnContext, state: _SignInState
) -> None:
"""Save the sign-in state to storage for the given context."""
"""Save the sign-in state to 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`
:param state: The sign-in state to save.
:type state: :class:`microsoft_agents.hosting.core.app.oauth._sign_in_state._SignInState`
"""
key = self._sign_in_state_key(context)
await self._storage.write({key: state})

async def _delete_sign_in_state(self, context: TurnContext) -> None:
"""Delete the sign-in state from storage for the given context."""
"""Delete 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`
"""
key = self._sign_in_state_key(context)
await self._storage.delete([key])

Expand Down Expand Up @@ -179,7 +195,7 @@ def _resolve_handler(self, handler_id: str) -> _AuthorizationHandler:
:param handler_id: The ID of the auth handler to resolve.
:type handler_id: str
:return: The corresponding AuthorizationHandler instance.
:rtype: AuthorizationHandler
:rtype: :class:`microsoft_agents.hosting.core.app.oauth._handlers._AuthorizationHandler`
:raises ValueError: If the handler ID is not recognized or not configured.
"""
if handler_id not in self._handlers:
Expand All @@ -200,13 +216,13 @@ async def _start_or_continue_sign_in(
Storage is updated as needed with _SignInState data for caching purposes.

:param context: The turn context for the current turn of conversation.
:type context: TurnContext
:type context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext`
:param state: The turn state for the current turn of conversation.
:type state: TurnState
:type state: :class:`microsoft_agents.hosting.core.app.state.turn_state.TurnState`
:param auth_handler_id: The ID of the auth handler to use for sign-in. If None, the first handler will be used.
:type auth_handler_id: str
:return: A _SignInResponse indicating the result of the sign-in attempt.
:rtype: _SignInResponse
:rtype: :class:`microsoft_agents.hosting.core.app.oauth._sign_in_response._SignInResponse`
"""

auth_handler_id = auth_handler_id or self._default_handler_id
Expand Down Expand Up @@ -250,7 +266,7 @@ async def sign_out(
"""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: TurnContext
: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]
:return: None
Expand All @@ -272,11 +288,11 @@ async def _on_turn_auth_intercept(
from the cached _SignInState.

:param context: The context object for the current turn.
:type context: TurnContext
:type context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext`
:param state: The turn state for the current turn.
:type state: TurnState
: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[Activity]]
:rtype: tuple[bool, Optional[:class:`microsoft_agents.activity.Activity`]]
"""
sign_in_state = await self._load_sign_in_state(context)

Expand Down Expand Up @@ -306,11 +322,11 @@ async def get_token(
The token is taken from cache, so this does not initiate nor continue a sign-in flow.

:param context: The context object for the current turn.
:type context: TurnContext
:type context: :class:`microsoft_agents.hosting.core.turn_context.TurnContext`
:param auth_handler_id: The ID of the auth handler to get the token for.
:type auth_handler_id: str
:return: The token response from the OAuth provider.
:rtype: TokenResponse
:rtype: :class:`microsoft_agents.activity.TokenResponse`
"""
return await self.exchange_token(context, auth_handler_id=auth_handler_id)

Expand All @@ -324,7 +340,7 @@ async def exchange_token(
"""Exchanges or refreshes the token for a specific auth handler or the default handler.

:param context: The context object for the current turn.
:type context: TurnContext
: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]]
Expand All @@ -335,7 +351,7 @@ async def exchange_token(
the connection defined in the AuthHandler configuration will be used.
:type exchange_connection: Optional[str]
:return: The token response from the OAuth provider.
:rtype: TokenResponse
:rtype: :class:`microsoft_agents.activity.TokenResponse`
:raises ValueError: If the specified auth handler ID is not recognized or not configured.
"""

Expand Down Expand Up @@ -376,6 +392,7 @@ def on_sign_in_success(
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]]
"""
self._sign_in_success_handler = handler

Expand All @@ -387,5 +404,6 @@ def on_sign_in_failure(
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]]
"""
self._sign_in_failure_handler = handler
Loading