Skip to content
Open
Show file tree
Hide file tree
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
8 changes: 8 additions & 0 deletions src/Primitives/CrestApps.Core.AI.Chat/Hubs/AIChatHubCore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using CrestApps.Core.AI.Exceptions;
using CrestApps.Core.AI.Models;
using CrestApps.Core.AI.Orchestration;
using CrestApps.Core.AI.Resilience;
using CrestApps.Core.AI.Profiles;
using CrestApps.Core.AI.ResponseHandling;
using CrestApps.Core.AI.Security;
Expand Down Expand Up @@ -175,6 +176,13 @@ protected virtual string GetFriendlyErrorMessage(Exception ex)
return GetInvalidChatModelSettingsMessage();
}

var providerDetail = AIProviderErrorHelper.TryExtractProviderMessage(ex);

if (!string.IsNullOrWhiteSpace(providerDetail))
{
return $"The AI model rejected the request: {providerDetail}";
}

return "An error occurred processing your message.";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using CrestApps.Core.AI.Deployments;
using CrestApps.Core.AI.Models;
using CrestApps.Core.AI.Orchestration;
using CrestApps.Core.AI.Resilience;
using CrestApps.Core.AI.Profiles;
using CrestApps.Core.AI.ResponseHandling;
using CrestApps.Core.AI.Security;
Expand Down Expand Up @@ -225,6 +226,13 @@ protected virtual string GetFriendlyErrorMessage(Exception ex)
return GetInvalidChatModelSettingsMessage();
}

var providerDetail = AIProviderErrorHelper.TryExtractProviderMessage(ex);

if (!string.IsNullOrWhiteSpace(providerDetail))
{
return $"The AI model rejected the request: {providerDetail}";
}

return "An error occurred while processing your message.";
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using CrestApps.Core.AI.Handlers;
using CrestApps.Core.AI.Models;
using CrestApps.Core.AI.Orchestration;
using CrestApps.Core.AI.Resilience;
using CrestApps.Core.AI.Tooling;
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Logging;
Expand Down Expand Up @@ -132,7 +133,12 @@ public async IAsyncEnumerable<ChatResponseUpdate> ExecuteStreamingAsync(
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogError(ex, "ClaudeOrchestrator: Unexpected error during Anthropic session.");
errorResponse = CreateTextResponse("An unexpected error occurred while communicating with Anthropic. Please try again.");
var providerDetail = AIProviderErrorHelper.TryExtractProviderMessage(ex);

errorResponse = string.IsNullOrWhiteSpace(providerDetail)
? CreateTextResponse("An unexpected error occurred while communicating with Anthropic. Please try again.")
: CreateTextResponse($"Anthropic returned an error: {providerDetail}");

break;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Net;
using System.Text.Json;

namespace CrestApps.Core.AI.Resilience;

Expand All @@ -8,6 +9,7 @@ namespace CrestApps.Core.AI.Resilience;
public static class AIProviderErrorHelper
{
private const string ClientResultExceptionName = "ClientResultException";
private const string RequestFailedExceptionName = "RequestFailedException";

private static readonly string[] _rateLimitIndicators = ["ratelimitreached", "rate limit", "too many requests"];

Expand Down Expand Up @@ -57,7 +59,8 @@ public static bool IsRateLimitException(Exception ex)
}

var type = ex.GetType();
if (!string.Equals(type.Name, ClientResultExceptionName, StringComparison.Ordinal))
if (!string.Equals(type.Name, ClientResultExceptionName, StringComparison.Ordinal)
&& !string.Equals(type.Name, RequestFailedExceptionName, StringComparison.Ordinal))
{
return null;
}
Expand All @@ -78,6 +81,70 @@ public static bool IsRateLimitException(Exception ex)
return null;
}

/// <summary>
/// Extracts the most specific human-readable error message from any AI provider exception.
/// Works for OpenAI (<c>ClientResultException</c>), Azure (<c>RequestFailedException</c>),
/// and any other provider that surfaces errors via <see cref="Exception.Message"/>.
/// </summary>
/// <param name="ex">The exception to inspect.</param>
/// <returns>The extracted message, or <see langword="null"/> when none can be determined.</returns>
public static string TryExtractProviderMessage(Exception ex)
{
if (ex is null)
{
return null;
}

foreach (var currentException in EnumerateExceptions(ex))
{
if (!string.Equals(currentException.GetType().Name, ClientResultExceptionName, StringComparison.Ordinal) && !string.Equals(currentException.GetType().Name, RequestFailedExceptionName, StringComparison.Ordinal))
{
continue;
}

// Prefer the structured error.message from the JSON body when present.
var jsonBodyIndex = currentException.Message?.LastIndexOf('{') ?? -1;

if (jsonBodyIndex >= 0)
{
try
{
using var logs = JsonDocument.Parse(currentException.Message.Substring(jsonBodyIndex));

var errorBody = logs.RootElement;

// OpenAI / Azure OpenAI / Anthropic: {"error":{"message":"..."}}
if (errorBody.TryGetProperty("error", out var errorNode) && errorNode.TryGetProperty("message", out var errorMessage))
{
return errorMessage.GetString();
}

// Azure AI Inference / generic: {"message":"..."}
if (errorBody.TryGetProperty("message", out var directMessage))
{
return directMessage.GetString();
}
}
catch (JsonException)
{
// Not valid JSON — fall through to raw message.
}
}

if (!string.IsNullOrWhiteSpace(currentException.Message))
{
var rawMessage = currentException.Message.TrimEnd();
var lastNewLineIndex = rawMessage.LastIndexOfAny(['\n', '\r']);
var lastLine = lastNewLineIndex >= 0 ? rawMessage.Substring(lastNewLineIndex + 1).Trim() : rawMessage.Trim();
var firstPeriodIndex = lastLine.IndexOf('.');

return firstPeriodIndex >= 0 ? lastLine.Substring(0, firstPeriodIndex + 1) : lastLine;
}
}

return null;
}

/// <summary>
/// Determines whether the specified message contains a rate-limit indicator.
/// </summary>
Expand Down
8 changes: 8 additions & 0 deletions src/Primitives/CrestApps.Core.AI/AIHubErrorMessageHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ public static LocalizedString GetFriendlyErrorMessage(Exception ex, IStringLocal
? S["Rate limit reached. Please wait and try again later."]
: S["Rate limit reached. {0}", retryAfterMessage];
}
else if (clientStatusCode == (int)HttpStatusCode.BadRequest)
{
var providerDetail = AIProviderErrorHelper.TryExtractProviderMessage(ex);

return string.IsNullOrWhiteSpace(providerDetail)
? S["Invalid request. Please verify your connection settings."]
: S["The AI model rejected the request: {0}", providerDetail];
}

if (ex is HttpRequestException httpEx)
{
Expand Down
Loading