openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
src/Custom/Assistants/Streaming/AsyncStreamingUpdateCollection.cs
151lines · modeblame
58f93c8dShivangiReja2 years ago | 1 | using System; |
9f9f2936Jose Arriaga Maldonado2 years ago | 2 | using System.ClientModel; |
| 3 | using System.ClientModel.Primitives; | |
| 4 | using System.Collections.Generic; | |
674e0f77Stephen Toub2 years ago | 5 | using System.Linq; |
| 6 | using System.Net.ServerSentEvents; | |
9f9f2936Jose Arriaga Maldonado2 years ago | 7 | using System.Threading; |
| 8 | using System.Threading.Tasks; | |
| 9 | | |
| 10 | #nullable enable | |
| 11 | | |
| 12 | namespace OpenAI.Assistants; | |
| 13 | | |
| 14 | /// <summary> | |
| 15 | /// Implementation of collection abstraction over streaming assistant updates. | |
| 16 | /// </summary> | |
7bdecfd8Anne Thompson2 years ago | 17 | internal class AsyncStreamingUpdateCollection : AsyncCollectionResult<StreamingUpdate> |
9f9f2936Jose Arriaga Maldonado2 years ago | 18 | { |
2ab1a942Jose Arriaga Maldonado1 years ago | 19 | private readonly Func<Task<ClientResult>> _sendRequestAsync; |
| 20 | private readonly CancellationToken _cancellationToken; | |
9f9f2936Jose Arriaga Maldonado2 years ago | 21 | |
2ab1a942Jose Arriaga Maldonado1 years ago | 22 | public AsyncStreamingUpdateCollection(Func<Task<ClientResult>> sendRequestAsync, |
| 23 | CancellationToken cancellationToken) | |
9f9f2936Jose Arriaga Maldonado2 years ago | 24 | { |
2ab1a942Jose Arriaga Maldonado1 years ago | 25 | Argument.AssertNotNull(sendRequestAsync, nameof(sendRequestAsync)); |
9f9f2936Jose Arriaga Maldonado2 years ago | 26 | |
2ab1a942Jose Arriaga Maldonado1 years ago | 27 | _sendRequestAsync = sendRequestAsync; |
| 28 | _cancellationToken = cancellationToken; | |
9f9f2936Jose Arriaga Maldonado2 years ago | 29 | } |
| 30 | | |
2ab1a942Jose Arriaga Maldonado1 years ago | 31 | public override ContinuationToken? GetContinuationToken(ClientResult page) |
| 32 | // Continuation is not supported for SSE streams. | |
| 33 | => null; | |
| 34 | | |
| 35 | public async override IAsyncEnumerable<ClientResult> GetRawPagesAsync() | |
9f9f2936Jose Arriaga Maldonado2 years ago | 36 | { |
2ab1a942Jose Arriaga Maldonado1 years ago | 37 | // We don't currently support resuming a dropped connection from the |
| 38 | // last received event, so the response collection has a single element. | |
| 39 | yield return await _sendRequestAsync(); | |
| 40 | } | |
| 41 | | |
| 42 | protected async override IAsyncEnumerable<StreamingUpdate> GetValuesFromPageAsync(ClientResult page) | |
| 43 | { | |
| 44 | await using IAsyncEnumerator<StreamingUpdate> enumerator = new AsyncStreamingUpdateEnumerator(page, _cancellationToken); | |
| 45 | while (await enumerator.MoveNextAsync().ConfigureAwait(false)) | |
| 46 | { | |
| 47 | yield return enumerator.Current; | |
| 48 | } | |
9f9f2936Jose Arriaga Maldonado2 years ago | 49 | } |
| 50 | | |
| 51 | private sealed class AsyncStreamingUpdateEnumerator : IAsyncEnumerator<StreamingUpdate> | |
| 52 | { | |
674e0f77Stephen Toub2 years ago | 53 | private static ReadOnlySpan<byte> TerminalData => "[DONE]"u8; |
9f9f2936Jose Arriaga Maldonado2 years ago | 54 | |
| 55 | private readonly CancellationToken _cancellationToken; | |
2ab1a942Jose Arriaga Maldonado1 years ago | 56 | private readonly PipelineResponse _response; |
9f9f2936Jose Arriaga Maldonado2 years ago | 57 | |
| 58 | // These enumerators represent what is effectively a doubly-nested | |
| 59 | // loop over the outer event collection and the inner update collection, | |
| 60 | // i.e.: | |
| 61 | // foreach (var sse in _events) { | |
| 62 | // // get _updates from sse event | |
| 63 | // foreach (var update in _updates) { ... } | |
| 64 | // } | |
674e0f77Stephen Toub2 years ago | 65 | private IAsyncEnumerator<SseItem<byte[]>>? _events; |
9f9f2936Jose Arriaga Maldonado2 years ago | 66 | private IEnumerator<StreamingUpdate>? _updates; |
| 67 | | |
| 68 | private StreamingUpdate? _current; | |
| 69 | private bool _started; | |
| 70 | | |
2ab1a942Jose Arriaga Maldonado1 years ago | 71 | public AsyncStreamingUpdateEnumerator(ClientResult page, CancellationToken cancellationToken) |
9f9f2936Jose Arriaga Maldonado2 years ago | 72 | { |
2ab1a942Jose Arriaga Maldonado1 years ago | 73 | Argument.AssertNotNull(page, nameof(page)); |
9f9f2936Jose Arriaga Maldonado2 years ago | 74 | |
2ab1a942Jose Arriaga Maldonado1 years ago | 75 | _response = page.GetRawResponse(); |
9f9f2936Jose Arriaga Maldonado2 years ago | 76 | _cancellationToken = cancellationToken; |
| 77 | } | |
| 78 | | |
| 79 | StreamingUpdate IAsyncEnumerator<StreamingUpdate>.Current | |
| 80 | => _current!; | |
| 81 | | |
| 82 | async ValueTask<bool> IAsyncEnumerator<StreamingUpdate>.MoveNextAsync() | |
| 83 | { | |
| 84 | if (_events is null && _started) | |
| 85 | { | |
| 86 | throw new ObjectDisposedException(nameof(AsyncStreamingUpdateEnumerator)); | |
| 87 | } | |
| 88 | | |
| 89 | _cancellationToken.ThrowIfCancellationRequested(); | |
2ab1a942Jose Arriaga Maldonado1 years ago | 90 | _events ??= CreateEventEnumeratorAsync(); |
9f9f2936Jose Arriaga Maldonado2 years ago | 91 | _started = true; |
| 92 | | |
| 93 | if (_updates is not null && _updates.MoveNext()) | |
| 94 | { | |
| 95 | _current = _updates.Current; | |
| 96 | return true; | |
| 97 | } | |
| 98 | | |
| 99 | if (await _events.MoveNextAsync().ConfigureAwait(false)) | |
| 100 | { | |
674e0f77Stephen Toub2 years ago | 101 | if (_events.Current.Data.AsSpan().SequenceEqual(TerminalData)) |
9f9f2936Jose Arriaga Maldonado2 years ago | 102 | { |
| 103 | _current = default; | |
| 104 | return false; | |
| 105 | } | |
| 106 | | |
| 107 | var updates = StreamingUpdate.FromEvent(_events.Current); | |
| 108 | _updates = updates.GetEnumerator(); | |
| 109 | | |
| 110 | if (_updates.MoveNext()) | |
| 111 | { | |
| 112 | _current = _updates.Current; | |
| 113 | return true; | |
| 114 | } | |
| 115 | } | |
| 116 | | |
| 117 | _current = default; | |
| 118 | return false; | |
| 119 | } | |
| 120 | | |
2ab1a942Jose Arriaga Maldonado1 years ago | 121 | private IAsyncEnumerator<SseItem<byte[]>> CreateEventEnumeratorAsync() |
9f9f2936Jose Arriaga Maldonado2 years ago | 122 | { |
2ab1a942Jose Arriaga Maldonado1 years ago | 123 | if (_response.ContentStream is null) |
9f9f2936Jose Arriaga Maldonado2 years ago | 124 | { |
| 125 | throw new InvalidOperationException("Unable to create result from response with null ContentStream"); | |
| 126 | } | |
| 127 | | |
2ab1a942Jose Arriaga Maldonado1 years ago | 128 | IAsyncEnumerable<SseItem<byte[]>> enumerable = SseParser.Create(_response.ContentStream, (_, bytes) => bytes.ToArray()).EnumerateAsync(); |
9f9f2936Jose Arriaga Maldonado2 years ago | 129 | return enumerable.GetAsyncEnumerator(_cancellationToken); |
| 130 | } | |
| 131 | | |
| 132 | public async ValueTask DisposeAsync() | |
| 133 | { | |
| 134 | await DisposeAsyncCore().ConfigureAwait(false); | |
| 135 | | |
| 136 | GC.SuppressFinalize(this); | |
| 137 | } | |
| 138 | | |
| 139 | private async ValueTask DisposeAsyncCore() | |
| 140 | { | |
| 141 | if (_events is not null) | |
| 142 | { | |
| 143 | await _events.DisposeAsync().ConfigureAwait(false); | |
| 144 | _events = null; | |
| 145 | | |
2ab1a942Jose Arriaga Maldonado1 years ago | 146 | // Dispose the response so we don't leave the network connection open. |
| 147 | _response?.Dispose(); | |
9f9f2936Jose Arriaga Maldonado2 years ago | 148 | } |
| 149 | } | |
| 150 | } | |
| 151 | } |