エージェントへの通知

通知モジュールを使用することで、Microsoft 365 アプリケーションからのイベントや通知に応答するエージェントを構築できます。 通知機能により、エージェントはユーザーがメール、ドキュメント コメント、その他の共同作業シナリオを通じてやり取りした際にアラートを受信して処理できます。

通知のワークフロー

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

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

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

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

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

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

通知の種類

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

通知の種類 内容 サブチャネル ID
電子メール エージェントは、自身にメンションされている、または宛先として指定されているメールを受信します email
Word エージェントは Word ドキュメントのコメントでメンションされている word
Excel エージェントは Excel ドキュメントのコメントでメンションされている excel
PowerPoint エージェントは PowerPoint ドキュメントのコメントでメンションされている powerpoint
ライフサイクル イベント エージェント ライフサイクル通知 (作成されたユーザー ID、ワークロード オンボード、ユーザー削除) 在庫切れ

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

エージェントのライフサイクル イベントにより、エージェントはエージェントユーザー ID 管理に関連する特定のシステム イベントに対応できます。 SDK では現在、次の 3 つのライフサイクル イベントがサポートされています:

イベント タイプ イベント ID 内容
作成されたユーザー ID agenticUserIdentityCreated エージェント ユーザー ID が作成された際にトリガーされます
ワークロード オンボードの更新 agenticUserWorkloadOnboardingUpdated エージェント ユーザーのワークロード オンボード状態が更新された際にトリガーされます
削除されたユーザー agenticUserDeleted エージェント ユーザー ID が削除された際にトリガーされます

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

通知ペイロードの参照

エージェントが通知を受信すると、そのペイロードには、通知の種類に応じた構造化データが含まれます。 これらのペイロードを理解することで、通知を効果的に処理するために必要な情報を抽出できるようになります。

メール通知のペイロード

ユーザーがエージェントにメールを送信したり、メール内でエージェントに言及したりすると、エージェントには次のような形式のメール通知が届きます:

{
  "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、またはP owerPoint のドキュメント内のコメントで担当者をメンションすると、その担当者に 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: 解析済み通知データを含むラッパーです。email_notificationwpx_comment_notification などの型指定されたプロパティを持ち、通知固有のメタデータ (ID、会話詳細、ドキュメント参照) を含みます。
  • NotificationTypes: サポートされている通知の種類 (EMAIL_NOTIFICATIONWPX_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プラットフォームがこのプロパティに送信者の基本情報を自動的に設定するため、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

重要

表示名はユーザー制御のテキストです。 LLM システムのプロンプトに注入する前に、プロンプトをサニタイズ (制御文字の削除、最大長さの制限) して、プロンプト インジェクション攻撃を防止します。

ヒント

エージェントに適切な権限がある場合、Microsoft Graph API と aadObjectId を使用して、拡張プロフィールデータ (役職、直属の上司、部署) を取得します。

特殊な通知ハンドラー

基本通知ルーティングを設定した後で、特殊なハンドラー メソッドを使用してより詳細な制御を行います。 これらの方法を使うことで、以下のことが可能になります:

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

メモ

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

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

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

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')

ライフサイクル イベント用の特殊なハンドラー

ユーザー ID の作成、ワークロードのオンボード、ユーザーの削除など、エージェント ライフサイクル イベントのハンドラーをさらに登録します。

from microsoft_agents_a365.notifications import 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):
    lifecycle_notification = notification.agent_lifecycle_notification
    if lifecycle_notification:
        event_type = lifecycle_notification.lifecycle_event_type
        
        if event_type == "agenticUserIdentityCreated":
            await context.send_activity('User identity created')
        elif event_type == "agenticUserWorkloadOnboardingUpdated":
            await context.send_activity('Workload onboarding completed')
        elif event_type == "agenticUserDeleted":
            await context.send_activity('User identity deleted')

詳細構成

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

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

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

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

サンプル コード

すべてのサポートフレームワークにおける通知処理の完全な実例については、Agent 365 Samplesを参照してください。

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

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

通知処理の監視

監視機能を追加して、エージェントの通知処理を監視します。 通知処理、応答時間、エラー率を追跡し、エージェントのパフォーマンスを把握します。 トレースと監視の実装の詳細