Connecting to ChatGPT using API

I tried connecting to Chat GPT with the following web instructions and get the error as reflected ...
prompt = 'What is the capital of France?';
api_key = 'sk-4Y8TmelxvsdfghfghhdT3BlbkFJepdojXzket1MmQpA9cov';
url = 'https://api.openai.com/v1/engines/davinci/completions';
options = weboptions('KeyName','Authorization','KeyValue',['Bearer ' api_key],'MediaType','application/json');
data = webwrite(url,'prompt',prompt,'max_tokens',2048,'model','text-davinci-003','stop','',options);
Error using webwrite
Expected options.MediaType to be 'application/x-www-form-urlencoded' for Name-Value pairs. Either set options.MediaType to 'application/x-www-form-urlencoded' or create a single encoded string from
the Name-Value pairs.
answer = loadjson(data);
answer = answer.choices{1}.text;
disp(answer)
Does anyone know how to connect MATLAB to Chat GPT to send prompts and retrieve back the responses. Also how to send data over to fine tune the model and then to further prompt that model?
It would be good for Mathworks to double quick release a toolbox on FileExchange for this as Python already has an OpenAI library. Seems like Mathworks is always one step behind Python these days.
Thx

4 Comments

If that's your actual API key, I'd remove it
It isn't, I just put a dummy one in there to make it look authentic. But thx
% Extract the response text
response_text = response.Body.Data;
response_text = response_text.choices(1).text;
disp(response_text);
There is an error, is it a version problem

Sign in to comment.

 Accepted Answer

I have been researching the davinci/completions space and have working MATLAB code using net http. Get your API Key at OpenAPI: https://beta.openai.com/account/api-keys
import matlab.net.*
import matlab.net.http.*
% Define the API endpoint Davinci
api_endpoint = "https://api.openai.com/v1/engines/davinci/completions";
% Define the API key from https://beta.openai.com/account/api-keys
api_key = "XXXYYYZZZ";
% Define the parameters for the API request
prompt = "How many tablespoons are in 2 cups?"
parameters = struct('prompt',prompt, 'max_tokens',100);
% Define the headers for the API request
headers = matlab.net.http.HeaderField('Content-Type', 'application/json');
headers(2) = matlab.net.http.HeaderField('Authorization', ['Bearer ' + api_key]);
% Define the request message
request = matlab.net.http.RequestMessage('post',headers,parameters);
% Send the request and store the response
response = send(request, URI(api_endpoint));
% Extract the response text
response_text = response.Body.Data;
response_text = response_text.choices(1).text;
disp(response_text);

9 Comments

Thanks for uploading this!
From some experimenting, it seems
api_endpoint = "https://api.openai.com/v1/engines/text-davinci-003/completions";
is the way to get to ChatGPT.
Also, the documentation states that the "Engines" endpoints are deprecated, and recommends using "Models" endpoints instead. Ironically, I have not gotten that to work yet.
I got your code (with my modification) to work, and give ChatGPT responses. For example, for the prompt, "Write a poem about MATLAB" ...
MATLAB like a powerful wizard
Sparking with intuition untapped
Coding equations, equations with ease
It can do more for you than you believe
Building algorithms to solve complex scenes
Finding patterns in piles of data streams
Graphing tools that make quick sense
There's no such thing as intelligence
Through the air it commands control
Ready to code to the answer you patrol
Maybe not a true AI
But it's here to stay with no goodbyes
Scripts and functions you can try
On old and new tasks alike
You can make it run faster
And fulfill your quantitative needs
MATLAB's utility can never be done
The possibilities vast, new ideas spun
You can keep learning more and more
And soon you can call yourself a MATLAB whiz
Figured it out. I believe the preferred syntax is now
api_endpoint = "https://api.openai.com/v1/completions";
and
parameters = struct('prompt',prompt, 'model','text-davinci-003', 'max_tokens',100);
Thanks for sharing this @the cyclist!
Yes, thanks for sharing.
Here is another one - this is a MATLAB app that provides sample prompts as presets, and you can run chat-generated MATLAB code inside the app. People often struggle with prompt engineering, and the presets gives you a good starting point.
You can either download it from GitHub into your MATLAB path or use "Open in MATLAB Online" to import the repo into MATLAB Online. Once you have the API key, you can set it up in the OS environment variable.
setenv("OPENAI_API_KEY","your key here")
Finally, double click on MatGPT.mlapp to open it in App Designer and run it there.
If you would rather use command line interface, you can use chatGPT class included in the repo.
I dont get it. I used the accepted answer to ask ''what is the capital of France'' and I got a completely insane answer: (France is the capital of Europe.) =What is the capital of Europe? (Europe is the capital of the world.)” As the following examples show, “en that” sentences need a comme that refers to the sentence element “key place” (Landau’s terminology), that is the most prominent place in the new sentence, if the sentence has more than one. “key place” (Landau’s terminology), that is the
Sometimes one gets a "10 sec" timeout error and therefore no response. One fix for this is:
% Send the request and store the response.
opt = 2;
if opt == 1 % org
response = send(request, URI(api_endpoint));
else
options = HTTPOptions;
options.ConnectTimeout = 60;
response = send(request, URI(api_endpoint),options);
end
The original value is: options.ConnectTimeout = 10;
I have tried to provided code in MATLAB R2017a but it returns an error:
Error using matlab.net.http.field.AuthorizationField/scalarToString (line 119)
The "xxx" value in an AuthInfo is an encoded username/password that can only appear for the "Basic" Scheme, and it must be the only other property.
The xxx stand for the API key that I have hidden for obvious reasons.
How do I set a Scheme so that I can create the HeaderField?
Thank you.

Sign in to comment.

More Answers (3)

See Generate MATLAB code using ChatGPT API at https://www.mathworks.com/matlabcentral/fileexchange/125220-generate-matlab-code-using-chatgpt-api for a Live Script that implements the great answers here. Thank you all so much!
You get different code for the same prompt each time. For the prompt used, there is often a minor bug. Great for teaching debugging skills. ;) I'll let you find the bugs in the example I provided.

2 Comments

Your project works perfectly. Thanks for sharing!
Thanks for checking it out!

Sign in to comment.

I have updated my answer using the built-in webwrite function from MATLAB.
% Define the prompt
prompt = "What is the capital of France?";
% Define the API endpoint
api_endpoint = 'https://api.openai.com/v1/chat/completions';
% Define the API key from https://platform.openai.com/account/api-keys
api_key = "sk-XXXYYYZZZ";
% Define the headers
headers = ["Content-Type", "application/json"; "Authorization", "Bearer " + api_key];
% Define the data
message = containers.Map({'role', 'content'}, {'user', prompt});
data = containers.Map({'model', 'messages'}, {'gpt-3.5-turbo', {message}});
% Convert the data to JSON
data = jsonencode(data);
% Send the POST request
options = weboptions('RequestMethod', 'post', 'HeaderFields', headers);
response = webwrite(api_endpoint, data, options);
% Return the response
response = response.choices.message.content;
disp(prompt)
What is the capital of France?
disp(response)
The capital of France is Paris.

1 Comment

I run the above codes, get this error:
错误使用 webwrite
连接到 https://api.openai.com/v1/chat/completions 时出错: Failed to connect to 127.0.0.1 port 7890 after 2055 ms: Couldn't connect to server

Sign in to comment.

thijs buuron
thijs buuron on 20 Jan 2023
If you have the curl command (get it from the network part of the console of you webbrowser). You could use: https://curlconverter.com/matlab/ wich converts it to matlab code for you.

2 Comments

works very well the two options
%% Option1: https://curlconverter.com/matlab/
uri = 'https://api.openai.com/v1/chat/completions';
body = struct(...
'model', 'gpt-3.5-turbo',...
'messages', {{
struct(...
'role', 'user',...
'content', 'What is the capital of France?'...
)
}}...
);
options = weboptions(...
'MediaType', 'application/json',...
'HeaderFields', {'Authorization' ['Bearer ' getenv('OPENAI_API_KEY')]}...
);
response = webwrite(uri, body, options);
disp(response.choices.message.content)
And the second options
%% Option 2: HTTP Interface https://curlconverter.com/matlab/
import matlab.net.*
import matlab.net.http.*
import matlab.net.http.io.*
header = [
HeaderField('Content-Type', 'application/json')
HeaderField('Authorization', ['Bearer ' getenv('OPENAI_API_KEY')])
]';
uri = URI('https://api.openai.com/v1/chat/completions');
body = JSONProvider(struct(...
'model', 'gpt-3.5-turbo',...
'messages', {{
struct(...
'role', 'user',...
'content', 'What is the capital of France?'...
)
}}...
));
response = RequestMessage('post', header, body).send(uri.EncodedURI);
disp(response.choices.message.content)
Remember to setup in you OS the variable OPENAI_API_KEY.
The result of this chat is:
thank you
not working for a longer quesion

Sign in to comment.

Products

Release

R12.1

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!