Skip to content

Instantly share code, notes, and snippets.

@rian-dolphin
Last active May 14, 2024 16:42
Show Gist options
  • Save rian-dolphin/22efb516c6d98b977c1c51e762f522b4 to your computer and use it in GitHub Desktop.
Save rian-dolphin/22efb516c6d98b977c1c51e762f522b4 to your computer and use it in GitHub Desktop.
def extract_dict_from_json_llm_response(text):
text = "{"+"{".join([xi.strip() for xi in text.split("{")[1:]])
text = "}".join([xi.strip() for xi in text.split("}")[:-1]])+"}"
return eval(text)
def extract_python_dict_from_response(text):
"""
LLM response formatted as python dicts.
Args:
text (str): LLM Response. Should contain at least one ```python ... ``` block.
Also works for block like ```...```
Returns:
List or Dict: The dict contained in the code block
"""
if len(text.split("```")) == 3:
code = text.split("```")[1]
if code[:6]=="python":
code = code[6:]
return eval(code)
else:
raise NotImplementedError("The text contains multiple snippets of code")
def extract_json_from_response(text):
if len(text.split("```")) == 3:
if text.find("[") < text.find("{"):
json_list = True
text = "["+"[".join([xi.strip() for xi in text.split("[")[1:]])
text = "]".join([xi.strip() for xi in text.split("]")[:-1]]) + "]"
text = "{"+"{".join([xi.strip() for xi in text.split("{")[1:]])
text = "}".join([xi.strip() for xi in text.split("}")[:-1]])+"}"
if json_list:
text = "["+text+"]"
return text
else:
raise NotImplementedError("The text contains multiple snippets of JSON")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment