将 OpenAI 集成到我的 Swift 应用程序时出现错误

问题描述 投票:0回答:1

我正在尝试制作一个应用程序,使用前 5 名医学期刊摘要向用户提供一个琐事问题,该问题将使用 openAI gpt 3.5 Turbo 生成。我在声明中不断收到错误:

let chatQuery = ChatQuery(messages: [message], model: "gpt-3.5-turbo") 

上面写着

无法转换“ChatQuery.ChatCompletionMessageParam”类型的值?预期元素类型“Array.ArrayLiteralElement”(又名“ChatQuery.ChatCompletionMessageParam”)

提前谢谢您!

这是完整的代码:

class PubMedViewModel: ObservableObject {
    @Published var articles: [Article] = []
    @Published var triviaScore: Int = 0
    private var currentTrivia: TriviaQuestion?
    private let openAI: OpenAI

    init() {
        self.openAI = OpenAI(apiToken: "YOUR_OPENAI_API_KEY")
        loadTriviaScore()
        generateDailyTrivia()
    }

    func generateDailyTrivia() {
        guard articles.count >= 5 else { return }
        
        let abstracts = articles.prefix(5).map { $0.abstract }.joined(separator: " ")
        let prompt = "Create a trivia question with four options from the following abstracts: \(abstracts)"
        
        Task {
            do {
                let message = ChatQuery.ChatCompletionMessageParam(role: .user, content: prompt)
                let chatQuery = ChatQuery(messages: [message], model: "gpt-3.5-turbo")
                let result = try await openAI.chats(query: chatQuery)
                
                if let triviaContent = result.choices.first?.message.content {
                    // Parse triviaContent to create a TriviaQuestion
                    // Example parsing logic:
                    let question = "What is the main topic?"
                    let options = ["Option 1", "Option 2", "Option 3", "Option 4"]
                    let correctAnswer = "Option 1"
                    
                    currentTrivia = TriviaQuestion(question: question, options: options, correctAnswer: correctAnswer)
                }
            } catch {
                print("Error generating trivia: \(error)")
            }
        }
    }

    func answerTrivia(with answer: String) {
        if let trivia = currentTrivia, answer == trivia.correctAnswer {
            triviaScore += 1
            saveTriviaScore()
        }
    }

    private func saveTriviaScore() {
        UserDefaults.standard.set(triviaScore, forKey: "triviaScore")
    }

    private func loadTriviaScore() {
        triviaScore = UserDefaults.standard.integer(forKey: "triviaScore")
    }
}

我尝试使用 AI 本身来帮助我回答,但它一直提示“确保非可选初始化:确保 ChatQuery.ChatCompletionMessageParam 直接初始化而无需选项。”我做了但没有解决问题

ios swift xcode openai-api
1个回答
0
投票

看起来从 ChatQuery.ChatCompletionMessageParam 返回的结果是可选的,但您之后调用的函数需要一个非可选值的数组。因此,您需要首先解开该可选选项,然后将其作为数组传递

guards let message = ChatQuery.ChatCompletionMessageParam(role: .user, content: prompt) else {
     return 
}
let chatQuery = ChatQuery(messages: [message], model: "gpt-3.5-turbo")

do {
    //rest of task code
© www.soinside.com 2019 - 2024. All rights reserved.