mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
e3b4b6662b
* feat(workflows): Make telemetry opt-in via WithOpenTelemetry() - Add WorkflowTelemetryOptions class with EnableSensitiveData property - Add WorkflowTelemetryContext to manage ActivitySource lifecycle - Add WithOpenTelemetry() extension method on WorkflowBuilder - Update all workflow components to use telemetry context: - WorkflowBuilder, Workflow, Executor - InProcessRunnerContext, InProcessRunner - LockstepRunEventStream, StreamingRunEventStream - All edge runners (Direct, FanIn, FanOut, Response) - Telemetry is now disabled by default - Users must call WithOpenTelemetry() to enable spans/activities BREAKING CHANGE: Workflow telemetry is now opt-in. Users who relied on automatic telemetry must add .WithOpenTelemetry() to their workflow builder. * refactor: Pass telemetry context as parameter instead of via interface - Remove IWorkflowContextWithTelemetry interface - Add internal ExecuteAsync overload that accepts WorkflowTelemetryContext - Public ExecuteAsync delegates with WorkflowTelemetryContext.Disabled - InProcessRunner passes TelemetryContext when calling ExecuteAsync - BoundContext now implements IWorkflowContext (not the removed interface) * Add optional ActivitySource parameter to WithOpenTelemetry Allow users to provide their own ActivitySource when enabling telemetry, giving them better control over the ActivitySource lifecycle. When not provided, the framework creates one internally (existing behavior). Changes: - Add optional activitySource parameter to WithOpenTelemetry() extension - Update WorkflowTelemetryContext to accept external ActivitySource - Add unit test for user-provided ActivitySource scenario * Add component-level telemetry control with disable flags Allow users to selectively disable specific activity types via WorkflowTelemetryOptions. All activities are enabled by default. New disable flags: - DisableWorkflowBuild: Disables workflow.build activities - DisableWorkflowRun: Disables workflow_invoke activities - DisableExecutorProcess: Disables executor.process activities - DisableEdgeGroupProcess: Disables edge_group.process activities - DisableMessageSend: Disables message.send activities Added helper methods to WorkflowTelemetryContext for each activity type and updated all activity creation sites to use them. * Implement EnableSensitiveData to log executor input/output When EnableSensitiveData is true in WorkflowTelemetryOptions, executor input and output are logged as JSON-serialized attributes in the executor.process activity. New activity tags: - executor.input: JSON serialized input message - executor.output: JSON serialized output result (non-void only) Added suppression attributes for AOT/trimming warnings since this is an opt-in feature for debugging/diagnostics. * Refactor activity start methods to centralize tagging logic Move tagging logic into WorkflowTelemetryContext methods: - StartExecutorProcessActivity now accepts executorId, executorType, messageType, and message; sets all tags including executor.input when EnableSensitiveData is true - Added SetExecutorOutput method to set executor.output after execution - StartMessageSendActivity now accepts sourceId, targetId, and message; sets all tags including message.content when EnableSensitiveData is true Simplified Executor.cs and InProcessRunnerContext.cs by removing inline tagging code. Added message.content tag constant. * Revert Python changes * Update samples and code cleanup * Fix file formatting * Add comment * Add telemetry configuration to declarative workflow * Remove delays in tests * Address comments
260 lines
9.4 KiB
C#
260 lines
9.4 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
|
|
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Diagnostics;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Agents.AI.Workflows.Observability;
|
|
using Microsoft.Extensions.AI;
|
|
using Microsoft.Extensions.Logging.Abstractions;
|
|
using Moq;
|
|
|
|
namespace Microsoft.Agents.AI.Workflows.Declarative.UnitTests;
|
|
|
|
/// <summary>
|
|
/// Tests for <see cref="DeclarativeWorkflowOptions"/> telemetry configuration.
|
|
/// </summary>
|
|
[Collection("DeclarativeWorkflowOptionsTest")]
|
|
public sealed class DeclarativeWorkflowOptionsTest : IDisposable
|
|
{
|
|
// These constants mirror Microsoft.Agents.AI.Workflows.Observability.ActivityNames
|
|
// which is internal and not accessible from this test project.
|
|
private const string WorkflowBuildActivityName = "workflow.build";
|
|
private const string WorkflowRunActivityName = "workflow_invoke";
|
|
|
|
// The default activity source name used by the workflow telemetry context.
|
|
private const string DefaultTelemetrySourceName = "Microsoft.Agents.AI.Workflows";
|
|
|
|
private const string SimpleWorkflowYaml = """
|
|
kind: Workflow
|
|
trigger:
|
|
kind: OnConversationStart
|
|
id: test_workflow
|
|
actions:
|
|
- kind: EndConversation
|
|
id: end_all
|
|
""";
|
|
|
|
private readonly ActivitySource _activitySource = new("TestSource");
|
|
private readonly ActivityListener _activityListener;
|
|
private readonly ConcurrentBag<Activity> _capturedActivities = [];
|
|
|
|
public DeclarativeWorkflowOptionsTest()
|
|
{
|
|
this._activityListener = new ActivityListener
|
|
{
|
|
ShouldListenTo = source =>
|
|
source.Name == DefaultTelemetrySourceName ||
|
|
source.Name == "TestSource",
|
|
Sample = (ref ActivityCreationOptions<ActivityContext> options) => ActivitySamplingResult.AllData,
|
|
ActivityStarted = activity => this._capturedActivities.Add(activity),
|
|
};
|
|
ActivitySource.AddActivityListener(this._activityListener);
|
|
}
|
|
|
|
public void Dispose()
|
|
{
|
|
this._activityListener.Dispose();
|
|
this._activitySource.Dispose();
|
|
}
|
|
|
|
[Fact]
|
|
public void ConfigureTelemetry_DefaultIsNull()
|
|
{
|
|
// Arrange
|
|
Mock<WorkflowAgentProvider> mockProvider = CreateMockProvider();
|
|
|
|
// Act
|
|
DeclarativeWorkflowOptions options = new(mockProvider.Object);
|
|
|
|
// Assert
|
|
Assert.Null(options.ConfigureTelemetry);
|
|
}
|
|
|
|
[Fact]
|
|
public void ConfigureTelemetry_CanBeSet()
|
|
{
|
|
// Arrange
|
|
Mock<WorkflowAgentProvider> mockProvider = CreateMockProvider();
|
|
bool callbackInvoked = false;
|
|
|
|
// Act
|
|
DeclarativeWorkflowOptions options = new(mockProvider.Object)
|
|
{
|
|
ConfigureTelemetry = opt =>
|
|
{
|
|
callbackInvoked = true;
|
|
opt.EnableSensitiveData = true;
|
|
}
|
|
};
|
|
|
|
// Assert
|
|
Assert.NotNull(options.ConfigureTelemetry);
|
|
WorkflowTelemetryOptions telemetryOptions = new();
|
|
options.ConfigureTelemetry(telemetryOptions);
|
|
Assert.True(callbackInvoked);
|
|
Assert.True(telemetryOptions.EnableSensitiveData);
|
|
}
|
|
|
|
[Fact]
|
|
public void TelemetryActivitySource_DefaultIsNull()
|
|
{
|
|
// Arrange
|
|
Mock<WorkflowAgentProvider> mockProvider = CreateMockProvider();
|
|
|
|
// Act
|
|
DeclarativeWorkflowOptions options = new(mockProvider.Object);
|
|
|
|
// Assert
|
|
Assert.Null(options.TelemetryActivitySource);
|
|
}
|
|
|
|
[Fact]
|
|
public void TelemetryActivitySource_CanBeSet()
|
|
{
|
|
// Arrange
|
|
Mock<WorkflowAgentProvider> mockProvider = CreateMockProvider();
|
|
|
|
// Act
|
|
DeclarativeWorkflowOptions options = new(mockProvider.Object)
|
|
{
|
|
TelemetryActivitySource = this._activitySource
|
|
};
|
|
|
|
// Assert
|
|
Assert.Same(this._activitySource, options.TelemetryActivitySource);
|
|
}
|
|
|
|
[Fact]
|
|
public async Task BuildWorkflow_WithDefaultTelemetry_AppliesTelemetryAsync()
|
|
{
|
|
// Arrange
|
|
using Activity testActivity = new Activity("DefaultTelemetryTest").Start()!;
|
|
Mock<WorkflowAgentProvider> mockProvider = CreateMockProvider();
|
|
DeclarativeWorkflowOptions options = new(mockProvider.Object)
|
|
{
|
|
ConfigureTelemetry = _ => { },
|
|
LoggerFactory = NullLoggerFactory.Instance
|
|
};
|
|
|
|
// Act
|
|
using StringReader reader = new(SimpleWorkflowYaml);
|
|
Workflow workflow = DeclarativeWorkflowBuilder.Build<string>(reader, options);
|
|
|
|
await using Run run = await InProcessExecution.RunAsync(workflow, "test input");
|
|
|
|
// Assert
|
|
Activity[] capturedActivities = this._capturedActivities
|
|
.Where(a => a.RootId == testActivity.RootId && a.Source.Name == DefaultTelemetrySourceName)
|
|
.ToArray();
|
|
|
|
Assert.NotEmpty(capturedActivities);
|
|
Assert.Contains(capturedActivities, a => a.OperationName.StartsWith(WorkflowBuildActivityName, StringComparison.Ordinal));
|
|
Assert.Contains(capturedActivities, a => a.OperationName.StartsWith(WorkflowRunActivityName, StringComparison.Ordinal));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task BuildWorkflow_WithTelemetryActivitySource_AppliesTelemetryAsync()
|
|
{
|
|
// Arrange
|
|
using Activity testActivity = new Activity("TelemetryActivitySourceTest").Start()!;
|
|
Mock<WorkflowAgentProvider> mockProvider = CreateMockProvider();
|
|
DeclarativeWorkflowOptions options = new(mockProvider.Object)
|
|
{
|
|
TelemetryActivitySource = this._activitySource,
|
|
LoggerFactory = NullLoggerFactory.Instance
|
|
};
|
|
|
|
// Act
|
|
using StringReader reader = new(SimpleWorkflowYaml);
|
|
Workflow workflow = DeclarativeWorkflowBuilder.Build<string>(reader, options);
|
|
|
|
await using Run run = await InProcessExecution.RunAsync(workflow, "test input");
|
|
|
|
// Assert
|
|
Activity[] capturedActivities = this._capturedActivities
|
|
.Where(a => a.RootId == testActivity.RootId && a.Source.Name == "TestSource")
|
|
.ToArray();
|
|
|
|
Assert.NotEmpty(capturedActivities);
|
|
Assert.All(capturedActivities, a => Assert.Equal("TestSource", a.Source.Name));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task BuildWorkflow_WithConfigureTelemetry_AppliesConfigurationAsync()
|
|
{
|
|
// Arrange
|
|
using Activity testActivity = new Activity("ConfigureTelemetryTest").Start()!;
|
|
Mock<WorkflowAgentProvider> mockProvider = CreateMockProvider();
|
|
bool configureInvoked = false;
|
|
DeclarativeWorkflowOptions options = new(mockProvider.Object)
|
|
{
|
|
ConfigureTelemetry = opt =>
|
|
{
|
|
configureInvoked = true;
|
|
opt.EnableSensitiveData = true;
|
|
},
|
|
LoggerFactory = NullLoggerFactory.Instance
|
|
};
|
|
|
|
// Act
|
|
using StringReader reader = new(SimpleWorkflowYaml);
|
|
Workflow workflow = DeclarativeWorkflowBuilder.Build<string>(reader, options);
|
|
|
|
await using Run run = await InProcessExecution.RunAsync(workflow, "test input");
|
|
|
|
// Assert
|
|
Assert.True(configureInvoked);
|
|
|
|
Activity[] capturedActivities = this._capturedActivities
|
|
.Where(a => a.RootId == testActivity.RootId && a.Source.Name == DefaultTelemetrySourceName)
|
|
.ToArray();
|
|
|
|
Assert.NotEmpty(capturedActivities);
|
|
Assert.Contains(capturedActivities, a => a.OperationName.StartsWith(WorkflowBuildActivityName, StringComparison.Ordinal));
|
|
Assert.Contains(capturedActivities, a => a.OperationName.StartsWith(WorkflowRunActivityName, StringComparison.Ordinal));
|
|
}
|
|
|
|
[Fact]
|
|
public async Task BuildWorkflow_WithoutTelemetry_DoesNotCreateActivitiesAsync()
|
|
{
|
|
// Arrange
|
|
using Activity testActivity = new Activity("NoTelemetryTest").Start()!;
|
|
Mock<WorkflowAgentProvider> mockProvider = CreateMockProvider();
|
|
DeclarativeWorkflowOptions options = new(mockProvider.Object)
|
|
{
|
|
LoggerFactory = NullLoggerFactory.Instance
|
|
};
|
|
|
|
// Act
|
|
using StringReader reader = new(SimpleWorkflowYaml);
|
|
Workflow workflow = DeclarativeWorkflowBuilder.Build<string>(reader, options);
|
|
|
|
await using Run run = await InProcessExecution.RunAsync(workflow, "test input");
|
|
|
|
// Assert - No workflow activities should be created when telemetry is disabled
|
|
Activity[] capturedActivities = this._capturedActivities
|
|
.Where(a => a.RootId == testActivity.RootId &&
|
|
(a.OperationName.StartsWith(WorkflowBuildActivityName, StringComparison.Ordinal) ||
|
|
a.OperationName.StartsWith(WorkflowRunActivityName, StringComparison.Ordinal)))
|
|
.ToArray();
|
|
|
|
Assert.Empty(capturedActivities);
|
|
}
|
|
|
|
private static Mock<WorkflowAgentProvider> CreateMockProvider()
|
|
{
|
|
Mock<WorkflowAgentProvider> mockAgentProvider = new(MockBehavior.Strict);
|
|
mockAgentProvider
|
|
.Setup(provider => provider.CreateConversationAsync(It.IsAny<CancellationToken>()))
|
|
.Returns(() => Task.FromResult(Guid.NewGuid().ToString("N")));
|
|
mockAgentProvider
|
|
.Setup(provider => provider.CreateMessageAsync(It.IsAny<string>(), It.IsAny<ChatMessage>(), It.IsAny<CancellationToken>()))
|
|
.Returns(Task.FromResult(new ChatMessage(ChatRole.Assistant, "Test response")));
|
|
return mockAgentProvider;
|
|
}
|
|
}
|