replicate / replicate-swift

Swift client for Replicate
https://replicate.com
Apache License 2.0
157 stars 33 forks source link

How to get array from output? #56

Closed lassemt closed 10 months ago

lassemt commented 10 months ago

I'm struggling a bit with the output in this example:

let output = try await replicate.run(
    "yorickvp/llava-13b:2facb4a474a0462c15041b78b1ad70952ea46b5ec6ad29583c0b29dbd4249591",
    ["prompt": "Describe this image", "image": "base64 image etc."]
)

Printing the output works fine and it show the words as an array with strings, but if I'm trying to do something with the output it is complaining that "type 'Value?' has no member X". For example

output.joined(separator: ", ")

will complain about "Value of type 'Value?' has no member 'joined'". What is the right way of handling output?

I aware defining a model is probably a better approach, but I'm using this to learn swift, so I'm trying to do it a bit step by step 🥲

mattt commented 10 months ago

Hi @lassemt. The return value for run is a Value. The specific output type isn't known at compile time, because run can specify any model version. Because you know the model will produce an array, you can call output?.arrayValue. The elements of the resulting array are themselves a Value, so you can do:

output?.arrayValue?.flatMap({ $0.stringValue }).joined(separator: ", ")
lassemt commented 10 months ago

flatMap, of course! Thank you for the answer and example @mattt 🙌