aboutsummaryrefslogtreecommitdiff
path: root/autogpts/autogpt/autogpt/core/prompting/utils.py
blob: 4b1be47f4ca5e7673943e886accf0b57973f62e8 (plain)
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
27
28
29
import ast
import json


def to_numbered_list(
    items: list[str], no_items_response: str = "", **template_args
) -> str:
    if items:
        return "\n".join(
            f"{i+1}. {item.format(**template_args)}" for i, item in enumerate(items)
        )
    else:
        return no_items_response


def json_loads(json_str: str):
    # TODO: this is a hack function for now. We'll see what errors show up in testing.
    #   Can hopefully just replace with a call to ast.literal_eval.
    # Can't use json.loads because the function API still sometimes returns json strings
    #   with minor issues like trailing commas.
    try:
        json_str = json_str[json_str.index("{") : json_str.rindex("}") + 1]
        return ast.literal_eval(json_str)
    except json.decoder.JSONDecodeError as e:
        try:
            print(f"json decode error {e}. trying literal eval")
            return ast.literal_eval(json_str)
        except Exception:
            breakpoint()