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 แทนที่จะใช้ hardcoding ในซอร์สโค้ด
# .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 )
}