microsoft/teams.net

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v2.0.0-preview.6

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

62lines · modecode

1using System.Buffers;
2
3using OpenAI.Chat;
4
5namespace 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>
10public 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}