microsoft/teams.net

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
b9bc522d242ad42cba49791c95c73c0f2c1d2358

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

65lines · 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>
13public class StreamingChatToolCallsBuilder
14{
15 private readonly Dictionary<int, string> _indexToToolCallId = [];
16 private readonly Dictionary<int, string> _indexToFunctionName = [];
17 private readonly Dictionary<int, SequenceBuilder<byte>> _indexToFunctionArguments = [];
18
19 public void Append(StreamingChatToolCallUpdate toolCallUpdate)
20 {
21 // Keep track of which tool call ID belongs to this update index.
22 if (toolCallUpdate.ToolCallId is not null)
23 {
24 _indexToToolCallId[toolCallUpdate.Index] = toolCallUpdate.ToolCallId;
25 }
26
27 // Keep track of which function name belongs to this update index.
28 if (toolCallUpdate.FunctionName is not null)
29 {
30 _indexToFunctionName[toolCallUpdate.Index] = toolCallUpdate.FunctionName;
31 }
32
33 // Keep track of which function arguments belong to this update index,
34 // and accumulate the arguments as new updates arrive.
35 if (toolCallUpdate.FunctionArgumentsUpdate is not null && !toolCallUpdate.FunctionArgumentsUpdate.ToMemory().IsEmpty)
36 {
37 if (!_indexToFunctionArguments.TryGetValue(toolCallUpdate.Index, out SequenceBuilder<byte>? argumentsBuilder))
38 {
39 argumentsBuilder = new SequenceBuilder<byte>();
40 _indexToFunctionArguments[toolCallUpdate.Index] = argumentsBuilder;
41 }
42
43 argumentsBuilder.Append(toolCallUpdate.FunctionArgumentsUpdate);
44 }
45 }
46
47 public IReadOnlyList<ChatToolCall> Build()
48 {
49 List<ChatToolCall> toolCalls = [];
50
51 foreach (var kv in _indexToToolCallId)
52 {
53 ReadOnlySequence<byte> sequence = _indexToFunctionArguments[kv.Key].Build();
54
55 ChatToolCall toolCall = ChatToolCall.CreateFunctionToolCall(
56 id: kv.Value,
57 functionName: _indexToFunctionName[kv.Key],
58 functionArguments: BinaryData.FromBytes(sequence.ToArray()));
59
60 toolCalls.Add(toolCall);
61 }
62
63 return toolCalls;
64 }
65}