Flowise-Übungen stabilisieren und Lernfortschritt korrigieren
Vermeide kürzlich angezeigte Sätze bei neuen Übungen und frage Flowise bei Wiederholungen einmal erneut. Validiere strukturierte Antworten, protokolliere die Übungsquelle und schütze nutzerspezifische Übungs-IDs. Berechne schwierige Wörter anhand der neuesten Aussprache pro Wort. Passe das Lehrerfeedback an gute Bewertungen an und verbessere das Laden neuer Übungen im Web. Ergänze gezielte Go-Tests.
This commit is contained in:
@@ -10,6 +10,8 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"speech-learning-api/internal/config"
|
||||
"speech-learning-api/internal/domain"
|
||||
@@ -53,18 +55,20 @@ func (f *FlowiseTeacher) NextExercise(ctx context.Context, input domain.Generate
|
||||
Source: "fallback",
|
||||
}
|
||||
payload := map[string]any{
|
||||
"task": "next_exercise",
|
||||
"user_id": input.UserID,
|
||||
"target_language": input.TargetLanguage,
|
||||
"cefr_level": input.CEFRLevel,
|
||||
"ui_language": input.UILanguage,
|
||||
"profile": input.Profile,
|
||||
"progress": input.Progress,
|
||||
"recent_weak_words": input.RecentWeakWords,
|
||||
"preferred_type": valueOr(input.PreferredType, "repeat_sentence"),
|
||||
"rules": "Generate one A1 English pronunciation exercise. Return valid JSON only with fields: exercise_type, target_language, cefr_level, reference_text, display_prompt, tts_text, focus_points, success_criteria, reason_for_choice.",
|
||||
"task": "next_exercise",
|
||||
"user_id": input.UserID,
|
||||
"target_language": input.TargetLanguage,
|
||||
"cefr_level": input.CEFRLevel,
|
||||
"ui_language": input.UILanguage,
|
||||
"profile": input.Profile,
|
||||
"progress": input.Progress,
|
||||
"recent_weak_words": input.RecentWeakWords,
|
||||
"preferred_type": valueOr(input.PreferredType, "repeat_sentence"),
|
||||
"avoid_reference_text": input.AvoidReferenceText,
|
||||
"avoid_reference_texts": input.AvoidReferenceTexts,
|
||||
"rules": "Generate one A1 English pronunciation exercise. Return valid JSON only with fields: exercise_type, target_language, cefr_level, reference_text, display_prompt, tts_text, focus_points, success_criteria, reason_for_choice. The reference_text must differ from every sentence in avoid_reference_texts. The same target word may still be used.",
|
||||
}
|
||||
return f.askExercise(ctx, payload, input.SessionID, fallback)
|
||||
return f.askExercise(ctx, payload, input, fallback)
|
||||
}
|
||||
|
||||
func (f *FlowiseTeacher) FeedbackForAttempt(ctx context.Context, targetText string, result domain.PronunciationResult, weakWords []domain.WordScore) (domain.TeacherResponse, error) {
|
||||
@@ -100,7 +104,7 @@ func (f *FlowiseTeacher) ContinueConversation(ctx context.Context, targetLanguag
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (f *FlowiseTeacher) askExercise(ctx context.Context, payload any, sessionID string, fallback domain.GeneratedExercise) (domain.GeneratedExercise, error) {
|
||||
func (f *FlowiseTeacher) askExercise(ctx context.Context, payload map[string]any, input domain.GeneratedExerciseRequest, fallback domain.GeneratedExercise) (domain.GeneratedExercise, error) {
|
||||
if f.cfg.FlowiseChatflow == "" || f.cfg.FlowiseBaseURL == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
@@ -108,7 +112,7 @@ func (f *FlowiseTeacher) askExercise(ctx context.Context, payload any, sessionID
|
||||
reqBody, _ := json.Marshal(map[string]any{
|
||||
"question": string(body),
|
||||
"overrideConfig": map[string]any{
|
||||
"sessionId": sessionID,
|
||||
"sessionId": input.SessionID,
|
||||
},
|
||||
})
|
||||
endpoint := strings.TrimRight(f.cfg.FlowiseBaseURL, "/") + "/api/v1/prediction/" + f.cfg.FlowiseChatflow
|
||||
@@ -137,11 +141,20 @@ func (f *FlowiseTeacher) askExercise(ctx context.Context, payload any, sessionID
|
||||
return fallback, nil
|
||||
}
|
||||
if exercise, ok := parseGeneratedExerciseEnvelope(respBody); ok {
|
||||
exercise.TargetLanguage = valueOr(exercise.TargetLanguage, fallback.TargetLanguage)
|
||||
exercise.CEFRLevel = valueOr(exercise.CEFRLevel, fallback.CEFRLevel)
|
||||
exercise.ExerciseType = valueOr(exercise.ExerciseType, fallback.ExerciseType)
|
||||
exercise.DisplayPrompt = valueOr(exercise.DisplayPrompt, fallback.DisplayPrompt)
|
||||
exercise.TTSText = valueOr(exercise.TTSText, exercise.ReferenceText)
|
||||
if reason := generatedExerciseValidationError(exercise, input); reason != "" {
|
||||
if strings.HasPrefix(reason, "reference_text repeats") && payload["retry_instruction"] == nil {
|
||||
f.logger.Info("flowise repeated a recent exercise, requesting another sentence")
|
||||
retryPayload := make(map[string]any, len(payload)+1)
|
||||
for key, value := range payload {
|
||||
retryPayload[key] = value
|
||||
}
|
||||
retryPayload["retry_instruction"] = "The previous reference_text was rejected because it repeats a recent exercise. Choose a different natural A1 sentence that is not in avoid_reference_texts. Keep the required JSON format."
|
||||
return f.askExercise(ctx, retryPayload, input, fallback)
|
||||
}
|
||||
f.logger.Warn("flowise exercise response failed validation", "reason", reason)
|
||||
return fallback, nil
|
||||
}
|
||||
exercise.ID = "" // Exercise IDs are assigned by the API, never by Flowise.
|
||||
exercise.Source = "flowise"
|
||||
return exercise, nil
|
||||
}
|
||||
@@ -149,20 +162,74 @@ func (f *FlowiseTeacher) askExercise(ctx context.Context, payload any, sessionID
|
||||
return fallback, nil
|
||||
}
|
||||
|
||||
func parseGeneratedExerciseEnvelope(body []byte) (domain.GeneratedExercise, bool) {
|
||||
var envelope struct {
|
||||
Text string `json:"text"`
|
||||
JSON json.RawMessage `json:"json"`
|
||||
func validGeneratedExercise(exercise domain.GeneratedExercise, input domain.GeneratedExerciseRequest) bool {
|
||||
return generatedExerciseValidationError(exercise, input) == ""
|
||||
}
|
||||
|
||||
func generatedExerciseValidationError(exercise domain.GeneratedExercise, input domain.GeneratedExerciseRequest) string {
|
||||
if input.AvoidReferenceText != "" && sameReferenceText(exercise.ReferenceText, input.AvoidReferenceText) {
|
||||
return "reference_text repeats the previous exercise"
|
||||
}
|
||||
if err := json.Unmarshal(body, &envelope); err == nil {
|
||||
if envelope.Text != "" {
|
||||
if parsed, ok := parseGeneratedExercise(envelope.Text); ok {
|
||||
return parsed, true
|
||||
}
|
||||
for _, previous := range input.AvoidReferenceTexts {
|
||||
if sameReferenceText(exercise.ReferenceText, previous) {
|
||||
return "reference_text repeats a recent exercise"
|
||||
}
|
||||
if len(envelope.JSON) > 0 && string(envelope.JSON) != "null" {
|
||||
if parsed, ok := parseGeneratedExerciseJSON(envelope.JSON); ok {
|
||||
return parsed, true
|
||||
}
|
||||
if exercise.ExerciseType != "repeat_sentence" {
|
||||
return "unsupported exercise_type"
|
||||
}
|
||||
if exercise.TargetLanguage != input.TargetLanguage {
|
||||
return "target_language does not match the request"
|
||||
}
|
||||
if exercise.CEFRLevel != input.CEFRLevel {
|
||||
return "cefr_level does not match the request"
|
||||
}
|
||||
for _, field := range []struct {
|
||||
name string
|
||||
value string
|
||||
limit int
|
||||
}{
|
||||
{"reference_text", exercise.ReferenceText, 160},
|
||||
{"display_prompt", exercise.DisplayPrompt, 240},
|
||||
{"tts_text", exercise.TTSText, 160},
|
||||
{"reason_for_choice", exercise.ReasonForChoice, 300},
|
||||
} {
|
||||
if !validExerciseText(field.value, field.limit) {
|
||||
return field.name + " is missing or invalid"
|
||||
}
|
||||
}
|
||||
if len(exercise.FocusPoints) < 1 || len(exercise.FocusPoints) > 5 || len(exercise.SuccessCriteria) < 1 || len(exercise.SuccessCriteria) > 5 {
|
||||
return "focus_points or success_criteria has an invalid count"
|
||||
}
|
||||
for _, point := range exercise.FocusPoints {
|
||||
if !validExerciseText(point, 80) {
|
||||
return "focus_points contains an invalid value"
|
||||
}
|
||||
}
|
||||
for _, criterion := range exercise.SuccessCriteria {
|
||||
if !validExerciseText(criterion, 120) {
|
||||
return "success_criteria contains an invalid value"
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func sameReferenceText(a, b string) bool {
|
||||
return strings.EqualFold(strings.Join(strings.Fields(a), " "), strings.Join(strings.Fields(b), " "))
|
||||
}
|
||||
|
||||
func validExerciseText(value string, limit int) bool {
|
||||
return strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= limit && strings.IndexFunc(value, unicode.IsControl) == -1
|
||||
}
|
||||
|
||||
func parseGeneratedExerciseEnvelope(body []byte) (domain.GeneratedExercise, bool) {
|
||||
var envelope map[string]json.RawMessage
|
||||
if err := json.Unmarshal(body, &envelope); err == nil {
|
||||
for _, key := range []string{"text", "json", "output"} {
|
||||
if raw := envelope[key]; len(raw) > 0 && string(raw) != "null" {
|
||||
if parsed, ok := parseGeneratedExerciseJSON(raw); ok {
|
||||
return parsed, true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,22 +260,31 @@ func parseGeneratedExerciseJSON(value json.RawMessage) (domain.GeneratedExercise
|
||||
}
|
||||
|
||||
func mockFeedback(targetText string, result domain.PronunciationResult) domain.TeacherResponse {
|
||||
weak := "den roten Woertern"
|
||||
weakWord := ""
|
||||
for _, word := range result.WordScores {
|
||||
if word.Highlight == "weak" {
|
||||
weak = fmt.Sprintf("'%s'", word.Word)
|
||||
weakWord = word.Word
|
||||
break
|
||||
}
|
||||
}
|
||||
feedback := fmt.Sprintf("Guter Versuch. Uebe jetzt besonders %s. Sprich langsam und halte die Endlaute klar.", weak)
|
||||
if result.OverallScore >= 85 {
|
||||
feedback = "Sehr solide. Wiederhole den Satz einmal etwas natuerlicher und mit ruhigem Rhythmus."
|
||||
feedback := "Der Satz braucht noch etwas Übung. Sprich ihn noch einmal nach."
|
||||
nextRecommendation := "Wiederhole diese Übung."
|
||||
switch {
|
||||
case result.OverallScore >= 95 && result.AccuracyScore >= 95 && result.FluencyScore >= 95 && result.CompletenessScore >= 95:
|
||||
feedback = "Ausgezeichnet gesprochen! Die Aussprache dieses Satzes wurde sehr hoch bewertet."
|
||||
nextRecommendation = "Du kannst mit einer neuen Übung weitermachen."
|
||||
case weakWord != "":
|
||||
feedback = fmt.Sprintf("Das Wort %q wurde noch unsicher bewertet. Übe es im Satz noch einmal.", weakWord)
|
||||
nextRecommendation = fmt.Sprintf("Wiederhole den Satz und achte besonders auf %q.", weakWord)
|
||||
case result.OverallScore >= 85:
|
||||
feedback = "Gut gesprochen! Die Aussprache dieses Satzes wurde hoch bewertet."
|
||||
nextRecommendation = "Du kannst mit einer neuen Übung weitermachen."
|
||||
}
|
||||
return domain.TeacherResponse{
|
||||
ExerciseType: "repeat_sentence",
|
||||
TargetText: targetText,
|
||||
TeacherFeedback: feedback,
|
||||
TTSText: targetText,
|
||||
NextRecommendation: "Noch einmal sprechen und auf die markierten Woerter achten.",
|
||||
NextRecommendation: nextRecommendation,
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user