#GPT Functions return structured data

3 messages · Page 1 of 1 (latest)

median hamlet
#

I'm trying to figure out how to use functions to return structured data.

For example, say I have a query from a user:
There are 8 sticks, and 3 cones

I would like to use a function call with GPT so it reads the query and returns a JSON like:

{
  'sticks': 8,
  'cones':3
}

How can I achieve this?

acoustic wave
#

this will do it 🙂 You dont have to define the function. all you need is the function description in this case. Pay attention that we are forcing gpt to call the function by setting function_call to the name of the function instead of "auto"

import openai
import json


response = openai.ChatCompletion.create(
    model="gpt-3.5-turbo-0613", # use gpt-4-0613 for better results
    messages=[{"role":"user", "content": "There are 8 sticks, and 3 cones"}],
    functions = [
        {
            "name": "get_number_of_sticks_and_cones",
            "description": "Get the number of sticks and cones in a given sentence",
            "parameters": {
                "type": "object",
                "properties": {
                    "sticks": {
                        "type": "string",
                        "description": "The number of sticks",
                    },
                    "cones": {
                        "type": "string",
                        "description": "The number of cones",
                    },
                },
                "required": ["sticks", "cones"],
            },
        }
    ],
    function_call={"name": "get_number_of_sticks_and_cones"},

)

response = response.choices[0].message
response_args = json.loads(response["function_call"]["arguments"])

print(response_args)
rugged flower
#

how long does it take to create json?