matlab.net vs webwrite
Mostrar comentarios más antiguos
Why the function not commented works perfectly, but the function commented always returns error 401 ?
Both use the same <API_KEY>
function [result,tokens] = getGPT4Response(content)
import matlab.net.*
import matlab.net.http.*
% Define the API endpoint
api_endpoint = "https://api.openai.com/v1/chat/completions";
% Define the API key from https://beta.openai.com/account/api-keys
api_key = "<API_KEY>";
data = jsondecode('{"model":"gpt-3.5-turbo","messages":[{"role":"system","content":"You are an assistant."},{"role":"user","content":"'+content+'"}]}');
% Define the headers for the API request
headers(1) = 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,data);
% Send the request and store the response
response = send(request, URI(api_endpoint));
% Extract the response text
result = response.Body.Data.choices.message.content;
tokens = response.Body.Data.usage;
end
%**********************************************************************************************************
% function response = getGPT4Response(prompt)
% % Define the API endpoint
% url = 'https://api.openai.com/v1/chat/completions'; % Replace with the actual GPT-4 API endpoint when available
%
% % Define the headers
% headers = ["Content-Type:", "application/json"; "Authorization:", "<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, 'MediaType', 'application/json');
% response = webwrite(url, data, options);
%
% % Parse the response
% response = jsondecode(response);
%
% % Extract the text
% response = response.choices.text;
% end
%
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre Call Web Services from MATLAB Using HTTP en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!