File size: 877 Bytes
3e363e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""Parse structured values produced by a language model, without executing them."""

from __future__ import annotations

import ast
import json
from typing import Any


def parse_literal(text: str) -> Any:
    """Parse JSON, or a Python literal, from ``text``; never evaluate code.

    JSON is tried first because it is what the models are asked for; it also
    accepts ``null``/``true``/``false``, which Python literals do not.  A Python
    literal (single quotes, for instance) is the fallback.  Anything else raises
    ``ValueError``, so callers' existing handlers apply unchanged.
    """
    try:
        return json.loads(text)
    except ValueError:
        pass
    try:
        return ast.literal_eval(text)
    except (ValueError, SyntaxError, TypeError, MemoryError, RecursionError) as error:
        raise ValueError(f"not a literal value: {error}") from error