Search code examples
swiftopenai-apigpt-3

OpenAI GPT-3 API error: "You must provide a model parameter"


I am trying to POST a question to openAI API via SWIFT. It works fine, if I use the same payload via Postman, but in the Xcode-Condole I got the following response from openAI:

Response data string:
{
     "error": {
         "message": "you must provide a model parameter",
         "type": "invalid_request_error",
         "param": null,
         "code": null
    }
 }

This is my code:

 func getActivityAnalysis(){
    
    let url = URL(string: "https://api.openai.com/v1/completions")
    guard let requestUrl = url else { fatalError() }
    
    // Prepare URL Request Object
    var request = URLRequest(url: requestUrl)
    request.setValue("Bearer blaaaablaa", forHTTPHeaderField: "Authorization")
    request.httpMethod = "POST"
    
    
    let prompt = "just a test"
    let requestBody = OpenAIRequest(model: "text-davinci-003", prompt: prompt, max_tokens: 300, temperature: 0.5)
    
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    let data = try! encoder.encode(requestBody)
    print(String(data: data, encoding: .utf8)!)
    
     
    // Set HTTP Request Body
    request.httpBody = data
    
    print("\(request.httpMethod!) \(request.url!)")
    print(request.allHTTPHeaderFields!)
    print(String(data: request.httpBody ?? Data(), encoding: .utf8)!)
    
    
    
    // Perform HTTP Request
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            
            // Check for Error
            if let error = error {
                print("Error took place \(error)")
                return
            }
     
            // Convert HTTP Response Data to a String
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("Response data string:\n \(dataString)")
                self.openAIResponse = dataString
            }
    }
    task.resume()
    
}`

If I print the http request, it seems fine for me as well:

 POST https://api.openai.com/v1/completions
 ["Authorization": "Bearer blaaaaa"]
 {
    "temperature" : 0.5,
    "model" : "text-davinci-003",
    "prompt" : "just a test",
    "max_tokens" : 300
 }

I tried to use the same payload in my Postman request. It worked fine here. I also tried to use different encodings, but it always throws the same error.

Not sure, what I am doing wrong. Maybe someone can help?

Thank you in advance.

Bets, Tobi


Solution

  • Your HTTP request reveals the problem. You need to add 'Content-Type: application/json'.

    According to GeeksforGeeks:

    Content-Type is an HTTP header that is used to indicate the media type of the resource and in the case of responses, it tells the browser about what actually content type of the returned content is.