Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,9 @@
<ProjectReference Include="..\..\Infrastructure\BotSharp.Core\BotSharp.Core.csproj" />
</ItemGroup>

<ItemGroup>
<!-- ReconstructToolCalls is tested directly. -->
<InternalsVisibleTo Include="BotSharp.Core.UnitTests" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -326,23 +328,24 @@ public async Task<RoleDialogModel> 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)
Expand Down Expand Up @@ -695,4 +698,49 @@ public void SetModelName(string model)
{
_model = model;
}

/// <summary>
/// Rebuilds the tool calls a streaming reply asked for.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
internal static List<LlmToolCall> ReconstructToolCalls(List<StreamingChatToolCallUpdate> updates)
{
var calls = new SortedDictionary<int, (LlmToolCall Call, StringBuilder Arguments)>();

foreach (var update in updates)
{
if (!calls.TryGetValue(update.Index, out var call))
{
call = (new LlmToolCall(), new StringBuilder());
calls.Add(update.Index, call);
}

if (string.IsNullOrEmpty(call.Call.Id) && !string.IsNullOrEmpty(update.ToolCallId))
{
call.Call.Id = update.ToolCallId;
}

if (string.IsNullOrEmpty(call.Call.FunctionName) && !string.IsNullOrEmpty(update.FunctionName))
{
call.Call.FunctionName = update.FunctionName;
}

if (update.FunctionArgumentsUpdate != null)
{
call.Arguments.Append(update.FunctionArgumentsUpdate.ToString());
}
}

var result = new List<LlmToolCall>(calls.Count);
foreach (var (call, arguments) in calls.Values)
{
call.FunctionArgs = arguments.ToString();
result.Add(call);
}

return result;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -784,43 +784,44 @@ internal static string DescribeContent(string? text)
/// Rebuilds the tool calls a streaming reply asked for.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
internal static List<LlmToolCall> ReconstructToolCalls(List<StreamingChatToolCallUpdate> updates)
{
var calls = new List<LlmToolCall>();
var args = new List<StringBuilder>();
var calls = new SortedDictionary<int, (LlmToolCall Call, StringBuilder Arguments)>();

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<LlmToolCall>(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;
}
}
2 changes: 2 additions & 0 deletions tests/BotSharp.Core.UnitTests/BotSharp.Core.UnitTests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
<ProjectReference Include="..\..\src\Infrastructure\BotSharp.OpenAPI\BotSharp.OpenAPI.csproj" />
<!-- For StreamingToolCallReconstructionTests: the streamed tool-call reconstruction lives here. -->
<ProjectReference Include="..\..\src\Plugins\BotSharp.Plugin.OpenAI\BotSharp.Plugin.OpenAI.csproj" />
<!-- For AzureStreamingToolCallReconstructionTests. -->
<ProjectReference Include="..\..\src\Plugins\BotSharp.Plugin.AzureOpenAI\BotSharp.Plugin.AzureOpenAI.csproj" />
<!-- For AnthropicStreamedContentTests: the streamed final-message content lives here. -->
<ProjectReference Include="..\..\src\Plugins\BotSharp.Plugin.AnthropicAI\BotSharp.Plugin.AnthropicAI.csproj" />
<!-- For ReadPdfFnDefaultModelTests: the PDF reading fallback model lives here. -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using OpenAI.Chat;
using Xunit;
using ChatCompletionProvider = BotSharp.Plugin.AzureOpenAI.Providers.Chat.ChatCompletionProvider;

namespace BotSharp.Core.UnitTests.Routing;

/// <summary>
/// The Azure OpenAI counterpart of <see cref="StreamingToolCallReconstructionTests"/>.
/// </summary>
public class AzureStreamingToolCallReconstructionTests
{
private static StreamingChatToolCallUpdate Update(int index = 0, string? id = null, string? name = null, string? args = null)
=> OpenAIChatModelFactory.StreamingChatToolCallUpdate(
index: index,
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(1, id: "call_2", name: "get_time", args: "{\"zone\":"),
Update(args: "\"Chicago\"}"),
Update(1, 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);
});
}

[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);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,11 @@ namespace BotSharp.Core.UnitTests.Routing;
/// branch logs its calls under <c>#if DEBUG</c>, so a Release deployment that uses it shows
/// nothing at all.
/// </summary>
/// <remarks>
/// Why reassembly is guesswork in the first place: <see cref="StreamingChatToolCallUpdate"/> 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.
/// <para>
/// 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.
/// </para>
/// </remarks>
public class StreamingToolCallReconstructionTests
{
/// <summary>
/// One streamed fragment. Null <paramref name="id"/> means the update continues the call in
/// progress, which is how the SDK reports every fragment after the first of a call.
/// </summary>
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!,
Expand Down Expand Up @@ -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);
Expand All @@ -79,16 +63,15 @@ public void Reconstruct_KeepsTwoCallsArgumentsApart()

/// <summary>
/// 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.
/// </summary>
[Fact]
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);
Expand Down Expand Up @@ -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));
Expand All @@ -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);
Expand Down
Loading