Enhance exercise_ai and openrouter_chat modules with improved JSON handling and error management
Deploy Development / deploy (push) Successful in 42s
Test Suite / pytest-backend (push) Successful in 38s
Test Suite / lint-backend (push) Successful in 0s
Test Suite / build-frontend (push) Successful in 13s
Test Suite / k6 /health Baseline (push) Successful in 33s
Test Suite / playwright-tests (push) Successful in 1m18s

- Added a new function `_first_balanced_json_array` to extract the first complete top-level JSON array from arbitrary text, enhancing robustness in parsing.
- Updated the `run_exercise_ai_suggestion` function to raise clear HTTP exceptions for empty responses from the OpenRouter, ensuring better error handling.
- Introduced `_flatten_message_content` in the `openrouter_chat` module to handle structured message content from OpenAI, improving compatibility with various content formats.
- Incremented the application version to 0.8.156 and updated the changelog to reflect these enhancements, including improved error messages and JSON parsing capabilities.
This commit is contained in:
Lars committed 2026-05-22 10:09:07 +02:00
1 parent 9be69ace5c
commit a28a9d399a
5 files changed
+427 -67

No files matched your search

+45 -1
View File
@@ -505,6 +505,36 @@ def _render_template(template: str, ctx: Dict[str, str]) -> str:
return out
def _first_balanced_json_array(text: str) -> Optional[str]:
"""Findet das erste vollständig geschlossene Top-Level-JSON-Array in beliebigem Fließtext."""
i = text.find("[")
if i < 0:
return None
depth = 0
in_str = False
esc = False
for j in range(i, len(text)):
ch = text[j]
if in_str:
if esc:
esc = False
elif ch == "\\":
esc = True
elif ch == '"':
in_str = False
continue
if ch == '"':
in_str = True
continue
if ch == "[":
depth += 1
elif ch == "]":
depth -= 1
if depth == 0:
return text[i : j + 1]
return None
def _extract_json_array(text: str) -> Any:
s = text.strip()
if s.startswith("```"):
@@ -658,6 +688,11 @@ def run_exercise_ai_suggestion(
except OpenRouterError as e:
raise HTTPException(status_code=502, detail=f"OpenRouter: {e}") from e
text = (raw or "").strip()
if not text:
raise HTTPException(
status_code=502,
detail="OpenRouter/KI lieferte eine leere Kurzfassung (kein Modelltext).",
)
if len(text) > _MAX_SUMMARY_CHARS:
text = text[: _MAX_SUMMARY_CHARS - 1].rstrip() + "…"
result["summary"] = {"text": text, "ai_generated": True, "model": model}
@@ -698,8 +733,17 @@ def run_exercise_ai_suggestion(
)
except OpenRouterError as e:
raise HTTPException(status_code=502, detail=f"OpenRouter: {e}") from e
body = (raw or "").strip()
if not body:
raise HTTPException(
status_code=502,
detail="OpenRouter/KI lieferte leeren Inhalt für Skill-JSON.",
)
frag = _first_balanced_json_array(body)
if frag:
body = frag
try:
parsed = _extract_json_array(raw)
parsed = _extract_json_array(body)
except (json.JSONDecodeError, ValueError) as e:
raise HTTPException(
status_code=502,