I am developing a project with swift.
How can I have chatGPT solve a “string” type math problem using the API?
**let apiKey = “API_KEY”
let endpoint = “https://api.openai.com/v1/engines/davinci-codex/completions”
func solveEquation(equation: String, completion: @escaping (String?) -> Void) {
guard let url = URL(string: endpoint) else {
completion(nil)
return
}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer (apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters: [String: Any] = [
"prompt": "Solve the following equation: (equation)",
"max_tokens": 100
]
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
} catch {
completion(nil)
return
}
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil, let data = data else {
completion(nil)
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let choices = json["choices"] as? [[String: Any]],
let text = choices.first?["text"] as? String {
completion(text.trimmingCharacters(in: .whitespacesAndNewlines))
} else {
completion(nil)
}
} catch {
completion(nil)
}
}
task.resume()
}**
CONSOLE LOG :
Failed to get the home directory when checking model path.
nw_connection_copy_connected_local_endpoint_block_invoke [C1] Connection has no local endpoint
New contributor
Cihangir İncaz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.