diff --git a/src/services/kiaai/chat.py b/src/services/kiaai/chat.py index 50136ea..bbb8c2c 100644 --- a/src/services/kiaai/chat.py +++ b/src/services/kiaai/chat.py @@ -1,3 +1,4 @@ +import json import httpx from langchain_core.messages import ( AIMessage, @@ -75,9 +76,28 @@ class KiaAIService: print(f"[KiaAI] HTTP {resp.status_code}") resp.raise_for_status() - data = resp.json() + raw_text = resp.text - print(f"[KiaAI] Raw response keys: {list(data.keys())}") + print(f"[KiaAI] Raw response text:\n{raw_text}\n---") + + # KIA may return NDJSON (multiple JSON lines) instead of a single JSON object. + # We pick the last non-empty line that contains "choices" as the final completion chunk. + data = None + lines = [line.strip() for line in raw_text.strip().splitlines() if line.strip()] + for line in reversed(lines): + try: + candidate = json.loads(line) + if "choices" in candidate and candidate["choices"]: + data = candidate + break + except json.JSONDecodeError: + continue + + if data is None: + # Fallback: try parsing the whole text as one JSON + data = json.loads(raw_text) + + print(f"[KiaAI] Parsed response keys: {list(data.keys())}") content = data["choices"][0]["message"]["content"] usage = data.get("usage") or {}