Coverage for /home/admin/Documents/AI/applications/lexigram-dev/lexigram/experimental/ai/lexigram-ai-rag/src/lexigram/ai/rag/reasoning/parsers.py: 87%
31 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-25 07:19 +0800
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-25 07:19 +0800
1from __future__ import annotations
3from typing import Any
6def parse_reasoning_response_text(text: str) -> dict[str, Any]:
7 """Parse a reasoning response text into structured parts.
9 Expected keys in text: REASONING:, ANSWER:, CONFIDENCE:, IS_FINAL:, NEXT_QUESTION:
10 """
11 result: dict[str, Any] = {
12 "reasoning": "",
13 "answer": "",
14 "confidence": 0.5,
15 "is_final": False,
16 "next_question": None,
17 }
19 lines = text.strip().split("\n")
20 current_key: str | None = None
22 for raw_line in lines:
23 line = raw_line.strip()
24 if not line:
25 continue
27 if line.startswith("REASONING:"):
28 current_key = "reasoning"
29 result[current_key] = line.replace("REASONING:", "").strip()
30 elif line.startswith("ANSWER:"):
31 current_key = "answer"
32 result[current_key] = line.replace("ANSWER:", "").strip()
33 elif line.startswith("CONFIDENCE:"):
34 try:
35 conf_str = line.replace("CONFIDENCE:", "").strip()
36 result["confidence"] = float(conf_str)
37 except ValueError:
38 result["confidence"] = 0.5
39 elif line.startswith("IS_FINAL:"):
40 is_final_str = line.replace("IS_FINAL:", "").strip().lower()
41 result["is_final"] = is_final_str in ("yes", "true", "1")
42 elif line.startswith("NEXT_QUESTION:"):
43 current_key = "next_question"
44 result[current_key] = line.replace("NEXT_QUESTION:", "").strip()
45 elif current_key is not None and line:
46 result[current_key] = (
47 (result[current_key] + " " + line)
48 if isinstance(result[current_key], str)
49 else line
50 )
52 return result