Connecting to ChatGPT using API

617 vues (au cours des 30 derniers jours)
John Adams
John Adams le 15 Jan 2023
Commenté : jyoti sharma le 16 Jan 2024
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 = '';
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;
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.
  5 commentaires
Yakoub le 28 Oct 2023
jyoti sharma
jyoti sharma le 16 Jan 2024
code for resource allocation in matlab using Massive mimo in 5g

Connectez-vous pour commenter.

Réponse acceptée

Hans Scharler
Hans Scharler le 23 Jan 2023
I have been researching the davinci/completions space and have working MATLAB code using net http. Get your API Key at OpenAPI:
% Define the API endpoint Davinci
api_endpoint = "";
% Define the API key from
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 ='Content-Type', 'application/json');
headers(2) ='Authorization', ['Bearer ' + api_key]);
% Define the request message
request ='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;
  8 commentaires
012786534 le 23 Mar 2023
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
Georgi Nalbantov
Georgi Nalbantov le 18 Juin 2023
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));
options = HTTPOptions;
options.ConnectTimeout = 60;
response = send(request, URI(api_endpoint),options);
The original value is: options.ConnectTimeout = 10;

Connectez-vous pour commenter.

Plus de réponses (3)

Duncan Carlsmith
Duncan Carlsmith le 23 Fév 2023
See Generate MATLAB code using ChatGPT API at 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 commentaires
Hans Scharler
Hans Scharler le 23 Fév 2023
Your project works perfectly. Thanks for sharing!
Duncan Carlsmith
Duncan Carlsmith le 24 Fév 2023
Thanks for checking it out!

Connectez-vous pour commenter.

Hans Scharler
Hans Scharler le 27 Sep 2023
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 = '';
% Define the API key from
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;
What is the capital of France?
The capital of France is Paris.

thijs buuron
thijs buuron le 20 Jan 2023
If you have the curl command (get it from the network part of the console of you webbrowser). You could use: wich converts it to matlab code for you.
  2 commentaires
Gregorio Ariel Guerrero Moral
Modifié(e) : Gregorio Ariel Guerrero Moral le 6 Avr 2023
works very well the two options
%% Option1:
uri = '';
body = struct(...
'model', 'gpt-3.5-turbo',...
'messages', {{
'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);
And the second options
%% Option 2: HTTP Interface
header = [
HeaderField('Content-Type', 'application/json')
HeaderField('Authorization', ['Bearer ' getenv('OPENAI_API_KEY')])
uri = URI('');
body = JSONProvider(struct(...
'model', 'gpt-3.5-turbo',...
'messages', {{
'role', 'user',...
'content', 'What is the capital of France?'...
response = RequestMessage('post', header, body).send(uri.EncodedURI);
Remember to setup in you OS the variable OPENAI_API_KEY.
The result of this chat is:
tony le 10 Sep 2023
thank you
not working for a longer quesion

Connectez-vous pour commenter.


En savoir plus sur Call Web Services from MATLAB Using HTTP dans Help Center et File Exchange




Community Treasure Hunt

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

Start Hunting!

Translated by