Skip to content

Commit dc60722

Browse files
giles17CopilotCopilot
authored
.NET: Project ToolExecution events as FunctionCallContent/FunctionResultContent in GitHubCopilotAgent streaming (microsoft#6228)
* Project ToolExecution events as FunctionCallContent/FunctionResultContent GitHubCopilotAgent's event-dispatch switch previously had no case for ToolExecutionStartEvent or ToolExecutionCompleteEvent. Both fell through to the default case and were wrapped as opaque AIContent with RawRepresentation, preventing downstream consumers and models from recognizing tool call results. Add explicit cases that project: - ToolExecutionStartEvent → FunctionCallContent (role: Assistant) - ToolExecutionCompleteEvent → FunctionResultContent (role: Tool) This mirrors the Python fix already shipped in microsoft#4734/microsoft#4814/microsoft#4828. Fixes microsoft#5897 Co-authored-by: Copilot <[email protected]> * fix(microsoft#5897): Address review feedback for ParseArguments robustness - Handle non-generic IDictionary variants (Hashtable, etc.) that don't match IDictionary<string, object?> due to generic invariance - Return null for empty/whitespace string arguments instead of wrapping them in a spurious { value = "" } dictionary, aligning with ParseFunctionArgumentsObject convention elsewhere in the repo - Add test coverage for Dictionary, Hashtable, and JsonElement argument types - Add edge-case test for Success=true with null Result Co-authored-by: Copilot <[email protected]> * Fix non-generic IDictionary key handling in ParseArguments (microsoft#5897) Use direct (string) cast for dictionary keys instead of ToString() coercion, matching the established pattern in ObjectExtensions and PortableValueExtensions. This validates keys are actually strings rather than silently accepting and coercing non-string keys. Add test verifying non-string dictionary keys throw InvalidCastException. Co-authored-by: Copilot <[email protected]> * Fix missing 'using System' in ToolExecutionEventProjectionTests Add the missing 'using System' directive needed for InvalidCastException reference at line 375 of ToolExecutionEventProjectionTests.cs. Fixes microsoft#5897 Co-authored-by: Copilot <[email protected]> * Use source-generated JsonTypeInfo for AOT-safe argument deserialization Replace reflection-based JsonSerializer.Deserialize<T>() calls with the JsonTypeInfo overload that uses source-generated metadata, eliminating IL2026/IL3050 trimming and AOT warnings without suppressions. Changes: - Register Dictionary<string, object?> in GitHubCopilotJsonUtilities JsonContext - Add JsonSerializerOptions constructor parameter (defaults to GitHubCopilotJsonUtilities.DefaultOptions) - Use GetTypeInfo()-based Deserialize overload in ParseArguments - Remove [UnconditionalSuppressMessage] attributes Co-authored-by: Copilot <[email protected]> * Fix dotnet format: add 'this.' qualification to instance method call Co-authored-by: Copilot <[email protected]> * Adapt to GitHub.Copilot.SDK 1.0.0 API after merge with main - Update ToolExecutionEventProjectionTests: Arguments is now JsonElement? (not object?), remove tests for string/Dictionary/Hashtable arguments - Remove AutoStart option (removed in 1.0.0) - Simplify ParseArguments to handle JsonElement primarily - Add tests for empty object and nested JSON arguments Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot <[email protected]>
1 parent 2f5a76a commit dc60722

3 files changed

Lines changed: 418 additions & 3 deletions

File tree

‎dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/GitHubCopilotAgent.cs‎

Lines changed: 92 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
using System.Linq;
77
using System.Runtime.CompilerServices;
88
using System.Text.Json;
9+
using System.Text.Json.Serialization.Metadata;
910
using System.Threading;
1011
using System.Threading.Channels;
1112
using System.Threading.Tasks;
@@ -29,6 +30,7 @@ public sealed class GitHubCopilotAgent : AIAgent, IAsyncDisposable
2930
private readonly string _description;
3031
private readonly SessionConfig? _sessionConfig;
3132
private readonly bool _ownsClient;
33+
private readonly JsonSerializerOptions _jsonSerializerOptions;
3234

3335
/// <summary>
3436
/// Initializes a new instance of the <see cref="GitHubCopilotAgent"/> class.
@@ -39,13 +41,15 @@ public sealed class GitHubCopilotAgent : AIAgent, IAsyncDisposable
3941
/// <param name="id">The unique identifier for the agent.</param>
4042
/// <param name="name">The name of the agent.</param>
4143
/// <param name="description">The description of the agent.</param>
44+
/// <param name="jsonSerializerOptions">Optional JSON serializer options. Defaults to <see cref="GitHubCopilotJsonUtilities.DefaultOptions"/>.</param>
4245
public GitHubCopilotAgent(
4346
CopilotClient copilotClient,
4447
SessionConfig? sessionConfig = null,
4548
bool ownsClient = false,
4649
string? id = null,
4750
string? name = null,
48-
string? description = null)
51+
string? description = null,
52+
JsonSerializerOptions? jsonSerializerOptions = null)
4953
{
5054
_ = Throw.IfNull(copilotClient);
5155

@@ -55,6 +59,7 @@ public GitHubCopilotAgent(
5559
this._id = id;
5660
this._name = name ?? DefaultName;
5761
this._description = description ?? DefaultDescription;
62+
this._jsonSerializerOptions = jsonSerializerOptions ?? GitHubCopilotJsonUtilities.DefaultOptions;
5863
}
5964

6065
/// <summary>
@@ -67,21 +72,24 @@ public GitHubCopilotAgent(
6772
/// <param name="description">The description of the agent.</param>
6873
/// <param name="tools">The tools to make available to the agent.</param>
6974
/// <param name="instructions">Optional instructions to append as a system message.</param>
75+
/// <param name="jsonSerializerOptions">Optional JSON serializer options. Defaults to <see cref="GitHubCopilotJsonUtilities.DefaultOptions"/>.</param>
7076
public GitHubCopilotAgent(
7177
CopilotClient copilotClient,
7278
bool ownsClient = false,
7379
string? id = null,
7480
string? name = null,
7581
string? description = null,
7682
IList<AITool>? tools = null,
77-
string? instructions = null)
83+
string? instructions = null,
84+
JsonSerializerOptions? jsonSerializerOptions = null)
7885
: this(
7986
copilotClient,
8087
GetSessionConfig(tools, instructions),
8188
ownsClient,
8289
id,
8390
name,
84-
description)
91+
description,
92+
jsonSerializerOptions)
8593
{
8694
}
8795

@@ -182,6 +190,14 @@ protected override async IAsyncEnumerable<AgentResponseUpdate> RunCoreStreamingA
182190
channel.Writer.TryWrite(this.ConvertToAgentResponseUpdate(assistantMessage, isStreaming));
183191
break;
184192

193+
case ToolExecutionStartEvent toolStart:
194+
channel.Writer.TryWrite(this.ConvertToAgentResponseUpdate(toolStart));
195+
break;
196+
197+
case ToolExecutionCompleteEvent toolComplete:
198+
channel.Writer.TryWrite(this.ConvertToAgentResponseUpdate(toolComplete));
199+
break;
200+
185201
case AssistantUsageEvent usageEvent:
186202
channel.Writer.TryWrite(this.ConvertToAgentResponseUpdate(usageEvent));
187203
break;
@@ -349,6 +365,79 @@ internal AgentResponseUpdate ConvertToAgentResponseUpdate(AssistantMessageEvent
349365
};
350366
}
351367

368+
internal AgentResponseUpdate ConvertToAgentResponseUpdate(ToolExecutionStartEvent toolStart)
369+
{
370+
IDictionary<string, object?>? arguments = this.ParseArguments(toolStart.Data?.Arguments);
371+
372+
FunctionCallContent content = new(
373+
toolStart.Data?.ToolCallId ?? string.Empty,
374+
toolStart.Data?.ToolName ?? string.Empty,
375+
arguments)
376+
{
377+
RawRepresentation = toolStart
378+
};
379+
380+
return new AgentResponseUpdate(ChatRole.Assistant, [content])
381+
{
382+
AgentId = this.Id,
383+
CreatedAt = toolStart.Timestamp
384+
};
385+
}
386+
387+
internal AgentResponseUpdate ConvertToAgentResponseUpdate(ToolExecutionCompleteEvent toolComplete)
388+
{
389+
object? result = toolComplete.Data?.Success == true
390+
? toolComplete.Data?.Result?.Content
391+
: toolComplete.Data?.Error?.Message ?? "Tool execution failed";
392+
393+
FunctionResultContent content = new(
394+
toolComplete.Data?.ToolCallId ?? string.Empty,
395+
result)
396+
{
397+
RawRepresentation = toolComplete
398+
};
399+
400+
return new AgentResponseUpdate(ChatRole.Tool, [content])
401+
{
402+
AgentId = this.Id,
403+
CreatedAt = toolComplete.Timestamp
404+
};
405+
}
406+
407+
private IDictionary<string, object?>? ParseArguments(object? arguments)
408+
{
409+
if (arguments is null)
410+
{
411+
return null;
412+
}
413+
414+
if (arguments is JsonElement jsonElement)
415+
{
416+
if (jsonElement.ValueKind == JsonValueKind.Null || jsonElement.ValueKind == JsonValueKind.Undefined)
417+
{
418+
return null;
419+
}
420+
421+
var typeInfo = (JsonTypeInfo<Dictionary<string, object?>>)this._jsonSerializerOptions.GetTypeInfo(typeof(Dictionary<string, object?>));
422+
423+
try
424+
{
425+
return JsonSerializer.Deserialize(jsonElement.GetRawText(), typeInfo);
426+
}
427+
catch (JsonException)
428+
{
429+
return new Dictionary<string, object?> { ["value"] = jsonElement.ToString() };
430+
}
431+
}
432+
433+
if (arguments is IDictionary<string, object?> dict)
434+
{
435+
return dict;
436+
}
437+
438+
return new Dictionary<string, object?> { ["value"] = arguments.ToString() };
439+
}
440+
352441
private AgentResponseUpdate ConvertToAgentResponseUpdate(AssistantUsageEvent usageEvent)
353442
{
354443
UsageDetails usageDetails = new()

‎dotnet/src/Microsoft.Agents.AI.GitHub.Copilot/GitHubCopilotJsonUtilities.cs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Copyright (c) Microsoft. All rights reserved.
22

3+
using System.Collections.Generic;
34
using System.Diagnostics.CodeAnalysis;
45
using System.Text.Encodings.Web;
56
using System.Text.Json;
@@ -43,6 +44,7 @@ private static JsonSerializerOptions CreateDefaultOptions()
4344
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
4445
NumberHandling = JsonNumberHandling.AllowReadingFromString)]
4546
[JsonSerializable(typeof(GitHubCopilotAgentSession))]
47+
[JsonSerializable(typeof(Dictionary<string, object?>))]
4648
[ExcludeFromCodeCoverage]
4749
private sealed partial class JsonContext : JsonSerializerContext;
4850
}

0 commit comments

Comments
 (0)