I’m fairly new to Xcode and swift. I’m building my first application. It’s a simple chat box GUI in swift that uses ChatGPT via openai's api that I've imported into my backend python program. I want to use my python program to be able to send and receive requests in the SwiftUI chat-box GUI. My python program is using the Fast API framework and I’ve set the port to 8080 in my swift GUI on the front end. when I try building my application in Xcode the build is successful but if I try to hit the send button in the simulator I get this error and I’ve tried everything to fix it.
The said error that appears in the Xcode console(I shortened the error message for simplicity):
"2023-03-12 21:55:14.750406-0400 Mac GPT[75198:3546121] [connection] nw_socket_handle_socket_event [C1:2] Socket SO_ERROR [61: Connection refused]"
Below is my swiftUI code for the front end chatbox GUI:
import SwiftUI
struct ContentView: View {
@State private var text: String = ""
func sendRequest() {
guard let url = URL(string:"http://"MY MACHINES IP ADDRESS HERE":8080/MacGPT") else {
return
}
var request = URLRequest(url:url)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let parameters = ["text" : text]
request.httpBody = try? JSONSerialization.data(withJSONObject: parameters , options: [])
URLSession.shared.dataTask(with: request) { data, response,error in if let error = error { print("Error:(error)")
return
}
guard let data = data else {
print("Data not found")
return
}
if let response = String(data: data, encoding: .utf8){
print("Response: (response)")
}else{
print("Invalid respnose type")
}
} .resume()
}
var body: some View {
HStack {
VStack(alignment: .center, spacing: 20) {
Image(systemName: "globe")
.foregroundColor(Color.blue)
.font(.system(size: 30))
Text("Access the power of AI right from your Mac's homescreen, just for Mac.")
.font(Font.custom("Futura", size: 15))
.fontWeight(.bold)
HStack {
TextField("Ask Mac GPT...", text: $text)
.font(Font.custom("Futura", size: 13.4))
.fontWeight(.bold)
.padding(.horizontal, 5)
.padding(.vertical, 13)
.background(Color.white)
.cornerRadius(29)
Button(action:sendRequest)
{
Image(systemName: "arrow.up.circle.fill")
.foregroundColor(Color.blue)
.frame(width: 50, height: 45 )
.font(Font.system(size: 35))
}
.buttonStyle(PlainButtonStyle())
}
.padding()
.background(Color.white.opacity(0.9))
.cornerRadius(50)
.padding(.horizontal, 20)
.padding(.bottom, 70)
}
.frame(minWidth: 900, maxWidth: 6000, minHeight: 600, maxHeight: 7000)
.background(Color.white.opacity(0.1))
.cornerRadius(29)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
}
And below this is my Python program with Fast API that I want to add into my swift Xcode project:
import os import fastapi import openai import tkinter as tk from fastapi import FastAPI, Request import uvicorn import requests import socket
app = FastAPI(max_request_size = 100000000)
API_KEY = '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' engine = "text-davinci-003"
os.environ['AI_KEY'] = API_KEY openai.api_key = os.environ['AI_KEY']
@app.get("/") async def handle_requests(): return{"demo"}
async def MacGPT(request : Request): print(f"max request size: {request.app.max_request_size}") data = await request.json() userMessage = data['userMessage'] response = openai.Completion.create(engine = engine, prompt = userMessage, max_tokens = 200) result = response ["choices"][0]["text"] return {"result" : result}
@app.post("/MacGPT") async def MacGPT(request : Request): data = await request.json() userMessage = data['userMessage'] response = openai.Completion.create(engine = engine, prompt = userMessage, max_tokens = 200) result = response ["choices"]['0']["text"] return {"result" : result }
def submit_callback(): prompt = user_input.get() response = openai.Completion.create(engine = engine, prompt = prompt, max_tokens = 200) result = response["choices"][0]["text"] result_label.config(text=result)
root = tk.Tk() root.title("Mac GPT") user_input = tk.Entry(root) user_input.pack()
user_submit_button = tk.Button(root, text="Send", command = submit_callback ) user_submit_button.pack() result_label = tk.Label(root, text="") result_label.pack()
root.mainloop()