通知 Agent

透過使用通知模組,您可以建置能回應 Microsoft 365 應用程式事件與通知的 Agent。 透過使用通知支援,Agent可以在使用者透過電子郵件、文件評論或其他協作情境與其互動時,接收並處理通知。

通知工作流程

請依照以下工作流程啟用您的 AI Agent 應用程式的通知:

  1. 安裝應用程式封裝

  2. 匯入通知元件

    • 匯入通知類別與處理常式。
    • 匯入活動類型與管道識別碼。
  3. 註冊通知處理常式

    • 使用通知處理常式方法來註冊路由。
    • 針對特定通知類型設定處理常式,例如電子郵件、Word、Excel 或 PowerPoint。
  4. 在 Agent 程式碼中處理通知

    • Agent 會接收來自 Microsoft 365 應用程式的通知。
    • 處理收到的通知並適當回應。

通知類型

Agent 365 SDK 支援下列通知類型:

通知類型 Description 子管道識別碼
電子郵件 Agent 會收到內容提及或直接寄給 Agent 的郵件 email
Word Agent 在 Word 文件的註解中受提及 word
Excel Agent 在 Excel 文件的註解中受提及 excel
PowerPoint Agent 在 PowerPoint 文件的註解中受提及 powerpoint
生命週期事件 Agent 生命週期通知 (使用者身分識別建立、工作負載上線、已刪除的使用者) 不適用

Agent 生命週期事件

Agent 生命週期事件可讓您的 Agent 回應與 Agent 使用者身分識別管理相關的特定系統事件。 SDK 目前支援三個生命週期事件:

事件類型 事件識別碼 Description
已建立的使用者身分識別 agenticUserIdentityCreated 當 Agent 使用者身分識別建立時觸發
已更新的工作負載上線 agenticUserWorkloadOnboardingUpdated 當 Agent 使用者的工作負載上線狀態為更新時會觸發
已刪除的使用者 agenticUserDeleted 當 Agent 使用者身分識別遭到刪除時觸發

Agent 可以使用這些事件,執行初始化工作、清理作業或狀態管理以回應使用者生命週期變更。

通知酬載偏好

當您的 Agent 收到通知時,籌載會包含特定於通知類型的結構化資料。 了解這些酬載可以協助您有效擷取處理通知所需的資訊。

電子郵件通知酬載

當使用者寄送電子郵件給您的 Agent 或在郵件中提及 Agent 時, Agent 會收到以下結構的電子郵件通知:

{
  "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 文件中的註解提及您的 Agent 時,您的 Agent 會收到一則 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"
    }
  ]
}

將通知新增至您的 Agent

請依照以下步驟,為您現有的 Agent 啟用通知處理:

匯入通知元件

將以下匯入項目新增到您的 Agent 檔案:

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) 的包裝函式,這些屬性包含通知特定的中繼資料,例如識別碼、交談細節及文件參考。
  • NotificationTypes:列舉支援的通知類型,如 EMAIL_NOTIFICATIONWPX_COMMENT
  • ChannelId:用來指定通知管道,例如 ChannelId(channel="agents", sub_channel="*")
  • 授權:用來處理通知的授權上下文。
  • TurnContext:來自 Agents SDK 的目前交談回合上下文。

在您的 Agent 中註冊通知處理常式

將通知處理常式新增至您的 Agent 初始化:

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 管道使用者識別碼
aad_object_id Entra 物件識別碼

重要

顯示名稱是使用者控制的文字。 在將其注入 LLM 系統提示前,請先清理 (移除控制字元,並強制執行長度上限),以防止提示注入攻擊。

提示

當您的 Agent 具有適當權限時,請透過 Microsoft 圖形 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')

生命週期事件的專用處理常式

註冊更多用於 Agent 生命週期事件,例如使用者身分識別建立、工作負載上線和使用者刪除的處理常式:

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 樣本

使用通知測試您的 Agent

在實作通知處理常式後,測試您的 Agent,確保它能正確接收並處理不同類型的通知。 請依循測試指南來設定您的環境,然後將重點主要放在使用通知活動測試區段,以使用 Agent 驗證來確認您的通知。

監控通知處理

新增可檢視性功能以監控 Agent 的通知處理。 追蹤通知流程、回覆時間及錯誤率,以了解 Agent 效能。 深入了解如何實作追蹤和監視