// Copyright (c) Microsoft. All rights reserved. using Microsoft.Extensions.AI; namespace Microsoft.Agents.AI; /// /// Contains extension methods for /// public static class ChatMessageExtensions { /// /// Gets the source type of the provided in the context of messages passed into an agent run. /// /// The for which we need the source type. /// An value indicating the source type of the . Defaults to if no explicit source is defined. public static AgentRequestMessageSourceType GetAgentRequestMessageSourceType(this ChatMessage message) { if (message.AdditionalProperties?.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out var attribution) is true && attribution is AgentRequestMessageSourceAttribution typedAttribution) { return typedAttribution.SourceType; } return AgentRequestMessageSourceType.External; } /// /// Gets the source id of the provided in the context of messages passed into an agent run. /// /// The for which we need the source id. /// An value indicating the source id of the . Defaults to /// if no explicit source id is defined. public static string? GetAgentRequestMessageSourceId(this ChatMessage message) { if (message.AdditionalProperties?.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out var attribution) is true && attribution is AgentRequestMessageSourceAttribution typedAttribution) { return typedAttribution.SourceId; } return null; } /// /// Ensure that the provided message is tagged with the provided source type and source id in the context of a specific agent run. /// /// The message to tag. /// The source type to tag the message with. /// The source id to tag the message with. /// The tagged message. /// /// If the message is already tagged with the provided source type and source id, it is returned as is. /// Otherwise, a cloned message is returned with the appropriate tagging in the AdditionalProperties. /// public static ChatMessage WithAgentRequestMessageSource(this ChatMessage message, AgentRequestMessageSourceType sourceType, string? sourceId = null) { if (message.AdditionalProperties != null // Check if the message was already tagged with the required source type and source id && message.AdditionalProperties.TryGetValue(AgentRequestMessageSourceAttribution.AdditionalPropertiesKey, out var messageSourceAttribution) && messageSourceAttribution is AgentRequestMessageSourceAttribution typedMessageSourceAttribution && typedMessageSourceAttribution.SourceType == sourceType && typedMessageSourceAttribution.SourceId == sourceId) { return message; } message = message.Clone(); message.AdditionalProperties ??= new(); message.AdditionalProperties[AgentRequestMessageSourceAttribution.AdditionalPropertiesKey] = new AgentRequestMessageSourceAttribution(sourceType, sourceId); return message; } }