エージェントへの通知

Notifications モジュールを使用すると、アプリケーションからのイベントと通知に応答するエージェントMicrosoft 365構築できます。 通知サポートを利用することで、エージェントはユーザーがメールやドキュメントコメント、その他の協働的なシナリオでやり取りした際にアラートを受け取り処理できます。

通知のワークフロー

このワークフローに従って、AI エージェント アプリケーションの通知を有効にします。

  1. 通知パッケージをインストールします。

  2. 通知コンポーネントのインポート

    • 通知クラスとハンドラーをインポートします。
    • アクティビティの種類とチャネル識別子をインポートします。
  3. 通知ハンドラーを登録する

    • 通知ハンドラー メソッドを使用してルートを登録します。
    • 電子メール、Word、Excel、PowerPointなど、特定の通知の種類のハンドラーを構成します。
  4. エージェント コードで通知を処理する

    • エージェントは、Microsoft 365 アプリケーションから通知を受け取ります。
    • 受信通知を処理し、適切に応答します。

通知の種類

Agent 365 SDKは以下の通知タイプをサポートしています:

通知の種類 Description サブチャネル ID
電子メール エージェントはその名前や住所が記載されたメールを受け取ります email
Word エージェントがWordドキュメントのコメントに記載されている word
エクセル エージェントが Excel ドキュメントのコメントで言及されています excel
PowerPoint エージェントがPowerPointドキュメントのコメントに記載されている powerpoint
ライフサイクル イベント ユーザーIDの作成、更新、削除、無効化などのエージェントライフサイクル通知。 完全なリストについては、 エージェントのライフサイクルイベントを参照してください。 N/A

エージェントのライフサイクル イベント

エージェントのライフサイクル イベントを使用すると、エージェントのユーザー ID 管理に関連する特定のシステム イベントにエージェントが応答できます。 SDKは以下のライフサイクルイベントをサポートしています:

イベントの種類 イベント ID Description
作成されたユーザー ID agenticUserIdentityCreated エージェント ユーザー ID が作成されたときにトリガーされます
ワークロード導入の更新 agenticUserWorkloadOnboardingUpdated エージェント ユーザーのワークロードオンボード状態が更新されたときにトリガーされます
削除されたユーザー agenticUserDeleted エージェント ユーザー ID が削除されたときにトリガーされます
ユーザーの削除を取り消しました agenticUserUndeleted 削除されたエージェントのユーザーIDが復元されたときにトリガーされます
ユーザーIDが更新されました agenticUserIdentityUpdated エージェントのユーザーIDが更新されたときにトリガーされます
ユーザー マネージャーが更新されました agenticUserManagerUpdated エージェントのユーザーのマネージャーが更新されたときにトリガーされます
ユーザーが有効 agenticUserEnabled エージェントユーザーが有効化されたときにトリガーされます
無効化済みのユーザー agenticUserDisabled エージェントユーザーが無効化されたときにトリガーされます

Note

PythonおよびJavaScriptのSDKは、バージョン2.0以降で「ユーザー削除解除」「ユーザーID更新」「ユーザーマネージャー更新」「ユーザー有効化」「ユーザー無効化」イベントをサポートしています。 詳細については、「Microsoft Agent 365 SDK 2.0への移行」をご覧ください。

各SDKは各イベントに対応するハンドラーを提供します:

イベントの種類 Python AgentLifecycleEvent JavaScript .NET
作成されたユーザー ID USERCREATED onAgenticUserCreatedNotification OnAgenticUserIdentityCreatedNotification
ワークロード導入の更新 USERWORKLOADONBOARDINGUPDATED onAgenticUserWorkloadOnboardingNotification OnAgenticUserWorkloadOnboardingNotification
削除されたユーザー USERDELETED onAgenticUserDeletedNotification OnAgenticUserDeletedNotification
ユーザーの削除を取り消しました USERUNDELETED onAgenticUserUndeletedNotification OnAgenticUserUndeletedNotification
ユーザーID更新されました USERUPDATED onAgenticUserUpdatedNotification OnAgenticUserIdentityUpdatedNotification
User Manager を更新しました USERMANAGERUPDATED onAgenticUserManagerUpdatedNotification OnAgenticUserManagerUpdatedNotification
ユーザー有効 USERENABLED onAgenticUserEnabledNotification OnAgenticUserEnabledNotification
ユーザーは無効です USERDISABLED onAgenticUserDisabledNotification OnAgenticUserDisabledNotification

Pythonでは、ハンドラを on_agent_lifecycle_notification("*") で登録し、小文字のイベントIDを AgentLifecycleEvent の値と比較します。 JavaScriptや.NETでは、すべてのライフサイクルイベントを処理するためにonLifecycleNotificationまたはOnLifecycleNotificationを使用します。 例については、 ライフサイクルイベントの専門ハンドラーを参照してください。

これらのイベントを使用すると、エージェントは、ユーザーのライフサイクルの変更に応じて、初期化タスク、クリーンアップ操作、または状態管理を実行できます。

通知ペイロードリファレンス

エージェントが通知を受け取ると、ペイロードには通知タイプ固有の構造化データが含まれています。 これらのペイロードを理解することで、通知を効果的に処理するために必要な情報を抽出できます。

メール通知のペイロード

ユーザーがエージェントにメールを送信したり、メールでエージェントの名前を述べると、エージェントは以下の形式のメール通知を受け取ります。

{
  "id": "aaaaaaaa-0000-1111-2222-bbbbbbbbbbbb",
  "timestamp": "2026-02-06T17:45:20.740Z",
  "channelId": "agents",
  "serviceUrl": "http://localhost:56150/_connector",
  "recipient": {
    "id": "AgentName@contoso.onmicrosoft.com",
    "name": "My Agent",
    "agenticUserId": "<agentic-user-id>",
    "agenticAppId": "<agentic-app-id>",
    "tenantId": "<tenant-id>",
    "role": "agenticUser"
  },
  "conversation": {
    "id": "<conversation-id>",
    "conversationType": "personal",
    "tenantId": "<tenant-id>"
  },
  "from": {
    "id": "sender@contoso.onmicrosoft.com",
    "name": "Sender Name",
    "role": "user"
  },
  "type": "message",
  "channelData": {
    "tenant": {
      "id": "<tenant-id>"
    }
  },
  "locale": "en-US",
  "name": "emailNotification",
  "entities": [
    {
      "type": "clientInfo",
      "locale": "en-US",
      "timezone": null
    },
    {
      "id": "email",
      "type": "productInfo"
    },
    {
      "type": "emailNotification",
      "id": "<email-id>",
      "conversationId": "<conversation-id>",
      "htmlBody": "<body dir=\"ltr\">\n<div class=\"elementToProof\">Your email message content here</div>\n</body>"
    }
  ]
}

ドキュメント コメント通知ペイロード (Word、Excel、PowerPoint)

ユーザーがWord、Excel、またはPowerPointドキュメント内のコメントでエージェントをメンションすると、エージェントは WPX (Word、PowerPoint、Excel) コメント通知を受け取ります。

{
  "id": "bbbbbbbb-1111-2222-3333-cccccccccccc",
  "timestamp": "2026-02-06T17:46:02.248Z",
  "channelId": "agents",
  "serviceUrl": "http://localhost:56150/_connector",
  "recipient": {
    "id": "AgentName@contoso.onmicrosoft.com",
    "name": "My Agent",
    "agenticUserId": "<agentic-user-id>",
    "agenticAppId": "<agentic-app-id>",
    "tenantId": "<tenant-id>",
    "role": "agenticUser"
  },
  "conversation": {
    "id": "<conversation-id>",
    "conversationType": "personal",
    "tenantId": "<tenant-id>",
    "topic": "<document-topic>"
  },
  "from": {
    "id": "sender@contoso.onmicrosoft.com",
    "name": "Sender Name",
    "role": "user"
  },
  "type": "message",
  "channelData": {
    "tenant": {
      "id": "<tenant-id>"
    },
    "productContext": "Word"
  },
  "locale": "en-US",
  "textFormat": "plain",
  "text": "<at>My Agent</at> - Please review this section\n",
  "attachments": [
    {
      "contentUrl": "<document-url>",
      "name": "<document-name>",
      "content": {
        "uniqueId": "<document-unique-id>",
        "fileType": "docx"
      },
      "contentType": "application/vnd.microsoft.teams.file.download.info"
    }
  ],
  "entities": [
    {
      "type": "clientInfo",
      "locale": "en-US",
      "timezone": null
    },
    {
      "mentioned": {
        "id": "AgentName@contoso.onmicrosoft.com",
        "name": "@My Agent"
      },
      "text": "<at>My Agent</at>",
      "type": "mention"
    },
    {
      "id": "Word",
      "type": "productInfo"
    },
    {
      "parentCommentId": "<parent-comment-id>",
      "commentId": "<comment-id>",
      "documentId": "<document-id>",
      "type": "wpxcomment"
    }
  ]
}

エージェントに通知を追加する

既存のエージェントで通知処理を有効にするには、次の手順に従います:

通知コンポーネントのインポート

エージェント ファイルに次のインポートを追加します:

from microsoft_agents_a365 import AgentApplication
from microsoft_agents_a365.notifications import (
    AgentNotification,
    AgentNotificationActivity,
    NotificationTypes
)
from microsoft_agents.activity import ChannelId
from microsoft_agents.hosting.core import Authorization, TurnContext
  • AgentApplication: Agent365 アプリケーションをビルドするための基本クラス。 アクティビティのルーティング、状態の管理、要求の処理のためのコア機能が提供されます。
  • AgentNotification: 通知ハンドラーをデコレーター メソッドに登録するクラス。 on_agent_notification()、on_email()、on_word()、およびその他の便利なデコレーターを提供します。
  • AgentNotificationActivity: 解析された通知データを含むラッパー。ID、会話の詳細、ドキュメント参照などの通知固有のメタデータを含む email_notification や wpx_comment_notification などの型指定されたプロパティを含みます。
  • NotificationTypes: EMAIL_NOTIFICATION、 WPX_COMMENTなど、サポートされている通知の種類の列挙型。
  • ChannelId: ChannelId(channel="agents", sub_channel="*")などの通知チャネルを指定するために使用します。
  • 承認: 通知を処理するための承認コンテキスト。
  • TurnContext: エージェント SDK からの現在の会話ターン コンテキスト。

エージェントに通知ハンドラーを登録する

エージェントの初期化に通知ハンドラーを追加します:

class YourAgent(AgentApplication):
    def __init__(self, app):
        # Create notification handler
        agent_notification = AgentNotification(app)
        
        # Register handler for all notifications
        @agent_notification.on_agent_notification(
            ChannelId(channel="agents", sub_channel="*")
        )
        async def handle_all_notifications(context, state, notification):
            # Route based on notification type
            if notification.notification_type == NotificationTypes.EMAIL_NOTIFICATION:
                await self.handle_email_notification(context, state, notification)
            elif notification.notification_type == NotificationTypes.WPX_COMMENT:
                await self.handle_comment_notification(context, state, notification)
            else:
                await context.send_activity('Notification type not yet implemented.')

特定の通知ハンドラーを実装する

通知の種類ごとにハンドラー メソッドを追加します:

class YourAgent(AgentApplication):
    # ... __init__ from above ...
    
    async def handle_email_notification(self, context, state, notification):
        """Handle email notifications"""
        email = notification.email_notification
        
        if not email:
            await context.send_activity('No email data found')
            return
        
        # Process the email
        await context.send_activity(
            f'Received email notification. Email ID: {email.id}'
        )
        
        # Your email processing logic here
    
    async def handle_comment_notification(self, context, state, notification):
        """Handle document comment notifications"""
        comment = notification.wpx_comment_notification
        
        if not comment:
            await context.send_activity('No comment data found')
            return
        
        # Process the comment
        await context.send_activity(
            f'Received comment notification. Document ID: {comment.document_id}'
        )
        
        # Your comment processing logic here

送信者を識別する

すべての通知アクティビティには Activity.Fromが含まれます。 A365 プラットフォームでは、このプロパティに送信者の基本的な ID が設定されるため、API 呼び出しやトークン取得は必要ありません。 任意の通知ハンドラー内でアクセスします。

async def handle_email_notification(self, context, state, notification):
    from_prop = context.activity.from_property
    logger.info(
        "Notification from — DisplayName: '%s', UserId: '%s', AadObjectId: '%s'",
        getattr(from_prop, "name", None) or "(unknown)",
        getattr(from_prop, "id", None) or "(unknown)",
        getattr(from_prop, "aad_object_id", None) or "(none)",
    )
    display_name = getattr(from_prop, "name", None) or "unknown"
    # Use display_name in your response or LLM prompt

Activity.from_property は、次のプロパティを持つ ChannelAccount クラス インスタンスです。

プロパティ Description
name 表示名
id チャネル ユーザー ID
aad_object_id Entra オブジェクトID

Important

表示名は、ユーザーが制御するテキストです。 プロンプトインジェクション攻撃を防ぐために、LLM システム プロンプトに挿入する前に、それをサニタイズします (コントロール文字を削除し、最大長を強制します)。

Tip

aadObjectIdを Microsoft Graph APIと共に使用して、エージェントに適切なアクセス許可がある場合に拡張プロファイル データ (役職、マネージャー、部門) を取得します。

特殊な通知ハンドラー

基本通知ルーティングを設定した後で、特殊なハンドラー メソッドを使用してより詳細な制御を行います。 これらのメソッドを使用すると、次のことができます。

  • 同じ通知の種類に対して複数のハンドラーを登録します。
  • ランク付けを使用してハンドラーの優先順位を設定します。
  • ハンドラーごとに自動認証を構成します。

Note

ほとんどのユース ケースでは、汎用ハンドラー パターンで十分です。 高度なルーティングや、同じ通知タイプに対して複数のハンドラーが必要な場合に、これらの専用ハンドラーを使用します。

すべての通知に特化されたハンドラー

すべての種類の通知を処理するハンドラーをさらに登録します。

from microsoft_agents_a365.notifications import (
    AgentNotification,
    NotificationTypes
)
from microsoft_agents.activity import ChannelId

# Create notification handler
agent_notification = AgentNotification(app)

# Register handler for all notifications
@agent_notification.on_agent_notification(
    ChannelId(channel="agents", sub_channel="*")
)
async def handle_all_notifications(context, state, notification):
    if notification.notification_type == NotificationTypes.EMAIL_NOTIFICATION:
        if notification.email_notification:
            await context.send_activity(f"Received email: {notification.email_notification.id}")
    elif notification.notification_type == NotificationTypes.WPX_COMMENT:
        if notification.wpx_comment_notification:
            await context.send_activity(f"Received comment: {notification.wpx_comment_notification.comment_id}")

メールの通知に特化されたハンドラー

メール通知用にさらに多くのハンドラを登録します:

from microsoft_agents_a365.notifications import AgentNotification
from microsoft_agents.activity import ChannelId, AgentSubChannel

# Create notification handler
agent_notification = AgentNotification(app)

# Use the convenience method for email notifications
@agent_notification.on_email()
async def handle_email(context, state, notification):
    email = notification.email_notification
    
    if not email:
        await context.send_activity('No email found')
        return
    
    # Process the email
    email_id = email.id
    conversation_id = email.conversation_id
    
    # Send response
    await context.send_activity('Thank you for your email!')

ドキュメント コメント用の特殊なハンドラー

Word、Excel、およびPowerPointコメント通知のハンドラーをさらに登録します。

from microsoft_agents_a365.notifications import AgentNotification

# Create notification handler
agent_notification = AgentNotification(app)

# Use convenience methods for document notifications
@agent_notification.on_word()
async def handle_word(context, state, notification):
    comment = notification.wpx_comment_notification
    
    if comment:
        document_id = comment.document_id
        comment_id = comment.comment_id
        await context.send_activity(f'Processing Word comment: {comment_id}')

@agent_notification.on_excel()
async def handle_excel(context, state, notification):
    comment = notification.wpx_comment_notification
    
    if comment:
        await context.send_activity('Processing Excel comment')

@agent_notification.on_powerpoint()
async def handle_powerpoint(context, state, notification):
    comment = notification.wpx_comment_notification
    
    if comment:
        await context.send_activity('Processing PowerPoint comment')

ライフサイクルイベント用の特化したハンドラー

ユーザーアイデンティティの作成、ワークロードのオンボーディング、ユーザー削除、ユーザー無効化などのエージェントライフサイクルイベントのために、より多くのハンドラーを登録してください。 イベントの全リストについては、 エージェントライフサイクルイベントを参照してください。

from microsoft_agents_a365.notifications import AgentLifecycleEvent, AgentNotification

# Create notification handler
agent_notification = AgentNotification(app)

# Handle all lifecycle events
@agent_notification.on_agent_lifecycle_notification("*")
async def handle_lifecycle(context, state, notification):
    # AgentLifecycleEvent values are lowercase
    event_type = (notification.activity.value_type or "").lower()

    if event_type == AgentLifecycleEvent.USERCREATED.value:
        await context.send_activity('User identity created')
    elif event_type == AgentLifecycleEvent.USERWORKLOADONBOARDINGUPDATED.value:
        await context.send_activity('Workload onboarding completed')
    elif event_type == AgentLifecycleEvent.USERDELETED.value:
        await context.send_activity('User identity deleted')
    elif event_type == AgentLifecycleEvent.USERDISABLED.value:
        await context.send_activity('User disabled')

詳細な構成

このセクションでは、通知ハンドラーを微調整する高度な構成オプションについて説明します。 これらの構成を使用すると、ハンドラーの実行順序を制御し、認証要件を管理し、複雑なシナリオに合わせて通知処理を最適化できます。

ハンドラーの優先順位とランク付け

複数の特殊化されたハンドラーを使用する場合は、ランク値を使用して優先順位を指定します。 ランク値が低いほど、優先度が高いことを示します。

from microsoft_agents_a365.notifications import AgentNotification
from microsoft_agents.activity import ChannelId, AgentSubChannel

# Create notification handler
agent_notification = AgentNotification(app)

# Higher priority handler (processed first)
@agent_notification.on_email(rank=100)
async def high_priority_email(context, state, notification):
    # Handle with high priority
    pass

# Lower priority handler (processed after higher priority)
@agent_notification.on_email(rank=200)
async def low_priority_email(context, state, notification):
    # Handle with lower priority
    pass

認証ハンドラー

認証が必要な通知に対して自動サインイン ハンドラーを構成する:

from microsoft_agents_a365.notifications import AgentNotification
from microsoft_agents.activity import ChannelId, AgentSubChannel

# Create notification handler
agent_notification = AgentNotification(app)

# Handler with automatic authentication
@agent_notification.on_email(auto_sign_in_handlers=['agentic'])
async def authenticated_email(context, state, notification):
    # Authentication is handled automatically
    pass

サンプル コード

サポートされているすべてのフレームワークでの通知処理の完全な動作例については、 エージェント 365 のサンプルを参照してください。

通知でエージェントをテストする

通知ハンドラーを実装した後は、テストを実施してエージェントが異なる通知タイプを正しく受信し処理できることを確認してください。 テスト ガイドに従って環境を設定し、エージェント認証を使用して通知を検証するには、主に 「通知アクティビティを使用したテスト」セクションに焦点を当てます。

通知処理の監視

監視機能を追加して、エージェントの通知処理を監視します。 通知処理、応答時間、エラー率を追跡し、エージェントのパフォーマンスを把握します。 追跡とモニタリングの実施について詳しく学びましょう。