O OpenAikit é um pacote SWIFT usado para se comunicar com a API Openai.
Adicione a dependência ao 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 " ) ,
] ) ,É incentivado a usar variáveis de ambiente para injetar a chave da API OpenAI, em vez de codificá -la no código -fonte.
# .env
OPENAI_API_KEY= " YOUR-API-KEY "
OPENAI_ORGANIZATION= " YOUR-ORGANIZATION " Crie um OpenAIKit.Client passando uma configuração.
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 )Se você não quiser usar o Swiftnio, pode usar o URLSession.
let urlSession = URLSession ( configuration : . default )
let configuration = Configuration ( apiKey : apiKey , organization : organization )
let openAIClient = OpenAIKit . Client ( session : urlSession , configuration : configuration ) O OpenAikit.client implementa um punhado de métodos para interagir com a API Openai:
import OpenAIKit
let completion = try await openAIClient . completions . create (
model : Model . GPT3 . davinci ,
prompts : [ " Write a haiku " ]
) Se a solicitação para a API falhar por qualquer motivo, um OpenAIKit.APIErrorResponse for thrown . Basta garantir que você pegue erros jogados como qualquer outra função de arremesso
do {
...
} catch let error as APIErrorResponse {
print ( error )
}