Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions dotnet/src/Microsoft.Agents.AI/OpenTelemetryAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,15 @@ public async Task<ChatResponse> GetResponseAsync(
// Update the current activity to reflect the agent invocation.
parentAgent.UpdateCurrentActivity(fo?.CurrentActivity);

// Capture the activity to preserve it across async boundaries
Activity? capturedActivity = fo?.CurrentActivity;

// Invoke the inner agent.
var response = await parentAgent.InnerAgent.RunAsync(messages, fo?.Thread, fo?.Options, cancellationToken).ConfigureAwait(false);

// Restore Activity.Current after ConfigureAwait(false) to ensure it's available to calling code
Activity.Current = capturedActivity;

// Wrap the response in a ChatResponse so we can pass it back through OpenTelemetryChatClient.
return response.AsChatResponse();
}
Expand All @@ -184,12 +190,21 @@ public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
// Update the current activity to reflect the agent invocation.
parentAgent.UpdateCurrentActivity(fo?.CurrentActivity);

// Capture the activity to preserve it across async boundaries
Activity? capturedActivity = fo?.CurrentActivity;

// Invoke the inner agent.
await foreach (var update in parentAgent.InnerAgent.RunStreamingAsync(messages, fo?.Thread, fo?.Options, cancellationToken).ConfigureAwait(false))
{
// Restore Activity.Current before yielding to ensure calling code has access to the trace context
Activity.Current = capturedActivity;

// Wrap the response updates in ChatResponseUpdates so we can pass them back through OpenTelemetryChatClient.
yield return update.AsChatResponseUpdate();
}

// Restore Activity.Current after streaming completes
Activity.Current = capturedActivity;
}

public object? GetService(Type serviceType, object? serviceKey = null) =>
Expand Down
Loading
Loading