This commit is contained in:
@@ -10,7 +10,14 @@ using System.Text.Json.Serialization;
|
||||
namespace LehrerApp.Desktop.Services;
|
||||
|
||||
/// <summary>Fehler beim Aufruf des KI-Backends, Message ist bereits deutsch und nutzergerichtet.</summary>
|
||||
public class AiBackendException(string userMessage) : Exception(userMessage);
|
||||
public class AiBackendException(string userMessage, string? rawResponse = null) : Exception(userMessage)
|
||||
{
|
||||
/// <summary>
|
||||
/// Unveränderte Modellantwort, sofern der Fehler beim Lesen einer Planungsantwort entstand.
|
||||
/// Sie wird ausschließlich für den ausdrücklich vom Nutzer gestarteten Rettungsdialog gehalten.
|
||||
/// </summary>
|
||||
public string? RawResponse { get; } = rawResponse;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Der KI-Wire-Vertrag verwendet deutsches Datumsformat (siehe ai-backend/plan.php Systemprompt,
|
||||
@@ -87,16 +94,19 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
private static async Task<AiBackendException> BuildRequestFailedExceptionAsync(HttpResponseMessage resp)
|
||||
{
|
||||
string? backendReason = null;
|
||||
string? rawResponse = null;
|
||||
try
|
||||
{
|
||||
var body = await resp.Content.ReadFromJsonAsync<BackendErrorResult>(JsonOptions);
|
||||
var responseText = await resp.Content.ReadAsStringAsync();
|
||||
var body = JsonSerializer.Deserialize<BackendErrorResult>(responseText, JsonOptions);
|
||||
backendReason = string.IsNullOrWhiteSpace(body?.Error) ? null : body!.Error;
|
||||
rawResponse = string.IsNullOrWhiteSpace(body?.RawResponse) ? null : body!.RawResponse;
|
||||
}
|
||||
catch { /* Antwortkörper war kein valides {"error": "..."}-JSON - Fallback unten greift. */ }
|
||||
|
||||
return new AiBackendException(backendReason is null
|
||||
? "Die Anfrage an den KI-Dienst ist fehlgeschlagen."
|
||||
: $"Die Anfrage an den KI-Dienst ist fehlgeschlagen: {backendReason}");
|
||||
: $"Die Anfrage an den KI-Dienst ist fehlgeschlagen: {backendReason}", rawResponse);
|
||||
}
|
||||
|
||||
public async Task<string> LoginAsync(string username, string password)
|
||||
@@ -352,14 +362,64 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
if (!resp.IsSuccessStatusCode)
|
||||
throw await BuildRequestFailedExceptionAsync(resp);
|
||||
|
||||
var responseText = await resp.Content.ReadAsStringAsync();
|
||||
try
|
||||
{
|
||||
var result = await resp.Content.ReadFromJsonAsync<AiPlanningResponse>(JsonOptions);
|
||||
var result = JsonSerializer.Deserialize<AiPlanningResponse>(responseText, JsonOptions);
|
||||
return result ?? throw new AiBackendException("Die Antwort der KI konnte nicht verarbeitet werden.");
|
||||
}
|
||||
catch (Exception ex) when (ex is not AiBackendException)
|
||||
{
|
||||
throw new AiBackendException("Die Antwort der KI konnte nicht verarbeitet werden. Bitte erneut versuchen.");
|
||||
string? rawModelResponse = null;
|
||||
try
|
||||
{
|
||||
using var envelope = JsonDocument.Parse(responseText);
|
||||
if (envelope.RootElement.TryGetProperty("rawResponse", out var rawElement)
|
||||
&& rawElement.ValueKind == JsonValueKind.String)
|
||||
rawModelResponse = rawElement.GetString();
|
||||
}
|
||||
catch (JsonException) { /* Die HTTP-Antwort selbst war ungültig; unten komplett zeigen. */ }
|
||||
|
||||
throw new AiBackendException(
|
||||
"Die Antwort der KI konnte nicht verarbeitet werden. Du kannst die Antwort manuell retten.",
|
||||
string.IsNullOrWhiteSpace(rawModelResponse) ? responseText : rawModelResponse);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Liest eine von Hand markierte Modellantwort. Akzeptiert die normale Antwort-Hülle, ein
|
||||
/// einzelnes Lesson-Objekt oder ein Array von Lessons, damit auch nur der relevante Ausschnitt
|
||||
/// der Rohantwort markiert werden kann.
|
||||
/// </summary>
|
||||
public static List<AiLesson> ParsePlanningLessons(string json)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(json))
|
||||
throw new AiBackendException("Bitte markiere zuerst den JSON-Abschnitt der Antwort.");
|
||||
|
||||
try
|
||||
{
|
||||
using var document = JsonDocument.Parse(json);
|
||||
var root = document.RootElement;
|
||||
List<AiLesson>? parsed = root.ValueKind switch
|
||||
{
|
||||
JsonValueKind.Object when root.TryGetProperty("lessons", out _) =>
|
||||
JsonSerializer.Deserialize<AiPlanningResponse>(json, JsonOptions)?.Lessons,
|
||||
JsonValueKind.Object =>
|
||||
[JsonSerializer.Deserialize<AiLesson>(json, JsonOptions)
|
||||
?? throw new JsonException("Leere Stunde")],
|
||||
JsonValueKind.Array => JsonSerializer.Deserialize<List<AiLesson>>(json, JsonOptions),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
if (parsed is null || parsed.Count == 0)
|
||||
throw new JsonException("Keine Stunde enthalten");
|
||||
if (parsed.Any(l => string.IsNullOrWhiteSpace(l.Topic)))
|
||||
throw new JsonException("Mindestens einer Stunde fehlt das Feld topic");
|
||||
return parsed;
|
||||
}
|
||||
catch (JsonException ex)
|
||||
{
|
||||
throw new AiBackendException($"Der markierte Text ist noch kein gültiges Stunden-JSON: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -541,5 +601,9 @@ public class AiPlanningService(HttpClient http, ILessonRepository lessons,
|
||||
|
||||
private class LoginResult { public string Token { get; set; } = ""; }
|
||||
private class BalanceResult { public decimal BalanceUsd { get; set; } }
|
||||
private class BackendErrorResult { public string? Error { get; set; } }
|
||||
private class BackendErrorResult
|
||||
{
|
||||
public string? Error { get; set; }
|
||||
public string? RawResponse { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user