Skip to content

Commit

Permalink
AIException, HttpRequestException, and RequestFailedException are rep…
Browse files Browse the repository at this point in the history
…laced/wrapped by HttpOperationException.
  • Loading branch information
SergeyMenshykh committed Jul 20, 2023
1 parent 8feb1b1 commit 5e2742d
Show file tree
Hide file tree
Showing 21 changed files with 404 additions and 446 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -89,44 +89,43 @@ public HuggingFaceTextCompletion(string model, string? apiKey = null, HttpClient

private async Task<IReadOnlyList<ITextStreamingResult>> ExecuteGetCompletionsAsync(string text, CancellationToken cancellationToken = default)
{
try
var completionRequest = new TextCompletionRequest
{
var completionRequest = new TextCompletionRequest
{
Input = text
};
Input = text
};

using var httpRequestMessage = HttpRequest.CreatePostRequest(this.GetRequestUri(), completionRequest);
using var httpRequestMessage = HttpRequest.CreatePostRequest(this.GetRequestUri(), completionRequest);

httpRequestMessage.Headers.Add("User-Agent", HttpUserAgent);
if (!string.IsNullOrEmpty(this._apiKey))
{
httpRequestMessage.Headers.Add("Authorization", $"Bearer {this._apiKey}");
}
httpRequestMessage.Headers.Add("User-Agent", HttpUserAgent);
if (!string.IsNullOrEmpty(this._apiKey))
{
httpRequestMessage.Headers.Add("Authorization", $"Bearer {this._apiKey}");
}

using var response = await this._httpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();
using var response = await this._httpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false);

var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

List<TextCompletionResponse>? completionResponse = JsonSerializer.Deserialize<List<TextCompletionResponse>>(body);
try
{
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException e)
{
throw new HttpOperationException(response.StatusCode, responseContent, e.Message, e);
}

if (completionResponse is null)
{
throw new AIException(AIException.ErrorCodes.InvalidResponseContent, "Unexpected response from model")
{
Data = { { "ResponseData", body } },
};
}
List<TextCompletionResponse>? completionResponse = JsonSerializer.Deserialize<List<TextCompletionResponse>>(responseContent);

return completionResponse.ConvertAll(c => new TextCompletionStreamingResult(c));
}
catch (Exception e) when (e is not AIException && !e.IsCriticalException())
if (completionResponse is null)
{
throw new AIException(
AIException.ErrorCodes.UnknownError,
$"Something went wrong: {e.Message}", e);
throw new AIException(AIException.ErrorCodes.InvalidResponseContent, "Unexpected response from model")
{
Data = { { "ResponseData", responseContent } },
};
}

return completionResponse.ConvertAll(c => new TextCompletionStreamingResult(c));
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel.AI;
using Microsoft.SemanticKernel.AI.TextCompletion;
using Microsoft.SemanticKernel.Diagnostics;

Expand Down Expand Up @@ -213,25 +212,27 @@ public sealed class OobaboogaTextCompletion : ITextCompletion
httpRequestMessage.Headers.Add("User-Agent", HttpUserAgent);

using var response = await this._httpClient.SendAsync(httpRequestMessage, cancellationToken).ConfigureAwait(false);
response.EnsureSuccessStatusCode();

var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
var responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

TextCompletionResponse? completionResponse = JsonSerializer.Deserialize<TextCompletionResponse>(body);
try
{
response.EnsureSuccessStatusCode();
}
catch (HttpRequestException e)
{
throw new HttpOperationException(response.StatusCode, responseContent, e.Message, e);
}

TextCompletionResponse? completionResponse = JsonSerializer.Deserialize<TextCompletionResponse>(responseContent);

if (completionResponse is null)
{
throw new OobaboogaInvalidResponseException<string>(body, "Unexpected response from Oobabooga API");
throw new OobaboogaInvalidResponseException<string>(responseContent, "Unexpected response from Oobabooga API");
}

return completionResponse.Results.Select(completionText => new TextCompletionResult(completionText)).ToList();
}
catch (Exception e) when (e is not AIException && !e.IsCriticalException())
{
throw new AIException(
AIException.ErrorCodes.UnknownError,
$"Something went wrong: {e.Message}", e);
}
finally
{
this.FinishConcurrentCall();
Expand Down
75 changes: 2 additions & 73 deletions dotnet/src/Connectors/Connectors.AI.OpenAI/AzureSdk/ClientBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -363,80 +363,9 @@ private static async Task<T> RunRequestAsync<T>(Func<Task<T>> request)
{
return await request.Invoke().ConfigureAwait(false);
}
catch (RequestFailedException e)
catch (RequestFailedException ex)
{
switch (e.Status)
{
case (int)HttpStatusCodeType.BadRequest:
case (int)HttpStatusCodeType.MethodNotAllowed:
case (int)HttpStatusCodeType.NotFound:
case (int)HttpStatusCodeType.NotAcceptable:
case (int)HttpStatusCodeType.Conflict:
case (int)HttpStatusCodeType.Gone:
case (int)HttpStatusCodeType.LengthRequired:
case (int)HttpStatusCodeType.PreconditionFailed:
case (int)HttpStatusCodeType.RequestEntityTooLarge:
case (int)HttpStatusCodeType.RequestUriTooLong:
case (int)HttpStatusCodeType.UnsupportedMediaType:
case (int)HttpStatusCodeType.RequestedRangeNotSatisfiable:
case (int)HttpStatusCodeType.ExpectationFailed:
case (int)HttpStatusCodeType.HttpVersionNotSupported:
case (int)HttpStatusCodeType.UpgradeRequired:
case (int)HttpStatusCodeType.MisdirectedRequest:
case (int)HttpStatusCodeType.UnprocessableEntity:
case (int)HttpStatusCodeType.Locked:
case (int)HttpStatusCodeType.FailedDependency:
case (int)HttpStatusCodeType.PreconditionRequired:
case (int)HttpStatusCodeType.RequestHeaderFieldsTooLarge:
throw new AIException(
AIException.ErrorCodes.InvalidRequest,
$"The request is not valid, HTTP status: {e.Status}",
e.Message, e);

case (int)HttpStatusCodeType.Unauthorized:
case (int)HttpStatusCodeType.Forbidden:
case (int)HttpStatusCodeType.ProxyAuthenticationRequired:
case (int)HttpStatusCodeType.UnavailableForLegalReasons:
case (int)HttpStatusCodeType.NetworkAuthenticationRequired:
throw new AIException(
AIException.ErrorCodes.AccessDenied,
$"The request is not authorized, HTTP status: {e.Status}",
e.Message, e);

case (int)HttpStatusCodeType.RequestTimeout:
throw new AIException(
AIException.ErrorCodes.RequestTimeout,
$"The request timed out, HTTP status: {e.Status}");

case (int)HttpStatusCodeType.TooManyRequests:
throw new AIException(
AIException.ErrorCodes.Throttling,
$"Too many requests, HTTP status: {e.Status}",
e.Message, e);

case (int)HttpStatusCodeType.InternalServerError:
case (int)HttpStatusCodeType.NotImplemented:
case (int)HttpStatusCodeType.BadGateway:
case (int)HttpStatusCodeType.ServiceUnavailable:
case (int)HttpStatusCodeType.GatewayTimeout:
case (int)HttpStatusCodeType.InsufficientStorage:
throw new AIException(
AIException.ErrorCodes.ServiceError,
$"The service failed to process the request, HTTP status:{e.Status}",
e.Message, e);

default:
throw new AIException(
AIException.ErrorCodes.UnknownError,
$"Unexpected HTTP response, status: {e.Status}",
e.Message, e);
}
}
catch (Exception e) when (e is not AIException)
{
throw new AIException(
AIException.ErrorCodes.UnknownError,
$"Something went wrong: {e.Message}", e);
throw ex.ToHttpOperationException();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright (c) Microsoft. All rights reserved.

using System.Net;
using Azure;
using Microsoft.SemanticKernel.Diagnostics;

namespace Microsoft.SemanticKernel.Connectors.AI.OpenAI.AzureSdk;

/// <summary>
/// Provides extension methods for the <see cref="RequestFailedException"/> class.
/// </summary>
public static class RequestFailedExceptionExtensions
{
/// <summary>
/// Converts a <see cref="RequestFailedException"/> to an <see cref="HttpOperationException"/>.
/// </summary>
/// <param name="original">The original <see cref="RequestFailedException"/> object.</param>
/// <returns>An <see cref="HttpOperationException"/> instance.</returns>
public static HttpOperationException ToHttpOperationException(this RequestFailedException original)
{
const int NoResponseReceived = 0;

return new HttpOperationException(
original.Status == NoResponseReceived ? null : (HttpStatusCode?)original.Status,
null,
original.Message,
original);
}
}
Loading

0 comments on commit 5e2742d

Please sign in to comment.