Error accessing OpenAI API

Hi,

I am constantly getting the same error when trying to call the OpenAI API. I am using Swift (iOS) and whatever I do, every API all is getting the following error: The network connection was lost.

I checked my OpenAI Account if there is something wrong - but everything works well both from curl and jscript - i can access the API without any issues and it returns correct responses.

My code is:

let url = URL(string: “removed”)!
var request = URLRequest(url: url)
request.httpMethod = “POST”
request.setValue(“application/json”, forHTTPHeaderField: “Content-Type”)
request.setValue(“Bearer API_KEY_REMOVED”, forHTTPHeaderField: “Authorization”)

                                let requestBody: [String: Any] = [
                                    "model": "gpt-4o",
                                    "messages": [
                                        [
                                            "role": "user",
                                            "content": [
                                                [
                                                    "type": "text",
                                                    "text": "Write a haiku about weightlifting"
                                                ]
                                            ]
                                        ]
                                    ],
                                    "temperature": 1,
                                    "max_tokens": 100,
                                    "top_p": 1,
                                    "frequency_penalty": 0,
                                    "presence_penalty": 0,
                                    "response_format": [
                                        "type": "text"
                                    ]
                                ]
                                
                                do {
                                    request.httpBody = try JSONSerialization.data(withJSONObject: requestBody)
                                    
                                    let (responseData, response) = try await URLSession.shared.data(for: request)
                                    
                                    print(response)
                                    print(responseData)
                                    //print("-----> responseData \n \(String(data: responseData, encoding: .utf8) as AnyObject) \n")
                                }
                                catch { print(error) }

And this is the complete error message:

Error Domain=NSURLErrorDomain Code=-1005 “The network connection was lost.” UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x600000c40210 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 “(null)” UserInfo={NSErrorPeerAddressKey=<CFData 0x600002104870 [0x1e6ebb4f0]>{length = 16, capacity = 16, bytes = 0x100201bbac4200f30000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
“LocalDataTask .<1>”
), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=removed, NSErrorFailingURLKey=removed, _kCFStreamErrorDomainKey=4}

Anyone ideas?

Thanks,

Mario

Give this cleaned up code a try

let url = URL(string: "https://api.openai.com/v1/chat/completions")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer YOUR_API_KEY", forHTTPHeaderField: "Authorization")

let requestBody: [String: Any] = [
    "model": "gpt-4o",
    "messages": [
        [
            "role": "user",
            "content": "Write a haiku about weightlifting"
        ]
    ],
    "temperature": 1,
    "max_tokens": 100
]

request.httpBody = try! JSONSerialization.data(withJSONObject: requestBody)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let error = error {
        print("Request error:", error)
    } else if let data = data {
        print("Response:", String(data: data, encoding: .utf8)!)
    }
}
task.resume()

If you still get issues, check that Info.plist allows the connection. If curl is working your connectivity should be fine.

Thanks for your response. However, still getting the same error.

What do I need to set in the info.plist?

Currently, I only have one setting:

<key>UIBackgroundModes</key>
<array>
	<string>remote-notification</string>
</array>
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

That should allow temporary insecure connections, you’ll need to dig into your personal setup as I can’t see what you have.

Worth having a conversation with ChatGPT about it at this point as it will be down to a configuration issue.

Thanks, this has no effect as well.

I will try to open a support ticket with OpenAI :slight_smile:

I am not aware of an API support ticketing system, also as this is an issue with your configuration, you will need to fix that on your end, hence why working with ChatGPT to steo through the issue will be one of the best ways to go.

1 Like

sure

I also checked the os log, there are several errors:

nw_connection_copy_connected_local_endpoint_block_invoke [C2] Connection has no local endpoint

nw_connection_copy_connected_local_endpoint_block_invoke [C2] Connection has no local endpoint

quic_conn_retire_dcid unable to find DCID 01b837da9766188f43bbd7da856603c3e8d5fa89

quic_conn_change_current_path [C2.1.1.1:2] [-01b837da9766188f43bbd7da856603c3e8d5fa89] tried to change paths, but no alternatives were found

nw_flow_service_writes Failing write request <nw_write_request> [57: Socket is not connected]

nw_write_request_report [C2] Send failed with error “Socket is not connected”

Task <97E0C6DF-79D8-4A6E-8A28-87CB92A7E30B>.<2> HTTP load failed, 389/0 bytes (error code: -1005 [4:-4])

Connection 2: write error 1:57

nw_protocol_implementation_lookup_path [C2.1.1.1:2] No path found for f86ead4fe3a9cbcf

Connection 2: received failure notification

nw_endpoint_handler_unregister_context [C2.1.1.1 172.66.0.243:443 failed socket-flow (satisfied (Path is satisfied), interface: en0[802.11], uses wifi)] Cannot unregister after flow table is released

Task <97E0C6DF-79D8-4A6E-8A28-87CB92A7E30B>.<2> finished with error [-1005] Error Domain=NSURLErrorDomain Code=-1005 “The network connection was lost.” UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x600000c17b70 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 “(null)” UserInfo={NSErrorPeerAddressKey=<CFData 0x600002115400 [0x1e6ebb4f0]>{length = 16, capacity = 16, bytes = 0x100201bbac4200f30000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <97E0C6DF-79D8-4A6E-8A28-87CB92A7E30B>.<2>, _NSURLErrorRelatedURLSessionTaskErrorKey=(

“LocalDataTask <97E0C6DF-79D8-4A6E-8A28-87CB92A7E30B>.<2>”

), NSLocalizedDescription=The network connection was lost., NSErrorFailingURLStringKey=removed, NSErrorFailingURLKey=removed, _kCFStreamErrorDomainKey=4}

nw_endpoint_flow_fillout_data_transfer_snapshot copy_info() returned NULL

nw_connection_copy_connected_local_endpoint_block_invoke [C2] Connection has no local endpoint

UPDATE: it is due to an issue in the iOs 18.4 Simulator. It works in the 17.5 simulator

1 Like