OpenAI Chat API Sample

Want to talk about something that isn't covered by another category?

Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller, robinmiller

joseggarza
Posts: 44
Joined: Thu Jul 24, 2014 8:55 pm

OpenAI Chat API Sample

Post by joseggarza » Fri Oct 06, 2023 8:19 pm

ChatGPT from OpenAi is a HOT Topic now at days and I know people are looking for ways interact with OpenAI using Livecode.

The following code will help you to get started on your development and to get more ideas.
If somebody else has already a library to do this better, please share it here..


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
Attachments
ASKGPT-Sample.livecode.zip
(2.01 KiB) Downloaded 73 times
Last edited by joseggarza on Fri Oct 06, 2023 8:31 pm, edited 1 time in total.

dunbarx
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 9670
Joined: Wed May 06, 2009 2:28 pm
Location: New York, NY

Re: OpenAI Chat API Sample

Post by dunbarx » Fri Oct 06, 2023 9:04 pm

Jose.

I tried your stack. I got an error at line 23:

Code: Select all

 put jsonimport(it) into tArray
I dismissed it without reading the error, figuring I would restart LC and try again. But all subsequent times I got no error, but also no answer.

Craig

dunbarx
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 9670
Joined: Wed May 06, 2009 2:28 pm
Location: New York, NY

Re: OpenAI Chat API Sample

Post by dunbarx » Fri Oct 06, 2023 9:08 pm

Set a breakpoint and looked at the target variable "tArray" of the jsonImport command:
Screenshot 2023-10-06 at 4.05.12 PM.png.zip
(18.86 KiB) Downloaded 67 times
Craig

joseggarza
Posts: 44
Joined: Thu Jul 24, 2014 8:55 pm

Re: OpenAI Chat API Sample

Post by joseggarza » Fri Oct 06, 2023 10:54 pm

Hi Craig,

I think you just need to enter your own OPENAI KEY replacing the XXXXXX
put "XXXXXXXXXXXXXXXXXXXXXX" into tKey

Regards,
JG

Klaus
Posts: 13829
Joined: Sat Apr 08, 2006 8:41 am
Location: Germany
Contact:

Re: OpenAI Chat API Sample

Post by Klaus » Sat Oct 07, 2023 11:03 am

Hola Jose,

I think you could really profit from a little function like this:

Code: Select all

function q tString
   return QUOTE & tString & QUOTE
end q
Know what I mean? ;-)

And I am quite sure, Craig knows that XXXXXXXXXXXXXXXXXXXXXX is not the real key to use. :-D
At least I hope so...


Best

Klaus

joseggarza
Posts: 44
Joined: Thu Jul 24, 2014 8:55 pm

Re: OpenAI Chat API Sample

Post by joseggarza » Sat Oct 07, 2023 4:52 pm

Hi Klaus,

The following is the string to pass back to the API:

Code: Select all

{
  "model": "gpt-3.5-turbo",
  "messages": [
    {
      "role": "user",
      "content": "What is Livecode?"
    }
  ],
  "temperature": 1,
  "max_tokens": 256,
  "top_p": 1,
  "frequency_penalty": 0,
  "presence_penalty": 0
}

using your function

Code: Select all

function q tString
   return QUOTE & tString & QUOTE
end q
how can I use your function to insert the above string into a variable? that only takes care of the first and last quotes, right?



JG

Klaus
Posts: 13829
Joined: Sat Apr 08, 2006 8:41 am
Location: Germany
Contact:

Re: OpenAI Chat API Sample

Post by Klaus » Sat Oct 07, 2023 5:05 pm

Hola Jose,

this function will save you a LOT of typing, see my example:

Code: Select all

...
put merge("{" & q("role") & q(": ") & q("[[tRole]]") & q(",") & q("content") & q(": ") & q("[[tContent]]") & q("}")) into tMessage
##put merge("{"&quote&"role"&quote&": "&quote&"[[tRole]]"&quote&", "& quote&"content"&quote&": "&quote&"[[tContent]]"&quote&"}") into tMessage
...
See what I mean?
And please don't be too shy with using SPACES, that will make your script much more readable. 8-)

Best

Klaus

joseggarza
Posts: 44
Joined: Thu Jul 24, 2014 8:55 pm

Re: OpenAI Chat API Sample

Post by joseggarza » Sat Oct 07, 2023 10:21 pm

Hola Klaus,

Oh, what a surprise... :D :D :D .

I had such high hopes for finding a magical solution to the never-ending struggles I face when dealing with strings in Livecode Scripts. And I emphasize "Scripts" because I can paste those cryptic lines into a property of an object and somehow make it work. But when I'm stuck on a server with nothing but Livecode Scripts, trying to handle those enormous SQL strings feels like a never-ending nightmare.

Your "Q" function suggestion still leaves me scratching my head... :D :D :D . I highly doubt it's going to solve my intricate problem.

I suppose it might have some merit when dealing with quick, small, and uncomplicated strings, but my issues run much deeper.

Let me share my secret sauce for handling these strings:

Code: Select all

on mouseUp
   repeat for each line tLine in fld "Text"
      replace quote with quote & "&" & "quote" & "&" & quote in tLine
      put quote & tLine & quote && "& cr &" & " \" & cr after tConvertedText
   end repeat
   delete char -9 to -1 of tConvertedText
   put tConvertedText into fld "Text"
end mouseUp
I stumbled upon this incredibly useful script in this very forum a long time ago. It works like magic, transforming those Livecode cryptic strings into something more manageable that I can stash in a script variable.

Is there a better way? I'm not entirely sure, but for now, this one-click wonder has been my go-to solution.

And that's precisely how I conjured up the code you had the pleasure of witnessing.

Ah, the dream of effortlessly assigning lengthy, multiline text adorned with quotes to a variable, much like the enchanting triple-quoted strings in Python. It does sound like a utopian wish in the realm of Livecode Scripts, but who knows? Maybe someday, some coding wizard will conjure up a solution that makes this dream come true. Until then, we'll just have to make do with our trusty bag of Livecode tricks and workarounds. Keep on dreaming and coding!

Regards,

JG

Klaus
Posts: 13829
Joined: Sat Apr 08, 2006 8:41 am
Location: Germany
Contact:

Re: OpenAI Chat API Sample

Post by Klaus » Sun Oct 08, 2023 9:46 am

Your "Q" function suggestion still leaves me scratching my head... :D :D :D . I highly doubt it's going to solve my intricate problem.
I never said that it would solve your problem completely, just save some typing...

richmond62
Livecode Opensource Backer
Livecode Opensource Backer
Posts: 9389
Joined: Fri Feb 19, 2010 10:17 am
Location: Bulgaria

Re: OpenAI Chat API Sample

Post by richmond62 » Sun Oct 08, 2023 9:55 am

Obviously quite a few people hope that with the advent of A.I. there will come magical solutions to everything.

A bit like what my Granddad expected when his father installed electricity in their home . . .

bn
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 4003
Joined: Sun Jan 07, 2007 9:12 pm
Location: Bochum, Germany

Re: OpenAI Chat API Sample

Post by bn » Sun Oct 08, 2023 4:46 pm

Hi Jose,

would something like this work for you? It needs the script library "mergjson" to work. (Search your dictionary for "JSONToArray". If it finds it then mergjson is available.

Using your example try this

Code: Select all

   put "gpt-3.5-turbo" into tModel
   put "user" into tRole
   put fld "Question" into tContent
   
   put tModel into tPayload["model"]
   put tRole into tPayload["messages"][1]["role"]
   put tContent into tPayLoad["messages"][1]["content"]
   put 1 into tPayLoad["temperature"]
   put 256 into tPayLoad["max_tokens"]
   put 1 into tPayLoad["top_p"]
   put 0 into tPayLoad["frequency_penalty"]
   put 0 into tPayLoad["presence_penalty"]
   
   put ArrayToJSON(tPayLoad,,false) into tMyJson
   put tMyJson

it results in
{"model": "gpt-3.5-turbo","top_p": 1,"temperature": 1,"max_tokens": 256,"messages": [{"content": "tell me a joke about the ocean","role": "user"}],"presence_penalty": 0,"frequency_penalty": 0}
The order of elements is not the same as in your "merge" example. But I just assume it does not matter.
If this assumption is correct then it might be easier than "merge".
I could not test your example with my free key for chatGPT 3.5. Apparently you need a paid key for this to work.

Edit: I went to https://github.com/Ferruslogic/PhotonJSON and used it as Library. It produces the same result as using mergJson from above.
It might be an alternative in case you do not have mergJson available.

I also tried the "library.json" which is part of LC and I could not it to create the same json output as you have with merge. I see that you use "library.json" to convert from json to array.

Disclaimer: I know nothing about JSON, the same goes for the interface to chatGPT.

Kind regards
Bernd

bn
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 4003
Joined: Sun Jan 07, 2007 9:12 pm
Location: Bochum, Germany

Re: OpenAI Chat API Sample

Post by bn » Sun Oct 08, 2023 8:19 pm

Hi Jose,

after spending $10 for a key from ChatGPT it could test the stuff and can confirm that the code in the codefield above for generating valid jason works.
I learned some jokes.

I added some error checking:

Code: Select all

   put jsonimport(it) into tArray
   
   -- addition
   If tArray is empty then
      put "Answer is empty" into field "answer"
      exit mouseUp
   end if
   
   if tArray["error"] is not empty then
      put "Error" into tError
      put the keys of tArray["error"] into tKeys
      repeat for each line aKey in tKeys
         put cr & tab & aKey &":" && tArray["error"][aKey] after tError
      end repeat
      put tError into field "answer"
      exit mouseUp
   end if
   -- end addition
   -- more code
   
And I added a spinner widget to indicate that it is still working when the reply takes a bit longer

Code: Select all

   show widget "Spinner"
   post tPayload to url tURL
   hide widget "Spinner"
Thank you for bringing this chatGPT stuff up and posting the stack.
Kind regards
Bernd

joseggarza
Posts: 44
Joined: Thu Jul 24, 2014 8:55 pm

Re: OpenAI Chat API Sample

Post by joseggarza » Mon Oct 09, 2023 10:49 pm

Thank you, Bernd.

I've incorporated your code and added an additional command to allow for sequential calculations. For example, you can first ask it to add 2 plus 2, and in the following query, instruct it to multiply the previous result by 4, and so forth.

It's quite a nice Script!"

JG
Attachments
ASKGPT-Sample2.livecode.zip
(2.78 KiB) Downloaded 78 times

bn
VIP Livecode Opensource Backer
VIP Livecode Opensource Backer
Posts: 4003
Joined: Sun Jan 07, 2007 9:12 pm
Location: Bochum, Germany

Re: OpenAI Chat API Sample

Post by bn » Thu Oct 12, 2023 7:49 am

Hi Jose,

Thank you very much for the new version. The addition of the chat history is very useful and instructive. And it is fun to refine the questions by being able to relate to specifics of the conversation history.

Kind regards
Bernd

makeshyft
Posts: 220
Joined: Mon Apr 15, 2013 4:41 am
Contact:

Re: OpenAI Chat API Sample

Post by makeshyft » Thu Oct 12, 2023 10:39 pm

Cool, I built a a livecodeGPT plugin for my own needs, was thinking about open sourcing it, but now I don't have to.
Livecode & GPT can be magic. I have found a use case that I wish to turn into a product.
Founder & Developer @ MakeShyft R.D.A - https://www.makeshyft.com
Build Software with AppStarterStack for Livecode - https://www.AppStarterStack.com
Save Time with The Time Saver's Toolbox - https://www.TimeSaversToolbox.com

Post Reply

Return to “Off-Topic”