Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using OpenAI API with Swift

Introduction

This tutorial demonstrates how to integrate and use the OpenAI API with Swift to leverage advanced AI capabilities in your applications.

1. Setting Up Your OpenAI API Key

Before starting, make sure you have your OpenAI API key ready. You can obtain it from the OpenAI website after signing up for an account.

2. Making API Requests

To make requests to the OpenAI API using Swift, you'll use URLSession for HTTP requests.

Text Completion

Here’s an example of making a request for text completion:

import Foundation

let apiKey = "YOUR_API_KEY_HERE"
let url = URL(string: "https://api.openai.com/v1/completions")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")

let body: [String: Any] = [
    "model": "text-davinci-003",
    "prompt": "Translate English to French: Hello, how are you?",
    "max_tokens": 50
]

request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let data = data {
        if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            if let choices = json["choices"] as? [[String: Any]], let text = choices.first?["text"] as? String {
                print("Translated Text: \(text.trimmingCharacters(in: .whitespacesAndNewlines))")
            }
        }
    }
}

task.resume()
                    

Output: Translated Text: Bonjour, comment ça va?

This Swift code sends a POST request to the OpenAI API for text completion and prints the API response.

Code Generation

Here’s an example of making a request for code generation:

import Foundation

let apiKey = "YOUR_API_KEY_HERE"
let url = URL(string: "https://api.openai.com/v1/engines/davinci-codex/completions")!

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")

let body: [String: Any] = [
    "prompt": "Generate Python code to sort an array using bubble sort",
    "max_tokens": 150,
    "stop": ["\n"]
]

request.httpBody = try? JSONSerialization.data(withJSONObject: body)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    if let data = data {
        if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
            if let choices = json["choices"] as? [[String: Any]], let text = choices.first?["text"] as? String {
                print("Generated Code: \(text.trimmingCharacters(in: .whitespacesAndNewlines))")
            }
        }
    }
}

task.resume()
                    
Output: 
    ```python
    def bubble_sort(arr):
        n = len(arr)
        for i in range(n):
            for j in range(0, n-i-1):
                if arr[j] > arr[j+1]:
                    arr[j], arr[j+1] = arr[j+1], arr[j]
        return arr
    ```
                    

This Swift code sends a POST request to the OpenAI Codex engine for code generation and prints the generated code.

3. Handling Responses

Once you receive a response from the API, you can handle it in your Swift code.

Text Completion

Here’s how you might handle the completion response:

// Assuming `data` contains the API response data
if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
    if let choices = json["choices"] as? [[String: Any]], let text = choices.first?["text"] as? String {
        print("Translated Text: \(text.trimmingCharacters(in: .whitespacesAndNewlines))")
    }
}
                    

In this example, `data` contains the JSON response from the OpenAI API.

Code Generation

Here’s how you might handle the code generation response:

// Assuming `data` contains the API response data
if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
    if let choices = json["choices"] as? [[String: Any]], let text = choices.first?["text"] as? String {
        print("Generated Code: \(text.trimmingCharacters(in: .whitespacesAndNewlines))")
    }
}
                    

In this example, `data` contains the JSON response from the OpenAI API with the generated code.

Conclusion

Integrating the OpenAI API with Swift allows you to enhance your applications with powerful AI capabilities. Explore more API endpoints and functionalities to innovate further.