openai kit
OpenAIKit 1.8.2
Openaikit是用於與OpenAI API通信的Swift軟件包。
將依賴項添加到包裝。Swift:
dependencies: [
...
. package ( url : " https://github.com/dylanshine/openai-kit.git " , from : " 1.0.0 " )
] ,
targets: [
. target ( name : " App " , dependencies : [
. product ( name : " OpenAIKit " , package : " openai-kit " ) ,
] ) ,鼓勵使用環境變量注入OpenAI API密鑰,而不是將其用於源代碼中。
# .env
OPENAI_API_KEY= " YOUR-API-KEY "
OPENAI_ORGANIZATION= " YOUR-ORGANIZATION "通過傳遞配置來創建一個OpenAIKit.Client 。
var apiKey : String {
ProcessInfo . processInfo . environment [ " OPENAI_API_KEY " ] !
}
var organization : String {
ProcessInfo . processInfo . environment [ " OPENAI_ORGANIZATION " ] !
}
...
// Generally we would advise on creating a single HTTPClient for the lifecycle of your application and recommend shutting it down on application close.
let eventLoopGroup = MultiThreadedEventLoopGroup ( numberOfThreads : 1 )
let httpClient = HTTPClient ( eventLoopGroupProvider : . shared ( eventLoopGroup ) )
defer {
// it's important to shutdown the httpClient after all requests are done, even if one failed. See: https://github.com/swift-server/async-http-client
try ? httpClient . syncShutdown ( )
}
let configuration = Configuration ( apiKey : apiKey , organization : organization )
let openAIClient = OpenAIKit . Client ( httpClient : httpClient , configuration : configuration )如果您不想使用Swiftnio,則可以使用Urlsession。
let urlSession = URLSession ( configuration : . default )
let configuration = Configuration ( apiKey : apiKey , organization : organization )
let openAIClient = OpenAIKit . Client ( session : urlSession , configuration : configuration ) OpenAikit.Client實現了與OpenAI API交互的幾種方法:
import OpenAIKit
let completion = try await openAIClient . completions . create (
model : Model . GPT3 . davinci ,
prompts : [ " Write a haiku " ]
)如果出於任何原因對API的請求失敗,則thrown OpenAIKit.APIErrorResponse 。只需確保您像其他任何投擲功能一樣遇到錯誤
do {
...
} catch let error as APIErrorResponse {
print ( error )
}