There were three issues with the commented function.
- When you use headers for webwrite you do not have to include the ":" in the header label.
- The Authorization header needs the word "Bearer" infront of the API Key.
- webwrite returns an object not JSON.
Here's a working version of the function addressing the issues.
function response = getGPT4Response(prompt)
% Define the API endpoint
url = 'https://api.openai.com/v1/chat/completions';
% 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(url, data, options);
% Return the response
response = response.choices.message.content;
end
Let me know if you get tihs working.