Post

Replies

Boosts

Views

Activity

Reply to InferenceError with Apple Foundation Model – Context Length Exceeded on macOS 26.0 Beta
Hello Team, Thanks for your answer. Please find the code and screenshot of the issue. The issue is that in the same session, for some queries, I get the context length issue and for some I don't. import SwiftUI import FoundationModels struct ChatMessage: Identifiable { let id = UUID() let isUser: Bool let content: String let timestamp: Date = Date() } struct ContentView: View { @State private var prompt: String = "" @State private var messages: [ChatMessage] = [] @State private var isLoading: Bool = false @State private var session: LanguageModelSession? var body: some View { VStack(spacing: 0) { Text("💬 Chat Assistant") .font(.title2) .bold() .padding() Divider() ScrollViewReader { scrollProxy in ScrollView { LazyVStack(spacing: 12) { ForEach(messages) { message in HStack(alignment: .bottom, spacing: 10) { if message.isUser { Spacer() chatBubble(message.content, isUser: true) userAvatar } else { botAvatar chatBubble(message.content, isUser: false) Spacer() } } .padding(.horizontal) .id(message.id) } } .padding(.top, 10) } .onChange(of: messages.count) { _ in if let last = messages.last { scrollProxy.scrollTo(last.id, anchor: .bottom) } } } Divider() HStack { TextField("Type a message...", text: $prompt) .textFieldStyle(RoundedBorderTextFieldStyle()) .disabled(isLoading) if isLoading { ProgressView() .padding(.leading, 5) } Button("Send") { Task { await sendMessage() } } .disabled(prompt.isEmpty || isLoading) } .padding() } .task { do { session = try await LanguageModelSession() } catch { messages.append(.init(isUser: false, content: "❌ Failed to start session: \(error.localizedDescription)")) } } } func sendMessage() async { let userInput = prompt.trimmingCharacters(in: .whitespacesAndNewlines) prompt = "" messages.append(ChatMessage(isUser: true, content: userInput)) isLoading = true do { if let session { let output = try await session.respond(to: userInput) messages.append(ChatMessage(isUser: false, content: output.content)) } else { messages.append(ChatMessage(isUser: false, content: "❌ No valid session.")) } } catch { messages.append(ChatMessage(isUser: false, content: "❌ Error: \(error.localizedDescription)")) } isLoading = false } func chatBubble(_ text: String, isUser: Bool) -> some View { Text(text) .padding(12) .foregroundColor(.primary) .background(isUser ? Color.blue.opacity(0.2) : Color.gray.opacity(0.15)) .cornerRadius(16) .frame(maxWidth: 250, alignment: isUser ? .trailing : .leading) } var userAvatar: some View { Image(systemName: "person.crop.circle.fill") .resizable() .frame(width: 32, height: 32) .foregroundColor(.blue) } var botAvatar: some View { Image(systemName: "sparkles") .resizable() .frame(width: 32, height: 32) .foregroundColor(.purple) } }
Jul ’25