Swift 的 Replicate 工具包

这不是 Replicate 官方的 Swift 工具包。我做这个是因为我想支持那些为 Replicate 创建开源模型的人。

此软件包的 SwiftUI 示例

Replicate 工具包示例应用

The concept

Replicate 是一项服务,让您只需几行代码即可运行机器学习模型,而无需了解机器学习的工作原理。 此软件包是 Replicate API 和您的应用程序之间的 Swift 层。

如何使用

身份验证

所有 API 请求都必须使用令牌进行身份验证。 获取您的 API 密钥

        let url = URL(string: ReplicateAPI.Endpoint.baseURL)
        let apiKey = "your API key"
        api = ReplicateAPI(baseURL: url, apiKey: apiKey)

获取模型

    
   let model = try await api.getModel(owner: item.owner, name: item.name)

创建预测并获取结果

调用此操作会为您提供的版本和输入启动新的预测。 由于模型可能需要几秒或更长时间才能运行,因此输出不会立即可用。 要获得预测的最终结果,您应该提供一个 Webhook URL,以便在结果准备就绪时调用,或者等待预测结果直到它具有完成状态之一。

    guard let latest = model.latestVersion else {
        throw Errors.latestVersionIsEmpty
    }

    /// In the case of success, output will be an object containing the 
    ///  output of the model. Any files will be represented as URLs.
    let output: [String]? = try await api.createPrediction(
            version: latest.id,
            input: input.params /// ["prompt": "an astronaut riding a horse on mars"]
    ).output
"output": [
    "https://replicate.com/api/models/stability-ai/stable-diffusion/files/9c3b6fe4-2d37-4571-a17a-83951b1cb120/out-0.png"
  ]

每次预测生成输出时(请注意,预测可以生成多个输出),您可以在 模型页面 中找到模型的输入格式,例如

错误处理

当服务器由于被认为是客户端错误的原因而无法或不处理请求时,处理响应会出错。 The concept

Replicate API

    /// Get a collection of models
    /// - Parameter collection_slug: The slug of the collection, like
    /// super-resolution or image-restoration
    /// - Returns: a collection of models
    public func getCollections(collection_slug : String) async throws -> CollectionOfModels
    /// Get a model
    /// - Parameters:
    ///   - owner: Model owner
    ///   - name: Model name
    public func getModel(owner: String, name: String) async throws -> Model
    /// Create prediction
    /// - Parameters:
    ///   - versionId: Version id
    ///   - input: Input data
    ///   - expect: Logic for awaiting a prediction check out ``ReplicateAPI.Expect``
    ///  - webhook: An HTTPS URL for receiving a webhook when the prediction has new output.
    /// - Returns: Prediction result
    public func createPrediction<Input: Encodable, Output: Decodable>(
        version id : String,
        input: Input,
        expect: Expect = .yes(),
        webhook: URL? = nil
    ) async throws -> Prediction<Output>
    /// Get prediction
    /// Returns the same response as the create a prediction operation
    /// status will be one of ``Prediction.Status``
    /// In the case of success, output will be an object containing the output
    /// of the model. Any files will be represented as URLs.
    /// - Parameter id: Prediction id
    /// - Returns: Prediction
    public func getPrediction<Output: Decodable>(
        by id : String
    ) async throws -> Prediction<Output>

The concept

文档(API)

The concept