Skip to content
This repository has been archived by the owner on Aug 21, 2023. It is now read-only.

Commit

Permalink
.Net: [Error handling] [Part4] Replacing KernelException and OpenAIIn…
Browse files Browse the repository at this point in the history
…validResponseException exceptions by SKException (microsoft#2362) (#14)

### Motivation and Context
This PR is one of the follow-up PRs aimed at gradually replacing SK
custom exceptions with SKException to provide a simple, consistent, and
extensible exception model. You can find more details in the
[ADR](https://github.com/microsoft/semantic-kernel/blob/main/docs/decisions/0004-error-handling.md)
discussing error handling.

### Description
This PR updates a few SK components to throw SKException instead of
KernelException and OpenAIInvalidResponseException, and removes those
exceptions.

### Contribution Checklist

<!-- Before submitting this PR, please make sure: -->

- [x] The code builds clean without any errors or warnings
- [x] The PR follows the [SK Contribution
Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md)
and the [pre-submission formatting
script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts)
raises no violations
- [x] All unit tests pass, and I have added new tests where possible
- [x] I didn't break anyone 😄

---------

Co-authored-by: SergeyMenshykh <[email protected]>
Co-authored-by: Roger Barreto <[email protected]>
Co-authored-by: Dmytro Struk <[email protected]>
Co-authored-by: Shawn Callegari <[email protected]>
  • Loading branch information
5 people authored Aug 15, 2023
1 parent ca066b0 commit 302a3e0
Show file tree
Hide file tree
Showing 25 changed files with 70 additions and 276 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.Planning;
using Microsoft.SemanticKernel.Planning.Sequential;
Expand Down Expand Up @@ -272,7 +273,7 @@ private static async Task<Plan> ExecutePlanAsync(
Console.WriteLine(plan.State.ToString());
}
}
catch (KernelException e)
catch (SKException e)
{
Console.WriteLine("Step - Execution failed:");
Console.WriteLine(e.Message);
Expand Down
20 changes: 10 additions & 10 deletions dotnet/src/Connectors/Connectors.AI.OpenAI/AzureSdk/ClientBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,16 +66,16 @@ private protected async Task<IReadOnlyList<ITextResult>> InternalGetTextResultsA
Response<Completions>? response = await RunRequestAsync<Response<Completions>?>(
() => this.Client.GetCompletionsAsync(this.ModelId, options, cancellationToken)).ConfigureAwait(false);

if (response == null)
if (response is null)
{
throw new OpenAIInvalidResponseException<Completions>(null, "Text completions null response");
throw new SKException("Text completions null response");
}

var responseData = response.Value;

if (responseData.Choices.Count == 0)
{
throw new OpenAIInvalidResponseException<Completions>(responseData, "Text completions not found");
throw new SKException("Text completions not found");
}

return responseData.Choices.Select(choice => new TextResult(responseData, choice)).ToList();
Expand Down Expand Up @@ -126,14 +126,14 @@ private protected async Task<IList<ReadOnlyMemory<float>>> InternalGetEmbeddings
Response<Embeddings>? response = await RunRequestAsync<Response<Embeddings>?>(
() => this.Client.GetEmbeddingsAsync(this.ModelId, options, cancellationToken)).ConfigureAwait(false);

if (response == null)
if (response is null)
{
throw new OpenAIInvalidResponseException<Embeddings>(null, "Text embedding null response");
throw new SKException("Text embedding null response");
}

if (response.Value.Data.Count == 0)
{
throw new OpenAIInvalidResponseException<Embeddings>(response.Value, "Text embedding not found");
throw new SKException("Text embedding not found");
}

result.Add(response.Value.Data[0].Embedding.ToArray());
Expand Down Expand Up @@ -163,14 +163,14 @@ private protected async Task<IReadOnlyList<IChatResult>> InternalGetChatResultsA
Response<ChatCompletions>? response = await RunRequestAsync<Response<ChatCompletions>?>(
() => this.Client.GetChatCompletionsAsync(this.ModelId, chatOptions, cancellationToken)).ConfigureAwait(false);

if (response == null)
if (response is null)
{
throw new OpenAIInvalidResponseException<ChatCompletions>(null, "Chat completions null response");
throw new SKException("Chat completions null response");
}

if (response.Value.Choices.Count == 0)
{
throw new OpenAIInvalidResponseException<ChatCompletions>(response.Value, "Chat completions not found");
throw new SKException("Chat completions not found");
}

return response.Value.Choices.Select(chatChoice => new ChatResult(response.Value, chatChoice)).ToList();
Expand Down Expand Up @@ -200,7 +200,7 @@ private protected async IAsyncEnumerable<IChatStreamingResult> InternalGetChatSt

if (response is null)
{
throw new OpenAIInvalidResponseException<StreamingChatCompletions>(null, "Chat completions null response");
throw new SKException("Chat completions null response");
}

using StreamingChatCompletions streamingChatCompletions = response.Value;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -107,14 +107,14 @@ public async Task<string> GenerateImageAsync(string description, int width, int
var operationId = await this.StartImageGenerationAsync(description, width, height, cancellationToken).ConfigureAwait(false);
var result = await this.GetImageGenerationResultAsync(operationId, cancellationToken).ConfigureAwait(false);

if (result.Result == null)
if (result.Result is null)
{
throw new AzureSdk.OpenAIInvalidResponseException<AzureImageGenerationResponse>(null, "Azure Image Generation null response");
throw new SKException("Azure Image Generation null response");
}

if (result.Result.Images.Count == 0)
{
throw new AzureSdk.OpenAIInvalidResponseException<AzureImageGenerationResponse>(result, "Azure Image Generation result not found");
throw new SKException("Azure Image Generation result not found");
}

return result.Result.Images.First().Url;
Expand Down Expand Up @@ -184,7 +184,7 @@ private async Task<AzureImageGenerationResponse> GetImageGenerationResultAsync(s
}
else if (this.IsFailedOrCancelled(result.Status))
{
throw new AzureSdk.OpenAIInvalidResponseException<AzureImageGenerationResponse>(result, $"Azure OpenAI image generation {result.Status}");
throw new SKException($"Azure OpenAI image generation {result.Status}");
}

if (response.Headers.TryGetValues("retry-after", out var afterValues) && long.TryParse(afterValues.FirstOrDefault(), out var after))
Expand Down
8 changes: 2 additions & 6 deletions dotnet/src/InternalUtilities/src/Diagnostics/Verify.cs
Original file line number Diff line number Diff line change
Expand Up @@ -108,19 +108,15 @@ internal static void ParametersUniqueness(IList<ParameterView> parameters)

if (!seen.Add(p.Name))
{
throw new KernelException(
KernelException.ErrorCodes.InvalidFunctionDescription,
$"The function has two or more parameters with the same name '{p.Name}'");
throw new SKException($"The function has two or more parameters with the same name '{p.Name}'");
}
}
}
}

[DoesNotReturn]
private static void ThrowInvalidName(string kind, string name) =>
throw new KernelException(
KernelException.ErrorCodes.InvalidFunctionDescription,
$"A {kind} can contain only ASCII letters, digits, and underscores: '{name}' is not a valid name.");
throw new SKException($"A {kind} can contain only ASCII letters, digits, and underscores: '{name}' is not a valid name.");

[DoesNotReturn]
internal static void ThrowArgumentNullException(string? paramName) =>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.

using Microsoft.SemanticKernel.AI.ChatCompletion;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Services;

// Use base namespace for better discoverability and to avoid conflicts with other extensions.
Expand All @@ -17,11 +18,11 @@ public static class ChatCompletionServiceExtensions
/// <param name="services">The service provider.</param>
/// <param name="serviceId">Optional identifier of the desired service.</param>
/// <returns>The completion service id matching the given id or the default.</returns>
/// <exception cref="KernelException">Thrown when no suitable service is found.</exception>
/// <exception cref="SKException">Thrown when no suitable service is found.</exception>
public static IChatCompletion GetChatCompletionService(
this IAIServiceProvider services,
string? serviceId = null) => services.GetService<IChatCompletion>(serviceId)
?? throw new KernelException(KernelException.ErrorCodes.ServiceNotFound, "Chat completion service not found");
?? throw new SKException("Chat completion service not found");

/// <summary>
/// Returns true if a <see cref="IChatCompletion"/> exist with the specified ID.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.

using Microsoft.SemanticKernel.AI.Embeddings;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Services;

// Use base namespace for better discoverability and to avoid conflicts with other extensions.
Expand All @@ -17,12 +18,12 @@ public static class TextEmbeddingServiceExtensions
/// <param name="services">The service provider.</param>
/// <param name="serviceId">Optional identifier of the desired service.</param>
/// <returns>The embedding service matching the given id or the default service.</returns>
/// <exception cref="KernelException">Thrown when no suitable service is found.</exception>
/// <exception cref="SKException">Thrown when no suitable service is found.</exception>
public static ITextEmbeddingGeneration GetTextEmbeddingService(
this IAIServiceProvider services,
string? serviceId = null)
=> services.GetService<ITextEmbeddingGeneration>(serviceId)
?? throw new KernelException(KernelException.ErrorCodes.ServiceNotFound, "Text embedding service not available");
?? throw new SKException("Text embedding service not found");

/// <summary>
/// Returns true if a <see cref="ITextEmbeddingGeneration"/> exist with the specified ID.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.

using Microsoft.SemanticKernel.AI.ImageGeneration;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Services;

// Use base namespace for better discoverability and to avoid conflicts with other extensions.
Expand All @@ -17,11 +18,11 @@ public static class ImageGenerationServiceExtensions
/// <param name="services">The service provider.</param>
/// <param name="serviceId">Optional identifier of the desired service.</param>
/// <returns>The <see cref="IImageGeneration"/> id matching the given id or the default.</returns>
/// <exception cref="KernelException">Thrown when no suitable service is found.</exception>
/// <exception cref="SKException">Thrown when no suitable service is found.</exception>
public static IImageGeneration GetImageGenerationService(
this IAIServiceProvider services,
string? serviceId = null) => services.GetService<IImageGeneration>(serviceId)
?? throw new KernelException(KernelException.ErrorCodes.ServiceNotFound, "Image generation service not found");
?? throw new SKException("Image generation service not found");

/// <summary>
/// Returns true if a <see cref="IImageGeneration"/> exist with the specified ID.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft. All rights reserved.

using Microsoft.SemanticKernel.AI.TextCompletion;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Services;

// Use base namespace for better discoverability and to avoid conflicts with other extensions.
Expand All @@ -17,11 +18,11 @@ public static class TextCompletionServiceExtensions
/// <param name="services">The service provider.</param>
/// <param name="serviceId">Optional identifier of the desired service.</param>
/// <returns>The text completion service id matching the given ID or the default.</returns>
/// <exception cref="KernelException">Thrown when no suitable service is found.</exception>
/// <exception cref="SKException">Thrown when no suitable service is found.</exception>
public static ITextCompletion GetTextCompletionServiceOrDefault(
this IAIServiceProvider services,
string? serviceId = null) => services.GetService<ITextCompletion>(serviceId)
?? throw new KernelException(KernelException.ErrorCodes.ServiceNotFound, "Text completion service not found");
?? throw new SKException("Text completion service not found");

/// <summary>
/// Returns true if a <see cref="ITextCompletion"/> exist with the specified ID.
Expand Down
119 changes: 0 additions & 119 deletions dotnet/src/SemanticKernel.Abstractions/KernelException.cs

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Threading;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.SemanticKernel.Diagnostics;
using Microsoft.SemanticKernel.Memory;
using Microsoft.SemanticKernel.SkillDefinition;

Expand Down Expand Up @@ -199,7 +200,7 @@ public ISemanticTextMemory Memory
public SKContext Fail(string errorDescription, Exception? exception = null)
{
// Temporary workaround: if no exception is provided, create a new one.
this.LastException = exception ?? new KernelException(KernelException.ErrorCodes.UnknownError, errorDescription);
this.LastException = exception ?? new SKException(errorDescription);
return this;
}

Expand Down
Loading

0 comments on commit 302a3e0

Please sign in to comment.