• Stars
    star
    563
  • Rank 76,441 (Top 2 %)
  • Language
    Swift
  • License
    MIT License
  • Created over 1 year ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Access ChatGPT API using Swift

ChatGPTSwift API

Alt text

Access OpenAI ChatGPT Official API using Swift. Works on all Apple platforms.

Supported Platforms

  • iOS/tvOS 15 and above
  • macOS 12 and above
  • watchOS 8 and above
  • Linux

Installation

Swift Package Manager

Cocoapods

platform :ios, '15.0'
use_frameworks!

target 'MyApp' do
  pod 'ChatGPTSwift', '~> 1.3.1'
end

Requirement

Register for API key from OpenAI. Initialize with api key

let api = ChatGPTAPI(apiKey: "API_KEY")

Usage

There are 2 APIs: stream and normal

Stream

The server will stream chunks of data until complete, the method AsyncThrowingStream which you can loop using For-Loop like so:

Task {
    do {
        let stream = try await api.sendMessageStream(text: "What is ChatGPT?")
        for try await line in stream {
            print(line)
        }
    } catch {
        print(error.localizedDescription)
    }
}

Normal

A normal HTTP request and response lifecycle. Server will send the complete text (it will take more time to response)

Task {
    do {
        let response = try await api.sendMessage(text: "What is ChatGPT?")
        print(response)
    } catch {
        print(error.localizedDescription)
    }
}
        

Providing extra parameters

Optionally, you can provide the model, system prompt, temperature, and model like so.

let response = try await api.sendMessage(text: "What is ChatGPT?",
                                         model: "gpt-4",
                                         systemText: "You are a CS Professor",
                                         temperature: 0.5)

Default values for these parameters are:

  • model: gpt-3.5-turbo
  • systemText: You're a helpful assistant
  • temperature: 0.5

To learn more about those parameters, you can visit the official ChatGPT API documentation and ChatGPT API Introduction Page

History List

The client stores the history list of the conversation that will be included in the new prompt so ChatGPT aware of the previous context of conversation. When sending new prompt, the client will make sure the token count is not exceeding 4096 using GPTEncoder library to calculate tokens in string, in case it exceeded the token, some of previous conversations will be truncated. In future i will provide an API to specify the token threshold as new gpt-4 model accept much bigger 8k tokens in a prompt.

View Current History List

You can view current history list from the historyList property.

print(api.historyList)

Delete History List

You can also delete the history list by invoking

api.deleteHistoryList()

Replace History List

You can provide your own History List, this will replace the stored history list. Remember not to pass the 4096 tokens threshold.

let myHistoryList = [
    Message(role: "user", content: "who is james bond?")
    Message(role: "assistant", content: "secret british agent with codename 007"),
    Message(role: "user", content: "which one is the latest movie?"),
    Message(role: "assistant", content: "It's No Time to Die played by Daniel Craig")
]

api.replaceHistoryList(with: myHistoryList)

GPT Encoder Lib

I've also created GPTEncoder Swift BPE Encoder/Decoder for OpenAI GPT Models. A programmatic interface for tokenizing text for OpenAI GPT API.

GPT Tokenizer UI Lib

I've also created GPTTokenizerUI, a SPM lib you can integrate in your app for providing GUI to input text and show the tokenization results used by GPT API.

Alt text

Demo Apps

You can check the demo apps for iOS and macOS from the SwiftUIChatGPT repo

More Repositories

1

ChatGPTSwiftUI

A ChatGPT native iOS, macOS, watchOS, tvOS SwiftUI Application
Swift
540
star
2

CoronaVirusTrackerSwiftUI

Corona Virus Tracker & Advices iOS App with SwiftUI
Swift
369
star
3

SwiftUICDExpenseTrackerCompleted

Building Expense Tracker iOS App with Core Data & SwiftUI Completed Project
Swift
320
star
4

SwiftUI-MovieDB

SwiftUI MovieDB prototype app built with Xcode 11 Beta & macOS 10.15 Catalina
Swift
309
star
5

NewsAppSwiftUI

A Full News App based on the latest SwiftUI 3 API and Swift 5.5 that fetches latest news from newsapi.org. Multiplatform support targeting iOS 15, macOS 12, watchOS 8, tvOS 15.
Swift
184
star
6

flutter_qr_code_scanner_generator_sharing

Flutter App For Scanning, Generating, Sharing QR Code
Dart
137
star
7

SwiftUITMDbV2

SwiftUI MovieDB with TMDb API App with UI similar to Apple TV iOS App
Swift
108
star
8

KanbanDragDropiOS

Kanban Board using Drag & Drop iOS API
Swift
106
star
9

SwiftUI-TrelloClone

Trello Clone iOS App build with SwiftUI
Swift
102
star
10

CoronaVirusTrackerFlutter

Corona Virus Tracker & Advices App with Flutter
Dart
89
star
11

ImageFilterSwiftUICompleted

Completed Project for Cross Platform Image Filter SwiftUI macOS & iOS App
Swift
87
star
12

AppClipCodeGenerator

App Clip Code Generator macOS App built with SwiftUI
Swift
83
star
13

FootballDataSwiftUI

Display Football Data such as scores, upcoming match, team standing, top scorers with football Data API and SwiftUI
Swift
83
star
14

GPTEncoder

Swift BPE Encoder/Decoder for OpenAI GPT Models. A programmatic interface for tokenizing text for OpenAI ChatGPT API.
Swift
72
star
15

AppleCombineMarbleVisualizer

Live Marble Diagram Visualizer for Apple Combine framework on Apple Platform
Swift
65
star
16

Covid19StatsWidgetKit

COVID-19 Stats WidgetKit sample implementation. Uses API from https://covid19api.com
Swift
64
star
17

NoteAppSwiftData

SwiftData Sample Note App
Swift
61
star
18

macOS-iOS-Catalyst-MovieDB-App

macOS & iOS Catalyst MovieDB app built with Xcode 11
Swift
61
star
19

CoreMLVisionScanner

CoreML Vision Text Data & Animal Detector iOS App
Swift
58
star
20

node-grpc-server-note-crud

gRPC Server and Client Example for CRUD Note Service using node.js
JavaScript
58
star
21

ARInventorySwiftUI

A visionOS & iOS Realtime Inventory Tracker App with seamless Augmented Reality Integration
Swift
50
star
22

SwiftUIAuthenticationCompleted

Completed Project for Authentication in SwiftUI using Firebase Auth SDK & Sign in with Apple
Swift
49
star
23

BarcodeTextScannerSwiftUI

Live Barcode & Text Scanner SwiftUI App with VisionKit
Swift
49
star
24

XCAStocksAPI

Swift wrapper for Yahoo Finance REST API
Swift
49
star
25

vCardCoreNFCWriter

vCard writer and reader using iOS 13 CoreNFC API
Swift
48
star
26

flutter_placez

Display & Search your nearby places. This app uses Flutter 1.0 PlatformView to display Google Map as a Flutter Widget in iOS & Android device
Dart
48
star
27

ExpenseTrackerSwiftUICDCKCompleted

Completed Project for Building Expense Tracker iOS & MacOS SwiftUI App with Core Data CloudKit Syncing
Swift
47
star
28

XCAAiAssistant

GPT4 Voice Assistant SwiftUI App
Swift
42
star
29

AppStoreCompositionalLayout

App Store UI using Collection View Compositional Layout
Swift
42
star
30

CryptoTrackerMenuBar

A Realtime Crypto Tracker macOS Menu Bar App built with SwiftUI & WebSocket
Swift
41
star
31

MovieInfoMVVMiOS

Movie Info app using TMDb API built with MVVM
Swift
40
star
32

FlutterMusic

Flutter App that uses Apple Music API to display catalog of music
Dart
39
star
33

FlutterShoppingPayment

Flutter Shopping App with Midtrans as payment gateway
Dart
39
star
34

SwiftUIRealtimeShoppingCart

SwiftUI Collaborative Shopping Cart with Firestore Database
Swift
39
star
35

CoreData-Fetch-API-Background

iOS App that Fetch Star Wars API Using Core Data Background Context
Swift
36
star
36

GPTTokenizerUI

SwiftUI GUI to calculate tokens used by GPT Models
Swift
36
star
37

MRTScheduleSwiftUI

MRT Schedule & Locator iOS App built using SwiftUI
Swift
34
star
38

MovieDBAppClip

MovieDB App Clip iOS 14 Implementation
Swift
33
star
39

USDZScanner

SPM USDZ Lidar Scanner/Capture for iOS based on Apple Object Capture Sample Code
Swift
32
star
40

flutter-hackernews

Hacker News client implemented using Flutter
Dart
31
star
41

iOSCustomInteractivePushNotification

A simple demo showcasing interactive custom push notification UI that has several custom UI
Swift
30
star
42

GenericTableViewController

An example of Generic UITableViewController implementation
Swift
30
star
43

stocksapptutorial

SwiftUI Stocks App Tutorial Completed Project Files
Swift
30
star
44

ImageFilterSwiftUIMac

GPUImage2 based image filtering built with SwiftUI for macOS
Swift
29
star
45

SwiftUIMLKitTranslator

SwiftUI MLKit Language Identification & Translator
Swift
27
star
46

XCAFootballStats

SwiftUI VisionOS App that fetches latest standings and top scorers table
Swift
27
star
47

serverless-node-crud-cloud-function

JavaScript
24
star
48

MovieDBtvOS

Movie Database tvOS App using The Movie DB API
Swift
23
star
49

SwiftUIStaggeredNote

Example app of using StaggeredList in SwiftUI
Swift
21
star
50

SwftGenSwiftUIMac

SwiftUI based macOS app that uses SwiftGen CLI to generate Swift code from various resources
Swift
21
star
51

firestore_algolia_flutter_cloud_function

Firestore Full Text Search with Algolia with Flutter Client App
Dart
21
star
52

ExpenseTrackerWatchOS

Expense Tracker Apple Watch App with SwiftUI & Core Data
Swift
21
star
53

flutter_cloud_text_to_speech

Flutter project that uses the Google Cloud Text to Speech API to synthesize test using REST API
Dart
20
star
54

SwiftUIBiography

SwiftUI iOS The Crazy Ones Biography App
Swift
20
star
55

AppIconGenerator

Import Image and Generate Assets for your iOS, Mac, and Apple Watch
Swift
20
star
56

ios-grpc-note-crud-app

Swift iOS gRPC Client Note Taking App
Swift
19
star
57

ReponsiveCollectionView

A responsive & adaptive Collection View with Dynamic List and Grid support
Swift
19
star
58

SwiftUICoreData

SwiftUI Integration With CoreData FetchedRequest property wrapper
Swift
18
star
59

flutter-github-search

github app built using flutter
Dart
18
star
60

SwiftUICDExpenseTrackerStarter

Starter Project for Building Expense Tracker iOS App with Core Data & SwiftUI
Swift
17
star
61

SwiftAWSLamdaRESTAPI

Swift Todo REST API with AWS Lambda & DynamoDB
Swift
16
star
62

CollectionViewDiffableGameDB

Game DB iOS App using iOS 13 NSDiffableDataSourceSnapshot to filter, sort, and search with animations
Swift
16
star
63

iOSSpeechNaturalLanguage

macOS Catalyst Video Speech Recognizer & Natural Language Recognition App demo
Swift
16
star
64

SVGImageSwiftUI

SwiftUI SVG Image wrapper over SVGKit
Swift
16
star
65

SpendingTracker

SwiftUI Spending Tracker App using Cloud Firestore & Sign in with Apple
Swift
15
star
66

swift-async-await-rest-api

Fetch Multiple Rest API using Swift 5.5 Async Await with Task, TaskGroup, Continuation API
Swift
15
star
67

LiveTextScannerInteraction

Live Text Scanner & Interaction SwiftUI App with VisionKit
Swift
14
star
68

iphonepip

PiP (Picture in Picture) prototype for iPhone
Swift
14
star
69

CoreNFCScanneriOS

Demo of using Core NFC to scan product SKU
Swift
14
star
70

ExpenseTrackerTVOS

Expense Tracker tvOS App SwiftUI and Core Data
Swift
14
star
71

SwiftUI2LazyVGrid

Adaptive Vertical Grid List with LazyVGrid in SwiftUI 2
Swift
14
star
72

chatgpt_api_dart

ChatGPT API Dart Client
Dart
14
star
73

iOSVisualRichLinkApp

Visual Rich Link iOS 13 Example App
Swift
13
star
74

NFCScanneriOSStarter

Starter project for NFC Product Scanner iOS Demo app
Swift
13
star
75

GCDGroup-Complete

Using Dispatch Group & Semaphore to Group iOS Async Tasks - Complete
Swift
13
star
76

XCAOpenAIClient

OpenAI Swift Client Generated from OpenAI OpenAPI YML
Swift
13
star
77

MovieCoordinator-Completed

Completed project of refactoring iOS MVC app using Coordinator for navigation
Swift
13
star
78

LivePolls

Live Activity Realtime Polls SwiftUI App Built with Firebase, APNS
Swift
13
star
79

SwiftUIWebSocketLiveUI

Using WebSocket with Kitura to reload live SwiftUI View
Swift
12
star
80

SwiftUIStaggeredList

Staggered Layout List Using SwiftUI
Swift
12
star
81

firenotes

Flutter note taking app using firestore and firebase storage
Dart
12
star
82

flutter_news_windows

A Windows News App built with Flutter and Fluent UI Theme
C++
12
star
83

XCAWAStickerMaker

A WhatsApp Sticker Maker iOS App with Vision API Subject Lifting / Background Removal
Swift
12
star
84

XCANewsLiveWidget

Swift
11
star
85

CombineFetchAPICompleted

Combine Fetch TMDb API completed project
Swift
11
star
86

CompletedTableViewDiffableDataSource

Swift
11
star
87

ios-todo-viper

iOS TodoList App using VIPER Architecture
Swift
11
star
88

FlutterPortableDashboard

Flutter Portable UI Dashboard
JavaScript
11
star
89

responsive-ios-collection-view-starter

Starter project for Responsive and Adaptive iOS App with Collection View
Swift
10
star
90

GameDBSearchToken

GameDB iOS 13 app showcasing the usage of UISearchToken to filter by genre and platforms using IGDB API
Swift
10
star
91

SwiftUI-GameDB-Completed

SwiftUI Game DB app that uses IGDB API to fetch game data
Swift
10
star
92

flutter_google_cloud_video_intelligence

Using Google Cloud Video Intelligence in Flutter App to analyze video
Dart
10
star
93

aitext2imageapp

AI Text2Image iOS App with OpenAPI <> OpenAI Swift Client Generation
Swift
10
star
94

SwiftUIPropertyWrappersDemo

SwiftUI Demo app showcasing the usage of custom property wrappers
Swift
10
star
95

ImageFilterSwiftUIStarter

Starter Project for Cross Platform Image Filter SwiftUI macOS & iOS App
Swift
10
star
96

Filter-MVC-iOS

Using Child View Controllers for encapsulation, reusability, and avoid Massive View Controller
Swift
10
star
97

AIExpenseTracker

Swift
10
star
98

ITunesFeedSwiftUI

This library provides SwiftUI Views and ObservableObject for fetching iTunes Feed using ITunesFeedGenerator library
Swift
9
star
99

SwiftUI2Outlines

Sample app to learn about how to represent hierarchical data in the UI using new SwiftUI 2.0 Views, Outline & Disclosure Group
Swift
9
star
100

FaceComparisonMacOS

Face Comparison App with SwiftUI and AWS Face Rekognition
Swift
9
star