I want to execute POST URLRequest but first I need to create request body.
The body should look like this:
{
"model": "gpt-4-vision-preview",
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": <mutableStringValue>
},
{
"type": "image_url",
"image_url": {
"url": <mutableStringValue>
}
}
]
}
],
"max_tokens": 300
}
I cannot hardcore this as .json
file because parameters "text"
(under first "type"
) and "image_url"
(under second "type"
) are given as function parameters.
I don’t know how to handle two "type"
keys.
As of now, I came up with something like this:
struct ImageInputRequestBody: Codable {
let model: String = "gpt-4-vision-preview"
let messages: [Message]
let maxTokens: Int = 300
enum CodingKeys: String, CodingKey {
case model, messages
case maxTokens = "max_tokens"
}
struct Message: Codable {
let role: String
let content: [Content]
}
struct Content: Codable {
let type: String
let text: String?
}
}
But here I’m missing second "type"
and "image_url"
content
2
Answers
You could try something simple like this:
Note, you need to add two
Content
to theMessage
object.For example:
As far as I remember, if your task is to only create the json mentioned in the question, you can simply make a multiline string, and then decode it into
Data
.Or it can be a
#""
string, to make the code more compact.If such JSONs may have a random number of items in "content", I would make an
enum
with 2 cases for text and image, and implementEncodable
‘s method to convert them properly. For instanceI also wanted to offer a more objective way, but for some reason Apple has made
encode(_:)
a generic method, and to do the following code, you would need to use another JSON parser: