MCPcopy Create free account
hub / github.com/BeingBeyond/BeTTER / extract_json_object_text

Function extract_json_object_text

src/task/specs/task_draft_model.py:106–143  ·  view source on GitHub ↗
(text: str)

Source from the content-addressed store, hash-verified

104
105
106def extract_json_object_text(text: str) -> str:
107 stripped = text.strip()
108 if stripped.startswith("```"):
109 lines = stripped.splitlines()
110 if len(lines) >= 3 and lines[-1].strip() == "```":
111 stripped = "\n".join(lines[1:-1]).strip()
112 if stripped.startswith("json"):
113 stripped = stripped[4:].lstrip()
114 if stripped.startswith("{") and stripped.endswith("}"):
115 return stripped
116
117 start = stripped.find("{")
118 if start < 0:
119 raise ValueError("Model response does not contain a JSON object.")
120
121 depth = 0
122 in_string = False
123 escape = False
124 for index in range(start, len(stripped)):
125 char = stripped[index]
126 if in_string:
127 if escape:
128 escape = False
129 elif char == "\\":
130 escape = True
131 elif char == '"':
132 in_string = False
133 continue
134 if char == '"':
135 in_string = True
136 elif char == "{":
137 depth += 1
138 elif char == "}":
139 depth -= 1
140 if depth == 0:
141 return stripped[start : index + 1]
142
143 raise ValueError("Model response does not contain a complete JSON object.")
144
145
146

Callers 1

generate_task_draftMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected