Direkte DeepSeek- und Mistral-Anbindung mit versionierten Aktionsprofilen, Budgetreservierung, Tokenabrechnung und administrativen Qualitätsprüfungen ersetzen die Flowise-Abhängigkeit im regulären Betrieb. 840 geprüfte A1-Aufgaben mit geschützter Testauswertung und konkreten offenen Arbeitsaufträgen ergänzen den Kurs. Inhalts- und Sprachbewertung bleiben von Azure-Aussprachewerten getrennt; historische Aufgaben und Antworten bleiben erhalten. Echte Wort- und Phonemmessungen werden mit Herkunft, Aktualität und Nachweisdichte gebündelt. Go bestimmt Trainingsziele und Wiederholungen, das Modell formuliert dazu passende Nachsprechübungen. Profilansicht und Auswahlgründe werden angezeigt. Validierung: Go-Race-Tests mit lokaler PostgreSQL-Integration, go vet, Web-Build, Audit aller 840 Aufgaben und drei Browser-Smokes mit lokalen Modell-/Speech-Fixtures bestanden. Keine Produktionsänderungen oder Live-Aufrufe.
272 lines
9.9 KiB
Go
272 lines
9.9 KiB
Go
package services
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"math"
|
|
"net/http"
|
|
"reflect"
|
|
"strings"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
|
|
"speech-learning-api/internal/domain"
|
|
)
|
|
|
|
type CourseAgent interface {
|
|
Teacher(context.Context, string, any, any) error
|
|
Generate(context.Context, any) ([]domain.AdaptiveTask, error)
|
|
}
|
|
type FlowiseCourseAgent struct{ teacher *FlowiseTeacher }
|
|
|
|
func NewFlowiseCourseAgent(f *FlowiseTeacher) *FlowiseCourseAgent {
|
|
return &FlowiseCourseAgent{teacher: f}
|
|
}
|
|
func (a *FlowiseCourseAgent) Teacher(ctx context.Context, task string, input any, out any) error {
|
|
key := valueOr(a.teacher.cfg.FlowiseCourseTeacherAPIKey, a.teacher.cfg.FlowiseAPIKey)
|
|
return a.call(ctx, a.teacher.cfg.FlowiseCourseTeacher, key, task, input, out)
|
|
}
|
|
func (a *FlowiseCourseAgent) Generate(ctx context.Context, input any) ([]domain.AdaptiveTask, error) {
|
|
var out struct {
|
|
SchemaVersion int `json:"schema_version"`
|
|
Approved bool `json:"approved"`
|
|
Tasks []domain.AdaptiveTask `json:"tasks"`
|
|
ReviewNotes string `json:"review_notes"`
|
|
}
|
|
err := a.call(ctx, a.teacher.cfg.FlowiseCourseChatflow, valueOr(a.teacher.cfg.FlowiseCourseAPIKey, a.teacher.cfg.FlowiseAPIKey), "generate_course_task", input, &out)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if out.SchemaVersion != 2 || !out.Approved || len(out.Tasks) == 0 {
|
|
return nil, errors.New("course reviewer did not approve tasks")
|
|
}
|
|
return out.Tasks, nil
|
|
}
|
|
func (a *FlowiseCourseAgent) call(ctx context.Context, flow, key, task string, input, out any) error {
|
|
if flow == "" || a.teacher.cfg.FlowiseBaseURL == "" {
|
|
return errors.New("course agent is not configured")
|
|
}
|
|
payload, err := json.Marshal(map[string]any{"schema_version": 2, "task": task, "input": input})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
body, err := json.Marshal(map[string]any{"question": string(payload), "streaming": false})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(a.teacher.cfg.FlowiseBaseURL, "/")+"/api/v1/prediction/"+flow, bytes.NewReader(body))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
if key != "" {
|
|
req.Header.Set("Authorization", "Bearer "+key)
|
|
}
|
|
// The caller owns the total operation deadline, including all agent stages.
|
|
client := &http.Client{Timeout: 0, Transport: a.teacher.client.Transport}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode != http.StatusOK {
|
|
return fmt.Errorf("course agent returned HTTP %d", resp.StatusCode)
|
|
}
|
|
data, err := io.ReadAll(io.LimitReader(resp.Body, 262145))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if len(data) > 262144 {
|
|
return errors.New("course agent response exceeds 256 KiB")
|
|
}
|
|
return decodeAdaptiveOutput(data, out)
|
|
}
|
|
func decodeAdaptiveOutput(data []byte, out any) error {
|
|
var err error
|
|
data, err = courseJSONContent(data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var envelope map[string]json.RawMessage
|
|
if err = json.Unmarshal(data, &envelope); err != nil {
|
|
return errors.New("course agent did not return JSON")
|
|
}
|
|
if _, direct := envelope["schema_version"]; !direct {
|
|
var failures []string
|
|
for _, field := range []string{"json", "text", "output"} {
|
|
if raw := envelope[field]; len(raw) > 0 && string(raw) != "null" {
|
|
if err := decodeAdaptiveDocument(raw, out); err == nil {
|
|
return nil
|
|
} else {
|
|
failures = append(failures, field+": "+err.Error())
|
|
}
|
|
}
|
|
}
|
|
if len(failures) > 0 {
|
|
return errors.New(strings.Join(failures, "; "))
|
|
}
|
|
}
|
|
return decodeAdaptiveDocument(data, out)
|
|
}
|
|
func decodeAdaptiveDocument(data []byte, out any) error {
|
|
var str string
|
|
if json.Unmarshal(data, &str) == nil {
|
|
data = []byte(str)
|
|
}
|
|
var err error
|
|
data, err = courseJSONContent(data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
dec := json.NewDecoder(bytes.NewReader(data))
|
|
dec.DisallowUnknownFields()
|
|
candidate := reflect.New(reflect.TypeOf(out).Elem()).Interface()
|
|
if err := dec.Decode(candidate); err != nil {
|
|
return fmt.Errorf("invalid agent contract: %w", err)
|
|
}
|
|
if dec.Decode(new(any)) != io.EOF {
|
|
return errors.New("trailing agent content")
|
|
}
|
|
if _, ok := out.(*domain.CourseEvaluation); ok {
|
|
var fields map[string]json.RawMessage
|
|
if err := json.Unmarshal(data, &fields); err != nil || len(fields["score"]) == 0 || string(fields["score"]) == "null" {
|
|
return errors.New("evaluation score is required")
|
|
}
|
|
}
|
|
reflect.ValueOf(out).Elem().Set(reflect.ValueOf(candidate).Elem())
|
|
return nil
|
|
}
|
|
func courseText(s string, max int) bool {
|
|
return strings.TrimSpace(s) != "" && utf8.RuneCountInString(s) <= max && strings.IndexFunc(s, func(r rune) bool { return unicode.IsControl(r) && r != '\n' && r != '\r' && r != '\t' }) < 0
|
|
}
|
|
func courseMember(s string, values []string) bool {
|
|
for _, v := range values {
|
|
if s == v {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// Technical validity only. No word lists, English patterns, fixed objectives,
|
|
// fixed distractors, or linguistic judgement live in the application.
|
|
func ValidateAdaptiveTask(t domain.AdaptiveTask, language, module, skill string) error {
|
|
if !courseText(t.ModuleID, 200) || !courseText(t.TargetLanguage, 50) || t.SchemaVersion != 2 || t.TargetLanguage != language || t.CourseVersion != domain.CourseVersion || t.CEFRLevel != "A1" || t.ModuleID != module || !courseMember(t.Skill, domain.CourseSkills) || (skill != "" && t.Skill != skill) {
|
|
return errors.New("task context mismatch")
|
|
}
|
|
if !courseMember(t.Kind, []string{"choice", "short_text", "free_text", "repeat_sentence", "free_speech"}) {
|
|
return errors.New("unsupported task renderer")
|
|
}
|
|
if !courseText(t.Prompt, 2000) || utf8.RuneCountInString(t.Passage) > 10000 || utf8.RuneCountInString(t.AudioText) > 4000 || utf8.RuneCountInString(t.ReferenceText) > 500 {
|
|
return errors.New("invalid task text length")
|
|
}
|
|
if t.Skill == "listening" && !courseText(t.AudioText, 4000) {
|
|
return errors.New("listening task needs a private audio text")
|
|
}
|
|
if t.Skill == "reading" && !courseText(t.Passage, 10000) {
|
|
return errors.New("reading task needs a passage")
|
|
}
|
|
if t.Kind == "repeat_sentence" && !courseText(t.ReferenceText, 500) {
|
|
return errors.New("speaking reference is missing")
|
|
}
|
|
if t.AnswerKey == nil || len(t.AnswerKey.Rubric) < 1 || len(t.AnswerKey.Rubric) > 8 || !courseText(t.AnswerKey.Explanation, 4000) || utf8.RuneCountInString(t.AnswerKey.ReferenceAnswer) > 10000 {
|
|
return errors.New("private assessment rubric is missing")
|
|
}
|
|
for _, r := range t.AnswerKey.Rubric {
|
|
if !courseText(r, 1000) {
|
|
return errors.New("invalid rubric")
|
|
}
|
|
}
|
|
if t.Kind == "choice" {
|
|
if len(t.Options) < 2 || len(t.Options) > 6 {
|
|
return errors.New("choice task needs two to six options")
|
|
}
|
|
ids, labels := map[string]bool{}, map[string]bool{}
|
|
for _, o := range t.Options {
|
|
label := strings.ToLower(strings.Join(strings.Fields(o.Label), " "))
|
|
if !courseText(o.ID, 80) || !courseText(o.Label, 1000) || ids[o.ID] || labels[label] {
|
|
return errors.New("duplicate or invalid option")
|
|
}
|
|
ids[o.ID] = true
|
|
labels[label] = true
|
|
}
|
|
if !ids[t.AnswerKey.CorrectOptionID] {
|
|
return errors.New("solution does not refer to an option")
|
|
}
|
|
} else if len(t.Options) > 0 {
|
|
return errors.New("options require the choice renderer")
|
|
}
|
|
return nil
|
|
}
|
|
func ValidateCourseEvaluation(e domain.CourseEvaluation) error {
|
|
if math.IsNaN(e.Score) || math.IsInf(e.Score, 0) || e.Score < 0 || e.Score > 100 || !courseMember(e.Verdict, []string{"correct", "partial", "incorrect"}) || !courseText(e.Feedback, 4000) || len(e.Issues) > 12 {
|
|
return errors.New("invalid course evaluation")
|
|
}
|
|
for _, issue := range e.Issues {
|
|
if !courseText(issue, 1000) {
|
|
return errors.New("invalid course issue")
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
func ValidateCourseBrief(b domain.CourseBrief, s domain.CourseSnapshot, module, skill string) error {
|
|
if b.SchemaVersion != 2 || b.TargetLanguage != s.TargetLanguage || b.CourseVersion != s.CourseVersion || b.ModuleID != module || !courseMember(b.Skill, domain.CourseSkills) || (skill != "" && skill != b.Skill) || !courseMember(b.Kind, []string{"choice", "short_text", "free_text", "repeat_sentence", "free_speech"}) || !courseText(b.Objective, 1500) || !courseText(b.Reason, 2000) || !courseText(b.Difficulty, 200) {
|
|
return errors.New("invalid learning brief")
|
|
}
|
|
return nil
|
|
}
|
|
func ValidateCourseAnalysis(a *domain.CourseAnalysis, s domain.CourseSnapshot) error {
|
|
if a.SchemaVersion != 2 || a.TargetLanguage != s.TargetLanguage || a.CourseVersion != s.CourseVersion || !courseText(a.Summary, 6000) || len(a.Modules) > 7 {
|
|
return errors.New("invalid learning analysis")
|
|
}
|
|
modules := map[string]bool{}
|
|
evidence := map[string]string{}
|
|
coverage := map[string]map[string]bool{}
|
|
for _, m := range s.Modules {
|
|
modules[m.ID] = true
|
|
}
|
|
if !modules[a.RecommendedModuleID] {
|
|
return errors.New("analysis recommends an unknown module")
|
|
}
|
|
for _, p := range s.Progress {
|
|
if p.EvidenceID != "" {
|
|
evidence[p.EvidenceID] = p.ModuleID
|
|
}
|
|
if coverage[p.ModuleID] == nil {
|
|
coverage[p.ModuleID] = map[string]bool{}
|
|
}
|
|
if p.Attempts > 0 && p.EvidenceID != "" && courseMember(p.Skill, domain.CourseSkills) {
|
|
coverage[p.ModuleID][p.Skill] = true
|
|
}
|
|
}
|
|
for _, attempt := range s.RecentAttempts {
|
|
evidence[attempt.ID] = attempt.ModuleID
|
|
}
|
|
seen := map[string]bool{}
|
|
for i, m := range a.Modules {
|
|
if !modules[m.ModuleID] || seen[m.ModuleID] || !courseText(m.Reason, 2000) || !courseText(m.Recommendation, 2000) || len(m.EvidenceIDs) > 30 || len(m.Strengths) > 12 || len(m.Weaknesses) > 12 {
|
|
return errors.New("invalid module analysis")
|
|
}
|
|
seen[m.ModuleID] = true
|
|
for _, id := range m.EvidenceIDs {
|
|
if evidence[id] != m.ModuleID {
|
|
return errors.New("analysis cites unavailable evidence")
|
|
}
|
|
}
|
|
for _, value := range append(append([]string{}, m.Strengths...), m.Weaknesses...) {
|
|
if !courseText(value, 1000) {
|
|
return errors.New("invalid analysis text")
|
|
}
|
|
}
|
|
if len(coverage[m.ModuleID]) < 6 {
|
|
a.Modules[i].ReadyForCompletion = false
|
|
}
|
|
}
|
|
a.FactsVersion = s.FactsVersion
|
|
return nil
|
|
}
|