Skip to content

Instantly share code, notes, and snippets.

@theoknock
Last active December 8, 2023 19:28
Show Gist options
  • Save theoknock/3f1aed48d93163e96fb46b7ed6e6425d to your computer and use it in GitHub Desktop.
Save theoknock/3f1aed48d93163e96fb46b7ed6e6425d to your computer and use it in GitHub Desktop.
Getting the Assistant ID (OpenAI - ChatGPT). The first step to setting up a multiturn conversation with ChatGPT...
struct Assistant: Codable {
let id: String
}
func getAssistant(globalData: GlobalData) {
let url = URL(string: "https://api.openai.com/v1/assistants")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer [key]", forHTTPHeaderField: "Authorization")
request.addValue("org-jGOqXYFRJHKlnkff8K836fK2", forHTTPHeaderField: "OpenAI-Organization")
request.addValue("assistants=v1", forHTTPHeaderField: "OpenAI-Beta")
let type: [Dictionary] = [["type": "code_interpreter"]]
let assistant_request: Dictionary =
[
"instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.",
"name": "Math Tutor",
"tools": type,
"model": "gpt-4"
] as [String : Any]
let jsonData = try! JSONSerialization.data(withJSONObject: assistant_request, options: [])
request.httpBody = jsonData
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if error == nil && data != nil {
do {
if let assistant_response = try JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any] {
let id = assistant_response["id"] as? String
print("id:\t\(id ?? "")")
DispatchQueue.main.async {
globalData.someGlobalData = id ?? "No ID"
}
print(assistant_response)
}
} catch {
print("Error")
}
}
}
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment