25.8 C
New York
Monday, September 2, 2024

ios – Swift: Question encountered an error: Error Area=NSCocoaErrorDomain Code=256 “The file “default.retailer” couldn’t be opened.”


I’m writing an software that shops two forms of knowledge, a Product and a ChatMessage. I retailer them utilizing SwiftData. My Product will get saved and retrieved high-quality, however each time I attempt to retrieve or retailer any ChatMessages, I get an error like:

Question encountered an error: Error Area=NSCocoaErrorDomain Code=256 “The file “default.retailer” couldn’t be opened.

or:

error: SQLCore dispatchRequest: exception dealing with request: , I/O error for database at /var/cell/Containers/Information/Utility/BE6DA08B-F6D6-4A52-9BCC-FD69F25A63F8/Library/Utility Help/default.retailer. SQLite error code:1, ‘no such desk: ZCHATMESSAGE’ with userInfo of {
NSFilePath = “/var/cell/Containers/Information/Utility/BE6DA08B-F6D6-4A52-9BCC-FD69F25A63F8/Library/Utility Help/default.retailer”;
NSSQLiteErrorDomain = 1;
}

Right here is the code that I’ve written up to now:

That is my ChatMessage.swift:

import Basis
import SwiftData

// Outline a ChatMessage mannequin for storing chat historical past
@Mannequin
ultimate class ChatMessage {
    var id: UUID
    var content material: String
    var sender: String // "person" or "ai"
    var timestamp: Date

    // Customized initializer for ChatMessage
    init(content material: String, sender: String, timestamp: Date = Date()) {
        self.id = UUID()
        self.content material = content material
        self.sender = sender
        self.timestamp = timestamp
    }
}

That is my ChatView.swift:

import SwiftUI
import Basis
import SwiftData

@MainActor
struct ChatView: View {
    @Atmosphere(.modelContext) non-public var modelContext
    
    // State properties to carry person enter and AI response
    @State non-public var userMessage: String = ""
    @State non-public var aiResponse: String = "Sort a message and press 'Ship' to begin."
    @State non-public var merchandise: [Product] = []
    @State non-public var isLoading: Bool = false
    @Question(type: ChatMessage.timestamp, order: .ahead) non-public var chatMessages: [ChatMessage]
    
    var physique: some View {
        VStack {
            // Show chat historical past in an inventory
            ScrollViewReader { proxy in
                ScrollView {
                    VStack(spacing: 10) {
                        ForEach(chatMessages) { message in
                            HStack {
                                if message.sender == "person" {
                                    Spacer()
                                    Textual content(message.content material)
                                        .padding()
                                        .background(Shade.crimson)
                                        .foregroundColor(.white)
                                        .cornerRadius(10)
                                } else {
                                    Textual content(message.content material)
                                        .padding()
                                        .background(Shade(.secondarySystemBackground))
                                        .cornerRadius(10)
                                    Spacer()
                                }
                            }
                        }
                    }
                    .padding(.horizontal)
                }
                .onChange(of: chatMessages.rely) {
                    if let lastMessage = chatMessages.final {
                        proxy.scrollTo(lastMessage.id, anchor: .backside)
                    }
                }
            }
            
            Spacer()
            
            // Textual content enter and ship button on the backside of the display
            HStack {
                TextField("Enter your message", textual content: $userMessage, onCommit: {
                    // Ship message when person presses return
                    Job {
                        await sendChatRequest()
                    }
                })
                .textFieldStyle(RoundedBorderTextFieldStyle())
                .padding(.horizontal)
                
                // Dynamic button: Present ProgressView when loading, in any other case present ship button
                if isLoading {
                    ProgressView()
                        .padding(.trailing, 10)
                } else {
                    Button(motion: {
                        Job {
                            await sendChatRequest()
                        }
                    }) {
                        Picture(systemName: "paperplane.fill")
                            .foregroundStyle(.white)
                            .padding(7)
                            .background(Shade.crimson)
                            .cornerRadius(5)
                    }
                    .padding(.trailing, 10)
                }
            }
            .padding(.backside)
        }
        .activity {
            // Fetch knowledge when the view seems
            await fetchProducts()
        }
    }
    
    // Perform to fetch merchandise from the Core Information context
    non-public func fetchProducts() async {
        do {
            let fetchDescriptor: FetchDescriptor = FetchDescriptor()
            merchandise = strive modelContext.fetch(fetchDescriptor)
        } catch {
            aiResponse = "Error fetching knowledge: (error.localizedDescription)"
        }
    }
    
    // Perform to deal with sending the chat request to the AI
    non-public func sendChatRequest() async {
        guard !userMessage.isEmpty else {
            let aiChatMessage = ChatMessage(content material: "Please enter a message earlier than sending", sender: "ai")
            modelContext.insert(aiChatMessage)
            return
        }
        
        // Create a brand new ChatMessage for the person's message and reserve it
        let userChatMessage = ChatMessage(content material: userMessage, sender: "person")
        modelContext.insert(userChatMessage)
        
        // Set loading state to true
        isLoading = true
        
        // Fetch AI abstract based mostly on person message and fetched merchandise
        if let aiResponseText = await chatBasedOnHistory(message: userMessage, merchandise: merchandise) {
            let aiChatMessage = ChatMessage(content material: aiResponseText, sender: "ai")
            modelContext.insert(aiChatMessage)
        } else {
            let aiChatMessage = ChatMessage(content material: "Did not generate abstract.", sender: "ai")
            modelContext.insert(aiChatMessage)
        }
        
        do {
            strive modelContext.save()
        } catch {
            print("Failed to avoid wasting context: (error.localizedDescription)")
        }
        
        // Clear the textual content area after sending the message
        userMessage = ""
        
        // Reset loading state
        isLoading = false
        
        print("Variety of messages: (chatMessages.rely)")
        for message in chatMessages {
            print("Message: (message.content material), Sender: (message.sender)")
        }
    }
}

That is my AIController.swift

// Perform to ship the POST request and deal with the response
func getAISummary(jsonString: String) async -> String? {
    let parameters = [
      "model": "llama-3.1-sonar-small-128k-online",
      "messages": [
        [
          "role": "system",
          "content": "Generate a concise summary of the overall quality and healthiness of the product based on the following product information."
        ],
        [
          "role": "user",
          "content": jsonString
        ]
      ],
      "return_citations": true
    ] as [String : Any?]

    do {
        let postData = strive JSONSerialization.knowledge(withJSONObject: parameters, choices: [])
        let url = URL(string: "https://api.perplexity.ai/chat/completions")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.timeoutInterval = 10
        request.allHTTPHeaderFields = [
            "accept": "application/json",
            "content-type": "application/json",
            "authorization": "Bearer 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"
        ]
        request.httpBody = postData

        let (knowledge, _) = strive await URLSession.shared.knowledge(for: request)
        
        // Parse the JSON response to extract the generated abstract
        if let responseJson = strive JSONSerialization.jsonObject(with: knowledge, choices: []) as? [String: Any],
           let decisions = responseJson["choices"] as? [[String: Any]],
           let message = decisions.first?["message"] as? [String: Any],
           let content material = message["content"] as? String {
            return content material
        }
    } catch {
        print("Error through the request: (error.localizedDescription)")
    }
    
    return nil
}

// Perform to generate a abstract utilizing AI based mostly on product historical past
func chatBasedOnHistory(message: String, merchandise: [Product]) async -> String? {
    // Convert merchandise to a JSON-compatible dictionary or array
    let foodHistory: [[String: Any]] = merchandise.map { product in
        return [
            "name": product.name,
            "brand": product.brand,
            "quantity": product.quantity,
            "ingredients": product.ingredients,
            "nutritionScore": product.nutritionScore,
        ]
    }

    do {
        // Convert meals historical past to JSON string
        let foodHistoryJSONData = strive JSONSerialization.knowledge(withJSONObject: foodHistory, choices: [])
        let foodHistoryJSONString = String(knowledge: foodHistoryJSONData, encoding: .utf8) ?? ""

        // Put together parameters for the API request
        let parameters: [String: Any] = [
            "model": "llama-3.1-sonar-small-128k-online",
            "messages": [
                [
                    "role": "system",
                    "content": message
                ],
                [
                    "role": "user",
                    "content": "This is information on what I have eaten in the past: (foodHistoryJSONString). nnKeep in mind that this is an app where the user can scan products and view their nutritional value. They can also keep a log of what they have eaten and see how many calories they have eaten this week and how much sugar they have eaten in the past week. Try to reccomend the user to use different parts of the app."
                ]
            ],
            "return_citations": true
        ]

        let postData = strive JSONSerialization.knowledge(withJSONObject: parameters, choices: [])

        // Create the API request
        let url = URL(string: "https://api.perplexity.ai/chat/completions")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.timeoutInterval = 10
        request.allHTTPHeaderFields = [
            "accept": "application/json",
            "content-type": "application/json",
            "authorization": "Bearer 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" // Use your actual API key
        ]
        request.httpBody = postData

        // Carry out the API request
        let (knowledge, response) = strive await URLSession.shared.knowledge(for: request)

        // Examine for profitable response standing
        if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
            // Parse the JSON response to extract the generated abstract
            if let responseJson = strive JSONSerialization.jsonObject(with: knowledge, choices: []) as? [String: Any],
               let decisions = responseJson["choices"] as? [[String: Any]],
               let message = decisions.first?["message"] as? [String: Any],
               let content material = message["content"] as? String {
                return content material
            }
        } else {
            print("Sudden response standing code: ((response as? HTTPURLResponse)?.statusCode ?? -1)")
            print("Response physique: (String(knowledge: knowledge, encoding: .utf8) ?? "Unknown response")")
        }
    } catch {
        print("Error through the request or knowledge fetching: (error.localizedDescription)")
    }

    return nil
}

That is my App.swift:

import SwiftUI
import SwiftData

@essential
struct CancerDetectorApp: App {
    @StateObject non-public var vm = AppViewModel()
    
    var sharedModelContainer: ModelContainer = {
        let schema = Schema([
            Product.self,
            ChatMessage.self
        ])
        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

        do {
            return strive ModelContainer(for: schema, configurations: [modelConfiguration])
        } catch {
            fatalError("Couldn't create ModelContainer: (error)")
        }
    }()
    
    var physique: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(vm)
                .modelContainer(sharedModelContainer)
        }
    }
}

Please let me know if any further data is required or when you discover some other errors in my code as that is my first time growing in Swift.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles