├── .github ├── FUNDING.yml └── workflows │ ├── code-quality.yml │ └── deploy-docs.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── Package.resolved ├── Package.swift ├── Playground ├── Playground.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ └── contents.xcworkspacedata └── Playground │ ├── App │ └── PlaygroundApp.swift │ ├── Preview Content │ └── Preview Assets.xcassets │ │ └── Contents.json │ ├── Resources │ └── Assets.xcassets │ │ ├── AccentColor.colorset │ │ └── Contents.json │ │ ├── AppIcon.appiconset │ │ └── Contents.json │ │ └── Contents.json │ ├── ViewModels │ └── AppViewModel.swift │ └── Views │ ├── AppView.swift │ ├── ModelListView.swift │ └── SettingsView.swift ├── README.md ├── Sources └── AIModelRetriever │ ├── AIModel.swift │ ├── AIModelRetriever.swift │ ├── AIModelRetrieverError.swift │ └── Documentation.docc │ └── Documentation.md └── Tests └── AIModelRetrieverTests ├── AIModelRetrieverTests.swift └── URLProtocolMock.swift /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: ["kevinhermawan"] 2 | custom: 3 | [ 4 | "https://buymeacoffee.com/kevinhermawan" 5 | ] 6 | -------------------------------------------------------------------------------- /.github/workflows/code-quality.yml: -------------------------------------------------------------------------------- 1 | name: Code Quality 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | test-ios: 13 | runs-on: macos-15 14 | 15 | steps: 16 | - uses: actions/checkout@v4 17 | 18 | - name: Build and test 19 | run: xcodebuild test -scheme AIModelRetriever -destination 'platform=iOS Simulator,name=iPhone 16 Pro' 20 | 21 | test-macos: 22 | runs-on: macos-15 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | 27 | - name: Build and test 28 | run: xcodebuild test -scheme AIModelRetriever -destination 'platform=macOS,arch=x86_64' 29 | -------------------------------------------------------------------------------- /.github/workflows/deploy-docs.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Docs 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | permissions: 8 | contents: read 9 | pages: write 10 | id-token: write 11 | 12 | concurrency: 13 | group: "pages" 14 | cancel-in-progress: false 15 | 16 | jobs: 17 | deploy: 18 | runs-on: macos-15 19 | 20 | environment: 21 | name: github-pages 22 | url: ${{ steps.deployment.outputs.page_url }} 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | - uses: actions/configure-pages@v5 27 | 28 | - name: Build docs 29 | run: swift package --allow-writing-to-directory ./docs generate-documentation --target AIModelRetriever --disable-indexing --output-path ./docs --transform-for-static-hosting --hosting-base-path swift-ai-model-retriever 30 | 31 | - uses: actions/upload-pages-artifact@v3 32 | with: 33 | path: "docs" 34 | 35 | - uses: actions/deploy-pages@v4 36 | id: deployment 37 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | /.build 3 | /Packages 4 | xcuserdata/ 5 | DerivedData/ 6 | .swiftpm/configuration/registries.json 7 | .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata 8 | .netrc 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 1.2.2 2 | 3 | - feat: adds new Anthropic model (`claude-3-7-sonnet`) by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/10 4 | - feat: adds new Google models (`gemini-2.0-*`) by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/11 5 | 6 | # 1.2.1 7 | 8 | - feat: adds new Anthropic model (`claude-3-5-haiku`) by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/8 9 | - feat: adds new Google model (`gemini-1.0-pro-vision`) by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/9 10 | 11 | # 1.2.0 12 | 13 | - refactor: adds `statusCode` to `serverError` by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/7 14 | 15 | # 1.1.0 16 | 17 | - improve: handles decoding error by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/6 18 | 19 | # 1.0.3 20 | 21 | - feat: conforms to `Sendable` by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/4 22 | - improve: adds better error handling by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/5 23 | 24 | # 1.0.2 25 | 26 | - feat: adds new provider (Cohere) by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/3 27 | 28 | # 1.0.1 29 | 30 | - chore: adds SPI badges by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/1 31 | - feat: adds new Anthropic model (`claude-3-5-sonnet-20241022`) by @kevinhermawan in https://github.com/kevinhermawan/swift-ai-model-retriever/pull/2 32 | 33 | # 1.0.0 34 | 35 | Initial release 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "pins" : [ 3 | { 4 | "identity" : "swift-docc-plugin", 5 | "kind" : "remoteSourceControl", 6 | "location" : "https://github.com/apple/swift-docc-plugin.git", 7 | "state" : { 8 | "revision" : "85e4bb4e1cd62cec64a4b8e769dcefdf0c5b9d64", 9 | "version" : "1.4.3" 10 | } 11 | }, 12 | { 13 | "identity" : "swift-docc-symbolkit", 14 | "kind" : "remoteSourceControl", 15 | "location" : "https://github.com/swiftlang/swift-docc-symbolkit", 16 | "state" : { 17 | "revision" : "b45d1f2ed151d057b54504d653e0da5552844e34", 18 | "version" : "1.0.0" 19 | } 20 | } 21 | ], 22 | "version" : 2 23 | } 24 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version: 5.10 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "AIModelRetriever", 8 | platforms: [.iOS(.v15), .macOS(.v12)], 9 | products: [ 10 | .library( 11 | name: "AIModelRetriever", 12 | targets: ["AIModelRetriever"]), 13 | ], 14 | dependencies: [ 15 | .package(url: "https://github.com/apple/swift-docc-plugin.git", .upToNextMajor(from: "1.4.3")) 16 | ], 17 | targets: [ 18 | .target( 19 | name: "AIModelRetriever"), 20 | .testTarget( 21 | name: "AIModelRetrieverTests", 22 | dependencies: ["AIModelRetriever"] 23 | ) 24 | ] 25 | ) 26 | -------------------------------------------------------------------------------- /Playground/Playground.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 77; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 0A2EB5DD2CBC85A600635480 /* AIModelRetriever in Frameworks */ = {isa = PBXBuildFile; productRef = 0A2EB5DC2CBC85A600635480 /* AIModelRetriever */; }; 11 | /* End PBXBuildFile section */ 12 | 13 | /* Begin PBXFileReference section */ 14 | 0A2EB5CA2CBC859100635480 /* Playground.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Playground.app; sourceTree = BUILT_PRODUCTS_DIR; }; 15 | /* End PBXFileReference section */ 16 | 17 | /* Begin PBXFileSystemSynchronizedRootGroup section */ 18 | 0A2EB5CC2CBC859100635480 /* Playground */ = { 19 | isa = PBXFileSystemSynchronizedRootGroup; 20 | path = Playground; 21 | sourceTree = ""; 22 | }; 23 | /* End PBXFileSystemSynchronizedRootGroup section */ 24 | 25 | /* Begin PBXFrameworksBuildPhase section */ 26 | 0A2EB5C72CBC859100635480 /* Frameworks */ = { 27 | isa = PBXFrameworksBuildPhase; 28 | buildActionMask = 2147483647; 29 | files = ( 30 | 0A2EB5DD2CBC85A600635480 /* AIModelRetriever in Frameworks */, 31 | ); 32 | runOnlyForDeploymentPostprocessing = 0; 33 | }; 34 | /* End PBXFrameworksBuildPhase section */ 35 | 36 | /* Begin PBXGroup section */ 37 | 0A2EB5C12CBC859100635480 = { 38 | isa = PBXGroup; 39 | children = ( 40 | 0A2EB5CC2CBC859100635480 /* Playground */, 41 | 0A2EB5CB2CBC859100635480 /* Products */, 42 | ); 43 | sourceTree = ""; 44 | }; 45 | 0A2EB5CB2CBC859100635480 /* Products */ = { 46 | isa = PBXGroup; 47 | children = ( 48 | 0A2EB5CA2CBC859100635480 /* Playground.app */, 49 | ); 50 | name = Products; 51 | sourceTree = ""; 52 | }; 53 | /* End PBXGroup section */ 54 | 55 | /* Begin PBXNativeTarget section */ 56 | 0A2EB5C92CBC859100635480 /* Playground */ = { 57 | isa = PBXNativeTarget; 58 | buildConfigurationList = 0A2EB5D82CBC859300635480 /* Build configuration list for PBXNativeTarget "Playground" */; 59 | buildPhases = ( 60 | 0A2EB5C62CBC859100635480 /* Sources */, 61 | 0A2EB5C72CBC859100635480 /* Frameworks */, 62 | 0A2EB5C82CBC859100635480 /* Resources */, 63 | ); 64 | buildRules = ( 65 | ); 66 | dependencies = ( 67 | ); 68 | fileSystemSynchronizedGroups = ( 69 | 0A2EB5CC2CBC859100635480 /* Playground */, 70 | ); 71 | name = Playground; 72 | packageProductDependencies = ( 73 | 0A2EB5DC2CBC85A600635480 /* AIModelRetriever */, 74 | ); 75 | productName = Playground; 76 | productReference = 0A2EB5CA2CBC859100635480 /* Playground.app */; 77 | productType = "com.apple.product-type.application"; 78 | }; 79 | /* End PBXNativeTarget section */ 80 | 81 | /* Begin PBXProject section */ 82 | 0A2EB5C22CBC859100635480 /* Project object */ = { 83 | isa = PBXProject; 84 | attributes = { 85 | BuildIndependentTargetsInParallel = 1; 86 | LastSwiftUpdateCheck = 1600; 87 | LastUpgradeCheck = 1600; 88 | TargetAttributes = { 89 | 0A2EB5C92CBC859100635480 = { 90 | CreatedOnToolsVersion = 16.0; 91 | }; 92 | }; 93 | }; 94 | buildConfigurationList = 0A2EB5C52CBC859100635480 /* Build configuration list for PBXProject "Playground" */; 95 | developmentRegion = en; 96 | hasScannedForEncodings = 0; 97 | knownRegions = ( 98 | en, 99 | Base, 100 | ); 101 | mainGroup = 0A2EB5C12CBC859100635480; 102 | minimizedProjectReferenceProxies = 1; 103 | packageReferences = ( 104 | 0A2EB5DB2CBC85A600635480 /* XCLocalSwiftPackageReference "../../swift-ai-model-retriever" */, 105 | ); 106 | preferredProjectObjectVersion = 77; 107 | productRefGroup = 0A2EB5CB2CBC859100635480 /* Products */; 108 | projectDirPath = ""; 109 | projectRoot = ""; 110 | targets = ( 111 | 0A2EB5C92CBC859100635480 /* Playground */, 112 | ); 113 | }; 114 | /* End PBXProject section */ 115 | 116 | /* Begin PBXResourcesBuildPhase section */ 117 | 0A2EB5C82CBC859100635480 /* Resources */ = { 118 | isa = PBXResourcesBuildPhase; 119 | buildActionMask = 2147483647; 120 | files = ( 121 | ); 122 | runOnlyForDeploymentPostprocessing = 0; 123 | }; 124 | /* End PBXResourcesBuildPhase section */ 125 | 126 | /* Begin PBXSourcesBuildPhase section */ 127 | 0A2EB5C62CBC859100635480 /* Sources */ = { 128 | isa = PBXSourcesBuildPhase; 129 | buildActionMask = 2147483647; 130 | files = ( 131 | ); 132 | runOnlyForDeploymentPostprocessing = 0; 133 | }; 134 | /* End PBXSourcesBuildPhase section */ 135 | 136 | /* Begin XCBuildConfiguration section */ 137 | 0A2EB5D62CBC859300635480 /* Debug */ = { 138 | isa = XCBuildConfiguration; 139 | buildSettings = { 140 | ALWAYS_SEARCH_USER_PATHS = NO; 141 | ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; 142 | CLANG_ANALYZER_NONNULL = YES; 143 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 144 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; 145 | CLANG_ENABLE_MODULES = YES; 146 | CLANG_ENABLE_OBJC_ARC = YES; 147 | CLANG_ENABLE_OBJC_WEAK = YES; 148 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 149 | CLANG_WARN_BOOL_CONVERSION = YES; 150 | CLANG_WARN_COMMA = YES; 151 | CLANG_WARN_CONSTANT_CONVERSION = YES; 152 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 153 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 154 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 155 | CLANG_WARN_EMPTY_BODY = YES; 156 | CLANG_WARN_ENUM_CONVERSION = YES; 157 | CLANG_WARN_INFINITE_RECURSION = YES; 158 | CLANG_WARN_INT_CONVERSION = YES; 159 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 160 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 161 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 162 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 163 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; 164 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 165 | CLANG_WARN_STRICT_PROTOTYPES = YES; 166 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 167 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 168 | CLANG_WARN_UNREACHABLE_CODE = YES; 169 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 170 | COPY_PHASE_STRIP = NO; 171 | DEBUG_INFORMATION_FORMAT = dwarf; 172 | ENABLE_STRICT_OBJC_MSGSEND = YES; 173 | ENABLE_TESTABILITY = YES; 174 | ENABLE_USER_SCRIPT_SANDBOXING = YES; 175 | GCC_C_LANGUAGE_STANDARD = gnu17; 176 | GCC_DYNAMIC_NO_PIC = NO; 177 | GCC_NO_COMMON_BLOCKS = YES; 178 | GCC_OPTIMIZATION_LEVEL = 0; 179 | GCC_PREPROCESSOR_DEFINITIONS = ( 180 | "DEBUG=1", 181 | "$(inherited)", 182 | ); 183 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 184 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 185 | GCC_WARN_UNDECLARED_SELECTOR = YES; 186 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 187 | GCC_WARN_UNUSED_FUNCTION = YES; 188 | GCC_WARN_UNUSED_VARIABLE = YES; 189 | IPHONEOS_DEPLOYMENT_TARGET = 18.0; 190 | LOCALIZATION_PREFERS_STRING_CATALOGS = YES; 191 | MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; 192 | MTL_FAST_MATH = YES; 193 | ONLY_ACTIVE_ARCH = YES; 194 | SDKROOT = iphoneos; 195 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; 196 | SWIFT_OPTIMIZATION_LEVEL = "-Onone"; 197 | }; 198 | name = Debug; 199 | }; 200 | 0A2EB5D72CBC859300635480 /* Release */ = { 201 | isa = XCBuildConfiguration; 202 | buildSettings = { 203 | ALWAYS_SEARCH_USER_PATHS = NO; 204 | ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; 205 | CLANG_ANALYZER_NONNULL = YES; 206 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 207 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; 208 | CLANG_ENABLE_MODULES = YES; 209 | CLANG_ENABLE_OBJC_ARC = YES; 210 | CLANG_ENABLE_OBJC_WEAK = YES; 211 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 212 | CLANG_WARN_BOOL_CONVERSION = YES; 213 | CLANG_WARN_COMMA = YES; 214 | CLANG_WARN_CONSTANT_CONVERSION = YES; 215 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; 216 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 217 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 218 | CLANG_WARN_EMPTY_BODY = YES; 219 | CLANG_WARN_ENUM_CONVERSION = YES; 220 | CLANG_WARN_INFINITE_RECURSION = YES; 221 | CLANG_WARN_INT_CONVERSION = YES; 222 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 223 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; 224 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 225 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 226 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; 227 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 228 | CLANG_WARN_STRICT_PROTOTYPES = YES; 229 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 230 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 231 | CLANG_WARN_UNREACHABLE_CODE = YES; 232 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 233 | COPY_PHASE_STRIP = NO; 234 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 235 | ENABLE_NS_ASSERTIONS = NO; 236 | ENABLE_STRICT_OBJC_MSGSEND = YES; 237 | ENABLE_USER_SCRIPT_SANDBOXING = YES; 238 | GCC_C_LANGUAGE_STANDARD = gnu17; 239 | GCC_NO_COMMON_BLOCKS = YES; 240 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 241 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 242 | GCC_WARN_UNDECLARED_SELECTOR = YES; 243 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 244 | GCC_WARN_UNUSED_FUNCTION = YES; 245 | GCC_WARN_UNUSED_VARIABLE = YES; 246 | IPHONEOS_DEPLOYMENT_TARGET = 18.0; 247 | LOCALIZATION_PREFERS_STRING_CATALOGS = YES; 248 | MTL_ENABLE_DEBUG_INFO = NO; 249 | MTL_FAST_MATH = YES; 250 | SDKROOT = iphoneos; 251 | SWIFT_COMPILATION_MODE = wholemodule; 252 | VALIDATE_PRODUCT = YES; 253 | }; 254 | name = Release; 255 | }; 256 | 0A2EB5D92CBC859300635480 /* Debug */ = { 257 | isa = XCBuildConfiguration; 258 | buildSettings = { 259 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 260 | ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; 261 | CODE_SIGN_STYLE = Automatic; 262 | CURRENT_PROJECT_VERSION = 1; 263 | DEVELOPMENT_ASSET_PATHS = "\"Playground/Preview Content\""; 264 | DEVELOPMENT_TEAM = 84ZM7K56B5; 265 | ENABLE_PREVIEWS = YES; 266 | GENERATE_INFOPLIST_FILE = YES; 267 | INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; 268 | INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; 269 | INFOPLIST_KEY_UILaunchScreen_Generation = YES; 270 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; 271 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; 272 | LD_RUNPATH_SEARCH_PATHS = ( 273 | "$(inherited)", 274 | "@executable_path/Frameworks", 275 | ); 276 | MARKETING_VERSION = 1.0; 277 | PRODUCT_BUNDLE_IDENTIFIER = "ai.hermawan.swift-ai-model-retriever.Playground"; 278 | PRODUCT_NAME = "$(TARGET_NAME)"; 279 | SWIFT_EMIT_LOC_STRINGS = YES; 280 | SWIFT_VERSION = 6.0; 281 | TARGETED_DEVICE_FAMILY = "1,2"; 282 | }; 283 | name = Debug; 284 | }; 285 | 0A2EB5DA2CBC859300635480 /* Release */ = { 286 | isa = XCBuildConfiguration; 287 | buildSettings = { 288 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 289 | ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; 290 | CODE_SIGN_STYLE = Automatic; 291 | CURRENT_PROJECT_VERSION = 1; 292 | DEVELOPMENT_ASSET_PATHS = "\"Playground/Preview Content\""; 293 | DEVELOPMENT_TEAM = 84ZM7K56B5; 294 | ENABLE_PREVIEWS = YES; 295 | GENERATE_INFOPLIST_FILE = YES; 296 | INFOPLIST_KEY_UIApplicationSceneManifest_Generation = YES; 297 | INFOPLIST_KEY_UIApplicationSupportsIndirectInputEvents = YES; 298 | INFOPLIST_KEY_UILaunchScreen_Generation = YES; 299 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; 300 | INFOPLIST_KEY_UISupportedInterfaceOrientations_iPhone = "UIInterfaceOrientationPortrait UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight"; 301 | LD_RUNPATH_SEARCH_PATHS = ( 302 | "$(inherited)", 303 | "@executable_path/Frameworks", 304 | ); 305 | MARKETING_VERSION = 1.0; 306 | PRODUCT_BUNDLE_IDENTIFIER = "ai.hermawan.swift-ai-model-retriever.Playground"; 307 | PRODUCT_NAME = "$(TARGET_NAME)"; 308 | SWIFT_EMIT_LOC_STRINGS = YES; 309 | SWIFT_VERSION = 6.0; 310 | TARGETED_DEVICE_FAMILY = "1,2"; 311 | }; 312 | name = Release; 313 | }; 314 | /* End XCBuildConfiguration section */ 315 | 316 | /* Begin XCConfigurationList section */ 317 | 0A2EB5C52CBC859100635480 /* Build configuration list for PBXProject "Playground" */ = { 318 | isa = XCConfigurationList; 319 | buildConfigurations = ( 320 | 0A2EB5D62CBC859300635480 /* Debug */, 321 | 0A2EB5D72CBC859300635480 /* Release */, 322 | ); 323 | defaultConfigurationIsVisible = 0; 324 | defaultConfigurationName = Release; 325 | }; 326 | 0A2EB5D82CBC859300635480 /* Build configuration list for PBXNativeTarget "Playground" */ = { 327 | isa = XCConfigurationList; 328 | buildConfigurations = ( 329 | 0A2EB5D92CBC859300635480 /* Debug */, 330 | 0A2EB5DA2CBC859300635480 /* Release */, 331 | ); 332 | defaultConfigurationIsVisible = 0; 333 | defaultConfigurationName = Release; 334 | }; 335 | /* End XCConfigurationList section */ 336 | 337 | /* Begin XCLocalSwiftPackageReference section */ 338 | 0A2EB5DB2CBC85A600635480 /* XCLocalSwiftPackageReference "../../swift-ai-model-retriever" */ = { 339 | isa = XCLocalSwiftPackageReference; 340 | relativePath = "../../swift-ai-model-retriever"; 341 | }; 342 | /* End XCLocalSwiftPackageReference section */ 343 | 344 | /* Begin XCSwiftPackageProductDependency section */ 345 | 0A2EB5DC2CBC85A600635480 /* AIModelRetriever */ = { 346 | isa = XCSwiftPackageProductDependency; 347 | productName = AIModelRetriever; 348 | }; 349 | /* End XCSwiftPackageProductDependency section */ 350 | }; 351 | rootObject = 0A2EB5C22CBC859100635480 /* Project object */; 352 | } 353 | -------------------------------------------------------------------------------- /Playground/Playground.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Playground/Playground/App/PlaygroundApp.swift: -------------------------------------------------------------------------------- 1 | // 2 | // PlaygroundApp.swift 3 | // Playground 4 | // 5 | // Created by Kevin Hermawan on 10/14/24. 6 | // 7 | 8 | import SwiftUI 9 | 10 | @main 11 | struct PlaygroundApp: App { 12 | @State private var viewModel = AppViewModel() 13 | 14 | var body: some Scene { 15 | WindowGroup { 16 | AppView() 17 | .environment(viewModel) 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Playground/Playground/Preview Content/Preview Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Playground/Playground/Resources/Assets.xcassets/AccentColor.colorset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "colors" : [ 3 | { 4 | "idiom" : "universal" 5 | } 6 | ], 7 | "info" : { 8 | "author" : "xcode", 9 | "version" : 1 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Playground/Playground/Resources/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "platform" : "ios", 6 | "size" : "1024x1024" 7 | }, 8 | { 9 | "appearances" : [ 10 | { 11 | "appearance" : "luminosity", 12 | "value" : "dark" 13 | } 14 | ], 15 | "idiom" : "universal", 16 | "platform" : "ios", 17 | "size" : "1024x1024" 18 | }, 19 | { 20 | "appearances" : [ 21 | { 22 | "appearance" : "luminosity", 23 | "value" : "tinted" 24 | } 25 | ], 26 | "idiom" : "universal", 27 | "platform" : "ios", 28 | "size" : "1024x1024" 29 | } 30 | ], 31 | "info" : { 32 | "author" : "xcode", 33 | "version" : 1 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Playground/Playground/Resources/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "author" : "xcode", 4 | "version" : 1 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /Playground/Playground/ViewModels/AppViewModel.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppViewModel.swift 3 | // Playground 4 | // 5 | // Created by Kevin Hermawan on 10/14/24. 6 | // 7 | 8 | import Foundation 9 | 10 | @MainActor 11 | @Observable 12 | final class AppViewModel { 13 | var cohereAPIKey: String 14 | var groqAPIKey: String 15 | var openaiAPIKey: String 16 | 17 | init() { 18 | self.cohereAPIKey = UserDefaults.standard.string(forKey: "cohereAPIKey") ?? "" 19 | self.groqAPIKey = UserDefaults.standard.string(forKey: "groqAPIKey") ?? "" 20 | self.openaiAPIKey = UserDefaults.standard.string(forKey: "openaiAPIKey") ?? "" 21 | } 22 | 23 | func saveAPIKeys() { 24 | UserDefaults.standard.set(cohereAPIKey, forKey: "cohereAPIKey") 25 | UserDefaults.standard.set(groqAPIKey, forKey: "groqAPIKey") 26 | UserDefaults.standard.set(openaiAPIKey, forKey: "openaiAPIKey") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Playground/Playground/Views/AppView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AppView.swift 3 | // Playground 4 | // 5 | // Created by Kevin Hermawan on 10/14/24. 6 | // 7 | 8 | import SwiftUI 9 | 10 | enum AIProvider: String, CaseIterable { 11 | case anthropic = "Anthropic" 12 | case cohere = "Cohere" 13 | case google = "Google" 14 | case ollama = "Ollama" 15 | case openai = "OpenAI" 16 | case groq = "OpenAI-Compatible (Groq)" 17 | } 18 | 19 | struct AppView: View { 20 | @Environment(AppViewModel.self) private var viewModel 21 | @State private var isSettingsPresented: Bool = false 22 | 23 | var body: some View { 24 | NavigationStack { 25 | List(AIProvider.allCases, id: \.rawValue) { provider in 26 | NavigationLink(provider.rawValue) { 27 | ModelListView(title: provider.rawValue, provider: provider) 28 | } 29 | .disabled(provider == .cohere && viewModel.cohereAPIKey.isEmpty) 30 | .disabled(provider == .groq && viewModel.groqAPIKey.isEmpty) 31 | .disabled(provider == .openai && viewModel.openaiAPIKey.isEmpty) 32 | } 33 | .navigationTitle("Playground") 34 | .navigationBarTitleDisplayMode(.inline) 35 | .toolbar { 36 | ToolbarItem(placement: .primaryAction) { 37 | Button("Settings", systemImage: "gearshape") { 38 | isSettingsPresented = true 39 | } 40 | } 41 | } 42 | .sheet(isPresented: $isSettingsPresented) { 43 | SettingsView() 44 | } 45 | } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Playground/Playground/Views/ModelListView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // ModelListView.swift 3 | // Playground 4 | // 5 | // Created by Kevin Hermawan on 10/14/24. 6 | // 7 | 8 | import SwiftUI 9 | import AIModelRetriever 10 | 11 | struct ModelListView: View { 12 | private let title: String 13 | private let provider: AIProvider 14 | private let retriever = AIModelRetriever() 15 | 16 | @Environment(AppViewModel.self) private var viewModel 17 | 18 | @State private var isFetching: Bool = false 19 | @State private var fetchTask: Task? 20 | @State private var models: [AIModel] = [] 21 | 22 | init(title: String, provider: AIProvider) { 23 | self.title = title 24 | self.provider = provider 25 | } 26 | 27 | var body: some View { 28 | VStack { 29 | if models.isEmpty, isFetching { 30 | VStack(spacing: 16) { 31 | ProgressView() 32 | 33 | Button("Cancel") { 34 | fetchTask?.cancel() 35 | } 36 | } 37 | } else { 38 | List(models) { model in 39 | VStack(alignment: .leading) { 40 | Text(model.id) 41 | .font(.footnote) 42 | .foregroundStyle(.secondary) 43 | 44 | Text(model.name) 45 | } 46 | } 47 | } 48 | } 49 | .navigationTitle(title) 50 | .task { 51 | isFetching = true 52 | 53 | fetchTask = Task { 54 | do { 55 | defer { 56 | self.isFetching = false 57 | self.fetchTask = nil 58 | } 59 | 60 | switch provider { 61 | case .anthropic: 62 | models = retriever.anthropic() 63 | case .cohere: 64 | models = try await retriever.cohere(apiKey: viewModel.cohereAPIKey) 65 | case .google: 66 | models = retriever.google() 67 | case .ollama: 68 | models = try await retriever.ollama() 69 | case .openai: 70 | models = try await retriever.openAI(apiKey: viewModel.openaiAPIKey) 71 | case .groq: 72 | models = try await retriever.openAI(apiKey: viewModel.groqAPIKey, endpoint: URL(string: "https://api.groq.com/openai/v1/models")) 73 | } 74 | } catch { 75 | print(String(describing: error)) 76 | } 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /Playground/Playground/Views/SettingsView.swift: -------------------------------------------------------------------------------- 1 | // 2 | // SettingsView.swift 3 | // Playground 4 | // 5 | // Created by Kevin Hermawan on 10/14/24. 6 | // 7 | 8 | import SwiftUI 9 | 10 | struct SettingsView: View { 11 | @Environment(\.dismiss) private var dismiss 12 | @Environment(AppViewModel.self) private var viewModel 13 | 14 | var body: some View { 15 | @Bindable var viewModelBindable: AppViewModel = viewModel 16 | 17 | NavigationStack { 18 | Form { 19 | Section("Cohere") { 20 | TextField("API Key", text: $viewModelBindable.cohereAPIKey) 21 | } 22 | 23 | Section("OpenAI") { 24 | TextField("API Key", text: $viewModelBindable.openaiAPIKey) 25 | } 26 | 27 | Section("OpenAI-Compatible (Groq)") { 28 | TextField("API Key", text: $viewModelBindable.groqAPIKey) 29 | } 30 | } 31 | .navigationTitle("Settings") 32 | .navigationBarTitleDisplayMode(.inline) 33 | .toolbar { 34 | ToolbarItem(placement: .cancellationAction) { 35 | Button("Cancel", action: { dismiss() }) 36 | } 37 | 38 | ToolbarItem(placement: .confirmationAction) { 39 | Button("Save") { 40 | viewModel.saveAPIKeys() 41 | dismiss() 42 | } 43 | .disabled(viewModel.openaiAPIKey.isEmpty && viewModel.groqAPIKey.isEmpty) 44 | } 45 | } 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AIModelRetriever 2 | 3 | [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fkevinhermawan%2Fswift-ai-model-retriever%2Fbadge%3Ftype%3Dswift-versions)](https://swiftpackageindex.com/kevinhermawan/swift-ai-model-retriever) [![](https://img.shields.io/endpoint?url=https%3A%2F%2Fswiftpackageindex.com%2Fapi%2Fpackages%2Fkevinhermawan%2Fswift-ai-model-retriever%2Fbadge%3Ftype%3Dplatforms)](https://swiftpackageindex.com/kevinhermawan/swift-ai-model-retriever) 4 | 5 | A utility for retrieving AI model information from various providers. 6 | 7 | ## Overview 8 | 9 | The `AIModelRetriever` package provides a simple and unified way to fetch AI model information from different providers such as Anthropic, Google, Ollama, and OpenAI (including OpenAI-compatible APIs). 10 | 11 | ## Installation 12 | 13 | You can add `AIModelRetriever` as a dependency to your project using Swift Package Manager by adding it to the dependencies value of your `Package.swift`. 14 | 15 | ```swift 16 | dependencies: [ 17 | .package(url: "https://github.com/kevinhermawan/swift-ai-model-retriever.git", .upToNextMajor(from: "1.0.0")) 18 | ], 19 | targets: [ 20 | .target( 21 | /// ... 22 | dependencies: [.product(name: "AIModelRetriever", package: "swift-ai-model-retriever")]) 23 | ] 24 | ``` 25 | 26 | Alternatively, in Xcode: 27 | 28 | 1. Open your project in Xcode. 29 | 2. Click on `File` -> `Swift Packages` -> `Add Package Dependency...` 30 | 3. Enter the repository URL: `https://github.com/kevinhermawan/swift-ai-model-retriever.git` 31 | 4. Choose the version you want to add. You probably want to add the latest version. 32 | 5. Click `Add Package`. 33 | 34 | ## Documentation 35 | 36 | You can find the documentation here: [https://kevinhermawan.github.io/swift-ai-model-retriever/documentation/aimodelretriever](https://kevinhermawan.github.io/swift-ai-model-retriever/documentation/aimodelretriever) 37 | 38 | ## Usage 39 | 40 | ### Initialization 41 | 42 | To start using the `AIModelRetriever` package, first import it and create an instance of the `AIModelRetriever` struct: 43 | 44 | ```swift 45 | import AIModelRetriever 46 | 47 | let modelRetriever = AIModelRetriever() 48 | ``` 49 | 50 | ### Retrieving Anthropic Models 51 | 52 | ```swift 53 | let models = modelRetriever.anthropic() 54 | 55 | for model in models { 56 | print("Model ID: \(model.id), Name: \(model.name)") 57 | } 58 | ``` 59 | 60 | > [!NOTE] 61 | > The Anthropic models are hardcoded. They do not require an API call to retrieve. 62 | 63 | ### Retrieving Cohere Models 64 | 65 | ```swift 66 | let models = modelRetriever.cohere(apiKey: "your-cohere-api-key") 67 | 68 | for model in models { 69 | print("Model ID: \(model.id), Name: \(model.name)") 70 | } 71 | ``` 72 | 73 | ### Retrieving Google Models 74 | 75 | ```swift 76 | let models = modelRetriever.google() 77 | 78 | for model in models { 79 | print("Model ID: \(model.id), Name: \(model.name)") 80 | } 81 | ``` 82 | 83 | > [!NOTE] 84 | > The Google models are hardcoded. They do not require an API call to retrieve. 85 | 86 | ### Retrieving Ollama Models 87 | 88 | ```swift 89 | do { 90 | let models = try await retriever.ollama() 91 | 92 | for model in models { 93 | print("Model ID: \(model.id), Name: \(model.name)") 94 | } 95 | } catch { 96 | print("Error retrieving Ollama models: \(error)") 97 | } 98 | ``` 99 | 100 | ### Retrieving OpenAI Models 101 | 102 | ```swift 103 | do { 104 | let models = try await retriever.openAI(apiKey: "your-openai-api-key") 105 | 106 | for model in models { 107 | print("Model ID: \(model.id), Name: \(model.name)") 108 | } 109 | } catch { 110 | print("Error retrieving OpenAI models: \(error)") 111 | } 112 | ``` 113 | 114 | ### Retrieving Models from OpenAI-compatible APIs 115 | 116 | The `openAI(apiKey:endpoint:headers:)` method can also be used with OpenAI-compatible APIs by specifying a custom endpoint: 117 | 118 | ```swift 119 | let customEndpoint = URL(string: "https://api.your-openai-compatible-service.com/v1/models")! 120 | 121 | do { 122 | let models = try await modelRetriever.openAI(apiKey: "your-api-key", endpoint: customEndpoint) 123 | 124 | for model in models { 125 | print("Model ID: \(model.id), Name: \(model.name)") 126 | } 127 | } catch { 128 | print("Error retrieving models from OpenAI-compatible API: \(error)") 129 | } 130 | ``` 131 | 132 | ### Error Handling 133 | 134 | `AIModelRetrieverError` provides structured error handling through the `AIModelRetrieverError` enum. This enum contains several cases that represent different types of errors you might encounter: 135 | 136 | ```swift 137 | do { 138 | let models = try await modelRetriever.openAI(apiKey: "your-api-key") 139 | } catch let error as AIModelRetrieverError { 140 | switch error { 141 | case .serverError(let statusCode, let message): 142 | // Handle server-side errors (e.g., invalid API key, rate limits) 143 | print("Server Error [\(statusCode)]: \(message)") 144 | case .networkError(let error): 145 | // Handle network-related errors (e.g., no internet connection) 146 | print("Network Error: \(error.localizedDescription)") 147 | case .decodingError(let error): 148 | // Handle errors that occur when the response cannot be decoded 149 | print("Decoding Error: \(error)") 150 | case .cancelled: 151 | // Handle requests that are cancelled 152 | print("Request was cancelled") 153 | } 154 | } catch { 155 | // Handle any other errors 156 | print("An unexpected error occurred: \(error)") 157 | } 158 | ``` 159 | 160 | ## Support 161 | 162 | If you find `AIModelRetriever` helpful and would like to support its development, consider making a donation. Your contribution helps maintain the project and develop new features. 163 | 164 | - [GitHub Sponsors](https://github.com/sponsors/kevinhermawan) 165 | - [Buy Me a Coffee](https://buymeacoffee.com/kevinhermawan) 166 | 167 | Your support is greatly appreciated! ❤️ 168 | 169 | ## Contributing 170 | 171 | Contributions are welcome! Please open an issue or submit a pull request if you have any suggestions or improvements. 172 | 173 | ## License 174 | 175 | This repository is available under the [Apache License 2.0](LICENSE). 176 | -------------------------------------------------------------------------------- /Sources/AIModelRetriever/AIModel.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AIModel.swift 3 | // AIModelRetriever 4 | // 5 | // Created by Kevin Hermawan on 10/13/24. 6 | // 7 | 8 | import Foundation 9 | 10 | /// A struct that represents an AI model. 11 | public struct AIModel: Identifiable, Sendable { 12 | /// The unique identifier of the model. 13 | public let id: String 14 | 15 | /// The display name of the model. 16 | public let name: String 17 | } 18 | -------------------------------------------------------------------------------- /Sources/AIModelRetriever/AIModelRetriever.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AIModelRetriever.swift 3 | // AIModelRetriever 4 | // 5 | // Created by Kevin Hermawan on 10/13/24. 6 | // 7 | 8 | import Foundation 9 | #if canImport(FoundationNetworking) 10 | import FoundationNetworking 11 | #endif 12 | 13 | /// A struct that retrieves AI models from various providers. 14 | public struct AIModelRetriever: Sendable { 15 | /// Initializes a new instance of ``AIModelRetriever``. 16 | public init() {} 17 | 18 | private func performRequest(_ request: URLRequest, errorType: E.Type) async throws -> T { 19 | do { 20 | let (data, response) = try await URLSession.shared.data(for: request) 21 | 22 | guard let httpResponse = response as? HTTPURLResponse else { 23 | throw AIModelRetrieverError.serverError(statusCode: 0, message: response.description) 24 | } 25 | 26 | // Check for API errors first, as they might come with 200 status 27 | if let errorResponse = try? JSONDecoder().decode(E.self, from: data) { 28 | throw AIModelRetrieverError.serverError(statusCode: httpResponse.statusCode, message: errorResponse.errorMessage) 29 | } 30 | 31 | guard let httpResponse = response as? HTTPURLResponse, 200...299 ~= httpResponse.statusCode else { 32 | throw AIModelRetrieverError.serverError(statusCode: httpResponse.statusCode, message: response.description) 33 | } 34 | 35 | return try JSONDecoder().decode(T.self, from: data) 36 | } catch is CancellationError { 37 | throw AIModelRetrieverError.cancelled 38 | } catch let error as URLError where error.code == .cancelled { 39 | throw AIModelRetrieverError.cancelled 40 | } catch let error as DecodingError { 41 | throw AIModelRetrieverError.decodingError(error) 42 | } catch let error as AIModelRetrieverError { 43 | throw error 44 | } catch { 45 | throw AIModelRetrieverError.networkError(error) 46 | } 47 | } 48 | 49 | private func createRequest(for endpoint: URL, with headers: [String: String]? = nil) -> URLRequest { 50 | var request = URLRequest(url: endpoint) 51 | request.httpMethod = "GET" 52 | 53 | headers?.forEach { key, value in 54 | request.addValue(value, forHTTPHeaderField: key) 55 | } 56 | 57 | return request 58 | } 59 | } 60 | 61 | // MARK: - Anthropic 62 | public extension AIModelRetriever { 63 | /// Retrieves a list of AI models from Anthropic. 64 | /// 65 | /// The list of available models is sourced from Anthropic's official documentation: 66 | /// [Anthropic Models Documentation](https://docs.anthropic.com/en/docs/about-claude/models) 67 | /// 68 | /// - Returns: An array of ``AIModel`` that represents Anthropic's available models. 69 | func anthropic() -> [AIModel] { 70 | return [ 71 | AIModel(id: "claude-3-7-sonnet-latest", name: "Claude 3.7 Sonnet"), 72 | AIModel(id: "claude-3-5-sonnet-latest", name: "Claude 3.5 Sonnet"), 73 | AIModel(id: "claude-3-5-haiku-latest", name: "Claude 3.5 Haiku"), 74 | AIModel(id: "claude-3-opus-latest", name: "Claude 3 Opus (Latest)") 75 | ] 76 | } 77 | } 78 | 79 | // MARK: - Cohere 80 | public extension AIModelRetriever { 81 | /// Retrieves a list of AI models from Cohere. 82 | /// 83 | /// - Parameters: 84 | /// - apiKey: The API key that authenticates with the API. 85 | /// 86 | /// - Returns: An array of ``AIModel`` that represents Cohere's available models. 87 | /// 88 | /// - Throws: An error that occurs if the request is cancelled, if the network request fails, if the server returns an error, or if the response cannot be decoded. 89 | func cohere(apiKey: String) async throws -> [AIModel] { 90 | guard let defaultEndpoint = URL(string: "https://api.cohere.com/v1/models?page_size=1000") else { return [] } 91 | 92 | let allHeaders = ["Authorization": "Bearer \(apiKey)"] 93 | 94 | let request = createRequest(for: defaultEndpoint, with: allHeaders) 95 | let response: CohereResponse = try await performRequest(request, errorType: CohereError.self) 96 | 97 | return response.models.map { AIModel(id: $0.name, name: $0.name) } 98 | } 99 | 100 | private struct CohereResponse: Decodable { 101 | let models: [CohereModel] 102 | } 103 | 104 | private struct CohereModel: Decodable { 105 | let name: String 106 | } 107 | 108 | private struct CohereError: ProviderError { 109 | let message: String 110 | 111 | var errorMessage: String { message } 112 | } 113 | } 114 | 115 | // MARK: - Google 116 | public extension AIModelRetriever { 117 | /// Retrieves a list of AI models from Google. 118 | /// 119 | /// The list of available models is sourced from Google's official documentation: 120 | /// [Google Models Documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models) 121 | /// 122 | /// - Returns: An array of ``AIModel`` that represents Google's available models. 123 | func google() -> [AIModel] { 124 | return [ 125 | AIModel(id: "gemini-2.0-flash-lite", name: "Gemini 2.0 Flash Lite"), 126 | AIModel(id: "gemini-2.0-flash", name: "Gemini 2.0 Flash"), 127 | AIModel(id: "gemini-1.5-flash", name: "Gemini 1.5 Flash"), 128 | AIModel(id: "gemini-1.5-pro", name: "Gemini 1.5 Pro"), 129 | AIModel(id: "gemini-1.0-pro-vision", name: "Gemini 1.0 Pro Vision"), 130 | AIModel(id: "gemini-1.0-pro", name: "Gemini 1.0 Pro") 131 | ] 132 | } 133 | } 134 | 135 | // MARK: - Ollama 136 | public extension AIModelRetriever { 137 | /// Retrieves a list of AI models from Ollama. 138 | /// 139 | /// - Parameters: 140 | /// - endpoint: The URL endpoint for the Ollama API. If not provided, it defaults to "http://localhost:11434/api/tags". 141 | /// - headers: Optional dictionary of HTTP headers to include in the request. 142 | /// 143 | /// - Returns: An array of ``AIModel`` that represents Ollama's available models. 144 | /// 145 | /// - Throws: An error that occurs if the request is cancelled, if the network request fails, if the server returns an error, or if the response cannot be decoded. 146 | func ollama(endpoint: URL? = nil, headers: [String: String]? = nil) async throws -> [AIModel] { 147 | guard let defaultEndpoint = URL(string: "http://localhost:11434/api/tags") else { return [] } 148 | 149 | let request = createRequest(for: endpoint ?? defaultEndpoint, with: headers) 150 | let response: OllamaResponse = try await performRequest(request, errorType: OllamaError.self) 151 | 152 | return response.models.map { AIModel(id: $0.model, name: $0.name) } 153 | } 154 | 155 | private struct OllamaResponse: Decodable { 156 | let models: [OllamaModel] 157 | } 158 | 159 | private struct OllamaModel: Decodable { 160 | let name: String 161 | let model: String 162 | } 163 | 164 | private struct OllamaError: ProviderError { 165 | let error: Error 166 | 167 | struct Error: Decodable { 168 | let message: String 169 | } 170 | 171 | var errorMessage: String { error.message } 172 | } 173 | } 174 | 175 | // MARK: - OpenAI 176 | public extension AIModelRetriever { 177 | /// Retrieves a list of AI models from OpenAI or OpenAI-compatible APIs. 178 | /// 179 | /// - Parameters: 180 | /// - apiKey: The API key that authenticates with the API. 181 | /// - endpoint: The URL endpoint for the API. If not provided, it defaults to "https://api.openai.com/v1/models". 182 | /// - headers: Optional dictionary of additional HTTP headers to include in the request. 183 | /// 184 | /// - Returns: An array of ``AIModel`` that represents the available models from the specified API. 185 | /// 186 | /// - Throws: An error that occurs if the request is cancelled, if the network request fails, if the server returns an error, or if the response cannot be decoded. 187 | func openAI(apiKey: String, endpoint: URL? = nil, headers: [String: String]? = nil) async throws -> [AIModel] { 188 | guard let defaultEndpoint = URL(string: "https://api.openai.com/v1/models") else { return [] } 189 | 190 | var allHeaders = headers ?? [:] 191 | allHeaders["Authorization"] = "Bearer \(apiKey)" 192 | 193 | let request = createRequest(for: endpoint ?? defaultEndpoint, with: allHeaders) 194 | let response: OpenAIResponse = try await performRequest(request, errorType: OpenAIError.self) 195 | 196 | return response.data.map { AIModel(id: $0.id, name: $0.id) } 197 | } 198 | 199 | private struct OpenAIResponse: Decodable { 200 | let data: [OpenAIModel] 201 | } 202 | 203 | private struct OpenAIModel: Decodable { 204 | let id: String 205 | } 206 | 207 | private struct OpenAIError: ProviderError { 208 | let error: Error 209 | 210 | struct Error: Decodable { 211 | let message: String 212 | } 213 | 214 | var errorMessage: String { error.message } 215 | } 216 | } 217 | 218 | // MARK: - Supporting Types 219 | private extension AIModelRetriever { 220 | protocol ProviderError: Decodable { 221 | var errorMessage: String { get } 222 | } 223 | } 224 | -------------------------------------------------------------------------------- /Sources/AIModelRetriever/AIModelRetrieverError.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AIModelRetrieverError.swift 3 | // AIModelRetriever 4 | // 5 | // Created by Kevin Hermawan on 10/13/24. 6 | // 7 | 8 | import Foundation 9 | 10 | /// An enum that represents errors that can occur during model retrieval. 11 | public enum AIModelRetrieverError: Error, Sendable { 12 | /// An error that occurs during JSON decoding. 13 | /// 14 | /// - Parameter error: The underlying decoding error. 15 | case decodingError(Error) 16 | 17 | /// An error that occurs during network operations. 18 | /// 19 | /// - Parameter error: The underlying network error. 20 | case networkError(Error) 21 | 22 | /// An error returned by the server. 23 | /// 24 | /// - Parameters: 25 | /// - statusCode: The HTTP status code returned by the server. 26 | /// - message: The error message received from the server. 27 | case serverError(statusCode: Int, message: String) 28 | 29 | /// An error that occurs when the request is cancelled. 30 | case cancelled 31 | } 32 | -------------------------------------------------------------------------------- /Sources/AIModelRetriever/Documentation.docc/Documentation.md: -------------------------------------------------------------------------------- 1 | # ``AIModelRetriever`` 2 | 3 | A utility for retrieving AI model information from various providers. 4 | 5 | ## Overview 6 | 7 | The ``AIModelRetriever`` package provides a simple and unified way to fetch AI model information from different providers such as Anthropic, Google, Ollama, and OpenAI (including OpenAI-compatible APIs). 8 | 9 | ## Usage 10 | 11 | ### Initialization 12 | 13 | To start using the ``AIModelRetriever`` package, first import it and create an instance of the ``AIModelRetriever`` struct: 14 | 15 | ```swift 16 | import AIModelRetriever 17 | 18 | let modelRetriever = AIModelRetriever() 19 | ``` 20 | 21 | ### Retrieving Anthropic Models 22 | 23 | ```swift 24 | let models = modelRetriever.anthropic() 25 | 26 | for model in models { 27 | print("Model ID: \(model.id), Name: \(model.name)") 28 | } 29 | ``` 30 | 31 | > The Anthropic models are hardcoded. They do not require an API call to retrieve. 32 | 33 | ### Retrieving Cohere Models 34 | 35 | ```swift 36 | let models = modelRetriever.cohere(apiKey: "your-cohere-api-key") 37 | 38 | for model in models { 39 | print("Model ID: \(model.id), Name: \(model.name)") 40 | } 41 | ``` 42 | 43 | ### Retrieving Google Models 44 | 45 | ```swift 46 | let models = modelRetriever.google() 47 | 48 | for model in models { 49 | print("Model ID: \(model.id), Name: \(model.name)") 50 | } 51 | ``` 52 | 53 | > The Google models are hardcoded. They do not require an API call to retrieve. 54 | 55 | ### Retrieving Ollama Models 56 | 57 | ```swift 58 | do { 59 | let models = try await retriever.ollama() 60 | 61 | for model in models { 62 | print("Model ID: \(model.id), Name: \(model.name)") 63 | } 64 | } catch { 65 | print("Error retrieving Ollama models: \(error)") 66 | } 67 | ``` 68 | 69 | ### Retrieving OpenAI Models 70 | 71 | ```swift 72 | do { 73 | let models = try await retriever.openAI(apiKey: "your-openai-api-key") 74 | 75 | for model in models { 76 | print("Model ID: \(model.id), Name: \(model.name)") 77 | } 78 | } catch { 79 | print("Error retrieving OpenAI models: \(error)") 80 | } 81 | ``` 82 | 83 | ### Retrieving Models from OpenAI-compatible APIs 84 | 85 | The `openAI(apiKey:endpoint:headers:)` method can also be used with OpenAI-compatible APIs by specifying a custom endpoint: 86 | 87 | ```swift 88 | let customEndpoint = URL(string: "https://api.your-openai-compatible-service.com/v1/models")! 89 | 90 | do { 91 | let models = try await modelRetriever.openAI(apiKey: "your-api-key", endpoint: customEndpoint) 92 | 93 | for model in models { 94 | print("Model ID: \(model.id), Name: \(model.name)") 95 | } 96 | } catch { 97 | print("Error retrieving models from OpenAI-compatible API: \(error)") 98 | } 99 | ``` 100 | 101 | ### Error Handling 102 | 103 | ``AIModelRetrieverError`` provides structured error handling through the ``AIModelRetrieverError`` enum. This enum contains several cases that represent different types of errors you might encounter: 104 | 105 | ```swift 106 | do { 107 | let models = try await modelRetriever.openAI(apiKey: "your-api-key") 108 | } catch let error as AIModelRetrieverError { 109 | switch error { 110 | case .serverError(let statusCode, let message): 111 | // Handle server-side errors (e.g., invalid API key, rate limits) 112 | print("Server Error [\(statusCode)]: \(message)") 113 | case .networkError(let error): 114 | // Handle network-related errors (e.g., no internet connection) 115 | print("Network Error: \(error.localizedDescription)") 116 | case .decodingError(let error): 117 | // Handle errors that occur when the response cannot be decoded 118 | print("Decoding Error: \(error)") 119 | case .cancelled: 120 | // Handle requests that are cancelled 121 | print("Request was cancelled") 122 | } 123 | } catch { 124 | // Handle any other errors 125 | print("An unexpected error occurred: \(error)") 126 | } 127 | ``` 128 | -------------------------------------------------------------------------------- /Tests/AIModelRetrieverTests/AIModelRetrieverTests.swift: -------------------------------------------------------------------------------- 1 | // 2 | // AIModelRetrieverTests.swift 3 | // AIModelRetriever 4 | // 5 | // Created by Kevin Hermawan on 10/14/24. 6 | // 7 | 8 | import XCTest 9 | @testable import AIModelRetriever 10 | 11 | final class AIModelRetrieverTests: XCTestCase { 12 | var retriever: AIModelRetriever! 13 | 14 | override func setUp() { 15 | super.setUp() 16 | 17 | retriever = AIModelRetriever() 18 | URLProtocol.registerClass(URLProtocolMock.self) 19 | } 20 | 21 | override func tearDown() { 22 | retriever = nil 23 | URLProtocol.unregisterClass(URLProtocolMock.self) 24 | URLProtocolMock.mockData = nil 25 | URLProtocolMock.mockError = nil 26 | 27 | super.tearDown() 28 | } 29 | 30 | /// Tests that the `anthropic` method returns a non-empty list of models 31 | /// and contains specific expected models. 32 | func testAnthropic() { 33 | let models = retriever.anthropic() 34 | 35 | XCTAssertFalse(models.isEmpty) 36 | XCTAssertTrue(models.contains { $0.id == "claude-3-5-sonnet-latest" }) 37 | XCTAssertTrue(models.contains { $0.name == "Claude 3.5 Sonnet" }) 38 | } 39 | 40 | /// Tests that the `cohere` method successfully retrieves models 41 | /// and maps them correctly from the API response. 42 | func testCohere() async throws { 43 | let mockResponseString = """ 44 | { 45 | "models": [ 46 | {"name": "test-model-1"}, 47 | {"name": "test-model-2"} 48 | ] 49 | } 50 | """ 51 | 52 | URLProtocolMock.mockData = mockResponseString.data(using: .utf8) 53 | 54 | let models = try await retriever.cohere(apiKey: "test-key") 55 | 56 | XCTAssertEqual(models.count, 2) 57 | XCTAssertEqual(models[0].id, "test-model-1") 58 | XCTAssertEqual(models[1].name, "test-model-2") 59 | } 60 | 61 | /// Tests that the `google` method returns a non-empty list of models 62 | /// and contains specific expected models. 63 | func testGoogle() { 64 | let models = retriever.google() 65 | 66 | XCTAssertFalse(models.isEmpty) 67 | XCTAssertTrue(models.contains { $0.id == "gemini-1.5-pro" }) 68 | XCTAssertTrue(models.contains { $0.name == "Gemini 1.5 Pro" }) 69 | } 70 | 71 | /// Tests that the `ollama` method successfully retrieves models 72 | /// and maps them correctly from the API response. 73 | func testOllama() async throws { 74 | let mockResponseString = """ 75 | { 76 | "models": [ 77 | {"name": "Test Model 1", "model": "test-model-1"}, 78 | {"name": "Test Model 2", "model": "test-model-2"} 79 | ] 80 | } 81 | """ 82 | 83 | URLProtocolMock.mockData = mockResponseString.data(using: .utf8) 84 | 85 | let models = try await retriever.ollama() 86 | 87 | XCTAssertEqual(models.count, 2) 88 | XCTAssertEqual(models[0].id, "test-model-1") 89 | XCTAssertEqual(models[1].name, "Test Model 2") 90 | } 91 | 92 | /// Tests that the `openAI` method successfully retrieves models from OpenAI 93 | /// and maps them correctly from the API response. 94 | func testOpenAI() async throws { 95 | let mockResponseString = """ 96 | { 97 | "data": [ 98 | {"id": "gpt-4"}, 99 | {"id": "gpt-3.5-turbo"} 100 | ] 101 | } 102 | """ 103 | 104 | URLProtocolMock.mockData = mockResponseString.data(using: .utf8) 105 | 106 | let models = try await retriever.openAI(apiKey: "test-key") 107 | 108 | XCTAssertEqual(models.count, 2) 109 | XCTAssertEqual(models[0].id, "gpt-4") 110 | XCTAssertEqual(models[1].id, "gpt-3.5-turbo") 111 | } 112 | 113 | /// Tests that the `openAI` method successfully retrieves models from an OpenAI-compatible API 114 | /// and maps them correctly from the API response. 115 | func testOpenAICompatible() async throws { 116 | let mockResponseString = """ 117 | { 118 | "data": [ 119 | {"id": "custom-model-1"}, 120 | {"id": "custom-model-2"} 121 | ] 122 | } 123 | """ 124 | 125 | URLProtocolMock.mockData = mockResponseString.data(using: .utf8) 126 | 127 | let customEndpoint = URL(string: "https://api.custom-openai-service.com/v1/models")! 128 | let models = try await retriever.openAI(apiKey: "test-key", endpoint: customEndpoint) 129 | 130 | XCTAssertEqual(models.count, 2) 131 | XCTAssertEqual(models[0].id, "custom-model-1") 132 | XCTAssertEqual(models[1].id, "custom-model-2") 133 | } 134 | } 135 | 136 | // MARK: - Error Handling 137 | extension AIModelRetrieverTests { 138 | /// Tests that a server error with status code 401 is correctly handled 139 | /// and throws `serverError` with the appropriate message. 140 | func testServerError() async throws { 141 | let mockErrorResponse = """ 142 | { 143 | "error": { 144 | "message": "Invalid API key provided" 145 | } 146 | } 147 | """ 148 | 149 | URLProtocolMock.mockData = mockErrorResponse.data(using: .utf8) 150 | URLProtocolMock.mockStatusCode = 401 151 | 152 | do { 153 | let _ = try await retriever.openAI(apiKey: "test-key") 154 | 155 | XCTFail("Expected serverError to be thrown") 156 | } catch let error as AIModelRetrieverError { 157 | switch error { 158 | case .serverError(let statusCode, let message): 159 | XCTAssertEqual(statusCode, 401) 160 | XCTAssertEqual(message, "Invalid API key provided") 161 | default: 162 | XCTFail("Expected serverError but got \(error)") 163 | } 164 | } 165 | } 166 | 167 | /// Tests that a server error with status code 200 but an error message in the response body 168 | /// is correctly handled and throws `serverError` with the appropriate message. 169 | func testServerErrorWithStatusCode200() async throws { 170 | let mockErrorResponse = """ 171 | { 172 | "error": { 173 | "message": "An error occurred" 174 | } 175 | } 176 | """ 177 | 178 | URLProtocolMock.mockData = mockErrorResponse.data(using: .utf8) 179 | URLProtocolMock.mockStatusCode = 200 180 | 181 | do { 182 | let _ = try await retriever.openAI(apiKey: "test-key") 183 | XCTFail("Expected serverError to be thrown") 184 | } catch let error as AIModelRetrieverError { 185 | switch error { 186 | case .serverError(let statusCode, let message): 187 | XCTAssertEqual(statusCode, 200) 188 | XCTAssertEqual(message, "An error occurred") 189 | default: 190 | XCTFail("Expected serverError but got \(error)") 191 | } 192 | } 193 | } 194 | 195 | /// Tests that a network error (e.g., no internet connection) is correctly handled 196 | /// and throws `networkError` with the appropriate underlying error. 197 | func testNetworkError() async throws { 198 | URLProtocolMock.mockError = NSError( 199 | domain: NSURLErrorDomain, 200 | code: NSURLErrorNotConnectedToInternet, 201 | userInfo: [NSLocalizedDescriptionKey: "The Internet connection appears to be offline."] 202 | ) 203 | 204 | do { 205 | let _ = try await retriever.openAI(apiKey: "test-key") 206 | 207 | XCTFail("Expected networkError to be thrown") 208 | } catch let error as AIModelRetrieverError { 209 | switch error { 210 | case .networkError(let underlyingError): 211 | XCTAssertEqual((underlyingError as NSError).code, NSURLErrorNotConnectedToInternet) 212 | default: 213 | XCTFail("Expected networkError but got \(error)") 214 | } 215 | } 216 | } 217 | 218 | /// Tests that a decoding error (invalid JSON response) is correctly handled 219 | /// and throws `decodingError` with the appropriate underlying error. 220 | func testDecodingError() async throws { 221 | let invalidJSON = "Invalid JSON" 222 | 223 | URLProtocolMock.mockData = invalidJSON.data(using: .utf8) 224 | URLProtocolMock.mockStatusCode = 200 225 | 226 | do { 227 | let _ = try await retriever.openAI(apiKey: "test-key") 228 | 229 | XCTFail("Expected decodingError to be thrown") 230 | } catch let error as AIModelRetrieverError { 231 | switch error { 232 | case .decodingError(let underlyingError): 233 | XCTAssertTrue(underlyingError is DecodingError) 234 | default: 235 | XCTFail("Expected decodingError but got \(error)") 236 | } 237 | } 238 | } 239 | 240 | /// Tests that a cancellation error (e.g., URL loading cancelled) is correctly handled 241 | /// and throws `cancelled`. 242 | func testURLErrorCancelled() async throws { 243 | URLProtocolMock.mockError = URLError(.cancelled) 244 | 245 | do { 246 | let _ = try await retriever.openAI(apiKey: "test-key") 247 | 248 | XCTFail("Expected cancelled error to be thrown") 249 | } catch let error as AIModelRetrieverError { 250 | switch error { 251 | case .cancelled: 252 | break 253 | default: 254 | XCTFail("Expected cancelled error but got \(error)") 255 | } 256 | } 257 | } 258 | 259 | /// Tests that a task cancellation is correctly handled 260 | /// and throws `cancelled` when the task is cancelled before completion. 261 | func testCancellationError() async throws { 262 | let mockResponseString = """ 263 | { 264 | "data": [ 265 | {"id": "gpt-4"}, 266 | {"id": "gpt-3.5-turbo"} 267 | ] 268 | } 269 | """ 270 | 271 | URLProtocolMock.mockData = mockResponseString.data(using: .utf8) 272 | URLProtocolMock.mockStatusCode = 200 273 | URLProtocolMock.responseDelay = 1.0 274 | 275 | let expectation = expectation(description: "Wait for task cancellation") 276 | 277 | let task = Task { 278 | do { 279 | let _ = try await retriever.openAI(apiKey: "test-key") 280 | XCTFail("Expected task to be cancelled") 281 | } catch let error as AIModelRetrieverError { 282 | switch error { 283 | case .cancelled: 284 | expectation.fulfill() 285 | default: 286 | XCTFail("Expected cancelled error but got \(error)") 287 | expectation.fulfill() 288 | } 289 | } catch { 290 | XCTFail("Unexpected error: \(error)") 291 | expectation.fulfill() 292 | } 293 | } 294 | 295 | DispatchQueue.global().asyncAfter(deadline: .now() + 0.1) { 296 | task.cancel() 297 | } 298 | 299 | await fulfillment(of: [expectation], timeout: 2.0) 300 | 301 | URLProtocolMock.responseDelay = nil 302 | } 303 | } 304 | -------------------------------------------------------------------------------- /Tests/AIModelRetrieverTests/URLProtocolMock.swift: -------------------------------------------------------------------------------- 1 | // 2 | // URLProtocolMock.swift 3 | // AIModelRetriever 4 | // 5 | // Created by Kevin Hermawan on 10/14/24. 6 | // 7 | 8 | import Foundation 9 | 10 | final class URLProtocolMock: URLProtocol { 11 | static var mockData: Data? 12 | static var mockError: Error? 13 | static var mockStatusCode: Int? 14 | static var responseDelay: TimeInterval? 15 | 16 | override class func canInit(with request: URLRequest) -> Bool { 17 | return true 18 | } 19 | 20 | override class func canonicalRequest(for request: URLRequest) -> URLRequest { 21 | return request 22 | } 23 | 24 | override func startLoading() { 25 | if let error = URLProtocolMock.mockError { 26 | client?.urlProtocol(self, didFailWithError: error) 27 | client?.urlProtocolDidFinishLoading(self) 28 | return 29 | } 30 | 31 | if let delay = URLProtocolMock.responseDelay { 32 | DispatchQueue.global().asyncAfter(deadline: .now() + delay) { 33 | self.sendResponse() 34 | } 35 | } else { 36 | sendResponse() 37 | } 38 | } 39 | 40 | private func sendResponse() { 41 | if let data = URLProtocolMock.mockData, let url = request.url { 42 | let response = HTTPURLResponse(url: url, statusCode: URLProtocolMock.mockStatusCode ?? 200, httpVersion: nil, headerFields: nil)! 43 | client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed) 44 | client?.urlProtocol(self, didLoad: data) 45 | client?.urlProtocolDidFinishLoading(self) 46 | return 47 | } 48 | 49 | client?.urlProtocol(self, didFailWithError: NSError(domain: "No mock data", code: -1, userInfo: nil)) 50 | client?.urlProtocolDidFinishLoading(self) 51 | } 52 | 53 | override func stopLoading() {} 54 | } 55 | --------------------------------------------------------------------------------