How to Connecting to ChatGPT using API

Technical Source
2 min readApr 1, 2023

--

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.

NOTE:-

Matlabsolutions.com provide latest MatLab Homework Help,MatLab Assignment Help , Finance Assignment Help for students, engineers and researchers in Multiple Branches like ECE, EEE, CSE, Mechanical, Civil with 100% output.Matlab Code for B.E, B.Tech,M.E,M.Tech, Ph.D. Scholars with 100% privacy guaranteed. Get MATLAB projects with source code for your learning and research.

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

SEE COMPLETE ANSWER CLICK THE LINK

--

--

Technical Source

Simple! That is me, a simple person. I am passionate about knowledge and reading. That’s why I have decided to write and share a bit of my life and thoughts to.