black and yellow printed paper
Machine Learning

Structured Response from GPT

Apart from getting a response in text format from a GPT model, it’s also possible to specify the desired response format in the prompt and get a response in a structured format such as HTML, XML, JSON etc. This capability is extremely powerful to automate multi-step tasks where one query’s output becomes another’s input.

Let’s see a couple of example prompts for achieving this. The first example is for getting the list of European countries with the corresponding capital cities in HTML format.

prompt = '''
    Give me the list of all European countries with the name of corresponding capital cities. 

    Please format the response in HTML table with one column for country and another for capital.    
    '''

response = get_completion_response(prompt)
print(response)

Here is another example to receive the same data in JSON array format.

prompt = '''
    Give me the list of all European countries with the name of corresponding capital cities. 

    Please format the response in JSON array with one key for country and another for capital.
    '''

response = get_completion_response(prompt)

You can have a look at the full notebook code here:
https://github.com/git-mhaque/OpenAI_Experiments/blob/main/structured-output.ipynb