forked from microsoft/Generative-AI-for-beginners-dotnet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStreamConsoleHelper.cs
More file actions
189 lines (165 loc) · 6.11 KB
/
Copy pathStreamConsoleHelper.cs
File metadata and controls
189 lines (165 loc) · 6.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
/// <summary>
/// Small helper to keep console printing consistent and easy to read.
/// Uses simple colored output and labeled sections to make the streaming flow obvious.
/// Renamed to StreamConsoleHelper to avoid conflicts with other helpers in the solution.
/// </summary>
internal static class StreamConsoleHelper
{
private static readonly System.Text.StringBuilder _accum = new System.Text.StringBuilder();
private static string? _firstTimestamp;
public static void PrintHeader(string text, bool clearConsole = true)
{
if (clearConsole)
{
Console.Clear();
}
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(new string('=', 60));
Console.WriteLine(text);
Console.WriteLine(new string('=', 60));
Console.ResetColor();
Console.WriteLine();
}
public static void PrintSection(string title)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"--- {title} ---");
Console.ResetColor();
}
public static void PrintUpdate(string updateText, string? continuationToken)
{
var timestamp = DateTime.Now.ToString("HH:mm:ss.fff");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write($"[{timestamp}] ");
Console.ResetColor();
// Print the update text (streaming chunk)
if (string.IsNullOrEmpty(updateText))
{
Console.WriteLine("(empty update)");
}
else
{
Console.WriteLine(updateText);
}
// Print a compact representation of the continuation token for debugging
if (!string.IsNullOrWhiteSpace(continuationToken))
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine($" token: {Truncate(continuationToken, 60)}");
Console.ResetColor();
}
}
/// <summary>
/// Prepare internal accumulator to join token fragments into readable sentences.
/// Call before starting the continuation streaming loop.
/// </summary>
public static void StartAccumulatedStream()
{
_accum.Clear();
_firstTimestamp = null;
}
/// <summary>
/// Accumulates small token fragments and prints a joined sentence when a sentence terminator
/// or newline is encountered, or when accumulated length grows large.
/// This makes streaming tokens readable as sentences or phrases instead of individual tokens.
/// </summary>
public static void AccumulateAndPrint(string updateText, string? continuationToken)
{
if (string.IsNullOrEmpty(updateText))
{
return; // nothing to accumulate
}
if (_accum.Length == 0)
{
_firstTimestamp = DateTime.Now.ToString("HH:mm:ss.fff");
}
_accum.Append(updateText);
// Decide when to flush: sentence end, newline, or buffer too long
var trimmed = updateText.TrimEnd();
bool endsWithSentence = trimmed.EndsWith('.') || trimmed.EndsWith('!') || trimmed.EndsWith('?');
bool containsNewline = updateText.Contains("\n");
bool tooLong = _accum.Length > 250;
if (endsWithSentence || containsNewline || tooLong)
{
FlushAccumulatedInternal(continuationToken);
}
}
/// <summary>
/// Flushes any remaining accumulated fragments (prints the partial sentence if present).
/// </summary>
public static void FlushAccumulated()
{
if (_accum.Length > 0)
{
FlushAccumulatedInternal(null);
}
}
private static void FlushAccumulatedInternal(string? continuationToken)
{
var ts = _firstTimestamp ?? DateTime.Now.ToString("HH:mm:ss.fff");
Console.ForegroundColor = ConsoleColor.Green;
Console.Write($"[{ts}] ");
Console.ResetColor();
var textToPrint = _accum.ToString().Replace("\n", " ").Trim();
Console.WriteLine(textToPrint);
if (!string.IsNullOrWhiteSpace(continuationToken))
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine($" token: {Truncate(continuationToken, 60)}");
Console.ResetColor();
}
_accum.Clear();
_firstTimestamp = null;
}
public static void PrintLabeled(string label, string content)
{
Console.ForegroundColor = ConsoleColor.Magenta;
Console.Write($"{label}: ");
Console.ResetColor();
Console.WriteLine(content);
}
public static void PrintInfo(string message)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(message);
Console.ResetColor();
}
public static void PrintError(string message)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
public static void PrintFooter(string text)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine();
Console.WriteLine(new string('=', 60));
Console.WriteLine(text);
Console.WriteLine(new string('=', 60));
Console.ResetColor();
}
private static string Truncate(string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
return value.Length <= maxLength ? value : value.Substring(0, maxLength) + "...";
}
internal static void PrintUpdate(string text)
{
PrintUpdate(text, "");
}
internal static void AccumulateAndPrint(string text)
{
AccumulateAndPrint(text, "");
}
// New helper method: start accumulation, append the provided text, and immediately flush.
// Useful for callers that have a single response text and want it printed using the
// same accumulation rules (sentence assembly, newline handling) without manually calling
// StartAccumulatedStream / AccumulateAndPrint / FlushAccumulated each time.
public static void PrintAccumulatedLine(string text, string? continuationToken = null)
{
StartAccumulatedStream();
AccumulateAndPrint(text, continuationToken);
FlushAccumulated();
}
}