diff --git a/.env.example b/.env.example index a370198..b2d7783 100644 --- a/.env.example +++ b/.env.example @@ -19,6 +19,7 @@ AZURE_SPEECH_REGION= AZURE_ENABLE_MOCK=true FLOWISE_BASE_URL=http://flowise:3000 +# When set, Flowise generates the next exercise before the API falls back to seed data. FLOWISE_CHATFLOW_ID= FLOWISE_API_KEY= diff --git a/apps/api/internal/domain/models.go b/apps/api/internal/domain/models.go index ca1dd40..3109073 100644 --- a/apps/api/internal/domain/models.go +++ b/apps/api/internal/domain/models.go @@ -45,6 +45,7 @@ type Exercise struct { PromptText string `json:"prompt_text"` TargetText string `json:"target_text"` Difficulty int `json:"difficulty"` + Source string `json:"source,omitempty"` } type WordScore struct { @@ -90,6 +91,32 @@ type ProgressSummary struct { DailyGoalMinutes int `json:"daily_goal_minutes"` } +type GeneratedExerciseRequest struct { + UserID string `json:"user_id"` + Profile LearnerProfile `json:"profile"` + Progress ProgressSummary `json:"progress"` + TargetLanguage string `json:"target_language"` + CEFRLevel string `json:"cefr_level"` + UILanguage string `json:"ui_language"` + SessionID string `json:"session_id"` + RecentWeakWords []WordScore `json:"recent_weak_words"` + PreferredType string `json:"preferred_type"` +} + +type GeneratedExercise struct { + ID string `json:"exercise_id"` + ExerciseType string `json:"exercise_type"` + TargetLanguage string `json:"target_language"` + CEFRLevel string `json:"cefr_level"` + ReferenceText string `json:"reference_text"` + DisplayPrompt string `json:"display_prompt"` + TTSText string `json:"tts_text"` + FocusPoints []string `json:"focus_points"` + SuccessCriteria []string `json:"success_criteria"` + ReasonForChoice string `json:"reason_for_choice"` + Source string `json:"source"` +} + type Dashboard struct { User User `json:"user"` Profile LearnerProfile `json:"profile"` diff --git a/apps/api/internal/httpapi/server.go b/apps/api/internal/httpapi/server.go index db19cbf..a810f20 100644 --- a/apps/api/internal/httpapi/server.go +++ b/apps/api/internal/httpapi/server.go @@ -22,6 +22,7 @@ type DataStore interface { ListLanguages(ctx context.Context) ([]domain.LanguageProfile, error) GetLanguage(ctx context.Context, code string) (domain.LanguageProfile, error) NextLessonAndExercise(ctx context.Context, profile domain.LearnerProfile) (domain.Lesson, domain.Exercise, error) + SaveGeneratedExercise(ctx context.Context, userID string, generated domain.GeneratedExercise) (domain.Lesson, domain.Exercise, error) GetExercise(ctx context.Context, id string) (domain.Exercise, error) SaveAttempt(ctx context.Context, attempt domain.Attempt) (domain.Attempt, error) Progress(ctx context.Context, userID string, limit int) (domain.ProgressSummary, error) @@ -189,7 +190,7 @@ func (s *Server) dashboard(w http.ResponseWriter, r *http.Request) { writeError(w, http.StatusInternalServerError, err) return } - lesson, exercise, err := s.store.NextLessonAndExercise(r.Context(), profile) + lesson, exercise, err := s.nextAgentExercise(r.Context(), user, profile, progress) if err != nil { writeError(w, http.StatusNotFound, err) return @@ -209,12 +210,23 @@ func (s *Server) progress(w http.ResponseWriter, r *http.Request) { } func (s *Server) nextLesson(w http.ResponseWriter, r *http.Request) { - profile, err := s.store.GetPrimaryProfile(r.Context(), currentUserID(r)) + userID := currentUserID(r) + user, err := s.store.GetUser(r.Context(), userID) if err != nil { writeError(w, http.StatusNotFound, err) return } - lesson, exercise, err := s.store.NextLessonAndExercise(r.Context(), profile) + profile, err := s.store.GetPrimaryProfile(r.Context(), userID) + if err != nil { + writeError(w, http.StatusNotFound, err) + return + } + progress, err := s.store.Progress(r.Context(), userID, 10) + if err != nil { + writeError(w, http.StatusInternalServerError, err) + return + } + lesson, exercise, err := s.nextAgentExercise(r.Context(), user, profile, progress) if err != nil { writeError(w, http.StatusNotFound, err) return @@ -222,6 +234,31 @@ func (s *Server) nextLesson(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, map[string]any{"lesson": lesson, "exercise": exercise}) } +func (s *Server) nextAgentExercise(ctx context.Context, user domain.User, profile domain.LearnerProfile, progress domain.ProgressSummary) (domain.Lesson, domain.Exercise, error) { + generated, err := s.teacher.NextExercise(ctx, domain.GeneratedExerciseRequest{ + UserID: user.ID, + Profile: profile, + Progress: progress, + TargetLanguage: profile.TargetLanguage, + CEFRLevel: profile.CEFRLevel, + UILanguage: user.UILanguage, + SessionID: flowiseSessionID(user.ID, profile.TargetLanguage, "practice"), + RecentWeakWords: progress.WeakWords, + PreferredType: "repeat_sentence", + }) + if err == nil && generated.Source == "flowise" && strings.TrimSpace(generated.ReferenceText) != "" { + lesson, exercise, saveErr := s.store.SaveGeneratedExercise(ctx, user.ID, generated) + if saveErr == nil { + return lesson, exercise, nil + } + s.logger.Warn("saving generated exercise failed, using seed fallback", "error", saveErr) + } + if err != nil { + s.logger.Warn("flowise next exercise failed, using seed fallback", "error", err) + } + return s.store.NextLessonAndExercise(ctx, profile) +} + func (s *Server) createAttempt(w http.ResponseWriter, r *http.Request) { if err := r.ParseMultipartForm(24 << 20); err != nil { writeError(w, http.StatusBadRequest, err) @@ -372,6 +409,14 @@ func firstNonEmpty(values ...string) string { return "" } +func flowiseSessionID(userID, targetLanguage, scope string) string { + parts := []string{strings.TrimSpace(userID), strings.TrimSpace(targetLanguage), strings.TrimSpace(scope)} + for i, part := range parts { + parts[i] = strings.ReplaceAll(part, " ", "_") + } + return strings.Join(parts, ":") +} + func valueOr(value, fallback string) string { if strings.TrimSpace(value) == "" { return fallback diff --git a/apps/api/internal/services/flowise.go b/apps/api/internal/services/flowise.go index e6cdfa5..34ddbdf 100644 --- a/apps/api/internal/services/flowise.go +++ b/apps/api/internal/services/flowise.go @@ -16,6 +16,7 @@ import ( ) type TeacherAgent interface { + NextExercise(ctx context.Context, input domain.GeneratedExerciseRequest) (domain.GeneratedExercise, error) FeedbackForAttempt(ctx context.Context, targetText string, result domain.PronunciationResult, weakWords []domain.WordScore) (domain.TeacherResponse, error) StartConversation(ctx context.Context, targetLanguage, cefrLevel string) (domain.TeacherResponse, error) ContinueConversation(ctx context.Context, targetLanguage, cefrLevel, userText string) (domain.TeacherResponse, error) @@ -37,59 +38,78 @@ func NewFlowiseTeacher(cfg config.Config, logger *slog.Logger) *FlowiseTeacher { } } -func (f *FlowiseTeacher) FeedbackForAttempt(ctx context.Context, targetText string, result domain.PronunciationResult, weakWords []domain.WordScore) (domain.TeacherResponse, error) { - prompt := map[string]any{ - "task": "practice_feedback", - "target_text": targetText, - "recognized_text": result.RecognizedText, - "scores": result, - "weak_words": weakWords, - "rules": "Answer in German. A1 learner. Max two corrections. Return valid JSON only.", +func (f *FlowiseTeacher) NextExercise(ctx context.Context, input domain.GeneratedExerciseRequest) (domain.GeneratedExercise, error) { + fallback := domain.GeneratedExercise{ + ID: "", + ExerciseType: "repeat_sentence", + TargetLanguage: valueOr(input.TargetLanguage, "en-US"), + CEFRLevel: valueOr(input.CEFRLevel, "A1"), + ReferenceText: "Hello, my name is Anna.", + DisplayPrompt: "Sprich den Satz klar nach.", + TTSText: "Hello, my name is Anna.", + FocusPoints: []string{"clear rhythm", "final sounds"}, + SuccessCriteria: []string{"accuracy above 80"}, + ReasonForChoice: "Fallback exercise because Flowise did not return a valid exercise.", + Source: "fallback", } - return f.ask(ctx, prompt, mockFeedback(targetText, result)) + 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.", + } + return f.askExercise(ctx, payload, input.SessionID, fallback) +} + +func (f *FlowiseTeacher) FeedbackForAttempt(ctx context.Context, targetText string, result domain.PronunciationResult, weakWords []domain.WordScore) (domain.TeacherResponse, error) { + _ = ctx + _ = weakWords + return mockFeedback(targetText, result), nil } func (f *FlowiseTeacher) StartConversation(ctx context.Context, targetLanguage, cefrLevel string) (domain.TeacherResponse, error) { - prompt := map[string]any{ - "task": "start_conversation", - "target_language": targetLanguage, - "cefr_level": cefrLevel, - "rules": "Create a simple A1 roleplay. Return valid JSON only.", - } - return f.ask(ctx, prompt, domain.TeacherResponse{ + _ = ctx + _ = targetLanguage + _ = cefrLevel + return domain.TeacherResponse{ ExerciseType: "conversation", TargetText: "Hello. What is your name?", TeacherFeedback: "Wir starten sehr einfach. Antworte mit: My name is ...", TTSText: "Hello. What is your name?", NextRecommendation: "Antworten: My name is ...", - }) + }, nil } func (f *FlowiseTeacher) ContinueConversation(ctx context.Context, targetLanguage, cefrLevel, userText string) (domain.TeacherResponse, error) { - prompt := map[string]any{ - "task": "continue_conversation", - "target_language": targetLanguage, - "cefr_level": cefrLevel, - "user_text": userText, - "rules": "Continue a simple A1 conversation. Return valid JSON only.", - } - return f.ask(ctx, prompt, domain.TeacherResponse{ + _ = ctx + _ = targetLanguage + _ = cefrLevel + _ = userText + return domain.TeacherResponse{ ExerciseType: "conversation", TargetText: "Nice to meet you. Where are you from?", TeacherFeedback: "Gut. Jetzt uebe einen kurzen Satz mit Herkunft.", TTSText: "Nice to meet you. Where are you from?", NextRecommendation: "Antworten: I am from ...", - }) + }, nil } -func (f *FlowiseTeacher) ask(ctx context.Context, payload any, fallback domain.TeacherResponse) (domain.TeacherResponse, error) { +func (f *FlowiseTeacher) askExercise(ctx context.Context, payload any, sessionID string, fallback domain.GeneratedExercise) (domain.GeneratedExercise, error) { if f.cfg.FlowiseChatflow == "" || f.cfg.FlowiseBaseURL == "" { return fallback, nil } body, _ := json.Marshal(payload) - question := string(body) reqBody, _ := json.Marshal(map[string]any{ - "question": question, + "question": string(body), + "overrideConfig": map[string]any{ + "sessionId": sessionID, + }, }) endpoint := strings.TrimRight(f.cfg.FlowiseBaseURL, "/") + "/api/v1/prediction/" + f.cfg.FlowiseChatflow @@ -104,7 +124,7 @@ func (f *FlowiseTeacher) ask(ctx context.Context, payload any, fallback domain.T resp, err := f.client.Do(req) if err != nil { - f.logger.Warn("flowise unavailable, using fallback", "error", err) + f.logger.Warn("flowise exercise generation unavailable, using fallback", "error", err) return fallback, nil } defer resp.Body.Close() @@ -113,56 +133,63 @@ func (f *FlowiseTeacher) ask(ctx context.Context, payload any, fallback domain.T return fallback, err } if resp.StatusCode >= 300 { - f.logger.Warn("flowise returned error, using fallback", "status", resp.StatusCode, "body", string(respBody)) + f.logger.Warn("flowise exercise generation returned error, using fallback", "status", resp.StatusCode, "body", string(respBody)) 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) + exercise.Source = "flowise" + return exercise, nil + } + f.logger.Warn("flowise exercise response not parseable, using fallback", "body", string(respBody)) + return fallback, nil +} +func parseGeneratedExerciseEnvelope(body []byte) (domain.GeneratedExercise, bool) { var envelope struct { Text string `json:"text"` JSON json.RawMessage `json:"json"` } - if err := json.Unmarshal(respBody, &envelope); err == nil { + if err := json.Unmarshal(body, &envelope); err == nil { if envelope.Text != "" { - if parsed, ok := parseTeacherResponse(envelope.Text); ok { - return parsed, nil + if parsed, ok := parseGeneratedExercise(envelope.Text); ok { + return parsed, true } - fallback.TeacherFeedback = envelope.Text - return fallback, nil } if len(envelope.JSON) > 0 && string(envelope.JSON) != "null" { - if parsed, ok := parseTeacherResponseJSON(envelope.JSON); ok { - return parsed, nil + if parsed, ok := parseGeneratedExerciseJSON(envelope.JSON); ok { + return parsed, true } } } - if parsed, ok := parseTeacherResponse(string(respBody)); ok { - return parsed, nil - } - f.logger.Warn("flowise response not parseable, using fallback", "body", string(respBody)) - return fallback, nil + return parseGeneratedExercise(string(body)) } -func parseTeacherResponse(value string) (domain.TeacherResponse, bool) { +func parseGeneratedExercise(value string) (domain.GeneratedExercise, bool) { value = strings.TrimSpace(value) value = strings.TrimPrefix(value, "```json") value = strings.TrimPrefix(value, "```") value = strings.TrimSuffix(value, "```") - var out domain.TeacherResponse + var out domain.GeneratedExercise if err := json.Unmarshal([]byte(strings.TrimSpace(value)), &out); err != nil { - return domain.TeacherResponse{}, false + return domain.GeneratedExercise{}, false } - return out, out.TeacherFeedback != "" || out.TargetText != "" || out.TTSText != "" + return out, strings.TrimSpace(out.ReferenceText) != "" } -func parseTeacherResponseJSON(value json.RawMessage) (domain.TeacherResponse, bool) { - if parsed, ok := parseTeacherResponse(string(value)); ok { +func parseGeneratedExerciseJSON(value json.RawMessage) (domain.GeneratedExercise, bool) { + if parsed, ok := parseGeneratedExercise(string(value)); ok { return parsed, true } var text string if err := json.Unmarshal(value, &text); err != nil { - return domain.TeacherResponse{}, false + return domain.GeneratedExercise{}, false } - return parseTeacherResponse(text) + return parseGeneratedExercise(text) } func mockFeedback(targetText string, result domain.PronunciationResult) domain.TeacherResponse { diff --git a/apps/api/internal/services/flowise_test.go b/apps/api/internal/services/flowise_test.go index 1503f5d..245221e 100644 --- a/apps/api/internal/services/flowise_test.go +++ b/apps/api/internal/services/flowise_test.go @@ -13,73 +13,27 @@ import ( "speech-learning-api/internal/domain" ) -func TestParseTeacherResponse(t *testing.T) { - response, ok := parseTeacherResponse(`{ - "exercise_type": "repeat_sentence", - "target_text": "Hello.", - "teacher_feedback": "Gut.", - "tts_text": "Hello.", - "ssml": "", - "next_recommendation": "Noch einmal." - }`) - - if !ok { - t.Fatal("expected response to parse") - } - if response.TargetText != "Hello." { - t.Fatalf("unexpected target text %q", response.TargetText) - } -} - -func TestParseTeacherResponseJSONFromObject(t *testing.T) { - response, ok := parseTeacherResponseJSON(json.RawMessage(`{ - "exercise_type": "repeat_sentence", - "target_text": "Hello.", - "teacher_feedback": "Gut.", - "tts_text": "Hello.", - "ssml": "", - "next_recommendation": "Noch einmal." - }`)) - - if !ok { - t.Fatal("expected response to parse") - } - if response.TeacherFeedback != "Gut." { - t.Fatalf("unexpected feedback %q", response.TeacherFeedback) - } -} - -func TestParseTeacherResponseJSONFromString(t *testing.T) { - response, ok := parseTeacherResponseJSON(json.RawMessage(`"{\"exercise_type\":\"repeat_sentence\",\"target_text\":\"Hello.\",\"teacher_feedback\":\"Gut.\",\"tts_text\":\"Hello.\",\"ssml\":\"\",\"next_recommendation\":\"Noch einmal.\"}"`)) - - if !ok { - t.Fatal("expected response to parse") - } - if response.NextRecommendation != "Noch einmal." { - t.Fatalf("unexpected recommendation %q", response.NextRecommendation) - } -} - -func TestFlowiseAskSendsQuestionOnly(t *testing.T) { +func TestFlowiseNextExerciseSendsSessionAndParsesResponse(t *testing.T) { var requestBody map[string]json.RawMessage server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/api/v1/prediction/chatflow-id" { t.Fatalf("unexpected path %q", r.URL.Path) } - if r.Header.Get("Authorization") != "Bearer api-key" { - t.Fatalf("unexpected authorization header %q", r.Header.Get("Authorization")) - } if err := json.NewDecoder(r.Body).Decode(&requestBody); err != nil { t.Fatalf("decode request body: %v", err) } - response := domain.TeacherResponse{ - ExerciseType: "conversation", - TargetText: "Hello.", - TeacherFeedback: "Gut.", - TTSText: "Hello.", - NextRecommendation: "Noch einmal.", + response := domain.GeneratedExercise{ + ExerciseType: "repeat_sentence", + TargetLanguage: "en-US", + CEFRLevel: "A1", + ReferenceText: "I live in Berlin.", + DisplayPrompt: "Sprich den Satz klar nach.", + TTSText: "I live in Berlin.", + FocusPoints: []string{"live"}, + SuccessCriteria: []string{"accuracy above 80"}, + ReasonForChoice: "Uebt einen kurzen A1-Satz.", } responseText, err := json.Marshal(response) if err != nil { @@ -94,22 +48,61 @@ func TestFlowiseAskSendsQuestionOnly(t *testing.T) { teacher := NewFlowiseTeacher(config.Config{ FlowiseBaseURL: server.URL, FlowiseChatflow: "chatflow-id", - FlowiseAPIKey: "api-key", }, slog.New(slog.NewTextHandler(io.Discard, nil))) - response, err := teacher.ask(context.Background(), map[string]any{"task": "start_conversation"}, domain.TeacherResponse{ - TeacherFeedback: "fallback", + exercise, err := teacher.NextExercise(context.Background(), domain.GeneratedExerciseRequest{ + UserID: "usr_1", + TargetLanguage: "en-US", + CEFRLevel: "A1", + SessionID: "usr_1:en-US:practice", }) if err != nil { - t.Fatalf("ask: %v", err) + t.Fatalf("NextExercise: %v", err) } - if response.TeacherFeedback != "Gut." { - t.Fatalf("unexpected feedback %q", response.TeacherFeedback) + if exercise.ReferenceText != "I live in Berlin." { + t.Fatalf("unexpected reference text %q", exercise.ReferenceText) } - if _, ok := requestBody["question"]; !ok { - t.Fatal("expected question in request body") + if exercise.Source != "flowise" { + t.Fatalf("unexpected source %q", exercise.Source) } - if _, ok := requestBody["form"]; ok { - t.Fatal("did not expect form in request body") + + var override struct { + SessionID string `json:"sessionId"` + } + if err := json.Unmarshal(requestBody["overrideConfig"], &override); err != nil { + t.Fatalf("decode overrideConfig: %v", err) + } + if override.SessionID != "usr_1:en-US:practice" { + t.Fatalf("unexpected sessionId %q", override.SessionID) + } + + var question map[string]any + if err := json.Unmarshal(requestBody["question"], &question); err == nil { + t.Fatalf("expected question to be a JSON string, got object %#v", question) + } + var questionText string + if err := json.Unmarshal(requestBody["question"], &questionText); err != nil { + t.Fatalf("decode question text: %v", err) + } + if err := json.Unmarshal([]byte(questionText), &question); err != nil { + t.Fatalf("decode question payload: %v", err) + } + if question["task"] != "next_exercise" { + t.Fatalf("unexpected task %#v", question["task"]) + } +} + +func TestParseGeneratedExerciseEnvelope(t *testing.T) { + body := []byte(`{"text":"{\"exercise_type\":\"repeat_sentence\",\"target_language\":\"en-US\",\"cefr_level\":\"A1\",\"reference_text\":\"I live in Berlin.\",\"display_prompt\":\"Sprich den Satz klar nach.\",\"tts_text\":\"I live in Berlin.\",\"focus_points\":[\"live\"],\"success_criteria\":[\"accuracy above 80\"],\"reason_for_choice\":\"Practise /l/.\"}"}`) + + exercise, ok := parseGeneratedExerciseEnvelope(body) + if !ok { + t.Fatal("expected generated exercise to parse") + } + if exercise.ReferenceText != "I live in Berlin." { + t.Fatalf("unexpected reference text %q", exercise.ReferenceText) + } + if len(exercise.FocusPoints) != 1 || exercise.FocusPoints[0] != "live" { + t.Fatalf("unexpected focus points %#v", exercise.FocusPoints) } } diff --git a/apps/api/internal/store/store.go b/apps/api/internal/store/store.go index df3db5d..1051c90 100644 --- a/apps/api/internal/store/store.go +++ b/apps/api/internal/store/store.go @@ -43,6 +43,91 @@ func (s *PostgresStore) Init(ctx context.Context) error { return nil } +func (s *PostgresStore) EnsureGeneratedLesson(ctx context.Context, targetLanguage, cefrLevel string) (domain.Lesson, error) { + lesson := domain.Lesson{ + ID: "les_generated_" + strings.ToLower(strings.ReplaceAll(targetLanguage, "-", "_")) + "_" + strings.ToLower(cefrLevel), + TargetLanguage: targetLanguage, + CEFRLevel: cefrLevel, + Topic: "agent_generated", + Title: "Agent generated practice", + } + row := s.db.QueryRowContext(ctx, ` + INSERT INTO lessons (id, target_language, cefr_level, topic, title) + VALUES ($1, $2, $3, $4, $5) + ON CONFLICT (id) DO UPDATE SET + target_language = EXCLUDED.target_language, + cefr_level = EXCLUDED.cefr_level, + topic = EXCLUDED.topic, + title = EXCLUDED.title + RETURNING id, target_language, cefr_level, topic, title + `, lesson.ID, lesson.TargetLanguage, lesson.CEFRLevel, lesson.Topic, lesson.Title) + if err := row.Scan(&lesson.ID, &lesson.TargetLanguage, &lesson.CEFRLevel, &lesson.Topic, &lesson.Title); err != nil { + return domain.Lesson{}, err + } + return lesson, nil +} + +func (s *PostgresStore) SaveGeneratedExercise(ctx context.Context, userID string, generated domain.GeneratedExercise) (domain.Lesson, domain.Exercise, error) { + targetLanguage := valueOr(generated.TargetLanguage, "en-US") + cefrLevel := valueOr(generated.CEFRLevel, "A1") + lesson, err := s.EnsureGeneratedLesson(ctx, targetLanguage, cefrLevel) + if err != nil { + return domain.Lesson{}, domain.Exercise{}, err + } + focusPoints, err := json.Marshal(generated.FocusPoints) + if err != nil { + return domain.Lesson{}, domain.Exercise{}, err + } + successCriteria, err := json.Marshal(generated.SuccessCriteria) + if err != nil { + return domain.Lesson{}, domain.Exercise{}, err + } + exercise := domain.Exercise{ + ID: valueOr(generated.ID, NewID("exg")), + LessonID: lesson.ID, + TargetLanguage: targetLanguage, + CEFRLevel: cefrLevel, + Type: valueOr(generated.ExerciseType, "repeat_sentence"), + PromptText: valueOr(generated.DisplayPrompt, "Sprich den Satz klar nach."), + TargetText: generated.ReferenceText, + Difficulty: 1, + Source: "flowise", + } + if strings.TrimSpace(exercise.TargetText) == "" { + return domain.Lesson{}, domain.Exercise{}, errors.New("generated exercise reference_text is required") + } + row := s.db.QueryRowContext(ctx, ` + INSERT INTO exercises ( + id, lesson_id, target_language, cefr_level, type, prompt_text, target_text, + difficulty, source, created_by_user_id, tts_text, focus_points_json, + success_criteria_json, reason_for_choice, agent_context_json + ) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 'flowise', $9, $10, $11, $12, $13, $14) + ON CONFLICT (id) DO UPDATE SET + lesson_id = EXCLUDED.lesson_id, + target_language = EXCLUDED.target_language, + cefr_level = EXCLUDED.cefr_level, + type = EXCLUDED.type, + prompt_text = EXCLUDED.prompt_text, + target_text = EXCLUDED.target_text, + difficulty = EXCLUDED.difficulty, + source = EXCLUDED.source, + created_by_user_id = EXCLUDED.created_by_user_id, + tts_text = EXCLUDED.tts_text, + focus_points_json = EXCLUDED.focus_points_json, + success_criteria_json = EXCLUDED.success_criteria_json, + reason_for_choice = EXCLUDED.reason_for_choice, + agent_context_json = EXCLUDED.agent_context_json + RETURNING id, lesson_id, target_language, cefr_level, type, prompt_text, target_text, difficulty, source + `, exercise.ID, exercise.LessonID, exercise.TargetLanguage, exercise.CEFRLevel, exercise.Type, + exercise.PromptText, exercise.TargetText, exercise.Difficulty, userID, generated.TTSText, + string(focusPoints), string(successCriteria), generated.ReasonForChoice, mustJSON(generated)) + if err := row.Scan(&exercise.ID, &exercise.LessonID, &exercise.TargetLanguage, &exercise.CEFRLevel, &exercise.Type, &exercise.PromptText, &exercise.TargetText, &exercise.Difficulty, &exercise.Source); err != nil { + return domain.Lesson{}, domain.Exercise{}, err + } + return lesson, exercise, nil +} + func (s *PostgresStore) DebugStatus(ctx context.Context) domain.DebugDBStatus { status := domain.DebugDBStatus{ Counts: map[string]int{}, @@ -210,10 +295,11 @@ func (s *PostgresStore) NextLessonAndExercise(ctx context.Context, profile domai row := s.db.QueryRowContext(ctx, ` SELECT l.id, l.target_language, l.cefr_level, l.topic, l.title, e.id, e.lesson_id, e.target_language, e.cefr_level, e.type, - e.prompt_text, e.target_text, e.difficulty + e.prompt_text, e.target_text, e.difficulty, COALESCE(e.source, 'seed') FROM exercises e JOIN lessons l ON l.id = e.lesson_id WHERE e.target_language = $1 AND e.cefr_level = $2 + AND (COALESCE(e.source, 'seed') = 'seed' OR e.created_by_user_id = $3) ORDER BY ( SELECT COUNT(*) FROM attempts a @@ -224,7 +310,7 @@ func (s *PostgresStore) NextLessonAndExercise(ctx context.Context, profile domai if err := row.Scan( &lesson.ID, &lesson.TargetLanguage, &lesson.CEFRLevel, &lesson.Topic, &lesson.Title, &exercise.ID, &exercise.LessonID, &exercise.TargetLanguage, &exercise.CEFRLevel, &exercise.Type, - &exercise.PromptText, &exercise.TargetText, &exercise.Difficulty, + &exercise.PromptText, &exercise.TargetText, &exercise.Difficulty, &exercise.Source, ); err != nil { if errors.Is(err, sql.ErrNoRows) { return domain.Lesson{}, domain.Exercise{}, ErrNotFound @@ -237,11 +323,11 @@ func (s *PostgresStore) NextLessonAndExercise(ctx context.Context, profile domai func (s *PostgresStore) GetExercise(ctx context.Context, id string) (domain.Exercise, error) { var e domain.Exercise row := s.db.QueryRowContext(ctx, ` - SELECT id, lesson_id, target_language, cefr_level, type, prompt_text, target_text, difficulty + SELECT id, lesson_id, target_language, cefr_level, type, prompt_text, target_text, difficulty, COALESCE(source, 'seed') FROM exercises WHERE id = $1 `, id) - if err := row.Scan(&e.ID, &e.LessonID, &e.TargetLanguage, &e.CEFRLevel, &e.Type, &e.PromptText, &e.TargetText, &e.Difficulty); err != nil { + if err := row.Scan(&e.ID, &e.LessonID, &e.TargetLanguage, &e.CEFRLevel, &e.Type, &e.PromptText, &e.TargetText, &e.Difficulty, &e.Source); err != nil { if errors.Is(err, sql.ErrNoRows) { return domain.Exercise{}, ErrNotFound } @@ -401,6 +487,14 @@ func valueOr(value, fallback string) string { return value } +func mustJSON(value any) string { + body, err := json.Marshal(value) + if err != nil { + return "{}" + } + return string(body) +} + const schemaSQL = ` CREATE TABLE IF NOT EXISTS users ( id TEXT PRIMARY KEY, @@ -446,9 +540,26 @@ CREATE TABLE IF NOT EXISTS exercises ( type TEXT NOT NULL, prompt_text TEXT NOT NULL, target_text TEXT NOT NULL, - difficulty INT NOT NULL DEFAULT 1 + difficulty INT NOT NULL DEFAULT 1, + source TEXT NOT NULL DEFAULT 'seed', + created_by_user_id TEXT REFERENCES users(id) ON DELETE SET NULL, + tts_text TEXT NOT NULL DEFAULT '', + focus_points_json JSONB NOT NULL DEFAULT '[]'::jsonb, + success_criteria_json JSONB NOT NULL DEFAULT '[]'::jsonb, + reason_for_choice TEXT NOT NULL DEFAULT '', + agent_context_json JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT now() ); +ALTER TABLE exercises ADD COLUMN IF NOT EXISTS source TEXT NOT NULL DEFAULT 'seed'; +ALTER TABLE exercises ADD COLUMN IF NOT EXISTS created_by_user_id TEXT REFERENCES users(id) ON DELETE SET NULL; +ALTER TABLE exercises ADD COLUMN IF NOT EXISTS tts_text TEXT NOT NULL DEFAULT ''; +ALTER TABLE exercises ADD COLUMN IF NOT EXISTS focus_points_json JSONB NOT NULL DEFAULT '[]'::jsonb; +ALTER TABLE exercises ADD COLUMN IF NOT EXISTS success_criteria_json JSONB NOT NULL DEFAULT '[]'::jsonb; +ALTER TABLE exercises ADD COLUMN IF NOT EXISTS reason_for_choice TEXT NOT NULL DEFAULT ''; +ALTER TABLE exercises ADD COLUMN IF NOT EXISTS agent_context_json JSONB NOT NULL DEFAULT '{}'::jsonb; +ALTER TABLE exercises ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now(); + CREATE TABLE IF NOT EXISTS attempts ( id TEXT PRIMARY KEY, user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE, diff --git a/apps/web/src/api/types.ts b/apps/web/src/api/types.ts index 91aec4c..265be96 100644 --- a/apps/web/src/api/types.ts +++ b/apps/web/src/api/types.ts @@ -30,6 +30,7 @@ export type Exercise = { prompt_text: string; target_text: string; difficulty: number; + source?: 'seed' | 'flowise' | 'fallback' | string; }; export type WordScore = { diff --git a/docs/agent-design.md b/docs/agent-design.md index 1006b42..563cd35 100644 --- a/docs/agent-design.md +++ b/docs/agent-design.md @@ -8,24 +8,28 @@ The Flowise agent acts as a precise A1 English teacher for German-speaking adult - `target_language` - `cefr_level` -- current exercise -- Azure scores +- learner profile +- progress summary - weak words - recent attempts ## Output -The backend expects valid JSON: +For task `next_exercise`, the backend expects valid JSON: ```json { "exercise_type": "repeat_sentence", - "target_text": "Hello, my name is Anna.", - "teacher_feedback": "Uebe besonders 'name'.", + "target_language": "en-US", + "cefr_level": "A1", + "reference_text": "Hello, my name is Anna.", + "display_prompt": "Sprich den Satz klar nach.", "tts_text": "Hello, my name is Anna.", - "ssml": "", - "next_recommendation": "Sprich den Satz noch einmal langsam." + "focus_points": ["name"], + "success_criteria": ["accuracy above 80"], + "reason_for_choice": "Kurzer Satz fuer klare A1-Aussprache." } ``` -The agent must not create pronunciation scores. Azure is the scoring source. +The agent must not create pronunciation scores. Azure is the scoring source. Feedback and simple +conversation are local backend logic in this phase; Flowise is used only for exercise generation. diff --git a/docs/architecture.md b/docs/architecture.md index fe88b58..d4fc153 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,13 +13,20 @@ FlowiseAI runs as a Docker container on the same VPS and Docker network. The fro ## Backend -The Go API is the system of record. It owns auth, learner profiles, language profiles, exercises, attempts, progress, Azure calls, and Flowise calls. +The Go API is the system of record. It owns auth, learner profiles, language profiles, generated exercises, attempts, progress, Azure calls, and Flowise calls. + +Flowise owns the first version of the lesson logic: when the dashboard or `POST /lessons/next` +needs the next task, the API sends profile/progress context to Flowise with a stable +`sessionId`. Flowise returns one exercise JSON object. The API stores that exercise in PostgreSQL +for the current user and returns it to the frontend. If Flowise is unavailable or returns invalid +JSON, the API falls back to seeded A1 exercises. Feedback and the simple conversation screen stay +local backend behavior in this first Flowise-generation phase. Important boundaries: - `httpapi`: request/response handling. - `services`: auth, Azure Speech, Flowise teacher logic. -- `store`: PostgreSQL schema, seed data, repositories. +- `store`: PostgreSQL schema, seed data, generated exercise persistence, repositories. - `domain`: shared API/domain structs. ## Multilingual Design diff --git a/flowise/README.md b/flowise/README.md index 4a54f3e..0a32397 100644 --- a/flowise/README.md +++ b/flowise/README.md @@ -6,7 +6,7 @@ Flowise laeuft in Docker als Service `flowise` und ist vom Backend intern ueber Fuer Agentflow V2 nutze zuerst die konkrete Anleitung in [`agentflow-v2-setup.md`](./agentflow-v2-setup.md). Sie passt zur aktuellen -Go-Backend-Anbindung, die Flowise mit `question` und `form` aufruft. +Go-Backend-Anbindung, die Flowise mit `question` und `overrideConfig.sessionId` aufruft. 1. Flowise im Browser oeffnen: http://localhost:3000 2. Einen Chatflow oder Agentflow fuer `A1 English Teacher` erstellen. @@ -17,17 +17,21 @@ Go-Backend-Anbindung, die Flowise mit `question` und `form` aufruft. FLOWISE_CHATFLOW_ID=... ``` -Das Backend erwartet JSON-Antworten mit: +Fuer die naechste Uebung erwartet das Backend JSON-Antworten mit: ```json { "exercise_type": "repeat_sentence", - "target_text": "Hello, my name is Anna.", - "teacher_feedback": "Uebe besonders 'name'.", + "target_language": "en-US", + "cefr_level": "A1", + "reference_text": "Hello, my name is Anna.", + "display_prompt": "Sprich den Satz klar nach.", "tts_text": "Hello, my name is Anna.", - "ssml": "", - "next_recommendation": "Sprich den Satz noch einmal langsam." + "focus_points": ["name"], + "success_criteria": ["accuracy above 80"], + "reason_for_choice": "Kurzer A1-Satz fuer klare Betonung." } ``` -Wenn keine Chatflow-ID gesetzt ist, nutzt die API einen lokalen Fallback. +Feedback und einfache Konversation laufen vorerst lokal im Backend. Wenn keine Chatflow-ID gesetzt +ist oder Flowise kein valides JSON liefert, nutzt die API Seed-Uebungen als Fallback. diff --git a/flowise/agentflow-v2-setup.md b/flowise/agentflow-v2-setup.md index 8dda8d2..d2c463b 100644 --- a/flowise/agentflow-v2-setup.md +++ b/flowise/agentflow-v2-setup.md @@ -11,32 +11,27 @@ It is designed for the current Go backend adapter. - Internal Flowise URL for the API container: `http://flowise:3000` - Verified Flowise version on the existing instance: `3.0.11` - The Go backend calls Flowise with `POST /api/v1/prediction/{FLOWISE_CHATFLOW_ID}`. -- The request body includes `question` as a JSON string and `form` as the same structured object. +- The request body includes `question` as one JSON string and `overrideConfig.sessionId`. Build the first V2 flow with Start Node input type `Chat Input`; it is the simplest path because -all current tasks arrive as one JSON context. V2 `Form Input` is also possible now, but only if the -form fields match the backend payload fields for the task you want to handle. +the backend sends one JSON context as the chat input. V2 `Form Input` can come later if you split +the flow into typed task-specific flows. The backend parses Flowise responses from `text`, `json`, or a raw JSON response. A plain JSON text reply is still the easiest response format to debug in Flowise and in the app. ## Current backend tasks -The current backend can call the agent for these tasks: +The current backend sends only one task to Flowise: -1. `practice_feedback` - - Sent after Azure/mock pronunciation assessment. - - Context includes `target_text`, `recognized_text`, `scores`, `weak_words`, and rules. - - The agent must never create or modify pronunciation scores. -2. `start_conversation` - - Starts a short A1 roleplay. - - Context includes `target_language` and `cefr_level`. -3. `continue_conversation` - - Continues a short A1 roleplay. - - Context includes `target_language`, `cefr_level`, and `user_text`. +1. `next_exercise` + - Sent when dashboard or `POST /lessons/next` needs the next speaking exercise. + - Context includes learner profile, recent progress, weak words, target language, CEFR level, and rules. + - The agent creates exactly one A1 exercise. The backend stores it in PostgreSQL for that user. -The backend does not currently call Flowise to choose the next DB exercise. The prompt -`prompts/exercise_generation.md` is useful for a later backend extension, but it is not used now. +Flowise owns the exercise-generation logic. PostgreSQL remains the durable system of record for +users, profiles, generated exercises, attempts, and progress. Pronunciation scoring stays in Azure +Speech/the backend. Feedback and the simple conversation screen are local fallback logic for now. ## Recommended V2 graph @@ -65,7 +60,8 @@ Start Node: LLM/Agent Node: - Input Message: `{{ $flow.input }}` -- Memory: off for now. The backend does not pass a Flowise `sessionId` yet. +- Memory: on or Flowise chat memory enabled if you want per-user continuity. +- The backend sends `overrideConfig.sessionId` in the shape `user_id:target_language:practice`. - Output: JSON text only. Direct Reply Node: @@ -83,55 +79,47 @@ You receive one JSON object as the user message. It contains a field named "task Global rules: - Return valid JSON only. No Markdown. No code fences. No commentary outside JSON. -- Use exactly this JSON shape: +- Read the input JSON field "task". +- If task is "next_exercise", use exactly this JSON shape: { "exercise_type": "repeat_sentence", - "target_text": "English text the learner should say next", - "teacher_feedback": "Short German feedback", - "tts_text": "Text for speech synthesis", - "ssml": "", - "next_recommendation": "One short next step in German" + "target_language": "en-US", + "cefr_level": "A1", + "reference_text": "English sentence the learner must pronounce", + "display_prompt": "Short German instruction", + "tts_text": "English text for speech synthesis", + "focus_points": ["one or two words or sounds to practise"], + "success_criteria": ["concrete success criterion"], + "reason_for_choice": "Short German reason based on learner progress" } -- Allowed exercise_type values: "repeat_sentence", "conversation". +- If the task is missing or unknown, still return one safe A1 repeat_sentence exercise in this same shape. +- Allowed exercise_type value for now: "repeat_sentence". - Keep the learner at CEFR A1 unless the input explicitly says otherwise. -- Explain in German. Target sentences and roleplay turns are in English. -- Use short, everyday A1 English. Prefer 3 to 9 words for target_text when possible. -- Give at most two corrections per turn. +- Use German for display_prompt and reason_for_choice. +- Use English for reference_text and tts_text. +- Use short, everyday A1 English. Prefer 3 to 9 words for reference_text when possible. - Do not invent pronunciation scores. Scores come only from Azure Speech or the backend mock. -- Do not change score values. Use scores only to decide feedback. -- Prefer repetition, minimal pairs, shadowing, short roleplay, and one clear next step. -- Keep ssml as an empty string unless the backend later asks for SSML. +- Use recent weak_words if present. +- Prefer repetition, minimal pairs, shadowing, and one clear pronunciation focus. Task rules: -If task is "practice_feedback": -- Use target_text, recognized_text, scores, and weak_words. -- Mention the weakest word or sound if available. -- If overall_score is high, praise briefly and recommend a more natural rhythm. -- If weak_words are present, ask the learner to repeat the original target_text slowly. -- exercise_type must be "repeat_sentence". -- target_text and tts_text should usually equal the original target_text. - -If task is "start_conversation": -- Start one simple A1 roleplay. -- Use one short teacher sentence as target_text and tts_text. -- Give a German next_recommendation that tells the learner how to answer. -- exercise_type must be "conversation". - -If task is "continue_conversation": -- Read user_text and continue with one short teacher sentence. -- Correct only the most important issue, if any. -- Keep the roleplay moving with a simple A1 question or prompt. -- exercise_type must be "conversation". - -If the task is missing or unknown: -- Return a safe repeat_sentence response for A1 practice. +If task is "next_exercise": +- Create one short pronunciation exercise for the learner. +- exercise_type must be "repeat_sentence" for the current MVP. +- reference_text and tts_text should be English and usually identical. +- display_prompt and reason_for_choice should be German. +- Use recent weak_words if present. +- Keep the sentence short, natural, and useful for A1. +- Do not include pronunciation scores. ``` ## JSON contract Use this contract mentally or as a structured-output schema if the UI supports it. +Exercise generation response for `next_exercise`: + ```json { "type": "object", @@ -139,31 +127,49 @@ Use this contract mentally or as a structured-output schema if the UI supports i "properties": { "exercise_type": { "type": "string", - "enum": ["repeat_sentence", "conversation"] + "enum": ["repeat_sentence"] }, - "target_text": { + "target_language": { "type": "string" }, - "teacher_feedback": { + "cefr_level": { + "type": "string" + }, + "reference_text": { + "type": "string" + }, + "display_prompt": { "type": "string" }, "tts_text": { "type": "string" }, - "ssml": { - "type": "string" + "focus_points": { + "type": "array", + "items": { + "type": "string" + } }, - "next_recommendation": { + "success_criteria": { + "type": "array", + "items": { + "type": "string" + } + }, + "reason_for_choice": { "type": "string" } }, "required": [ "exercise_type", - "target_text", - "teacher_feedback", + "target_language", + "cefr_level", + "reference_text", + "display_prompt", "tts_text", - "ssml", - "next_recommendation" + "focus_points", + "success_criteria", + "reason_for_choice" ] } ``` @@ -172,34 +178,25 @@ Use this contract mentally or as a structured-output schema if the UI supports i Paste these as chat input in Flowise. -Practice feedback: +Next exercise: ```json -{"task":"practice_feedback","target_text":"Can I have a coffee, please?","recognized_text":"Can I have coffee please","scores":{"recognized_text":"Can I have coffee please","overall_score":72,"accuracy_score":70,"fluency_score":78,"completeness_score":82,"prosody_score":69,"word_scores":[{"word":"Can","accuracy":91,"highlight":"good"},{"word":"I","accuracy":88,"highlight":"good"},{"word":"have","accuracy":74,"highlight":"ok"},{"word":"a","accuracy":55,"highlight":"weak"},{"word":"coffee","accuracy":79,"highlight":"ok"},{"word":"please","accuracy":68,"highlight":"weak"}],"provider":"mock"},"weak_words":[{"word":"a","accuracy":55,"highlight":"weak"},{"word":"please","accuracy":68,"highlight":"weak"}],"rules":"Answer in German. A1 learner. Max two corrections. Return valid JSON only."} -``` - -Start conversation: - -```json -{"task":"start_conversation","target_language":"en-US","cefr_level":"A1","rules":"Create a simple A1 roleplay. Return valid JSON only."} -``` - -Continue conversation: - -```json -{"task":"continue_conversation","target_language":"en-US","cefr_level":"A1","user_text":"My name Anna","rules":"Continue a simple A1 conversation. Return valid JSON only."} +{"task":"next_exercise","user_id":"usr_demo","target_language":"en-US","cefr_level":"A1","ui_language":"de-DE","profile":{"target_language":"en-US","cefr_level":"A1","daily_goal_minutes":10},"progress":{"total_attempts":2,"average_score":73,"weak_words":[{"word":"please","accuracy":61,"highlight":"weak"}],"recent_attempts":[]},"recent_weak_words":[{"word":"please","accuracy":61,"highlight":"weak"}],"preferred_type":"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."} ``` Expected output example: ```json { - "exercise_type": "conversation", - "target_text": "Nice to meet you, Anna.", - "teacher_feedback": "Fast richtig: Sage \"My name is Anna.\"", - "tts_text": "Nice to meet you, Anna.", - "ssml": "", - "next_recommendation": "Antworte kurz: I am from ..." + "exercise_type": "repeat_sentence", + "target_language": "en-US", + "cefr_level": "A1", + "reference_text": "Can I have water, please?", + "display_prompt": "Sprich den Satz langsam und klar nach.", + "tts_text": "Can I have water, please?", + "focus_points": ["please", "water"], + "success_criteria": ["accuracy above 80", "clear final sounds"], + "reason_for_choice": "Die Uebung wiederholt ein schwaches Wort in einem kurzen Alltagssatz." } ``` @@ -226,7 +223,7 @@ docker compose up --build -d speech-api ## Validation 1. In Flowise, run each test payload and confirm the reply is plain JSON text. -2. In the app, submit a pronunciation attempt and verify that the `teacher` response is not the local fallback. +2. In the app, open the dashboard or click the next lesson button and verify that the returned exercise has `source: "flowise"`. 3. Use the Debug page or `GET /api/debug/flowise` after the API is recreated with `DEBUG_ENABLED=true`. If `/api/debug/*` returns `404`, the running API was started without debug routes. Recreate the @@ -234,11 +231,10 @@ If `/api/debug/*` returns `404`, the running API was started without debug route ## Later upgrades -These backend changes would unlock a more capable V2 agent: +Useful later upgrades: -- Send `overrideConfig.sessionId` and/or recent turns for conversation continuity. - Add typed V2 `Form Input` variants if individual task-specific flows are split out. -- Add a backend task for dynamic exercise generation using `prompts/exercise_generation.md`. +- Add Flowise tools for curriculum lookup, spaced repetition policy, or vector-memory retrieval. - Add a safe internal admin/debug tool only if the backend passes a scoped service credential. References: diff --git a/flowise/prompts/a1_teacher_system.md b/flowise/prompts/a1_teacher_system.md index 2ea30ef..7a25920 100644 --- a/flowise/prompts/a1_teacher_system.md +++ b/flowise/prompts/a1_teacher_system.md @@ -2,19 +2,21 @@ You are an A1 English teacher for German-speaking adult learners. Rules: - Keep the learner at CEFR A1 unless the backend explicitly sends another level. -- Answer explanations in German. -- Use short English target sentences. -- Give at most two corrections per turn. +- Use German for display_prompt and reason_for_choice. +- Use short English reference_text sentences. - Do not invent pronunciation scores. Scores come only from Azure Speech. -- Prefer repetition, minimal pairs, shadowing, and short roleplay. +- Prefer repetition, minimal pairs, and shadowing. - Return valid JSON only. -Required JSON shape: +Return this JSON shape: { - "exercise_type": "repeat_sentence | conversation", - "target_text": "English text the learner should say next", - "teacher_feedback": "Short German feedback", + "exercise_type": "repeat_sentence", + "target_language": "en-US", + "cefr_level": "A1", + "reference_text": "English text the learner should pronounce", + "display_prompt": "Short German instruction", "tts_text": "Text for speech synthesis", - "ssml": "", - "next_recommendation": "One short next step in German" + "focus_points": ["word or sound to practise"], + "success_criteria": ["concrete success criterion"], + "reason_for_choice": "Short German reason based on progress" }