LLM JSON Code-Block Parser
Language models frequently output JSON wrapped inside markdown code blocks (e.g., json ... ). Sometimes, they include additional leading/trailing newlines or whitespace.
Tasks
Implement a function parse_llm_json(raw_text) that:
- Trims any leading/trailing whitespace.
- Detects and extracts JSON string content if it is wrapped inside a markdown code block (handling both
json and plainblocks). - Parses the text into a Python object (dictionary or list).
- Raises a
ValueErrorwith a descriptive message if the string cannot be parsed into valid JSON.
Example
raw = "```json\n{\"sentiment\": \"positive\", \"score\": 0.95}\n```"
parse_llm_json(raw)
# Returns: {"sentiment": "positive", "score": 0.95}