Openaikit ist ein Swift -Paket, das zur Kommunikation mit der OpenAI -API verwendet wird.
Fügen Sie die Abhängigkeit zu Package hinzu.
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 " ) ,
] ) ,Es wird ermutigt, Umgebungsvariablen zu verwenden, um den OpenAI -API -Schlüssel zu injizieren, anstatt sie im Quellcode zu hartcodieren.
# .env
OPENAI_API_KEY= " YOUR-API-KEY "
OPENAI_ORGANIZATION= " YOUR-ORGANIZATION " Erstellen Sie ein OpenAIKit.Client , indem Sie eine Konfiguration übergeben.
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 )Wenn Sie Swiftnio nicht verwenden möchten, können Sie eine URLSession verwenden.
let urlSession = URLSession ( configuration : . default )
let configuration = Configuration ( apiKey : apiKey , organization : organization )
let openAIClient = OpenAIKit . Client ( session : urlSession , configuration : configuration ) Die Openaikit.Client implementiert eine Handvoll Methoden, um mit der OpenAI -API zu interagieren:
import OpenAIKit
let completion = try await openAIClient . completions . create (
model : Model . GPT3 . davinci ,
prompts : [ " Write a haiku " ]
) Wenn die Anfrage an die API aus irgendeinem Grund fehlgeschlagen ist, wird ein OpenAIKit.APIErrorResponse thrown . Stellen Sie einfach sicher, dass Sie Fehler aufnehmen, die wie jede andere Wurffunktion geworfen werden
do {
...
} catch let error as APIErrorResponse {
print ( error )
}