From 8890b7272dbb7e81e95ac087275f19cd1e77f6bb Mon Sep 17 00:00:00 2001 From: Alex Date: Fri, 27 Nov 2026 09:40:59 -0400 Subject: [PATCH 1/2] fix(azure-openai): keep parallel streamed tool calls apart The streaming path joined the argument fragments of every tool call into one string and reported only the first name and id, so a reply asking for two tools produced malformed arguments. Rebuild the calls per tool call id, as the OpenAI plugin does, and report them all in ToolCalls. Co-Authored-By: Claude Sonnet 5.5 --- .../BotSharp.Plugin.AzureOpenAI.csproj | 5 ++ .../Providers/Chat/ChatCompletionProvider.cs | 62 ++++++++++++++++--- .../BotSharp.Core.UnitTests.csproj | 2 + ...ureStreamingToolCallReconstructionTests.cs | 45 ++++++++++++++ 4 files changed, 105 insertions(+), 9 deletions(-) create mode 100644 tests/BotSharp.Core.UnitTests/Routing/AzureStreamingToolCallReconstructionTests.cs diff --git a/src/Plugins/BotSharp.Plugin.AzureOpenAI/BotSharp.Plugin.AzureOpenAI.csproj b/src/Plugins/BotSharp.Plugin.AzureOpenAI/BotSharp.Plugin.AzureOpenAI.csproj index 372fb3de5..9591da45e 100644 --- a/src/Plugins/BotSharp.Plugin.AzureOpenAI/BotSharp.Plugin.AzureOpenAI.csproj +++ b/src/Plugins/BotSharp.Plugin.AzureOpenAI/BotSharp.Plugin.AzureOpenAI.csproj @@ -19,4 +19,9 @@ + + + + + diff --git a/src/Plugins/BotSharp.Plugin.AzureOpenAI/Providers/Chat/ChatCompletionProvider.cs b/src/Plugins/BotSharp.Plugin.AzureOpenAI/Providers/Chat/ChatCompletionProvider.cs index 7ef687598..c0bb505aa 100644 --- a/src/Plugins/BotSharp.Plugin.AzureOpenAI/Providers/Chat/ChatCompletionProvider.cs +++ b/src/Plugins/BotSharp.Plugin.AzureOpenAI/Providers/Chat/ChatCompletionProvider.cs @@ -3,12 +3,14 @@ using BotSharp.Abstraction.Conversations.Enums; using BotSharp.Abstraction.Utilities; using BotSharp.Abstraction.Files.Utilities; +using BotSharp.Abstraction.Functions.Models; using BotSharp.Abstraction.Hooks; using BotSharp.Abstraction.MessageHub.Models; using BotSharp.Core.Infrastructures.Streams; using BotSharp.Core.MessageHub; using OpenAI.Chat; using System.ClientModel; +using System.Text; namespace BotSharp.Plugin.AzureOpenAI.Providers.Chat; @@ -326,23 +328,24 @@ public async Task GetChatCompletionsStreamingAsync(Agent agent, if (choice.FinishReason == ChatFinishReason.ToolCalls || choice.FinishReason == ChatFinishReason.FunctionCall) { - var meta = toolCalls.FirstOrDefault(x => !string.IsNullOrEmpty(x.FunctionName)); - var functionName = meta?.FunctionName; - var toolCallId = meta?.ToolCallId; - var args = toolCalls.Where(x => x.FunctionArgumentsUpdate != null).Select(x => x.FunctionArgumentsUpdate.ToString()).ToList(); - var functionArgument = string.Join(string.Empty, args); + var calls = ReconstructToolCalls(toolCalls); + var first = calls.FirstOrDefault(); #if DEBUG - _logger.LogCritical($"Tool Call (id: {toolCallId}) => {functionName}({functionArgument})"); + foreach (var call in calls) + { + _logger.LogDebug($"Tool Call (id: {call.Id}) => {call.FunctionName}({call.FunctionArgs})"); + } #endif responseMessage = new RoleDialogModel(AgentRole.Function, string.Empty) { CurrentAgentId = agent.Id, MessageId = messageId, - ToolCallId = toolCallId, - FunctionName = functionName, - FunctionArgs = functionArgument + ToolCallId = first?.Id, + FunctionName = first?.FunctionName, + FunctionArgs = first?.FunctionArgs ?? string.Empty, + ToolCalls = calls }; } else if (choice.FinishReason.HasValue) @@ -695,4 +698,45 @@ public void SetModelName(string model) { _model = model; } + + /// + /// Rebuilds the tool calls a streaming reply asked for. + /// + /// + /// Same approach as the OpenAI plugin: the SDK's update carries no public index, so an update + /// bearing a new tool call id starts a call, and the fragments following it belong to that one. + /// + internal static List ReconstructToolCalls(List updates) + { + var calls = new List(); + var args = new List(); + + foreach (var update in updates) + { + var opensCall = calls.Count == 0 + || (!string.IsNullOrEmpty(update.ToolCallId) && calls[^1].Id != update.ToolCallId); + + if (opensCall) + { + calls.Add(new LlmToolCall(update.ToolCallId, update.FunctionName, null)); + args.Add(new StringBuilder()); + } + else if (string.IsNullOrEmpty(calls[^1].FunctionName)) + { + calls[^1].FunctionName = update.FunctionName; + } + + if (update.FunctionArgumentsUpdate != null) + { + args[^1].Append(update.FunctionArgumentsUpdate.ToString()); + } + } + + for (var i = 0; i < calls.Count; i++) + { + calls[i].FunctionArgs = args[i].ToString(); + } + + return calls; + } } diff --git a/tests/BotSharp.Core.UnitTests/BotSharp.Core.UnitTests.csproj b/tests/BotSharp.Core.UnitTests/BotSharp.Core.UnitTests.csproj index fc1b8c1c2..f6249212b 100644 --- a/tests/BotSharp.Core.UnitTests/BotSharp.Core.UnitTests.csproj +++ b/tests/BotSharp.Core.UnitTests/BotSharp.Core.UnitTests.csproj @@ -45,6 +45,8 @@ + + diff --git a/tests/BotSharp.Core.UnitTests/Routing/AzureStreamingToolCallReconstructionTests.cs b/tests/BotSharp.Core.UnitTests/Routing/AzureStreamingToolCallReconstructionTests.cs new file mode 100644 index 000000000..48862a4d9 --- /dev/null +++ b/tests/BotSharp.Core.UnitTests/Routing/AzureStreamingToolCallReconstructionTests.cs @@ -0,0 +1,45 @@ +using OpenAI.Chat; +using Xunit; +using ChatCompletionProvider = BotSharp.Plugin.AzureOpenAI.Providers.Chat.ChatCompletionProvider; + +namespace BotSharp.Core.UnitTests.Routing; + +/// +/// The Azure OpenAI counterpart of . +/// +public class AzureStreamingToolCallReconstructionTests +{ + private static StreamingChatToolCallUpdate Update(string? id = null, string? name = null, string? args = null) + => OpenAIChatModelFactory.StreamingChatToolCallUpdate( + index: 0, + toolCallId: id!, + kind: ChatToolCallKind.Function, + functionName: name!, + functionArgumentsUpdate: args != null ? BinaryData.FromString(args) : null!); + + [Fact] + public void Reconstruct_KeepsTwoCallsArgumentsApart() + { + var calls = ChatCompletionProvider.ReconstructToolCalls( + [ + Update(id: "call_1", name: "get_weather", args: "{\"city\":"), + Update(args: "\"Chicago\"}"), + Update(id: "call_2", name: "get_time", args: "{\"zone\":"), + Update(args: "\"CST\"}") + ]); + + Assert.Collection(calls, + call => + { + Assert.Equal("call_1", call.Id); + Assert.Equal("get_weather", call.FunctionName); + Assert.Equal("{\"city\":\"Chicago\"}", call.FunctionArgs); + }, + call => + { + Assert.Equal("call_2", call.Id); + Assert.Equal("get_time", call.FunctionName); + Assert.Equal("{\"zone\":\"CST\"}", call.FunctionArgs); + }); + } +} From b105c56361279f4d5d3f2fbfba3c83544afcfbfc Mon Sep 17 00:00:00 2001 From: Alex Date: Sun, 29 Nov 2026 10:14:53 -0400 Subject: [PATCH 2/2] fix: reconstruct streamed chat tool calls by index --- .../Providers/Chat/ChatCompletionProvider.cs | 34 +++++++++-------- .../Chat/ChatCompletionProvider.Chat.cs | 37 ++++++++++--------- ...ureStreamingToolCallReconstructionTests.cs | 26 +++++++++++-- .../StreamingToolCallReconstructionTests.cs | 35 +++++------------- 4 files changed, 69 insertions(+), 63 deletions(-) diff --git a/src/Plugins/BotSharp.Plugin.AzureOpenAI/Providers/Chat/ChatCompletionProvider.cs b/src/Plugins/BotSharp.Plugin.AzureOpenAI/Providers/Chat/ChatCompletionProvider.cs index c0bb505aa..25729c00b 100644 --- a/src/Plugins/BotSharp.Plugin.AzureOpenAI/Providers/Chat/ChatCompletionProvider.cs +++ b/src/Plugins/BotSharp.Plugin.AzureOpenAI/Providers/Chat/ChatCompletionProvider.cs @@ -703,40 +703,44 @@ public void SetModelName(string model) /// Rebuilds the tool calls a streaming reply asked for. /// /// - /// Same approach as the OpenAI plugin: the SDK's update carries no public index, so an update - /// bearing a new tool call id starts a call, and the fragments following it belong to that one. + /// The SDK provides an index on every update, including fragments without an ID or name. + /// Keep each call's fragments together and return calls in index order. /// internal static List ReconstructToolCalls(List updates) { - var calls = new List(); - var args = new List(); + var calls = new SortedDictionary(); foreach (var update in updates) { - var opensCall = calls.Count == 0 - || (!string.IsNullOrEmpty(update.ToolCallId) && calls[^1].Id != update.ToolCallId); + if (!calls.TryGetValue(update.Index, out var call)) + { + call = (new LlmToolCall(), new StringBuilder()); + calls.Add(update.Index, call); + } - if (opensCall) + if (string.IsNullOrEmpty(call.Call.Id) && !string.IsNullOrEmpty(update.ToolCallId)) { - calls.Add(new LlmToolCall(update.ToolCallId, update.FunctionName, null)); - args.Add(new StringBuilder()); + call.Call.Id = update.ToolCallId; } - else if (string.IsNullOrEmpty(calls[^1].FunctionName)) + + if (string.IsNullOrEmpty(call.Call.FunctionName) && !string.IsNullOrEmpty(update.FunctionName)) { - calls[^1].FunctionName = update.FunctionName; + call.Call.FunctionName = update.FunctionName; } if (update.FunctionArgumentsUpdate != null) { - args[^1].Append(update.FunctionArgumentsUpdate.ToString()); + call.Arguments.Append(update.FunctionArgumentsUpdate.ToString()); } } - for (var i = 0; i < calls.Count; i++) + var result = new List(calls.Count); + foreach (var (call, arguments) in calls.Values) { - calls[i].FunctionArgs = args[i].ToString(); + call.FunctionArgs = arguments.ToString(); + result.Add(call); } - return calls; + return result; } } diff --git a/src/Plugins/BotSharp.Plugin.OpenAI/Providers/Chat/ChatCompletionProvider.Chat.cs b/src/Plugins/BotSharp.Plugin.OpenAI/Providers/Chat/ChatCompletionProvider.Chat.cs index b67b9dc18..fc5b0c608 100644 --- a/src/Plugins/BotSharp.Plugin.OpenAI/Providers/Chat/ChatCompletionProvider.Chat.cs +++ b/src/Plugins/BotSharp.Plugin.OpenAI/Providers/Chat/ChatCompletionProvider.Chat.cs @@ -784,43 +784,44 @@ internal static string DescribeContent(string? text) /// Rebuilds the tool calls a streaming reply asked for. /// /// - /// Arguments arrive chunked across updates and have to be accumulated, and the SDK's update - /// carries no index -- only a tool call id, which is present when a call opens. So an update - /// bearing a new id starts a call, and the fragments following it belong to that one. - /// Concatenating every fragment into a single string, as this did before, produced one - /// malformed argument blob as soon as the model asked for more than one tool at a time. + /// The SDK provides an index on every update, including fragments without an ID or name. + /// Keep each call's fragments together and return calls in index order. /// internal static List ReconstructToolCalls(List updates) { - var calls = new List(); - var args = new List(); + var calls = new SortedDictionary(); foreach (var update in updates) { - var opensCall = calls.Count == 0 - || (!string.IsNullOrEmpty(update.ToolCallId) && calls[^1].Id != update.ToolCallId); + if (!calls.TryGetValue(update.Index, out var call)) + { + call = (new LlmToolCall(), new StringBuilder()); + calls.Add(update.Index, call); + } - if (opensCall) + if (string.IsNullOrEmpty(call.Call.Id) && !string.IsNullOrEmpty(update.ToolCallId)) { - calls.Add(new LlmToolCall(update.ToolCallId, update.FunctionName, null)); - args.Add(new StringBuilder()); + call.Call.Id = update.ToolCallId; } - else if (string.IsNullOrEmpty(calls[^1].FunctionName)) + + if (string.IsNullOrEmpty(call.Call.FunctionName) && !string.IsNullOrEmpty(update.FunctionName)) { - calls[^1].FunctionName = update.FunctionName; + call.Call.FunctionName = update.FunctionName; } if (update.FunctionArgumentsUpdate != null) { - args[^1].Append(update.FunctionArgumentsUpdate.ToString()); + call.Arguments.Append(update.FunctionArgumentsUpdate.ToString()); } } - for (var i = 0; i < calls.Count; i++) + var result = new List(calls.Count); + foreach (var (call, arguments) in calls.Values) { - calls[i].FunctionArgs = args[i].ToString(); + call.FunctionArgs = arguments.ToString(); + result.Add(call); } - return calls; + return result; } } diff --git a/tests/BotSharp.Core.UnitTests/Routing/AzureStreamingToolCallReconstructionTests.cs b/tests/BotSharp.Core.UnitTests/Routing/AzureStreamingToolCallReconstructionTests.cs index 48862a4d9..b3e816dbc 100644 --- a/tests/BotSharp.Core.UnitTests/Routing/AzureStreamingToolCallReconstructionTests.cs +++ b/tests/BotSharp.Core.UnitTests/Routing/AzureStreamingToolCallReconstructionTests.cs @@ -9,9 +9,9 @@ namespace BotSharp.Core.UnitTests.Routing; /// public class AzureStreamingToolCallReconstructionTests { - private static StreamingChatToolCallUpdate Update(string? id = null, string? name = null, string? args = null) + private static StreamingChatToolCallUpdate Update(int index = 0, string? id = null, string? name = null, string? args = null) => OpenAIChatModelFactory.StreamingChatToolCallUpdate( - index: 0, + index: index, toolCallId: id!, kind: ChatToolCallKind.Function, functionName: name!, @@ -23,9 +23,9 @@ public void Reconstruct_KeepsTwoCallsArgumentsApart() var calls = ChatCompletionProvider.ReconstructToolCalls( [ Update(id: "call_1", name: "get_weather", args: "{\"city\":"), + Update(1, id: "call_2", name: "get_time", args: "{\"zone\":"), Update(args: "\"Chicago\"}"), - Update(id: "call_2", name: "get_time", args: "{\"zone\":"), - Update(args: "\"CST\"}") + Update(1, args: "\"CST\"}") ]); Assert.Collection(calls, @@ -42,4 +42,22 @@ public void Reconstruct_KeepsTwoCallsArgumentsApart() Assert.Equal("{\"zone\":\"CST\"}", call.FunctionArgs); }); } + + [Fact] + public void Reconstruct_KeepsEarlierArgumentsWhenTheIdArrivesLater() + { + var calls = ChatCompletionProvider.ReconstructToolCalls( + [ + Update(args: "{\"city\":"), + Update(1, id: "call_2", name: "get_time", args: "{}"), + Update(id: "call_1", name: "get_weather", args: "\"Chicago\"}") + ]); + + Assert.Equal(2, calls.Count); + Assert.Equal("call_1", calls[0].Id); + Assert.Equal("get_weather", calls[0].FunctionName); + Assert.Equal("{\"city\":\"Chicago\"}", calls[0].FunctionArgs); + Assert.Equal("call_2", calls[1].Id); + Assert.Equal("{}", calls[1].FunctionArgs); + } } diff --git a/tests/BotSharp.Core.UnitTests/Routing/StreamingToolCallReconstructionTests.cs b/tests/BotSharp.Core.UnitTests/Routing/StreamingToolCallReconstructionTests.cs index 461d76d67..a39d6fdeb 100644 --- a/tests/BotSharp.Core.UnitTests/Routing/StreamingToolCallReconstructionTests.cs +++ b/tests/BotSharp.Core.UnitTests/Routing/StreamingToolCallReconstructionTests.cs @@ -12,27 +12,11 @@ namespace BotSharp.Core.UnitTests.Routing; /// branch logs its calls under #if DEBUG, so a Release deployment that uses it shows /// nothing at all. /// -/// -/// Why reassembly is guesswork in the first place: in -/// the OpenAI SDK exposes only FunctionArgumentsUpdate, FunctionName, Kind and ToolCallId. There -/// is no public index, so which call a fragment belongs to has to be inferred -- an update -/// carrying a tool call id different from the one in progress starts a new call, and everything -/// after it belongs to that one. -/// -/// The case these exist for: two calls in one reply. Appending every fragment to a single string, -/// as this did originally, is invisible while a reply asks for one tool and produces a single -/// malformed argument blob the moment it asks for two. -/// -/// public class StreamingToolCallReconstructionTests { - /// - /// One streamed fragment. Null means the update continues the call in - /// progress, which is how the SDK reports every fragment after the first of a call. - /// - private static StreamingChatToolCallUpdate Update(string? id = null, string? name = null, string? args = null) + private static StreamingChatToolCallUpdate Update(int index = 0, string? id = null, string? name = null, string? args = null) => OpenAIChatModelFactory.StreamingChatToolCallUpdate( - index: 0, + index: index, toolCallId: id!, kind: ChatToolCallKind.Function, functionName: name!, @@ -65,9 +49,9 @@ public void Reconstruct_KeepsTwoCallsArgumentsApart() var calls = ChatCompletionProvider.ReconstructToolCalls( [ Update(id: "call_1", name: "get_weather", args: "{\"city\":"), + Update(1, id: "call_2", name: "get_time", args: "{\"zone\":"), Update(args: "\"Chicago\"}"), - Update(id: "call_2", name: "get_time", args: "{\"zone\":"), - Update(args: "\"CST\"}") + Update(1, args: "\"CST\"}") ]); Assert.Equal(2, calls.Count); @@ -79,8 +63,7 @@ public void Reconstruct_KeepsTwoCallsArgumentsApart() /// /// A reply really does ask for the same tool more than once -- production shows models doing - /// it with up to four copies of one name in a single reply. The id is the only thing telling - /// those apart, so grouping must not fall back to the name. + /// it with up to four copies of one name in a single reply. Each index identifies a separate call. /// [Fact] public void Reconstruct_SeparatesTwoCallsOfTheSameTool() @@ -88,7 +71,7 @@ public void Reconstruct_SeparatesTwoCallsOfTheSameTool() var calls = ChatCompletionProvider.ReconstructToolCalls( [ Update(id: "call_1", name: "process_wo_avoidance", args: "{\"key_words\":\"toilet leak\"}"), - Update(id: "call_2", name: "process_wo_avoidance", args: "{\"key_words\":\"roof repair\"}") + Update(1, id: "call_2", name: "process_wo_avoidance", args: "{\"key_words\":\"roof repair\"}") ]); Assert.Equal(2, calls.Count); @@ -183,8 +166,8 @@ public void Reconstruct_KeepsTheOrderTheModelSentThemIn() var calls = ChatCompletionProvider.ReconstructToolCalls( [ Update(id: "call_1", name: "a", args: "{}"), - Update(id: "call_2", name: "b", args: "{}"), - Update(id: "call_3", name: "c", args: "{}") + Update(1, id: "call_2", name: "b", args: "{}"), + Update(2, id: "call_3", name: "c", args: "{}") ]); Assert.Equal(["a", "b", "c"], calls.Select(x => x.FunctionName)); @@ -201,7 +184,7 @@ public void Reconstruct_ProducesCallsTheEngineCanDispatch() var calls = ChatCompletionProvider.ReconstructToolCalls( [ Update(id: "call_1", name: "get_weather", args: "{\"city\":\"Chicago\"}"), - Update(id: "call_2", name: "get_time", args: "{\"zone\":\"CST\"}") + Update(1, id: "call_2", name: "get_time", args: "{\"zone\":\"CST\"}") ]); Assert.Equal(2, calls.Count);