OpenAikit هي حزمة سريعة تستخدم للتواصل مع API Openai.
أضف التبعية إلى 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 حفنة من الطرق للتفاعل مع API Openai:
import OpenAIKit
let completion = try await openAIClient . completions . create (
model : Model . GPT3 . davinci ,
prompts : [ " Write a haiku " ]
) إذا فشل الطلب إلى واجهة برمجة التطبيقات لأي سبب من الأسباب ، يتم thrown OpenAIKit.APIErrorResponse . ما عليك سوى التأكد من أنك تمسك بالأخطاء التي ألقيت مثل أي وظيفة رمي أخرى
do {
...
} catch let error as APIErrorResponse {
print ( error )
}