通知代理

通过使用通知模块,可以生成响应来自Microsoft 365应用程序的事件和通知的代理。 通过使用通知支持,客服人员可以通过电子邮件、文档评论或其他协作场景与他们互动时接收并处理警报。

通知工作流

按照此工作流为 AI 代理应用程序启用通知:

  1. 安装通知包。

  2. 导入通知组件

    • 导入通知类和处理程序。
    • 导入活动类型和通道标识符。
  3. 注册通知处理器

    • 使用通知处理程序方法注册路由。
    • 为特定通知类型(如电子邮件、Word、Excel 或PowerPoint)配置处理程序。
  4. 在代理代码中处理通知

    • 代理从Microsoft 365应用程序接收通知。
    • 处理传入通知并相应地做出响应。

通知类型

Agent 365 SDK 支持以下通知类型:

通知类型 Description 子频道ID
电子邮件地址 代理人会收到一封提到或指名他们的邮件。 email
Word Word文档的注释中提到了代理 word
Excel Excel 文档中的注释中提到代理 excel
PowerPoint PowerPoint文档的批注中提到了代理 powerpoint
生命周期事件 代理生命周期通知,如用户身份的创建、更新、删除或禁用。 完整列表请参见 代理生命周期事件。 N/A

代理生命周期事件

代理生命周期事件使代理能够响应与代理用户标识管理相关的特定系统事件。 SDK支持以下生命周期事件:

事件类型 事件编号 Description
已创建用户标识 agenticUserIdentityCreated 创建代理用户标识时触发
工作负载载入已更新 agenticUserWorkloadOnboardingUpdated 在更新代理用户的工作负载载入状态时触发
用户已删除 agenticUserDeleted 删除代理用户标识时触发
用户已恢复 agenticUserUndeleted 当已删除的代理用户标识被恢复时触发
用户身份已更新 agenticUserIdentityUpdated 当代理用户身份更新时触发
用户管理器已更新 agenticUserManagerUpdated 当代理用户的经理更新时触发
用户已启用 agenticUserEnabled 当代理用户被启用时触发
用户已禁用 agenticUserDisabled 当代理用户被禁用时触发

Note

Python 和 JavaScript SDK 在 2.0 版本及以后版本中支持用户已恢复、用户身份更新、用户管理器更新、用户启用和用户禁用事件。 更多信息请参见“迁移至Microsoft Agent 365 SDK 2.0”。

每个SDK为每个事件提供一个处理程序:

事件类型 Python AgentLifecycleEvent JavaScript .NET
已创建用户标识 USERCREATED onAgenticUserCreatedNotification OnAgenticUserIdentityCreatedNotification
工作负载载入已更新 USERWORKLOADONBOARDINGUPDATED onAgenticUserWorkloadOnboardingNotification OnAgenticUserWorkloadOnboardingNotification
用户已删除 USERDELETED onAgenticUserDeletedNotification OnAgenticUserDeletedNotification
用户已恢复 USERUNDELETED onAgenticUserUndeletedNotification OnAgenticUserUndeletedNotification
用户身份已更新 USERUPDATED onAgenticUserUpdatedNotification OnAgenticUserIdentityUpdatedNotification
用户管理器已更新 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:包含已解析的通知数据以及具有特定类型属性的包装器,例如包括通知特定元数据的 email_notification 和 wpx_comment_notification,这些元数据可以是 ID、会话详细信息和文档引用等。
  • NotificationTypes:支持的通知类型的枚举,例如EMAIL_NOTIFICATION。 WPX_COMMENT
  • ChannelId:用于指定通知通道,例如 ChannelId(channel="agents", sub_channel="*")。
  • 授权:用于处理通知的授权上下文。
  • TurnContext:Agents 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

Important

显示名称是用户控制的文本。 在将内容注入 LLM 系统提示之前,请清理它(去除控制字符,强制设置最大长度),以防止提示注入攻击。

提示

在代理拥有适当权限的情况下,将 aadObjectId 与 Microsoft 图形 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 示例。

使用通知测试代理

实现通知处理程序后,测试代理以确保它正确接收和处理不同的通知类型。 按照 测试指南 设置环境,然后主要关注 “使用通知活动测试” 部分,使用代理身份验证来验证通知。

监控通知处理

添加可观测性功能来监视代理的通知处理。 跟踪通知处理、响应时间和错误率,以了解代理性能。 了解更多关于实施追踪和监控的信息。