elemental impure subroutine create_image(this, prompt, n, size, response_format, user_name)
use http, only: response_type, request, HTTP_POST, pair_type
use json_module, only: json_file
class(ImageGeneration), intent(inout) :: this
character(len=*), intent(in) :: prompt
integer, intent(in), optional :: n
character(len=*), intent(in), optional :: size
character(len=*), intent(in), optional :: response_format
character(len=*), intent(in), optional :: user_name
character(len=:), allocatable :: assistant_response
character(len=:), allocatable :: jsonstr
type(pair_type), allocatable :: req_header(:)
type(response_type) :: response
type(json_file) :: json
logical :: found
integer :: i
character(len=10) :: i_str
call this%set_prompt(prompt=prompt)
if (present(n)) call this%set_n(n=n)
if (present(size)) call this%set_size(size=size)
if (present(response_format)) call this%set_response_format(response_format=response_format)
if (present(user_name)) call this%set_user_name(user_name=user_name)
req_header = [&
pair_type('Content-Type', 'application/json'),&
pair_type('Authorization', 'Bearer '//trim(this%api_key)//''),&
pair_type('OpenAI-Organization', ' '//trim(this%organization)//'')&
]
call json%initialize()
call json%add('prompt', trim(this%prompt))
call json%add('n', this%n)
call json%add('size', trim(this%size))
call json%add('response_format', trim(this%response_format))
call json%add('user', trim(this%user_name))
call json%print_to_string(jsonstr)
call json%destroy()
response = request(url=trim(this%url), method=HTTP_POST, data=jsonstr, header=req_header)
if (response%ok) then
allocate(this%assistant_response(this%n))
call json%initialize()
call json%deserialize(response%content)
do i = 1, this%n
write (i_str, "(I10)") i
call json%get("data("//trim(i_str)//").url", assistant_response, found=found)
if (.not. found) then
call json%get("error.message", assistant_response)
call this%set_assistant_response(assistant_response=assistant_response, i=i)
exit
end if
call this%set_assistant_response(assistant_response=assistant_response, i=i)
end do
call json%destroy()
else
print '(A)', 'Sorry, an error occurred while processing your request.'
print '(A)', 'Error message:', response%err_msg
end if
end subroutine create_image