elemental impure subroutine create_chat_completion(this)
use http, only: response_type, request, HTTP_POST, pair_type
use json_module, only: json_file
class(ChatCompletion), intent(inout) :: this
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
integer :: error
call this%check(error)
if (error == 0) then
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('model', trim(this%model))
do i = 1, size(this%messages)
write (i_str, "(I10)") i
call json%add('messages('//trim(i_str)//').role', this%messages(i)%role)
call json%add('messages('//trim(i_str)//').content', this%messages(i)%content)
! call json%add('messages('//trim(i_str)//').name', this%messages(i)%name)
end do
call json%add('user', this%user_name)
call json%add('temperature', this%temperature)
call json%add('max_tokens', this%max_tokens)
call json%add('stream', this%stream)
call json%add('n', this%n)
call json%add('presence_penalty', this%presence_penalty)
call json%add('frequency_penalty', this%frequency_penalty)
call json%add('top_p', this%top_p)
call json%print_to_string(jsonstr)
call json%destroy()
response = request(url=this%url, method=HTTP_POST, data=jsonstr, header=req_header)
if (response%ok) then
call json%initialize()
call json%deserialize(response%content)
call json%get("choices(1).message.content", assistant_response, found=found)
if (found) then
call json%get("choices(1).finish_reason", this%finish_reason)
call json%get("usage.prompt_tokens", this%usage%prompt_tokens)
call json%get("usage.completion_tokens", this%usage%completion_tokens)
call json%get("usage.total_tokens", this%usage%total_tokens)
else
call json%get("error.message", jsonstr)
assistant_response = jsonstr
end if
call this%set_asisstant_response(response=assistant_response)
call json%destroy()
else
print '(A)', 'Sorry, an error occurred while processing your request.'
print '(A)', 'Error message:', response%err_msg
end if
end if
end subroutine create_chat_completion