OpenAI Chat API Sample
Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller, robinmiller
-
- Posts: 44
- Joined: Thu Jul 24, 2014 8:55 pm
OpenAI Chat API Sample
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("{""e&"role""e&": ""e&"[[tRole]]""e&", "& \
quote&"content""e&": ""e&"[[tContent]]""e&"}") into tMessage
put merge("{ ""e&"model""e&": ""e&"[[tModel]]""e&","& \
quote&"messages""e&": [ [[tMessage]] ], ""e&"temperature"& \
quote&": 1, ""e&"max_tokens""e&": 256, ""e&"top_p""e&": 1, "& \
quote&"frequency_penalty""e&": 0, ""e&"presence_penalty""e&": 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
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("{""e&"role""e&": ""e&"[[tRole]]""e&", "& \
quote&"content""e&": ""e&"[[tContent]]""e&"}") into tMessage
put merge("{ ""e&"model""e&": ""e&"[[tModel]]""e&","& \
quote&"messages""e&": [ [[tMessage]] ], ""e&"temperature"& \
quote&": 1, ""e&"max_tokens""e&": 256, ""e&"top_p""e&": 1, "& \
quote&"frequency_penalty""e&": 0, ""e&"presence_penalty""e&": 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 92 times
Last edited by joseggarza on Fri Oct 06, 2023 8:31 pm, edited 1 time in total.
-
- VIP Livecode Opensource Backer
- Posts: 9726
- Joined: Wed May 06, 2009 2:28 pm
- Location: New York, NY
Re: OpenAI Chat API Sample
Jose.
I tried your stack. I got an error at line 23:
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
I tried your stack. I got an error at line 23:
Code: Select all
put jsonimport(it) into tArray
Craig
-
- VIP Livecode Opensource Backer
- Posts: 9726
- Joined: Wed May 06, 2009 2:28 pm
- Location: New York, NY
Re: OpenAI Chat API Sample
Set a breakpoint and looked at the target variable "tArray" of the jsonImport command:
Craig
Craig
-
- Posts: 44
- Joined: Thu Jul 24, 2014 8:55 pm
Re: OpenAI Chat API Sample
Hi Craig,
I think you just need to enter your own OPENAI KEY replacing the XXXXXX
put "XXXXXXXXXXXXXXXXXXXXXX" into tKey
Regards,
JG
I think you just need to enter your own OPENAI KEY replacing the XXXXXX
put "XXXXXXXXXXXXXXXXXXXXXX" into tKey
Regards,
JG
Re: OpenAI Chat API Sample
Hola Jose,
I think you could really profit from a little function like this:
Know what I mean?
And I am quite sure, Craig knows that XXXXXXXXXXXXXXXXXXXXXX is not the real key to use.
At least I hope so...
Best
Klaus
I think you could really profit from a little function like this:
Code: Select all
function q tString
return QUOTE & tString & QUOTE
end q
And I am quite sure, Craig knows that XXXXXXXXXXXXXXXXXXXXXX is not the real key to use.
At least I hope so...
Best
Klaus
-
- Posts: 44
- Joined: Thu Jul 24, 2014 8:55 pm
Re: OpenAI Chat API Sample
Hi Klaus,
The following is the string to pass back to the API:
using your function
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
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
}
Code: Select all
function q tString
return QUOTE & tString & QUOTE
end q
JG
Re: OpenAI Chat API Sample
Hola Jose,
this function will save you a LOT of typing, see my example:
See what I mean?
And please don't be too shy with using SPACES, that will make your script much more readable.
Best
Klaus
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("{""e&"role""e&": ""e&"[[tRole]]""e&", "& quote&"content""e&": ""e&"[[tContent]]""e&"}") into tMessage
...
And please don't be too shy with using SPACES, that will make your script much more readable.
Best
Klaus
-
- Posts: 44
- Joined: Thu Jul 24, 2014 8:55 pm
Re: OpenAI Chat API Sample
Hola Klaus,
Oh, what a surprise... .
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... . 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:
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
Oh, what a surprise... .
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... . 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
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
Re: OpenAI Chat API Sample
I never said that it would solve your problem completely, just save some typing...Your "Q" function suggestion still leaves me scratching my head... . I highly doubt it's going to solve my intricate problem.
-
- Livecode Opensource Backer
- Posts: 9444
- Joined: Fri Feb 19, 2010 10:17 am
- Location: Bulgaria
Re: OpenAI Chat API Sample
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 . . .
A bit like what my Granddad expected when his father installed electricity in their home . . .
-
- VIP Livecode Opensource Backer
- Posts: 4013
- Joined: Sun Jan 07, 2007 9:12 pm
- Location: Bochum, Germany
Re: OpenAI Chat API Sample
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
it results in
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
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
The order of elements is not the same as in your "merge" example. But I just assume it does not matter.{"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}
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
-
- VIP Livecode Opensource Backer
- Posts: 4013
- Joined: Sun Jan 07, 2007 9:12 pm
- Location: Bochum, Germany
Re: OpenAI Chat API Sample
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:
And I added a spinner widget to indicate that it is still working when the reply takes a bit longer
Thank you for bringing this chatGPT stuff up and posting the stack.
Kind regards
Bernd
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
Code: Select all
show widget "Spinner"
post tPayload to url tURL
hide widget "Spinner"
Kind regards
Bernd
-
- Posts: 44
- Joined: Thu Jul 24, 2014 8:55 pm
Re: OpenAI Chat API Sample
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
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 94 times
-
- VIP Livecode Opensource Backer
- Posts: 4013
- Joined: Sun Jan 07, 2007 9:12 pm
- Location: Bochum, Germany
Re: OpenAI Chat API Sample
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
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
Re: OpenAI Chat API Sample
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.
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
Build Software with AppStarterStack for Livecode - https://www.AppStarterStack.com
Save Time with The Time Saver's Toolbox - https://www.TimeSaversToolbox.com