microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
Libraries/Microsoft.Teams.AI.Models.OpenAI/Builders/StreamingChatToolCallBuilder.cs
62lines · modecode
| 1 | using System.Buffers; |
| 2 | |
| 3 | using OpenAI.Chat; |
| 4 | |
| 5 | namespace Microsoft.Teams.AI.Models.OpenAI.Builders; |
| 6 | |
| 7 | /// <summary> |
| 8 | /// https://github.com/openai/openai-dotnet/blob/main/examples/Chat/Example04_FunctionCallingStreaming.cs#L18 |
| 9 | /// </summary> |
| 10 | public class StreamingChatToolCallsBuilder |
| 11 | { |
| 12 | private readonly Dictionary<int, string> _indexToToolCallId = []; |
| 13 | private readonly Dictionary<int, string> _indexToFunctionName = []; |
| 14 | private readonly Dictionary<int, SequenceBuilder<byte>> _indexToFunctionArguments = []; |
| 15 | |
| 16 | public void Append(StreamingChatToolCallUpdate toolCallUpdate) |
| 17 | { |
| 18 | // Keep track of which tool call ID belongs to this update index. |
| 19 | if (toolCallUpdate.ToolCallId is not null) |
| 20 | { |
| 21 | _indexToToolCallId[toolCallUpdate.Index] = toolCallUpdate.ToolCallId; |
| 22 | } |
| 23 | |
| 24 | // Keep track of which function name belongs to this update index. |
| 25 | if (toolCallUpdate.FunctionName is not null) |
| 26 | { |
| 27 | _indexToFunctionName[toolCallUpdate.Index] = toolCallUpdate.FunctionName; |
| 28 | } |
| 29 | |
| 30 | // Keep track of which function arguments belong to this update index, |
| 31 | // and accumulate the arguments as new updates arrive. |
| 32 | if (toolCallUpdate.FunctionArgumentsUpdate is not null && !toolCallUpdate.FunctionArgumentsUpdate.ToMemory().IsEmpty) |
| 33 | { |
| 34 | if (!_indexToFunctionArguments.TryGetValue(toolCallUpdate.Index, out SequenceBuilder<byte>? argumentsBuilder)) |
| 35 | { |
| 36 | argumentsBuilder = new SequenceBuilder<byte>(); |
| 37 | _indexToFunctionArguments[toolCallUpdate.Index] = argumentsBuilder; |
| 38 | } |
| 39 | |
| 40 | argumentsBuilder.Append(toolCallUpdate.FunctionArgumentsUpdate); |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | public IReadOnlyList<ChatToolCall> Build() |
| 45 | { |
| 46 | List<ChatToolCall> toolCalls = []; |
| 47 | |
| 48 | foreach (var kv in _indexToToolCallId) |
| 49 | { |
| 50 | ReadOnlySequence<byte> sequence = _indexToFunctionArguments[kv.Key].Build(); |
| 51 | |
| 52 | ChatToolCall toolCall = ChatToolCall.CreateFunctionToolCall( |
| 53 | id: kv.Value, |
| 54 | functionName: _indexToFunctionName[kv.Key], |
| 55 | functionArguments: BinaryData.FromBytes(sequence.ToArray())); |
| 56 | |
| 57 | toolCalls.Add(toolCall); |
| 58 | } |
| 59 | |
| 60 | return toolCalls; |
| 61 | } |
| 62 | } |