-
-
Save mbrian23/6863ffa705ccbb5097bd07efb2355a30 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import SwiftUI | |
import SwiftOpenAI | |
struct ContentView: View { | |
@State var openAIHandler = SwiftOpenAIHandler() | |
var body: some View { | |
Button("Run example") { | |
Task { | |
do { | |
let thread = try await openAIHandler.createThread() | |
let assistant = try await openAIHandler.getAssistant() | |
_ = try await openAIHandler.addMessage(thread: thread, prompt: "Hello, World") | |
_ = try await openAIHandler.createRun(thread: thread, assistant: assistant) | |
} catch { | |
print(error) | |
print(error.localizedDescription) | |
} | |
} | |
} | |
} | |
} | |
class SwiftOpenAIHandler { | |
private lazy var service: OpenAIService = getService() | |
private var assistant: AssistantObject? | |
private func getService() -> some OpenAIService { | |
#if DEBUG && targetEnvironment(simulator) | |
let service = OpenAIServiceFactory.service( | |
// TODO: Add these credentials | |
aiproxyPartialKey: , | |
aiproxyDeviceCheckBypass: | |
) | |
#else | |
let service = OpenAIServiceFactory.service( | |
// TODO: Add these credentials | |
aiproxyPartialKey: , | |
) | |
#endif | |
return service | |
} | |
func getAssistant() async throws -> AssistantObject { | |
// https://platform.openai.com/assistants | |
// TODO: Fill this | |
let assistantID = | |
let assistant = try await service.retrieveAssistant(id: assistantID) | |
return assistant | |
} | |
func createThread() async throws -> ThreadObject { | |
let parameters = CreateThreadParameters(messages: [], metadata: [:]) | |
let thread = try await service.createThread(parameters: parameters) | |
return thread | |
} | |
func addMessage(thread: ThreadObject, prompt: String) async throws -> MessageObject { | |
let parameters = MessageParameter(role: .user, content: prompt) | |
let message = try await service.createMessage(threadID: thread.id, parameters: parameters) | |
return message | |
} | |
func createRun(thread: ThreadObject, assistant: AssistantObject) async throws -> RunObject { | |
let assistantId = assistant.id | |
let threadId = thread.id | |
let parameters = RunParameter(assistantID: assistantId) | |
let run = try await service.createRun(threadID: threadId, parameters: parameters) | |
return run | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment