Chatbot with SwiftUI & OpenAI API
AI chatbots are transforming the way users interact with mobile applications. Whether it’s customer support, personal assistance, or interactive learning, integrating a conversational AI can take your app to the next level. In this tutorial, you’ll learn how to create a SwiftUI-based chatbot powered by the OpenAI API.
✨ What You’ll Build
A fully functional chatbot UI built with SwiftUI that communicates with OpenAI’s GPT model to generate intelligent responses.
๐ Requirements
- Xcode 15+
- SwiftUI
- OpenAI API Key (from https://platform.openai.com/)
๐ง Setting Up
- Create a new SwiftUI project in Xcode.
- Add networking support using
URLSession
. - Store your API Key securely (avoid hardcoding).
✏️ Define the Model
struct Message: Identifiable {
let id = UUID()
let text: String
let isUser: Bool
}
๐ ChatViewModel
class ChatViewModel: ObservableObject {
@Published var messages: [Message] = []
private let apiKey = "YOUR_OPENAI_API_KEY" // Use secure method in production
func sendMessage(_ userInput: String) {
let userMessage = Message(text: userInput, isUser: true)
messages.append(userMessage)
let systemPrompt = "You are a helpful assistant."
let requestBody: [String: Any] = [
"model": "gpt-3.5-turbo",
"messages": [
["role": "system", "content": systemPrompt],
["role": "user", "content": userInput]
]
]
guard let url = URL(string: "https://api.openai.com/v1/chat/completions"),
let bodyData = try? JSONSerialization.data(withJSONObject: requestBody) else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.httpBody = bodyData
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data,
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let choices = json["choices"] as? [[String: Any]],
let message = choices.first?["message"] as? [String: Any],
let content = message["content"] as? String else {
print("Failed to decode response")
return
}
DispatchQueue.main.async {
let botMessage = Message(text: content.trimmingCharacters(in: .whitespacesAndNewlines), isUser: false)
self.messages.append(botMessage)
}
}.resume()
}
}
๐จ Build the Chat UI
struct ChatView: View {
@StateObject private var viewModel = ChatViewModel()
@State private var inputText = ""
var body: some View {
VStack {
ScrollViewReader { proxy in
ScrollView {
VStack(alignment: .leading, spacing: 10) {
ForEach(viewModel.messages) { message in
HStack {
if message.isUser {
Spacer()
Text(message.text)
.padding()
.background(Color.blue.opacity(0.7))
.foregroundColor(.white)
.cornerRadius(12)
} else {
Text(message.text)
.padding()
.background(Color.gray.opacity(0.3))
.cornerRadius(12)
Spacer()
}
}
}
}
.padding()
}
}
HStack {
TextField("Enter your message...", text: $inputText)
.textFieldStyle(RoundedBorderTextFieldStyle())
Button(action: {
guard !inputText.trimmingCharacters(in: .whitespaces).isEmpty else { return }
viewModel.sendMessage(inputText)
inputText = ""
}) {
Image(systemName: "paperplane.fill")
.foregroundColor(.blue)
}
}
.padding()
}
}
}
๐ Final Result
You now have a working SwiftUI chatbot that uses OpenAI’s GPT model to generate responses.
You can customize it further by:
- Adding chat roles
- Displaying timestamps
- Persisting chat history
- Supporting markdown or rich content
๐ Wrap-Up
With just a few lines of code, you can integrate cutting-edge AI into your SwiftUI app. Use this power responsibly to build delightful and meaningful user experiences.
Comments
Post a Comment