Agenten op de hoogte stellen

Met de module Meldingen kunt u agents bouwen die reageren op gebeurtenissen en meldingen van Microsoft 365-toepassingen. Dankzij de ondersteuning voor meldingen kunnen agents waarschuwingen ontvangen en verwerken wanneer gebruikers met hen communiceren via e-mail, opmerkingen in documenten of andere samenwerkingsscenario's.

Werkstroom Meldingen

Volg deze werkstroom om meldingen in te schakelen voor uw AI-agenttoepassing:

  1. Installeer meldingspakketten.

  2. Importeer meldingsonderdelen

    • Importeer notificatieklassen en -handlers.
    • Importeer activiteitstypen en kanaal-ID's.
  3. Registreer meldingshandlers

    • Gebruik notificatiehandler-methoden om routes te registreren.
    • Configureer handlers voor specifieke notificatietypen, zoals e-mail, Word, Excel of PowerPoint.
  4. Verwerk meldingen in agentcode

    • De agent ontvangt meldingen van Microsoft 365-toepassingen.
    • Verwerk inkomende meldingen en reageer hierop op de juiste manier.

Meldingstypen

De Agent 365 SDK ondersteunt de volgende notificatietypen:

Meldingstype Omschrijving Subkanaal-id
E-mail De agent ontvangt een e-mail waarin hij/zij wordt genoemd of aangesproken email
Word Agent wordt vermeld in een opmerking in een Word-document word
Excel Agent wordt vermeld in een opmerking in een Excel-document excel
PowerPoint Agent wordt vermeld in een opmerking in een PowerPoint-document powerpoint
Levenscyclusgebeurtenissen Meldingen over de levenscyclus van agenten (gebruikersidentiteit gemaakt, onboarding van workload, gebruiker verwijderd) N.v.t.

Levenscyclusgebeurtenissen van agenten

Agentlevenscyclusgebeurtenissen stellen uw agent in staat te reageren op specifieke systeemgebeurtenissen met betrekking tot het beheer van de gebruikersidentiteit van de agent. De SDK ondersteunt momenteel drie levenscyclusgebeurtenissen:

Gebeurtenistype Gebeurtenis-id Omschrijving
Gebruikersidentiteit gemaakt agenticUserIdentityCreated Wordt geactiveerd wanneer een agentgebruikersidentiteit wordt aangemaakt
Onboarding van workload bijgewerkt agenticUserWorkloadOnboardingUpdated Wordt geactiveerd wanneer de onboardingstatus van de workload van een agentgebruiker wordt bijgewerkt
Gebruiker verwijderd agenticUserDeleted Wordt geactiveerd wanneer een agentgebruikersidentiteit wordt verwijderd

Met behulp van deze gebeurtenissen kunnen agents initialisatietaken, opschoonbewerkingen of statusbeheer uitvoeren als reactie op wijzigingen in de levenscyclus van gebruikers.

Referentie voor notificatiepayload

Wanneer uw agent een notificatie ontvangt, bevat de payload gestructureerde gegevens die specifiek zijn voor het notificatietype. Inzicht in deze payloads helpt u de informatie te extraheren die u nodig hebt om notificaties effectief te verwerken.

Payload voor e-mailnotificaties

Wanneer een gebruiker een e-mail naar uw agent stuurt of uw agent in een e-mail noemt, ontvangt uw agent een e-mailnotificatie met de volgende structuur:

{
  "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>"
    }
  ]
}

Payload voor documentcommentaarnotificaties (Word, Excel, PowerPoint)

Wanneer een gebruiker uw agent noemt in een opmerking in een Word-, Excel- of PowerPoint-document, ontvangt uw agent een WPX-commentaarnotificatie (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"
    }
  ]
}

Notificaties toevoegen aan uw agent

Volg deze stappen om de verwerking van meldingen in te schakelen in uw bestaande agent:

Importeer meldingsonderdelen

Voeg deze importbewerkingen toe aan uw agentbestand:

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: Basisklasse voor het bouwen van Agent365-applicaties. Het biedt kernfunctionaliteit voor het routeren van activiteiten, het beheren van de status en het verwerken van verzoeken.
  • AgentNotification: klasse voor het registreren van meldingshandlers met decorator-methoden. Het biedt on_agent_notification(), on_email(), on_word() en andere handige decorators.
  • AgentNotificationActivity: Wrapper met geparseerde notificatiegegevens met getypte eigenschappen zoals email_notification en wpx_comment_notification die notificatiespecifieke metadata bevatten, zoals ID's, gespreksdetails en documentreferenties.
  • NotificationTypes: Enum van ondersteunde notificatietypen zoals EMAIL_NOTIFICATION, WPX_COMMENT.
  • ChannelId: Gebruik dit om notificatiekanalen te specificeren, bijvoorbeeld ChannelId(channel="agents", sub_channel="*").
  • Authorization: Autorisatiecontext voor het verwerken van notificaties.
  • TurnContext: Huidige gesprekscontext van de Agents SDK.

Meldingshandlers registreren in uw agent

Voeg meldingshandlers toe aan de initialisatie van uw 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.')

Specifieke meldingshandlers implementeren

Voeg handlermethoden toe voor elk meldingstype:

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

Identificeer de afzender

Elke notificatieactiviteit bevat Activity.From. Het A365-platform vult deze eigenschap automatisch in met de basisidentiteit van de afzender, zodat u geen API-aanroepen of tokenverwerving nodig hebt. U kunt deze eigenschap in elke notificatiehandler benaderen:

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 is een instantie van de klasse ChannelAccount met de volgende eigenschappen:

Eigenschap Omschrijving
name Weergavenaam
id Kanaalgebruikers-ID
aad_object_id Entra-object-ID

Belangrijk

De weergavenaam is door de gebruiker ingevoerde tekst. Zorg ervoor dat deze tekst wordt opgeschoond (verwijder besturingstekens, handhaaf een maximale lengte) voordat u deze in LLM-systeemprompts injecteert om promptinjectieaanvallen te voorkomen.

Fooi

Gebruik aadObjectId met de Microsoft Graph API om uitgebreide profielgegevens (functietitel, manager, afdeling) op te halen wanneer uw agent de juiste machtigingen heeft.

Gespecialiseerde notificatiehandlers

Nadat u de basisroutering voor meldingen hebt ingesteld, gebruikt u gespecialiseerde handlermethoden voor meer gedetailleerde controle. Met deze methoden kunt u:

  • Meerdere handlers registreren voor hetzelfde notificatietype.
  • Handlerprioriteit instellen met behulp van rangschikking.
  • Automatische authenticatie configureren voor elke handler.

Notitie

In de meeste gevallen volstaat het algemene handlerpatroon. Gebruik deze gespecialiseerde handlers wanneer u geavanceerde routering of meerdere handlers nodig hebt voor hetzelfde meldingstype.

Gespecialiseerde handler voor alle meldingen

Registreer meer handlers die alle meldingstypen verwerken:

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}")

Gespecialiseerde handler voor e-mailmeldingen

Registreer meer handlers specifiek voor e-mailmeldingen:

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

Gespecialiseerde handlers voor documentopmerkingen

Registreer meer handlers voor meldingen voor opmerkingen in Word, Excel en 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')

Gespecialiseerde handlers voor levenscyclusgebeurtenissen

Registreer meer handlers voor gebeurtenissen in de levenscyclus van agenten, zoals het aanmaken van gebruikersidentiteiten, het toewijzen van workloads en het verwijderen van gebruikers:

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

Geavanceerde configuratie

In deze sectie worden geavanceerde configuratieopties beschreven voor het afstemmen van uw meldingshandlers. Met deze configuraties kunt u de uitvoeringsvolgorde van handlers bepalen, authenticatievereisten beheren en de verwerking van meldingen optimaliseren voor complexe scenario's.

Prioriteit en rangschikking van handler

Wanneer u meerdere gespecialiseerde handlers gebruikt, kunt u de prioriteitsvolgorde specificeren met behulp van rangwaarden. Een lagere rangschikkingswaarde duidt op een hogere prioriteit:

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

Verificatiehandlers

Configureer handlers voor automatische aanmelding voor meldingen waarvoor verificatie vereist is:

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

Voorbeeldcode

Voor volledige werkvoorbeelden van de afhandeling van meldingen in alle ondersteunde frameworks, zie de Agent 365-voorbeelden.

Uw agent testen met meldingen

Nadat u meldingshandlers hebt geïmplementeerd, test u uw agent om ervoor te zorgen dat deze op de juiste manier verschillende meldingstypen ontvangt en verwerkt. Volg de testhandleiding om uw omgeving in te stellen en concentreer u vervolgens vooral op de sectie Test met meldingsactiviteiten om uw meldingen te valideren met behulp van agentische authenticatie.

Verwerking van meldingen bewaken

Voeg observatiemogelijkheden toe om de afhandeling van meldingen door uw agent te controleren. Houd de verwerking van meldingen, reactietijden en foutpercentages bij om inzicht te krijgen in de prestaties van agenten. Meer informatie over het implementeren van tracering en controle.