How to interact with chatGPT with a LiveCode app

145 views Asked by At

I want to create an app in LiveCode, which (by clicking on a button) submits a question to chatGPT and puts the answer into a field called "Response". The code of the button is the following:

on mouseUp
  put "<my personal API key>" into api_key
  put "2 + x = 10, what is x?" into tQuestion
  put "https://api.openai.com/v1/chat/completions" into tURL
  put "Bearer" && api_key into tAuthorization
  put quote&"gpt-3.5-turbo"&quote into tModel 
  put "application/json" into tContentType
  put "json" into tEncode
  put "model: "&tModel&","&cr&"messages: [{role:"&quote&"user"&quote&",content:"&quote&tQuestion&quote&"}]" into tBody
  set the httpHeaders to "Authorization:" && tAuthorization && cr & "Content-Type:" && tContentType
  post tBody to tURL
  put it into field "Response"
end mouseUp

The answer of chatGPT (shown in field "Response") is the following: "We could not parse the JSON body of your request. (HINT: This likely means you aren't using your HTTP library correctly. The OpenAI API expects a JSON payload, but what was sent was not valid JSON."

I asked chatGPT to create/fix the code in LiveCode, but this also failed.

1

There are 1 answers

0
joseggarza On

Here is the code I did to make it work with Livecode. I hope this helps you with your development.

Since I have multi-Organizations I had to add the OpenAI-Organization, but you can remark it

You will need two Fields (Question and Answer)

JG

on mouseUp pMouseButton
   put "https://api.openai.com/v1/chat/completions" into tURL
   put "XXXXXXXXXXXXXXXXXXXXXX" into tKey
   put "Content-Type: application/json;charset=utf-8" & return into tHeader
   put "Authorization: Bearer " & tKey & return after tHeader
   --put "OpenAI-Organization: XXXXXXXXXXXXXXXXX" & return after tHeader
   set the httpHeaders to tHeader
   
   put "gpt-3.5-turbo" into tModel
   put "user" into tRole
   put fld"Question" into tContent
   put merge("{"&quote&"role"&quote&": "&quote&"[[tRole]]"&quote&", "& \
         quote&"content"&quote&": "&quote&"[[tContent]]"&quote&"}") into tMessage
   
   put merge("{ "&quote&"model"&quote&": "&quote&"[[tModel]]"&quote&","& \
         quote&"messages"&quote&": [ [[tMessage]] ], "&quote&"temperature"& \
         quote&": 1, "&quote&"max_tokens"&quote&": 256, "&quote&"top_p"&quote&": 1, "& \
         quote&"frequency_penalty"&quote&": 0, "&quote&"presence_penalty"&quote&": 0 }") into tPayload
   
   post tPayload to url tURL
   put textDecode(it,"UTF-8") into it
   put jsonimport(it) into tArray
   put tArray["choices"][1]["message"]["content"] into BotAnswer
   put BotAnswer into fld"answer"
   
end mouseUp