How to Connecting to ChatGPT using API

Illustration
John Adams - 2023-04-01T11:41:57+00:00
Question: How to 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.

Expert Answer

Profile picture of John Williams John Williams answered . 2025-11-20

I have been researching the davinci/completions space and have working MATLAB code using net http. Get your API Key at OpenAPI: 

 

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);

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!