Ask again until the JSON parses

Ask again until the JSON parses

OpenAI LLM Interview Question

Teams building on the OpenAI API ask the model for JSON so the reply can go straight into a database. The model mostly returns JSON. When it does not, it answers the question in prose instead, which is useful to a person and useless to the code waiting for a dictionary.

Write a function ask_for_json(prompt, attempts) that asks the model and returns the reply parsed into a dictionary. The prompt is sent again unchanged on each try, and the attempts are the most tries you will make. Each reply arrives on response.choices[0].message.content. A reply counts only when the whole of it parses as a JSON object, so a list or a number does not. When a reply does not count, ask again, and return None when none of them parse.

Asked of

  • AI Engineer
  • ML Engineer
  • Data Scientist

Example 1

Input

prompt = "Give me the user Ada as JSON", attempts = 3

The model says

call 1 -> "The user is Ada, aged 36."
call 2 -> "{\"name\": \"Ada\", \"age\": 36}"

Output

{"name": "Ada", "age": 36}

Example 2

Input

prompt = "Give me the user Ada as JSON", attempts = 2

The model says

call 1 -> "Ada is 36 years old."
call 2 -> "I can describe the user: Ada, age 36."

Output

None

Example 3

Input

prompt = "Did it work?", attempts = 3

The model says

call 1 -> "{\"ok\": true}"

Output

{"ok": True}

Explanation

In the first example the model answers in prose and the second attempt returns the object. In the second example neither attempt parses, so there is nothing to return.

Submit also runs 3 hidden test cases that check edge cases.

Similar questions