Enhance exercise_ai and openrouter_chat modules with AI debugging and improved content handling
Test Suite / lint-backend (push) Waiting to run
Test Suite / build-frontend (push) Waiting to run
Test Suite / k6 /health Baseline (push) Waiting to run
Test Suite / playwright-tests (push) Waiting to run
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Has been cancelled
Test Suite / lint-backend (push) Waiting to run
Test Suite / build-frontend (push) Waiting to run
Test Suite / k6 /health Baseline (push) Waiting to run
Test Suite / playwright-tests (push) Waiting to run
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Has been cancelled
- Introduced detailed logging for AI operations in the `exercise_ai` and `openrouter_chat` modules, activated by the `SHINKAN_AI_DEBUG` environment variable, to aid in debugging and performance monitoring. - Updated the `run_exercise_ai_suggestion` function to log prompt lengths, response sizes, and JSON parsing errors, enhancing transparency in AI interactions. - Improved the `_flatten_message_content` function to handle nested content structures more effectively, ensuring compatibility with various AI response formats. - Incremented the application version to 0.8.157 and updated the changelog to reflect these enhancements, including new logging features and content handling improvements.
This commit is contained in:
1 parent
a28a9d399a
commit
1942585546
5 files changed
+169
-39
No files matched your search
@@ -8,7 +8,9 @@ from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
from typing import Any, Dict, List, Mapping, MutableMapping, Optional, Sequence, Tuple
|
||||
|
||||
@@ -16,6 +18,13 @@ from fastapi import HTTPException
|
||||
|
||||
from openrouter_chat import OpenRouterError, normalize_openrouter_env, openrouter_chat_completion
|
||||
|
||||
_LOGGER = logging.getLogger("shinkan.exercise_ai")
|
||||
|
||||
|
||||
def _ai_debug_on() -> bool:
|
||||
return os.getenv("SHINKAN_AI_DEBUG", "").strip().lower() in ("1", "true", "yes", "full")
|
||||
|
||||
|
||||
_CANONICAL_SKILL_LEVELS = frozenset({"basis", "grundlagen", "aufbau", "fortgeschritten", "optimierung"})
|
||||
_LEGACY_SKILL_LEVEL_SLUG = {
|
||||
"einsteiger": "basis",
|
||||
@@ -672,6 +681,20 @@ def run_exercise_ai_suggestion(
|
||||
|
||||
result: Dict[str, Any] = {"model": model}
|
||||
|
||||
if _ai_debug_on():
|
||||
fid_list = ",".join(str(x) for x in _ordered_focus_ids(focus_areas_context))
|
||||
_LOGGER.warning(
|
||||
"AI_DEBUG exercise_ai suggest want_summary=%s want_skills=%s title_chars=%s goal_plain_chars=%s "
|
||||
"exec_plain_chars=%s focus_hint_chars=%s focus_ctx_ids=[%s]",
|
||||
want_summary,
|
||||
want_skills,
|
||||
len(t_title),
|
||||
len(g_plain),
|
||||
len(e_plain),
|
||||
len(focus),
|
||||
fid_list,
|
||||
)
|
||||
|
||||
if want_summary:
|
||||
prow = _load_prompt_row(cur, "exercise_summary")
|
||||
if not prow:
|
||||
@@ -683,10 +706,18 @@ def run_exercise_ai_suggestion(
|
||||
"exercise_execution": e_plain or "-",
|
||||
}
|
||||
prompt = _render_template(str(prow["template"]), ctx)
|
||||
if _ai_debug_on():
|
||||
_LOGGER.warning(
|
||||
"AI_DEBUG exercise_ai summary prompt_slug=exercise_summary prompt_chars=%s unreplaced_mustache_pairs=%s",
|
||||
len(prompt),
|
||||
prompt.count("{{"),
|
||||
)
|
||||
try:
|
||||
raw = openrouter_chat_completion(api_key=key, model=model, user_content=prompt)
|
||||
except OpenRouterError as e:
|
||||
raise HTTPException(status_code=502, detail=f"OpenRouter: {e}") from e
|
||||
if _ai_debug_on():
|
||||
_LOGGER.warning("AI_DEBUG exercise_ai summary response_chars=%s", len(raw or ""))
|
||||
text = (raw or "").strip()
|
||||
if not text:
|
||||
raise HTTPException(
|
||||
@@ -720,6 +751,14 @@ def run_exercise_ai_suggestion(
|
||||
"skills_catalog": catalog,
|
||||
}
|
||||
prompt = _render_template(str(srow["template"]), ctx)
|
||||
if _ai_debug_on():
|
||||
_LOGGER.warning(
|
||||
"AI_DEBUG exercise_ai skills prompt_slug=exercise_skill_suggestions catalog_chars=%s prompt_chars=%s "
|
||||
"template_has_skills_placeholder=%s",
|
||||
len(catalog),
|
||||
len(prompt),
|
||||
"{{skills_catalog}}" in str(srow.get("template") or ""),
|
||||
)
|
||||
sys_hint = (
|
||||
"Du antwortest nur mit validem JSON (Array). Keine Kommentare, keine Erklaerungen ausserhalb des JSON."
|
||||
)
|
||||
@@ -733,6 +772,8 @@ def run_exercise_ai_suggestion(
|
||||
)
|
||||
except OpenRouterError as e:
|
||||
raise HTTPException(status_code=502, detail=f"OpenRouter: {e}") from e
|
||||
if _ai_debug_on():
|
||||
_LOGGER.warning("AI_DEBUG exercise_ai skills response_chars=%s", len(raw or ""))
|
||||
body = (raw or "").strip()
|
||||
if not body:
|
||||
raise HTTPException(
|
||||
@@ -745,11 +786,21 @@ def run_exercise_ai_suggestion(
|
||||
try:
|
||||
parsed = _extract_json_array(body)
|
||||
except (json.JSONDecodeError, ValueError) as e:
|
||||
if _ai_debug_on():
|
||||
_LOGGER.warning(
|
||||
"AI_DEBUG exercise_ai skills JSON parse_failed err=%s head=%s",
|
||||
e,
|
||||
(body.replace("\r", "").replace("\n", " ").strip())[:400],
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail="KI lieferte kein verwertbares JSON fuer Skills.",
|
||||
) from e
|
||||
skills = _sanitize_skill_entries(cur, parsed)
|
||||
if _ai_debug_on():
|
||||
cand_n = len(parsed) if isinstance(parsed, list) else -1
|
||||
_LOGGER.warning("AI_DEBUG exercise_ai skills parsed_len=%s sanitized_kept=%s", cand_n, len(skills))
|
||||
|
||||
result["skills"] = skills
|
||||
|
||||
return result
|
||||
|
||||
Reference in new issue
Block a user