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 )
}