| | | 1 | | namespace NexusLabs.Needlr.AgentFramework.Diagnostics; |
| | | 2 | | |
| | | 3 | | /// <summary> |
| | | 4 | | /// Extensions for producing ordered timeline views of an <see cref="IAgentRunDiagnostics"/>. |
| | | 5 | | /// </summary> |
| | | 6 | | public static class AgentRunDiagnosticsTimelineExtensions |
| | | 7 | | { |
| | | 8 | | /// <summary> |
| | | 9 | | /// Merges the chat completions and tool calls into a single list ordered by |
| | | 10 | | /// <see cref="DiagnosticsTimelineEntry.StartedAt"/> (ascending), with |
| | | 11 | | /// <see cref="DiagnosticsTimelineEntry.Sequence"/> as a tiebreaker within the same |
| | | 12 | | /// kind. |
| | | 13 | | /// </summary> |
| | | 14 | | /// <param name="diagnostics">The agent run diagnostics to project.</param> |
| | | 15 | | /// <returns>A snapshot list of timeline entries. Never <see langword="null"/>; may be empty.</returns> |
| | | 16 | | public static IReadOnlyList<DiagnosticsTimelineEntry> GetOrderedTimeline( |
| | | 17 | | this IAgentRunDiagnostics diagnostics) |
| | | 18 | | { |
| | 15 | 19 | | ArgumentNullException.ThrowIfNull(diagnostics); |
| | | 20 | | |
| | 14 | 21 | | var entries = new List<DiagnosticsTimelineEntry>( |
| | 14 | 22 | | diagnostics.ChatCompletions.Count + diagnostics.ToolCalls.Count); |
| | | 23 | | |
| | 50 | 24 | | foreach (var chat in diagnostics.ChatCompletions) |
| | | 25 | | { |
| | 11 | 26 | | entries.Add(new DiagnosticsTimelineEntry( |
| | 11 | 27 | | Kind: DiagnosticsTimelineEntryKind.ChatCompletion, |
| | 11 | 28 | | Sequence: chat.Sequence, |
| | 11 | 29 | | StartedAt: chat.StartedAt, |
| | 11 | 30 | | CompletedAt: chat.CompletedAt, |
| | 11 | 31 | | ChatCompletion: chat, |
| | 11 | 32 | | ToolCall: null)); |
| | | 33 | | } |
| | | 34 | | |
| | 44 | 35 | | foreach (var tool in diagnostics.ToolCalls) |
| | | 36 | | { |
| | 8 | 37 | | entries.Add(new DiagnosticsTimelineEntry( |
| | 8 | 38 | | Kind: DiagnosticsTimelineEntryKind.ToolCall, |
| | 8 | 39 | | Sequence: tool.Sequence, |
| | 8 | 40 | | StartedAt: tool.StartedAt, |
| | 8 | 41 | | CompletedAt: tool.CompletedAt, |
| | 8 | 42 | | ChatCompletion: null, |
| | 8 | 43 | | ToolCall: tool)); |
| | | 44 | | } |
| | | 45 | | |
| | 14 | 46 | | entries.Sort(static (a, b) => |
| | 14 | 47 | | { |
| | 13 | 48 | | var startedComparison = a.StartedAt.CompareTo(b.StartedAt); |
| | 13 | 49 | | if (startedComparison != 0) |
| | 14 | 50 | | { |
| | 12 | 51 | | return startedComparison; |
| | 14 | 52 | | } |
| | 14 | 53 | | |
| | 1 | 54 | | if (a.Kind == b.Kind) |
| | 14 | 55 | | { |
| | 0 | 56 | | return a.Sequence.CompareTo(b.Sequence); |
| | 14 | 57 | | } |
| | 14 | 58 | | |
| | 1 | 59 | | return a.Kind == DiagnosticsTimelineEntryKind.ChatCompletion ? -1 : 1; |
| | 14 | 60 | | }); |
| | | 61 | | |
| | 14 | 62 | | return entries; |
| | | 63 | | } |
| | | 64 | | } |