Salesforce Apex to call OpenAI API with Prompt

Salesforce Apex to call OpenAI API with Prompt

Using Salesforce Apex, we can call the OpenAI API with Prompt.

Endpoint:

https://api.openai.com/v1/completions

Remote Site Settings:

Sample Code:

String strEndpoint = 'https://api.openai.com/v1/completions';
HTTP h = new HTTP();
HTTPRequest req = new HTTPRequest();
req.setEndPoint( strEndpoint );
req.setMethod( 'POST' );
req.setHeader( 
    'Content-Type', 'application/json' 
);
req.setHeader( 
    'Authorization', 'Bearer <SecrutiyKeyFromOpenAI>' 
);
req.setBody( 
    '{ "model" : "text-davinci-003", "prompt" :"Salesforce CORS", "n" : 3 }' 
);
HTTPResponse res = h.send(req);
System.debug( 
    'Response is ' + res.getBody() 
);

Leave a Reply