3
$\begingroup$

Using Mathematica 13.0 on Windows 10

codes are below

req=HTTPRequest["https://api.openai.com/v1/completions",
<|Method->"POST",
"Body"->{"model"->"text-davinci-003","prompt"->"Say this is a test"},
"Headers"->{"Authorization"->"Bearer sk-xxxxxxxxxxxxx"}|>]
URLExecute[req]

and here is the output

{error->{message->you must provide a model parameter,type->invalid_request_error,param->Null,code->Null}}

It seems I set the wrong body parameters especially in "model" part.

First I checked the openai Ducuments to set proper body parameters.Then I used postman to verify my body parameters and it works. However, when I try to reproduce POST request in Mathematica, the output returned by the site shows that I did not set body parameters correctly.

I also checked my request body by using

req["Body"]

and it returns normally

{"model": "text-davinci-003","prompt": "Say this is a test"}

I think the possible error is in setting the wrong format or position of the parameter. Could anyone give me some suggestions or hints on setting body parameter?

$\endgroup$
4
  • $\begingroup$ Most likely that body need to be converted to JSON. Try using "Body"->ExportString[{"model"->"text-davinci-003","prompt"->"Say this is a test"},"JSON"] $\endgroup$ Feb 9 at 3:51
  • $\begingroup$ @GustavoDelfino I tried and it returns the same error. You can directly evaluate your code to test because I provided the api key. $\endgroup$
    – Schwarzer
    Feb 9 at 5:16
  • $\begingroup$ <| Method -> "POST", "Body" -> ExportString[{"model" -> "text-davinci-003", "prompt" -> "Say this is a test"}, "JSON"], "ContentType" -> "application/json", $\endgroup$
    – Kuba
    Feb 9 at 11:09
  • $\begingroup$ @Kuba Thanks a lot!!! I didn't use the ContentType parameter to post request. $\endgroup$
    – Schwarzer
    Feb 9 at 12:08

1 Answer 1

4
$\begingroup$

According to Kuba's and GustavoDelfino's comments, the solution is to make sure to send a JSON body with a proper content-type header:

req = HTTPRequest[
  "https://api.openai.com/v1/completions",
  <| 
    Method -> "POST", 
    "Body" ->   ExportString[{"model" -> "text-davinci-003",      "prompt" -> "Say this is a test"}, "JSON"], 
    "ContentType" -> "application/json",
    "Headers" -> { "Authorization"-> ...} 
  |>
]

URLExecute[req]
$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.