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/SequenceBuilder.cs

70lines · modecode

1// Copyright (c) Microsoft Corporation. All rights reserved.
2// Licensed under the MIT License.
3
4using System.Buffers;
5using System.Diagnostics;
6
7namespace Microsoft.Teams.AI.Models.OpenAI.Builders;
8
9/// <summary>
10/// https://github.com/openai/openai-dotnet/blob/main/examples/Chat/Example04_FunctionCallingStreaming.cs#L74
11/// </summary>
12public class SequenceBuilder<T>
13{
14 Segment? _first;
15 Segment? _last;
16
17 public void Append(ReadOnlyMemory<T> data)
18 {
19 if (_first is null)
20 {
21 Debug.Assert(_last is null);
22 _first = new Segment(data);
23 _last = _first;
24 }
25 else
26 {
27 _last = _last!.Append(data);
28 }
29 }
30
31 public ReadOnlySequence<T> Build()
32 {
33 if (_first is null)
34 {
35 Debug.Assert(_last is null);
36 return ReadOnlySequence<T>.Empty;
37 }
38
39 if (_first == _last)
40 {
41 Debug.Assert(_first.Next is null);
42 return new ReadOnlySequence<T>(_first.Memory);
43 }
44
45 return new ReadOnlySequence<T>(_first, 0, _last!, _last!.Memory.Length);
46 }
47
48 private sealed class Segment : ReadOnlySequenceSegment<T>
49 {
50 public Segment(ReadOnlyMemory<T> items) : this(items, 0)
51 {
52 }
53
54 private Segment(ReadOnlyMemory<T> items, long runningIndex)
55 {
56 Debug.Assert(runningIndex >= 0);
57 Memory = items;
58 RunningIndex = runningIndex;
59 }
60
61 public Segment Append(ReadOnlyMemory<T> items)
62 {
63 long runningIndex;
64 checked { runningIndex = RunningIndex + Memory.Length; }
65 Segment segment = new(items, runningIndex);
66 Next = segment;
67 return segment;
68 }
69 }
70}