microsoft/teams.net

Public

mirrored fromhttps://github.com/microsoft/teams.netAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v2.0.8

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

Libraries/Microsoft.Teams.AI.Models.OpenAI/Builders/StreamingChatToolCallBuilder.cs

66lines · modecode

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