简单的URLSession在swift中不起作用,我做错了什么?



我希望在Swift中创建一个简单的CLI,用于使用OpenAI的GPT模型。我试过各种方法。下面的代码是最简单的版本,但仍然不起作用——我认为没有调用闭包。

let endpoint = "https://api.openai.com/v1/completions"
let headers = [
"Content-Type": "application/json",
"Authorization": "Bearer (oai_key)"
]
let prompt = "Create a simple function in Swift that adds two numbers."
let parameters = [
"model": "text-curie-001",
"prompt": prompt,
"max_tokens": 500,
"temperature": 0.5,
"n": 1
] as [String: Any]
let urlObject = URL(string: endpoint)!
var request = URLRequest(url: urlObject)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
} catch {
print(error)
}
func processResponseData(_ data: Data) {
print(String(data: data, encoding: .utf8) ?? "")
}
let newTask = URLSession.shared.dataTask(with: request) {
data, response, error in
print("Completion handler closure called")

if (error != nil) {
print("This error occured: (String(describing: error))")
} else {
print(String(describing: data))
if let data = data {
processResponseData(data)
}
}
}
print(newTask.state)
newTask.resume()
print(newTask.state)
print(newTask.response)
print(newTask.error)
print(newTask.progress)

在控制台中执行该命令的输出是:

NSURLSessionTaskState
NSURLSessionTaskState
nil
nil
<NSProgress: 0x600002c08b80> : Parent: 0x0 (portion: 0) / Fraction completed: 0.0000 / Completed: 0 of 100  
<NSProgress: 0x600002c08d80> : Parent: 0x600002c08b80 (portion: 95) / Fraction completed: 0.0000 / Completed: 0 of 100  
<NSProgress: 0x600002c08d00> : Parent: 0x600002c08b80 (portion: 5) / Fraction completed: 0.0000 / Completed: 0 of 100  
Program ended with exit code: 0

提前感谢!

感谢@vadian——runloop是一个很好的解决方案。

我最终在runloop工作后清理了代码,然后发现semaphore对我的实现很好。

下面是我写的代码:

let openAI = OpenAIAPI()
func getInput() -> String {
print("User:")
if let input = readLine() {
return input
}
return ""
}
func handleCompletion(responseText: String?) {
if let responseText = responseText {
print("Response:n(responseText)")
} else {
print("Error: Unable to get response")
}
}
while true {
let prompt = getInput()

if prompt.lowercased() == "finished" {
break
}

let semaphore = DispatchSemaphore(value: 0)

openAI.getCompletion(prompt: prompt) { responseText in
handleCompletion(responseText: responseText)
semaphore.signal()
}
semaphore.wait()
}

请注意,我在OpenAIAPI类中包装了前面发布的代码,并为其添加了额外的功能。

相关内容

  • 没有找到相关文章