änderungen von vorherigen Codexnutzung: sollte den Agent lassen die Aufgaben zu erzeugen
This commit is contained in:
@@ -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"`
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -30,6 +30,7 @@ export type Exercise = {
|
||||
prompt_text: string;
|
||||
target_text: string;
|
||||
difficulty: number;
|
||||
source?: 'seed' | 'flowise' | 'fallback' | string;
|
||||
};
|
||||
|
||||
export type WordScore = {
|
||||
|
||||
Reference in New Issue
Block a user