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
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:
1 parent
9be69ace5c
commit
a28a9d399a
5 files changed
+427
-67
No files matched your search
+45
-1
@@ -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,
|
||||
|
||||
@@ -10,6 +10,41 @@ from typing import Any, Dict, List, Optional
|
||||
import httpx
|
||||
|
||||
|
||||
def _flatten_message_content(content: Any) -> str:
|
||||
"""
|
||||
OpenAI-kompatibles Chat-Completion kann `content` als String oder als Liste
|
||||
strukturierter Blöcke liefern (z. B. Anthropic über OpenRouter/Bedrock).
|
||||
"""
|
||||
if content is None:
|
||||
return ""
|
||||
if isinstance(content, str):
|
||||
return content.strip()
|
||||
if isinstance(content, list):
|
||||
parts: List[str] = []
|
||||
for block in content:
|
||||
if isinstance(block, str):
|
||||
parts.append(block)
|
||||
elif isinstance(block, dict):
|
||||
t = block.get("type")
|
||||
txt = block.get("text")
|
||||
if txt is None and t == "text":
|
||||
txt = block.get("content")
|
||||
if isinstance(txt, str):
|
||||
parts.append(txt)
|
||||
elif txt is not None:
|
||||
parts.append(str(txt))
|
||||
return "".join(parts).strip()
|
||||
if isinstance(content, dict):
|
||||
txt = content.get("text")
|
||||
if txt is None:
|
||||
txt = content.get("content")
|
||||
if isinstance(txt, str):
|
||||
return txt.strip()
|
||||
if isinstance(txt, list):
|
||||
return _flatten_message_content(txt)
|
||||
return str(content).strip()
|
||||
|
||||
|
||||
class OpenRouterError(Exception):
|
||||
"""Upstream or transport failure."""
|
||||
|
||||
@@ -83,14 +118,17 @@ def openrouter_chat_completion(
|
||||
|
||||
msg0 = choices[0] if choices else {}
|
||||
inner = msg0.get("message") if isinstance(msg0, dict) else None
|
||||
content = ""
|
||||
raw: Any = None
|
||||
if isinstance(inner, dict):
|
||||
content = str(inner.get("content") or "")
|
||||
raw = inner.get("content")
|
||||
if raw is None and inner.get("refusal") is not None:
|
||||
raw = inner.get("refusal")
|
||||
elif isinstance(inner, str):
|
||||
content = inner
|
||||
elif isinstance(msg0.get("content"), str):
|
||||
content = msg0.get("content") or ""
|
||||
raw = inner
|
||||
if raw is None and isinstance(msg0, dict):
|
||||
raw = msg0.get("content")
|
||||
|
||||
content = _flatten_message_content(raw)
|
||||
return content.strip()
|
||||
|
||||
|
||||
|
||||
+12
-3
@@ -1,7 +1,7 @@
|
||||
# Shinkan Jinkendo Version Information
|
||||
|
||||
APP_VERSION = "0.8.155"
|
||||
BUILD_DATE = "2026-05-29"
|
||||
APP_VERSION = "0.8.156"
|
||||
BUILD_DATE = "2026-05-22"
|
||||
DB_SCHEMA_VERSION = "20260529068"
|
||||
|
||||
MODULE_VERSIONS = {
|
||||
@@ -23,7 +23,7 @@ MODULE_VERSIONS = {
|
||||
"skills": "0.1.1", # DB 065 karate_relevance + relevance_level; CRUD unterstützt Felder
|
||||
"skill_profiles": "1.0.0", # Phase 3: gewichtetes Fähigkeiten-Profil + skill-discovery/suggestions
|
||||
"methods": "0.1.0",
|
||||
"exercises": "2.30.1", # exercise_ai: Skills-JSON max. 250 Eintraege, Sanitize bricht nach 5 gueltigen ab (Performance)
|
||||
"exercises": "2.30.2", # OpenRouter strukturierte content-Bloecke (Claude4/Bedrock); exercise_ai Robustheit + klare 502 wenn leeres Modell JSON; Retrieval-Admin Formular Gewichte/Unterkategorien
|
||||
"training_units": "0.4.0", # POST .../publish-to-framework: Ablauf aus geplanter Einheit → Rahmen-Slot-Blueprint
|
||||
"training_programs": "0.1.0",
|
||||
"planning": "0.15.0", # Vorlagen: Strukturvorschau, Bearbeiten inkl. Split-Sessions + Beschreibung
|
||||
@@ -38,6 +38,15 @@ MODULE_VERSIONS = {
|
||||
}
|
||||
|
||||
CHANGELOG = [
|
||||
{
|
||||
"version": "0.8.156",
|
||||
"date": "2026-05-22",
|
||||
"changes": [
|
||||
"OpenRouter Client: Assistant-Content als Liste/Bloecke (Claude über Bedrock/OpenRouter)",
|
||||
"exercise_ai: leere Modelantwort als 502; Skill-JSON aus Fließtext per balanciertem Array-Zuschnitt robuster parsen",
|
||||
"Admin Retrieval-Profil: Gewichte/Unterkategorien per Formular ohne JSON-Editor",
|
||||
],
|
||||
},
|
||||
{
|
||||
"version": "0.8.155",
|
||||
"date": "2026-05-29",
|
||||
|
||||
Reference in new issue
Block a user