一個社區維護了OpenAI API的Swift SDK。
報告錯誤·請求功能
OpenAikit是一個以社區為導向的Swift SDK,旨在為Swift開發人員提供與OpenAI Rest端點互動的無縫,高效和搖擺的方式。我們的目的是降低迅速開發人員的障礙,使他們能夠將OpenAI的力量整合到其應用程序中,而不會深入研究RESTFUL服務的複雜性。
隨著對現代應用程序中對AI驅動功能的需求不斷增長,對於開發人員來說,可以使用簡化集成過程的工具至關重要。儘管Openai提供了令人難以置信的功能套件,但顯然需要一個專門的Swift SDK,該SDK與Swift Developer Community的語言習慣和期望保持一致。
我們設想了一種工具,該工具不僅可以為OpenAI功能提供原始訪問權限,還可以通過清晰直觀的API增強開發人員體驗。我們的最終目標是通過為Swift社區提供正確的工具來促進創新,以毫不費力地將AI功能集成到其應用程序中。
平台 | 最低快速版本 | 安裝 | 地位 |
---|---|---|---|
iOS 13.0+ / macOS 10.15+ / tvos 13.0+ / watchos 6.0+ / visionos 1.0+ | 5.7 | Swift軟件包管理器 | 經過全面測試 |
Swift軟件包管理器允許開發人員輕鬆地將軟件包集成到其Xcode項目和軟件包中;並已完全集成到swift
編譯器中。
https://github.com/OpenDive/OpenAIKit.git
設置了Swift軟件包後,將git鏈接添加在Package.swift
的dependencies
項值中。
dependencies: [
. package ( url : " https://github.com/OpenDive/OpenAIKit.git " , . upToNextMajor ( from : " 2.0.1 " ) )
]
要獲取API鍵,請在此處訪問您的帳戶頁面上的API Keys
頁面。
配x ?重要的是:不要將OpenAI API鍵直接存儲在代碼中! ?配x 在使用OpenAI的API時,由於安全原因,必須將API鍵直接嵌入應用程序代碼庫中。將密鑰直接嵌入您的源代碼中可以將其暴露於未經授權的用戶和惡意演員中,從而導致潛在的濫用。
最佳實踐:
- 環境變量:將API密鑰存儲在環境變量中,並在代碼中訪問它們。這樣,它們就不會對您的應用程序進行硬編碼,並且可以安全地管理。
- 秘密管理:使用安全的秘密管理工具或服務來存儲和檢索API密鑰。 AWS Secrets Manager,Hashicorp Vault,Firebase,CloudKit或Azure鍵值等工具旨在存儲,管理和檢索敏感數據。這樣,用戶就無法對密鑰進行設備訪問。
.gitignore
- 定期旋轉鍵:定期旋轉API鍵,以減輕洩漏的潛在影響。
請記住,安全至關重要。始終優先考慮諸如API鍵之類的敏感信息!
有關更多信息,請查看有關Swift Developers的API密鑰管理的所有信息。
通過Openai帶給您的Dall-E 2(即將推出,Dall-E 3),深入研究AI驅動圖像生成的下一個演變。 DALL-E 2以其前身的遺產為基礎,提供了增強的功能,可以從文本提示中實現複雜的視覺效果,從而在語言和圖像之間創建無縫的橋樑。開發人員可以利用這種開創性的技術來豐富用戶體驗,製作動態內容,並激發創造力的新途徑。通過整合dall-e 2的前沿力量,徹底改變了您的應用程序和項目。
OpenAI提供了三個端點,以與DALL -E 2交互: - createImage
是允許從文本提示符中直接生成的主要端點。這是有關如何使用端點以及相關輸出的一個示例:
do {
let imageParam = ImageParameters (
// A text description of the desired image(s).
prompt : " An armchair in the shape of an avocado " ,
// The size of the generated images.
resolution : . large ,
// The format in which the generated images are returned.
responseFormat : . base64Json
)
let result = try await openAi . createImage (
parameters : imageParam
)
let b64Image = result . data [ 0 ] . image
let image = try openAi . decodeBase64Image ( b64Image )
} catch {
// Insert your own error handling method here.
}
do {
let imageEditParam = try ImageEditParameters (
// The image to edit.
image : image ,
// An additional image whose fully transparent areas indicate where image should be edited.
mask : mask ,
// A text description of the desired image(s).
prompt : " The Mona Lisa wearing a beret, in the style of Leonardo DaVinci " ,
// The size of the generated images.
resolution : . large ,
// The format in which the generated images are returned.
responseFormat : . base64Json
)
let imageResponse = try await openAI . generateImageEdits (
parameters : imageEditParam
)
let image = try openAI . decodeBase64Image ( imageResponse . data [ 0 ] . image )
} catch {
// Insert your own error handling method here.
}
![]() | ![]() | ![]() |
---|---|---|
原來的 | 面具 | 編輯 |
- createImageVariation
允許開發人員創建給定輸入圖像的變化。這是有關如何使用端點以及相關輸出的一個示例:
do {
let imageVariationParam = try ImageVariationParameters (
// The image to use as the basis for the variation(s).
image : image ,
// The size of the generated images.
resolution : . large ,
// The format in which the generated images are returned.
responseFormat : . base64Json
)
let variationResponse = try await openAI . generateImageVariations (
parameters : imageVariationParam
)
self . image = try openAI . decodeBase64Image (
variationResponse . data [ 0 ] . image
)
} catch {
// Insert your own error handling method here.
}
![]() | ![]() |
---|---|
原來的 | 變化 |
Chatgpt建立在OpenAI的GPT-4體系結構上,是一種尖端的對話AI模型。它為開發人員提供了一個可靠的工具,可以將高級自然語言處理功能集成到應用程序中。使用ChatGpt可以在各種用例中增強用戶交互,提高效率並提供AI驅動的解決方案。將GPT-4的力量納入您的項目中,以取得切實的結果。
但是,此功能有一個端點,但是,該SDK將端點分為兩個函數,總共具有三個單獨的功能: - generateChatCompletion
允許開發人員使用OpenAI提供的模型來生成聊天完成;或開發人員擁有的微調模型。這是有關如何使用端點以及相關輸出的一個示例:
do {
let chat : [ ChatMessage ] = [
ChatMessage ( role : . system , content : " You are a helpful assistant. " ) ,
ChatMessage ( role : . user , content : " Who won the world series in 2020? " ) ,
ChatMessage ( role : . assistant , content : " The Los Angeles Dodgers won the World Series in 2020. " ) ,
ChatMessage ( role : . user , content : " Where was it played? " )
]
let chatParameters = ChatParameters (
model : . gpt4 , // ID of the model to use.
messages : chat // A list of messages comprising the conversation so far.
)
let chatCompletion = try await openAI . generateChatCompletion (
parameters : chatParameters
)
if let message = chatCompletion . choices [ 0 ] . message {
let content = message . content
}
} catch {
// Insert your own error handling method here.
}
ChatResponse(
id: "chatcmpl-88eG5VruffcNHPNVGBKGVAV5HGk4j",
object: OpenAIKit.OpenAIObject.chatCompletion,
created: 1697072069,
choices: [
OpenAIKit.ChatChoice(
message: Optional(
OpenAIKit.ChatMessage(
id: "250FDA2D-2F38-4E6F-B97E-DAD74FED1FB6",
role: OpenAIKit.ChatRole.assistant,
content: Optional(
"The 2020 World Series was played at Globe Life Field in Arlington, Texas."
),
functionCall: nil
)
),
delta: nil,
index: 0,
logprobs: nil,
finishReason: Optional("stop")
)
],
usage: Optional(
OpenAIKit.Usage(
promptTokens: 53,
completionTokens: 17,
totalTokens: 70
)
)
)
開發人員還能夠使用功能調用來執行各種功能(即獲取天氣信息,上傳文件等)。這是有關如何使用參數,相應響應以及具有本地函數的示例用法的示例。
do {
let functions : [ Function ] = [
Function (
name : " getCurrentWeather " ,
description : " Get the current weather in a given location " ,
parameters : Parameters (
type : " object " ,
properties : [
" location " : ParameterDetail (
type : " string " ,
description : " The city and state, e.g. San Francisco, CA "
) ,
" unit " : ParameterDetail (
type : " string " , enumValues : [ " fahrenheit " , " celsius " ]
)
] ,
required : [ " location " ]
)
)
]
let messages : [ ChatMessage ] = [
ChatMessage ( role : . user , content : " What's the weather like in Boston? " )
]
let chatParameters = ChatParameters (
model : . gpt4 , // ID of the model to use.
messages : messages , // A list of messages comprising the conversation so far.
functionCall : " auto " , // Controls how the model calls functions.
functions : functions // A list of functions the model may generate JSON inputs for.
)
let chatCompletion = try await openAI . generateChatCompletion (
parameters : chatParameters
)
} catch {
// Insert your own error handling method here.
}
ChatResponse(
id: "chatcmpl-88eVjsHEPtDDiSEuCexsqO8iuhnfG",
object: OpenAIKit.OpenAIObject.chatCompletion,
created: 1697073039,
choices: [
OpenAIKit.ChatChoice(
message: Optional(
OpenAIKit.ChatMessage(
id: "DCE5EECB-9521-481D-9E75-C7FF9390E4CF",
role: OpenAIKit.ChatRole.assistant,
content: nil,
functionCall: Optional(
OpenAIKit.FunctionCall(
arguments: "{n"location": "Boston, MA"n}",
name: "getCurrentWeather"
)
)
)
),
delta: nil,
index: 0,
logprobs: nil,
finishReason: Optional("function_call")
)
],
usage: Optional(OpenAIKit.Usage(promptTokens: 81, completionTokens: 16, totalTokens: 97))
)
func getCurrentWeather ( location : String , unit : TemperatureUnit = . fahrenheit ) -> WeatherInfo {
return WeatherInfo ( location : location , temperature : " 72 " , unit : unit , forecast : [ " sunny " , " windy " ] )
}
if let message = chatCompletion . choices [ 0 ] . message , let functionCall = message . functionCall {
let jsonString = functionCall . arguments
if let data = jsonString . data ( using : . utf8 ) {
do {
if
let json = try JSONSerialization . jsonObject ( with : data , options : [ ] ) as? [ String : Any ] ,
let location = json [ " location " ] as? String
{
self . weatherInfo = self . getCurrentWeather ( location : location )
}
} catch {
// Insert your own error handling method here.
}
}
}
- generateChatCompletionStreaming
允許開發人員從端點流式聊天完成數據。這是有關如何使用端點以及相關輸出的一個示例:
do {
let chat : [ ChatMessage ] = [
ChatMessage ( role : . system , content : " You are a helpful assistant. " ) ,
ChatMessage ( role : . user , content : " Who won the world series in 2020? " ) ,
ChatMessage ( role : . assistant , content : " The Los Angeles Dodgers won the World Series in 2020. " ) ,
ChatMessage ( role : . user , content : " Where was it played? " )
]
let chatParameters = ChatParameters ( model : . chatGPTTurbo , messages : chat )
let stream = try openAI . generateChatCompletionStreaming (
parameters : chatParameters
)
} catch {
// Insert your own error handling method here.
}
ChatResponse(
id: "chatcmpl-88enklY0vmc4fNkM1mJQCkzW6hcST",
object: OpenAIKit.OpenAIObject.chatCompletionChunk,
created: 1697074156,
choices: [
OpenAIKit.ChatChoice(
message: nil,
delta: Optional(
OpenAIKit.ChatDelta(
role: Optional(OpenAIKit.ChatRole.assistant),
content: Optional("")
)
),
index: 0,
logprobs: nil,
finishReason: nil
)
],
usage: nil
)
ChatResponse(
id: "chatcmpl-88enklY0vmc4fNkM1mJQCkzW6hcST",
object: OpenAIKit.OpenAIObject.chatCompletionChunk,
created: 1697074156,
choices: [
OpenAIKit.ChatChoice(
message: nil,
delta: Optional(
OpenAIKit.ChatDelta(
role: nil,
content: Optional("The")
)
),
index: 0,
logprobs: nil,
finishReason: nil
)
],
usage: nil
)
// ...
ChatResponse(
id: "chatcmpl-88enklY0vmc4fNkM1mJQCkzW6hcST",
object: OpenAIKit.OpenAIObject.chatCompletionChunk,
created: 1697074156,
choices: [
OpenAIKit.ChatChoice(
message: nil,
delta: Optional(
OpenAIKit.ChatDelta(
role: nil,
content: Optional(".")
)
),
index: 0,
logprobs: nil,
finishReason: nil
)
],
usage: nil
)
ChatResponse(
id: "chatcmpl-88enklY0vmc4fNkM1mJQCkzW6hcST",
object: OpenAIKit.OpenAIObject.chatCompletionChunk,
created: 1697074156,
choices: [
OpenAIKit.ChatChoice(
message: nil,
delta: Optional(
OpenAIKit.ChatDelta(
role: nil,
content: nil
)
),
index: 0,
logprobs: nil,
finishReason: Optional("stop")
)
],
usage: nil
)
Whisper是Openai的語音到文本AI模型,旨在精確轉錄口語內容。通過將音頻轉換為文本,它為開發人員提供了一個簡單的工具,用於諸如轉錄服務,語音命令,人聲語言翻譯或音頻索引之類的任務。實施耳語可以幫助簡化流程,使應用程序更容易訪問並有效利用語音數據。
有兩個主要端點使用竊竊私語模型: - createTranscription
是允許開發人員將語音音頻轉錄為文本的主要端點。這是有關如何使用端點的一個示例,以及相應的返回項目:
do {
let audioParameters = TranscriptionParameters ( file : audio )
let transcriptionCompletion = try await openAI . createTranscription ( parameters : audioParameters )
} catch {
// Insert your own error handling method here.
}
Arousing from the most profound of slumbers, we break the gossamer web of some dream. Yet in a second afterward, so frail may that web have been, we remember not that we have dreamed. In the return to life
from the swoon there are two stages, first, that of the sense of mental or spiritual, secondly, that of the sense of physical existence. It seems probable that if, upon reaching the second stage, we could
recall the impressions of the first, we should find these impressions eloquent in memories of the gulf beyond. And that gulf is what? How at least shall we distinguish its shadows from those of the tomb?
- createTranslation
是第二個端點,它允許開發人員將任何非英語音頻轉換為抄錄的英文文本。這是有關如何使用端點的一個示例,以及相應的返回項目:
do {
let audioParameters = TranscriptionParameters ( file : audio )
let transcriptionCompletion = try await openAI . createTranslation ( parameters : audioParameters )
} catch {
// Insert your own error handling method here.
}
In the night, when I was out of my mind, and I, pained, numb and tired, thought about the beauty and goodness of a long-forgotten lesson, and my head began to shake, I suddenly heard something tick that scared
me out of my sleep. Who could it be in that weather? A visitor is knocking, I thought, at my room in that weather. That's all it is, and nothing more.
嵌入使用OpenAI的GPT模型來生成文本密集的向量表示。這些嵌入式捕獲語義信息,使開發人員能夠在特定任務上執行相似性搜索,聚類或微調等任務。通過將GPT嵌入到應用程序中,開發人員可以增強文本分析和檢索功能,從而導致更有效的數據處理和見解。
這是有關如何使用它的示例,以及端點的預期輸出:
do {
let embeddingsParam = EmbeddingsParameters ( model : " text-similarity-ada-002 " , input : input )
self . embeddingsResponse = try await openAI . createEmbeddings ( parameters : embeddingsParam )
} catch {
// Insert your own error handling method here.
}
OpenAIKit.EmbeddingsResponse(
object: OpenAIKit.OpenAIObject.list,
data: [
OpenAIKit.EmbeddingsData(
object: OpenAIKit.OpenAIObject.embedding,
embedding: [
0.0028667077,
0.018867997,
-0.030135695,
// ...
-0.004177677,
-0.015615467,
-0.008131327
],
index: 0
)
],
model: "text-similarity-ada:002",
usage: OpenAIKit.EmbeddingsUsage(
promptTokens: 8,
totalTokens: 8
)
)
模型端點允許開發人員以及自己的微調型號從OpenAI獲取當前可用的模型。
此功能有兩個可用的端點:
listModels
將Avaialbe的整個模型列表提供給開發人員。這是一個示例用法,以及相應的輸出: do {
let modelsResponse = try await openAi . listModels ( )
} catch {
// Insert your own error handling method here.
}
ListModelResponse(
object: OpenAIKit.OpenAIObject.list,
data: [
OpenAIKit.Model(
id: "text-search-babbage-doc-001",
object: OpenAIKit.OpenAIObject.model,
created: 1651172509,
ownedBy: "openai-dev"
),
OpenAIKit.Model(
id: "curie-search-query",
object: OpenAIKit.OpenAIObject.model,
created: 1651172509,
ownedBy: "openai-dev"
),
OpenAIKit.Model(
id: "text-search-babbage-query-001",
object: OpenAIKit.OpenAIObject.model,
created: 1651172509,
ownedBy: "openai-dev"
),
OpenAIKit.Model(
id: "babbage",
object: OpenAIKit.OpenAIObject.model,
created: 1649358449,
ownedBy: "openai"
),
OpenAIKit.Model(
id: "gpt-3.5-turbo-instruct-0914",
object: OpenAIKit.OpenAIObject.model,
created: 1694122472,
ownedBy: "system"
)
// ...
]
)
retrieveModels
摘要獲取單個模型。這是一個示例用法,以及相應的輸出: do {
let model = try await openAI . retrieveModel ( modelId : " text-davinci-001 " )
} catch {
// Insert your own error handling method here.
}
OpenAIKit.Model(
id: "text-davinci-001",
object: OpenAIKit.OpenAIObject.model,
created: 1649364042,
ownedBy: "openai"
)
截至2023年7月6日,OpenAI宣布了完善API中舊型號的貶值,該模型定於2024年初退休。強烈建議過渡到聊天完成API,該API提供了更具結構化的及時及時插入界面和多轉向對話功能。事實證明,聊天完成API可以處理以前的絕大多數用例和具有更高靈活性和特異性的新對話需求,從而顯著增強了開發人員的體驗。有關更多詳細信息,請參閱官方公告。
截至2.x,聊天完成模型使用枚舉為默認模型的主要用法標記每個可用模型。這是一個示例,說明如何從使用較舊的初始化器將ChatParameter
遷移到2.x的初始化器:
// 1.x implementation
let chatParameters = ChatParameters ( model : " gpt4 " , messages : chat )
// ✅ 2.x implementation
let chatParameters = ChatParameters ( model : . gpt4 , messages : chat )
如果您需要用於微調型號的自定義字符串,請使用customModel
參數:
// ✅ 2.x implementation for custom model IDs
let chatParameters = ChatParameters ( customModel : " INSERT-MODEL-ID " , message : chat )
(TBD)
我們歡迎任何人在使用OpenAikit時遇到任何錯誤 /故障,通過發布問題為該項目做出貢獻;還可以創建拉動問題,從而為Openaikit添加任何其他功能。
OpenAikit是根據MIT許可發布的,任何使用OpenAI的剩餘端點的使用都將根據他們制定的使用政策。
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.