openai kit
OpenAIKit 1.8.2
Openaikit은 OpenAI API와 통신하는 데 사용되는 신속한 패키지입니다.
package.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에 대한 요청이 어떤 이유로 든 실패한 경우 OpenAIKit.APIErrorResponse 가 thrown . 다른 던지기 기능과 마찬가지로 오류를 잡아
do {
...
} catch let error as APIErrorResponse {
print ( error )
}