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

+43 -5
View File
@@ -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()