Skip to content

Commit 78efff5

Browse files
committed
Refactor the telemetry work
1 parent d7a00ce commit 78efff5

File tree

7 files changed

+249
-274
lines changed

7 files changed

+249
-274
lines changed

shell/agents/Microsoft.Azure.Agent/AzureAgent.cs

Lines changed: 25 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
using System.Diagnostics;
22
using System.Text;
3-
using System.Text.Json;
3+
44
using AIShell.Abstraction;
55
using Azure.Identity;
66
using Serilog;
@@ -17,6 +17,7 @@ public sealed class AzureAgent : ILLMAgent
1717
public string SettingFile { private set; get; }
1818

1919
internal ArgumentPlaceholder ArgPlaceholder { set; get; }
20+
internal CopilotResponse CopilotResponse { set; get; }
2021

2122
private const string SettingFileName = "az.config.json";
2223
private const string LoggingFileName = "log..txt";
@@ -37,13 +38,13 @@ 7. DO NOT include the placeholder summary when the commands contains no placehol
3738
""";
3839

3940
private int _turnsLeft;
40-
internal CopilotResponse _copilotResponse;
41+
private CopilotResponse _copilotResponse;
4142
private AgentSetting _setting;
4243

4344
private readonly string _instructions;
4445
private readonly StringBuilder _buffer;
4546
private readonly HttpClient _httpClient;
46-
internal readonly ChatSession _chatSession;
47+
private readonly ChatSession _chatSession;
4748
private readonly Dictionary<string, string> _valueStore;
4849
// private MetricHelper _metricHelper;
4950

@@ -111,36 +112,33 @@ public void Initialize(AgentConfig config)
111112
.CreateLogger();
112113
Log.Information("Azure agent initialized.");
113114
}
115+
116+
if (_setting.Telemetry)
117+
{
118+
Telemetry.Initialize();
119+
}
114120
}
115121

116122
public IEnumerable<CommandBase> GetCommands() => [new ReplaceCommand(this)];
117-
public bool CanAcceptFeedback(UserAction action) => !MetricHelper.TelemetryOptOut;
123+
public bool CanAcceptFeedback(UserAction action) => _setting.Telemetry;
118124
public void OnUserAction(UserActionPayload actionPayload) {
119125
// Send telemetry about the user action.
120-
// DisLike Action
121-
string DetailedMessage = null;
122-
bool IsUserFeedback = false;
123-
if (actionPayload.Action == UserAction.Dislike)
126+
bool isUserFeedback = false;
127+
string details = null;
128+
UserAction action = actionPayload.Action;
129+
130+
if (action is UserAction.Dislike)
124131
{
125-
IsUserFeedback = true;
126-
DislikePayload dislikePayload = (DislikePayload)actionPayload;
127-
DetailedMessage = string.Format("{0} | {1}", dislikePayload.ShortFeedback, dislikePayload.LongFeedback);
132+
var dislike = (DislikePayload) actionPayload;
133+
isUserFeedback = true;
134+
details = string.Format("{0} | {1}", dislike.ShortFeedback, dislike.LongFeedback);
128135
}
129-
else if (actionPayload.Action == UserAction.Like)
136+
else if (action is UserAction.Like)
130137
{
131-
IsUserFeedback = true;
138+
isUserFeedback = true;
132139
}
133140

134-
MetricHelper.metricHelper.LogTelemetry(
135-
new AzTrace()
136-
{
137-
Command = actionPayload.Action.ToString(),
138-
ConversationId = _chatSession.ConversationId,
139-
ActivityId = _copilotResponse.ReplyToId,
140-
EventType = IsUserFeedback ? "Feedback" : "UserAction",
141-
TopicName = _copilotResponse.TopicName,
142-
DetailedMessage = DetailedMessage
143-
});
141+
Telemetry.Log(AzTrace.UserAction(action.ToString(), _copilotResponse, details, isUserFeedback));
144142
}
145143

146144
public async Task RefreshChatAsync(IShell shell, bool force)
@@ -282,16 +280,9 @@ public async Task<bool> ChatAsync(string input, IShell shell)
282280
}
283281
}
284282

285-
if (!MetricHelper.TelemetryOptOut)
283+
if (Telemetry.Enabled)
286284
{
287-
MetricHelper.metricHelper.LogTelemetry(
288-
new AzTrace()
289-
{
290-
ConversationId = _chatSession.ConversationId,
291-
EventType = "Chat",
292-
TopicName = _copilotResponse.TopicName,
293-
ActivityId = _copilotResponse.ReplyToId
294-
});
285+
Telemetry.Log(AzTrace.Chat(_copilotResponse));
295286
}
296287
}
297288
catch (Exception ex) when (ex is TokenRequestException or ConnectionDroppedException)
@@ -401,18 +392,9 @@ private ResponseData ParseCLIHandlerResponse(IShell shell)
401392
else
402393
{
403394
// The placeholder section is not in the format as we've instructed ...
404-
// TODO: send telemetry about this case.
405-
if (!MetricHelper.TelemetryOptOut)
395+
if (Telemetry.Enabled)
406396
{
407-
MetricHelper.metricHelper.LogTelemetry(
408-
new AzTrace()
409-
{
410-
ConversationId = _chatSession.ConversationId,
411-
ActivityId = _copilotResponse.ReplyToId,
412-
EventType = "Exception",
413-
TopicName = _copilotResponse.TopicName,
414-
DetailedMessage = $"Placeholder section not in expected format:{text}"
415-
});
397+
Telemetry.Log(AzTrace.Exception(_copilotResponse, $"Placeholder section not in expected format: {text}"));
416398
}
417399
Log.Error("Placeholder section not in expected format:\n{0}", text);
418400
}

shell/agents/Microsoft.Azure.Agent/Command.cs

Lines changed: 13 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
using System.CommandLine;
22
using System.Text;
3-
using System.Text.Encodings.Web;
4-
using System.Text.Json;
5-
using System.Text.Unicode;
3+
64
using AIShell.Abstraction;
75

86
namespace Microsoft.Azure.Agent;
@@ -70,8 +68,6 @@ private void ReplaceAction()
7068

7169
try
7270
{
73-
// Detailed Message recorded indicating whether each placeholder is replaced.
74-
Dictionary<string, Boolean> DetailedMessage = new();
7571
for (int i = 0; i < items.Count; i++)
7672
{
7773
var item = items[i];
@@ -122,43 +118,17 @@ private void ReplaceAction()
122118

123119
_values.Add(item.Name, value);
124120
_agent.SaveUserValue(item.Name, value);
125-
DetailedMessage.Add(item.Name, true);
126121

127122
if (nameArgInfo is not null && nameArgInfo.NamingRule.TryMatchName(value, out string prodName, out string envName))
128123
{
129124
_productNames.Add(prodName.ToLower());
130125
_environmentNames.Add(envName.ToLower());
131126
}
132127
}
133-
else
134-
{
135-
DetailedMessage.Add(item.Name, false);
136-
}
137128

138129
// Write an extra new line.
139130
host.WriteLine();
140131
}
141-
142-
// Customize the Json Serializer Options to avoid unnecessary encoding.
143-
var options = new JsonSerializerOptions
144-
{
145-
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
146-
};
147-
148-
// Send Telemetry for Replace Action.
149-
if (!MetricHelper.TelemetryOptOut)
150-
{
151-
MetricHelper.metricHelper.LogTelemetry(
152-
new AzTrace()
153-
{
154-
Command = "Replace",
155-
ConversationId = _agent._chatSession.ConversationId,
156-
ActivityId = _agent._copilotResponse.ReplyToId,
157-
EventType = "UserAction",
158-
TopicName = _agent._copilotResponse.TopicName,
159-
DetailedMessage = JsonSerializer.Serialize(DetailedMessage, options)
160-
});
161-
}
162132
}
163133
catch (OperationCanceledException)
164134
{
@@ -189,6 +159,18 @@ private void ReplaceAction()
189159
host.RenderDivider("Regenerate", DividerAlignment.Left);
190160
host.MarkupLine($"\nQuery: [teal]{ap.Query}[/]");
191161

162+
if (Telemetry.Enabled)
163+
{
164+
Dictionary<string, bool> details = new(items.Count);
165+
foreach (var item in items)
166+
{
167+
string name = item.Name;
168+
details.Add(name, _values.ContainsKey(name));
169+
}
170+
171+
Telemetry.Log(AzTrace.UserAction("Replace", _agent.CopilotResponse, details));
172+
}
173+
192174
try
193175
{
194176
string answer = host.RunWithSpinnerAsync(RegenerateAsync).GetAwaiter().GetResult();

shell/agents/Microsoft.Azure.Agent/DataRetriever.cs

Lines changed: 13 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
using System.Text.RegularExpressions;
77

88
using AIShell.Abstraction;
9-
using Azure;
109
using Serilog;
1110

1211
namespace Microsoft.Azure.Agent;
@@ -578,47 +577,31 @@ private AzCLICommand QueryForMetadata(string azCommand)
578577
}
579578
else
580579
{
581-
if (!MetricHelper.TelemetryOptOut)
580+
Log.Error("[QueryForMetadata] Received status code '{0}' for command '{1}'", response.StatusCode, azCommand);
581+
if (Telemetry.Enabled)
582582
{
583-
Dictionary<string, string> errorMessage = new Dictionary<string, string>
583+
Dictionary<string, string> details = new()
584584
{
585-
{ "StatusCode", response.StatusCode.ToString() },
586-
{ "Command", azCommand },
587-
{ "ErrorMessage", $"[QueryForMetadata] Received status code {response.StatusCode} for command {azCommand}" },
585+
["StatusCode"] = response.StatusCode.ToString(),
586+
["Command"] = azCommand,
587+
["Message"] = "AzCLI metadata service returns unsuccessful status code for query."
588588
};
589-
MetricHelper.metricHelper.LogTelemetry(
590-
new AzTrace()
591-
{
592-
// ConversationId = _agent._chatSession.ConversationId,
593-
// ActivityId = _agent._copilotResponse.ReplyToId,
594-
EventType = "Exception",
595-
// TopicName = _agent._copilotResponse.TopicName,
596-
DetailedMessage = JsonSerializer.Serialize(errorMessage)
597-
});
589+
Telemetry.Log(AzTrace.Exception(response: null, details));
598590
}
599-
Log.Error("[QueryForMetadata] Received status code '{0}' for command '{1}'", response.StatusCode, azCommand);
600591
}
601592
}
602593
catch (Exception e)
603594
{
604-
if (!MetricHelper.TelemetryOptOut)
595+
Log.Error(e, "[QueryForMetadata] Exception while processing command: {0}", azCommand);
596+
if (Telemetry.Enabled)
605597
{
606-
Dictionary<string, string> errorMessage = new Dictionary<string, string>
598+
Dictionary<string, string> details = new()
607599
{
608-
{ "Command", azCommand },
609-
{ "ErrorMessage", $"[QueryForMetadata] Exception while processing command: {azCommand}" },
600+
["Command"] = azCommand,
601+
["Message"] = "AzCLI metadata query and process raised an exception."
610602
};
611-
MetricHelper.metricHelper.LogTelemetry(
612-
new AzTrace()
613-
{
614-
// ConversationId = _agent._chatSession.ConversationId,
615-
// ActivityId = _agent._copilotResponse.ReplyToId,
616-
EventType = "Exception",
617-
// TopicName = _agent._copilotResponse.TopicName,
618-
DetailedMessage = JsonSerializer.Serialize(errorMessage)
619-
});
603+
Telemetry.Log(AzTrace.Exception(response: null, details));
620604
}
621-
Log.Error(e, "[QueryForMetadata] Exception while processing command: {0}", azCommand);
622605
}
623606

624607
return command;

0 commit comments

Comments
 (0)