microsoft/teams.net
Publicmirrored fromhttps://github.com/microsoft/teams.netAvailable
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 | |
| 4 | using System.Buffers; |
| 5 | using System.Diagnostics; |
| 6 | |
| 7 | namespace 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> |
| 12 | public 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 | } |