Refactor Planning Exercise Suggestion and Enhance LLM Integration
Deploy Development / deploy (push) Successful in 45s
Test Suite / pytest-backend (push) Successful in 40s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 34s
Test Suite / playwright-tests (push) Successful in 1m16s

- Replaced the previous exercise matching logic with a new multistage planning retrieval process, improving the accuracy of exercise suggestions.
- Introduced LLM gates to limit LLM calls based on query length and intent application, optimizing performance and resource usage.
- Updated the `compose_retrieval_phase` function to include profile preselection, enhancing the retrieval process.
- Incremented version to 0.5.0 and updated changelog to reflect these significant enhancements in planning AI capabilities.
This commit is contained in:
Lars committed 2026-05-22 22:56:28 +02:00
1 parent b0611b9f7f
commit 8e68261bc1
6 files changed
+756 -275

No files matched your search

+191 -105
View File
@@ -29,6 +29,9 @@ import {
const PAGE_SIZE = 100
/** Backend POST /api/planning/exercise-suggest erlaubt max. 50 */
const PLANNING_SUGGEST_LIMIT = 50
/** Client-Hinweis — Backend entscheidet final über LLM-Gates (max. 1 Call). */
const PLANNING_LLM_INTENT_MIN_CHARS = 10
const PLANNING_LLM_RANK_MIN_CHARS = 24
const LEVEL_FILTER_OPTS = SKILL_LEVEL_OPTIONS.filter((o) => o.level != null)
const INITIAL_FILTERS = { ...INITIAL_EXERCISE_LIST_FILTERS }
@@ -79,8 +82,13 @@ export default function ExercisePickerModal({
const [planningContextSummary, setPlanningContextSummary] = useState(null)
const [planningTargetProfileSummary, setPlanningTargetProfileSummary] = useState(null)
const [planningLlmRankApplied, setPlanningLlmRankApplied] = useState(false)
const [planningLlmIntentApplied, setPlanningLlmIntentApplied] = useState(false)
const [planningRetrievalPhase, setPlanningRetrievalPhase] = useState('')
const [planningQueryIntentSummary, setPlanningQueryIntentSummary] = useState(null)
const [planningIntentResolved, setPlanningIntentResolved] = useState(null)
const [planningHasSearched, setPlanningHasSearched] = useState(false)
const [planningSubmittedQuery, setPlanningSubmittedQuery] = useState('')
const [planningSearchTick, setPlanningSearchTick] = useState(0)
const pickerScrollRef = useRef(null)
const resolvedPlanningUnitId = useMemo(() => {
@@ -124,13 +132,24 @@ export default function ExercisePickerModal({
!enableFreePlanningSearch
)
/** Gemeinsamer Suchtext — in Planung nur ein Feld; in Bibliothek beide Felder kombiniert. */
/** Gemeinsamer Suchtext — Planung: nur nach Button; Bibliothek: debounced live. */
const effectivePickerQuery = useMemo(() => {
if (usePlanningSearch) {
return (debouncedSearch || debouncedAi).trim()
return planningSubmittedQuery
}
return [debouncedSearch, debouncedAi].filter(Boolean).join(' ').trim()
}, [usePlanningSearch, debouncedSearch, debouncedAi])
}, [usePlanningSearch, planningSubmittedQuery, debouncedSearch, debouncedAi])
const submitPlanningSearch = useCallback((queryOverride) => {
const q =
queryOverride !== undefined && queryOverride !== null
? String(queryOverride).trim()
: (searchInput || aiSearchInput).trim()
setPlanningSubmittedQuery(q)
setPlanningHasSearched(true)
setList([])
setPlanningSearchTick((t) => t + 1)
}, [searchInput, aiSearchInput])
const {
title: quickTitle,
@@ -163,7 +182,8 @@ export default function ExercisePickerModal({
catalogsReady &&
!loading &&
list.length === 0 &&
(usePlanningSearch || effectivePickerQuery.length >= 3)
planningHasSearched &&
(usePlanningSearch ? true : effectivePickerQuery.length >= 3)
useEffect(() => {
if (!open) return
@@ -215,8 +235,13 @@ export default function ExercisePickerModal({
setPlanningContextSummary(null)
setPlanningTargetProfileSummary(null)
setPlanningLlmRankApplied(false)
setPlanningLlmIntentApplied(false)
setPlanningRetrievalPhase('')
setPlanningQueryIntentSummary(null)
setPlanningIntentResolved(null)
setPlanningHasSearched(false)
setPlanningSubmittedQuery('')
setPlanningSearchTick(0)
return
}
setFilters(mergeExerciseListPrefsFromApi(user?.exercise_list_prefs))
@@ -311,14 +336,46 @@ export default function ExercisePickerModal({
return q
}, [filters, effectivePickerQuery, exerciseKindAny])
const reload = useCallback(async () => {
if (!open || !catalogsReady) return
if (planningSearchBlocked) {
const reloadLibrary = useCallback(async () => {
if (!open || !catalogsReady || usePlanningSearch) return
setLoading(true)
try {
setPlanningContextSummary(null)
setPlanningTargetProfileSummary(null)
setPlanningLlmRankApplied(false)
setPlanningLlmIntentApplied(false)
setPlanningRetrievalPhase('')
setPlanningQueryIntentSummary(null)
setPlanningIntentResolved(null)
const batch = await api.listExercises({
...queryBase,
include_archived: true,
include_variants: true,
limit: PAGE_SIZE,
offset: 0,
})
setList(Array.isArray(batch) ? batch : [])
setHasMore(batch?.length === PAGE_SIZE)
} catch (e) {
console.error(e)
alert(e.message || 'Laden fehlgeschlagen')
setList([])
setHasMore(false)
} finally {
setLoading(false)
}
}, [open, catalogsReady, usePlanningSearch, queryBase])
const reloadPlanning = useCallback(async () => {
if (!open || !catalogsReady || !usePlanningSearch || planningSearchTick === 0) return
if (planningSearchBlocked || !activePlanningContext) {
setList([])
setHasMore(false)
setPlanningContextSummary(null)
setPlanningTargetProfileSummary(null)
setPlanningLlmRankApplied(false)
setPlanningLlmIntentApplied(false)
setPlanningRetrievalPhase('')
setPlanningQueryIntentSummary(null)
setPlanningIntentResolved(null)
setLoading(false)
@@ -326,83 +383,69 @@ export default function ExercisePickerModal({
}
setLoading(true)
try {
if (usePlanningSearch && activePlanningContext) {
const query = effectivePickerQuery
const requestBody = {
section_order_index:
activePlanningContext.sectionOrderIndex != null
? Number(activePlanningContext.sectionOrderIndex)
: null,
phase_order_index:
activePlanningContext.phaseOrderIndex != null
? Number(activePlanningContext.phaseOrderIndex)
: null,
parallel_stream_order_index:
activePlanningContext.parallelStreamOrderIndex != null
? Number(activePlanningContext.parallelStreamOrderIndex)
: null,
anchor_exercise_id:
activePlanningContext.anchorExerciseId != null
? Number(activePlanningContext.anchorExerciseId)
: null,
progression_graph_id:
activePlanningContext.progressionGraphId != null
? Number(activePlanningContext.progressionGraphId)
: null,
planned_exercise_ids:
Array.isArray(activePlanningContext.plannedExerciseIds) &&
activePlanningContext.plannedExerciseIds.length > 0
? activePlanningContext.plannedExerciseIds
.map((x) => Number(x))
.filter((x) => Number.isFinite(x) && x > 0)
: undefined,
include_llm_intent: Boolean(query),
include_llm_rank: Boolean(query),
query,
intent_hint: activePlanningContext.intentHint || (useFreePlanningSearch && query ? 'free_search' : null),
limit: PLANNING_SUGGEST_LIMIT,
exercise_kind_any:
Array.isArray(exerciseKindAny) && exerciseKindAny.length > 0 ? exerciseKindAny : undefined,
}
if (resolvedPlanningUnitId) {
requestBody.unit_id = Number(resolvedPlanningUnitId)
}
if (activePlanningContext.groupId) {
requestBody.group_id = Number(activePlanningContext.groupId)
}
const res = await api.suggestPlanningExercises(requestBody)
setPlanningContextSummary(res?.context_summary || null)
setPlanningTargetProfileSummary(res?.target_profile_summary || null)
setPlanningLlmRankApplied(Boolean(res?.llm_rank_applied))
setPlanningQueryIntentSummary(res?.query_intent_summary || null)
setPlanningIntentResolved(res?.intent_resolved || null)
const hits = (Array.isArray(res?.hits) ? res.hits : []).map((h) => ({
id: h.id,
title: h.title,
summary: h.summary,
focus_area: h.focus_area,
_planningScore: h.score,
_planningReasons: Array.isArray(h.reasons) ? h.reasons : [],
updated_at: new Date().toISOString(),
}))
setList(hits)
setHasMore(false)
} else {
setPlanningContextSummary(null)
setPlanningTargetProfileSummary(null)
setPlanningLlmRankApplied(false)
setPlanningQueryIntentSummary(null)
setPlanningIntentResolved(null)
const batch = await api.listExercises({
...queryBase,
include_archived: true,
include_variants: true,
limit: PAGE_SIZE,
offset: 0,
})
setList(Array.isArray(batch) ? batch : [])
setHasMore(batch?.length === PAGE_SIZE)
const query = planningSubmittedQuery
const requestBody = {
section_order_index:
activePlanningContext.sectionOrderIndex != null
? Number(activePlanningContext.sectionOrderIndex)
: null,
phase_order_index:
activePlanningContext.phaseOrderIndex != null
? Number(activePlanningContext.phaseOrderIndex)
: null,
parallel_stream_order_index:
activePlanningContext.parallelStreamOrderIndex != null
? Number(activePlanningContext.parallelStreamOrderIndex)
: null,
anchor_exercise_id:
activePlanningContext.anchorExerciseId != null
? Number(activePlanningContext.anchorExerciseId)
: null,
progression_graph_id:
activePlanningContext.progressionGraphId != null
? Number(activePlanningContext.progressionGraphId)
: null,
planned_exercise_ids:
Array.isArray(activePlanningContext.plannedExerciseIds) &&
activePlanningContext.plannedExerciseIds.length > 0
? activePlanningContext.plannedExerciseIds
.map((x) => Number(x))
.filter((x) => Number.isFinite(x) && x > 0)
: undefined,
include_llm_intent: query.length >= PLANNING_LLM_INTENT_MIN_CHARS,
include_llm_rank: query.length >= PLANNING_LLM_RANK_MIN_CHARS,
query,
intent_hint:
activePlanningContext.intentHint || (useFreePlanningSearch && query ? 'free_search' : null),
limit: PLANNING_SUGGEST_LIMIT,
exercise_kind_any:
Array.isArray(exerciseKindAny) && exerciseKindAny.length > 0 ? exerciseKindAny : undefined,
}
if (resolvedPlanningUnitId) {
requestBody.unit_id = Number(resolvedPlanningUnitId)
}
if (activePlanningContext.groupId) {
requestBody.group_id = Number(activePlanningContext.groupId)
}
const res = await api.suggestPlanningExercises(requestBody)
setPlanningContextSummary(res?.context_summary || null)
setPlanningTargetProfileSummary(res?.target_profile_summary || null)
setPlanningLlmRankApplied(Boolean(res?.llm_rank_applied))
setPlanningLlmIntentApplied(Boolean(res?.llm_intent_applied))
setPlanningRetrievalPhase(res?.retrieval_phase || '')
setPlanningQueryIntentSummary(res?.query_intent_summary || null)
setPlanningIntentResolved(res?.intent_resolved || null)
const hits = (Array.isArray(res?.hits) ? res.hits : []).map((h) => ({
id: h.id,
title: h.title,
summary: h.summary,
focus_area: h.focus_area,
_planningScore: h.score,
_planningReasons: Array.isArray(h.reasons) ? h.reasons : [],
updated_at: new Date().toISOString(),
}))
setList(hits)
setHasMore(false)
} catch (e) {
console.error(e)
alert(e.message || 'Laden fehlgeschlagen')
@@ -411,6 +454,8 @@ export default function ExercisePickerModal({
setPlanningContextSummary(null)
setPlanningTargetProfileSummary(null)
setPlanningLlmRankApplied(false)
setPlanningLlmIntentApplied(false)
setPlanningRetrievalPhase('')
setPlanningQueryIntentSummary(null)
setPlanningIntentResolved(null)
} finally {
@@ -419,19 +464,23 @@ export default function ExercisePickerModal({
}, [
open,
catalogsReady,
queryBase,
usePlanningSearch,
planningSearchTick,
planningSearchBlocked,
activePlanningContext,
effectivePickerQuery,
planningSubmittedQuery,
exerciseKindAny,
resolvedPlanningUnitId,
useFreePlanningSearch,
])
useEffect(() => {
reload()
}, [reload])
reloadLibrary()
}, [reloadLibrary])
useEffect(() => {
reloadPlanning()
}, [reloadPlanning])
const loadMore = async () => {
if (!hasMore || loadingMore || loading) return
@@ -655,7 +704,11 @@ export default function ExercisePickerModal({
? ` · ${String(planningQueryIntentSummary.scenario).replace(/_/g, ' ')}`
: null}
{planningLlmRankApplied ? ' · KI-Ranking aktiv' : null}
{planningQueryIntentSummary?.llm_applied ? ' · KI-Intent aktiv' : null}
{planningLlmIntentApplied ? ' · KI-Intent aktiv' : null}
{!planningLlmRankApplied && !planningLlmIntentApplied && usePlanningSearch
? ' · ohne LLM (Profil/Hybrid)'
: null}
{planningRetrievalPhase ? ` · ${planningRetrievalPhase}` : null}
</p>
) : null}
</div>
@@ -729,20 +782,51 @@ export default function ExercisePickerModal({
{usePlanningSearch ? (
<div>
<label className="form-label">Planungs-Anfrage (KI)</label>
<input
type="search"
className="form-input"
placeholder="z. B. Schlage mir die nächste Übung vor, baut auf dem Plan auf und trainiert Schnellkraft …"
value={searchInput || aiSearchInput}
onChange={(e) => {
const v = e.target.value
setSearchInput(v)
setAiSearchInput(v)
}}
autoComplete="off"
/>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '0.5rem', alignItems: 'stretch' }}>
<input
type="text"
className="form-input"
style={{ flex: '1 1 220px', minWidth: 0 }}
placeholder="z. B. Vertiefung Reaktion mit Partner, baut auf dem Plan auf …"
value={searchInput || aiSearchInput}
onChange={(e) => {
const v = e.target.value
setSearchInput(v)
setAiSearchInput(v)
}}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
submitPlanningSearch()
}
}}
autoComplete="off"
/>
<button
type="button"
className="btn btn-primary"
disabled={loading || planningSearchBlocked}
onClick={() => submitPlanningSearch()}
>
{loading ? 'Suche …' : 'Vorschläge laden'}
</button>
<button
type="button"
className="btn btn-secondary"
disabled={loading || planningSearchBlocked}
title="Leere Anfrage — nur Planungskontext (Anker, Plan, Profil), ohne LLM"
onClick={() => {
setSearchInput('')
setAiSearchInput('')
submitPlanningSearch('')
}}
>
Nächste aus Kontext
</button>
</div>
<p style={{ margin: '4px 0 0', fontSize: '11px', color: 'var(--text3)' }}>
Leer lassen = nächste Übung aus Planungskontext. Mit Text = KI-Intent + Profil + Ranking.
Suche startet erst per Button (oder Enter) — nicht beim Tippen. LLM nur bei längeren Anfragen,
maximal ein KI-Call pro Suche.
</p>
</div>
) : (
@@ -943,11 +1027,13 @@ export default function ExercisePickerModal({
onRunAi={runQuickCreateAiSuggest}
/>
) : (
<p style={{ color: 'var(--text2)', textAlign: 'center' }}>
<p style={{ color: 'var(--text2)', textAlign: 'center', lineHeight: 1.5 }}>
{usePlanningSearch
? effectivePickerQuery
? 'Keine KI-Vorschläge für diese Anfrage.'
: 'Keine Vorschläge — Einheit speichern und Planungskontext prüfen, oder Anfrage eingeben.'
? !planningHasSearched
? 'Anfrage formulieren und „Vorschläge laden“ klicken — oder „Nächste aus Kontext“ ohne Freitext.'
: effectivePickerQuery
? 'Keine KI-Vorschläge für diese Anfrage.'
: 'Keine Vorschläge aus dem Planungskontext — Anker, Plan oder Profil prüfen.'
: effectivePickerQuery.length >= 3
? 'Keine Treffer.'
: 'Suchbegriff eingeben (mind. 3 Zeichen) …'}