Openaikit adalah paket Swift yang digunakan untuk berkomunikasi dengan API Openai.
Tambahkan ketergantungan ke paket.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 " ) ,
] ) ,Didorong untuk menggunakan variabel lingkungan untuk menyuntikkan kunci API OpenAI, alih -alih hardcoding dalam kode sumber.
# .env
OPENAI_API_KEY= " YOUR-API-KEY "
OPENAI_ORGANIZATION= " YOUR-ORGANIZATION " Buat OpenAIKit.Client dengan melewati konfigurasi.
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 )Jika Anda tidak ingin menggunakan Swiftnio, Anda dapat menggunakan urlsession.
let urlSession = URLSession ( configuration : . default )
let configuration = Configuration ( apiKey : apiKey , organization : organization )
let openAIClient = OpenAIKit . Client ( session : urlSession , configuration : configuration ) Openaikit.Client mengimplementasikan beberapa metode untuk berinteraksi dengan API OpenAI:
import OpenAIKit
let completion = try await openAIClient . completions . create (
model : Model . GPT3 . davinci ,
prompts : [ " Write a haiku " ]
) Jika permintaan ke API gagal karena alasan apa pun OpenAIKit.APIErrorResponse thrown . Cukup pastikan Anda menangkap kesalahan yang dilemparkan seperti fungsi lemparan lainnya
do {
...
} catch let error as APIErrorResponse {
print ( error )
}