Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fallback method for HttpClient.Send on unsupported platforms #316

Merged
merged 3 commits into from
Aug 6, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 26 additions & 5 deletions OpenAI.SDK/Extensions/HttpclientExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,38 @@ public static HttpResponseMessage PostAsStreamAsync(this HttpClient client, stri

var content = JsonContent.Create(requestModel, null, settings);

using var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
request.Content = content;
using var request = CreatePostEventStreamRequest(uri, content);

#if NET6_0_OR_GREATER
return client.Send(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
try
{
return client.Send(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
}
catch (PlatformNotSupportedException)
{
using var newRequest = CreatePostEventStreamRequest(uri, content);

return SendRequestPreNet6(client, newRequest, cancellationToken);
}
#else
return SendRequestPreNet6(client, request, cancellationToken);
#endif
}

private static HttpResponseMessage SendRequestPreNet6(HttpClient client, HttpRequestMessage request, CancellationToken cancellationToken)
{
var responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
var response = responseTask.GetAwaiter().GetResult();
return response;
#endif
}

private static HttpRequestMessage CreatePostEventStreamRequest(string uri, HttpContent content)
{
var request = new HttpRequestMessage(HttpMethod.Post, uri);
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
request.Content = content;

return request;
}

public static async Task<TResponse> PostFileAndReadAsAsync<TResponse>(this HttpClient client, string uri, HttpContent content, CancellationToken cancellationToken = default)
Expand Down