This function is the principal function that will be used to call the OpenAI API.
It will take a prompt which need to describe what we want to output.
We construct a prompt from our generic type T with this part:
The describeConstructor function will return a string that describe the constructor of our generic type T.
This message will be used to ask the user to provide a response only in a JSON format that can be parsed into an object of type T.
It’s quite important to carefully construct the prompt because you need a valid JSON format to be able to parse it into an object.
The last part take the answer from the API and parse it into an object of type T.
The createInstanceFromJson function is a simple function that use the Jackson library to parse the JSON into an object of type T.
Examples
Let’s take a simple example with a Circle class.
We can now call the askWithOutput function to create a circle of radius 5 and print the area of the circle.
That will print:
Given a Book class:
We can now call the askWithOutput function to create an array of books and print the title, author and year of all books.
That will print:
Go Further
You could also want to return an object that is not a simple object but an object that contains other objects.
We can call the askWithOutput function to create a person and print the address of the person.
Unfortunately, the API will not return a valid JSON format for this example because of additional properties.
We can try to avoid this problem by using FAIL_ON_UNKNOWN_PROPERTIES = false in the ObjectMapper.
Example of outputs:
My Person object is created and the address object is created too !
That solution need to be improved because we need to manual prompting GPT to described nested objects.
We could imagine a solution that will automatically prompt GPT to describe nested objects, but we need to avoid
stack overflow and infinite loop.