Invalid content type. image_url is only supported by certain models

No he podido hacer que la api me procese la imagen que le subo siempre me da este error ya sea por link o por base64 quien ha solucionado esto

What model are you using? What billing Tier are you?

1 Like

gpt-4o-mini-2024-07-18, no entiendo a 2da pregunta

1 Like

Apologies, I meant your billing tier. It shouldn’t matter, though.

Can you share the code that’s not working? Thanks!

[
        'model' => 'gpt-4o-mini-2024-07-18',
        'messages' => array_merge([['role' => 'system', 'content' => $role_system]], $context),
        'max_tokens' => 1848,
        'temperature' => 1,
        'top_p' => 1,
        'frequency_penalty' => 0,
        'presence_penalty' => 0,
        'functions' => [
            [
                'name' => 'consulta_cita',
                'description' => 'Consulta la próxima cita médica del paciente.',
                'parameters' => [
                    'type' => 'object',
                    'properties' => [
                        'numeroidentificacion' => [
                            'type' => 'string',
                            'description' => 'El nĂşmero de documento del paciente.'
                        ]
                    ],
                    'required' => ['numeroidentificacion']
                ]
            ]
        ]

if (file_exists($filePath)) {
            $imageData = file_get_contents($filePath);
            $base64Image = base64_encode($imageData);

            $context[] = [
                'role' => 'user',
                'content' => [
                    [
                        'type' => 'text',
                        'text' => 'Interpreta la imagen verifica que sea una orden de servicio medicos a nombre del paciente que esta consultando y dirigida a ENDOGASTRO DEL CESAR'
                    ],
                    [
                        'type' => 'image_url',
                        'url' => 'data:image/jpeg;base64,' . $base64Image,
                        'detail' => 'low',
                    ]
                ]
            ];
        } else {
            errlog('Error: El archivo ' . $filePath . ' no existe.');
        } 
est es el error comleto que meda:

{
  "error": {
    "message": "Invalid content type. image_url is only supported by certain models.",
    "type": "invalid_request_error",
    "param": "messages.[76].content.[1].type",
    "code": null
  }
}

Hrm. This is the working example from the docs for Node… What language are you using? Have the latest OpenAI library?

import OpenAI from "openai";

const openai = new OpenAI();

async function main() {
  const response = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages: [
      {
        role: "user",
        content: [
          { type: "text", text: "What’s in this image?" },
          {
            type: "image_url",
            image_url: {
              "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg",
            },
          },
        ],
      },
    ],
  });
  console.log(response.choices[0]);
}
main();

Uso php sin blibliotecas hago una peticiĂłn curl directa que deberia funcionar sin problema

I see. I’d keep looking at your Message object as I think that’s your problem… Though the error is apparently seeing the image_url, so I could be wrong.

Maybe try the “generic” one?

    model: "gpt-4o-mini",

he probado con todos y me da el mismo error, si alguien la ha funcionado ultimamente esto en cualquier lenguaje que me informe, las peticiones api sea con cual sea el lenguaje debe de funcionar.

Right, but pure cURL in PHP is tricky, especially with images.

Can you post your full code?

There’s a lot of examples of it working …

if ($urlfile !== null) {
        // Verifica si la imagen se descargĂł correctamente
        $filePath = 'whatskapp/media/' . $urlfile;
        if (file_exists($filePath)) {
            $imageData = file_get_contents($filePath);
            $base64Image = base64_encode($imageData);

            $context[] = [
                'role' => 'user',
                'content' => [
                    [
                        'type' => 'text',
                        'text' => 'Interpreta la imagen verifica que sea una orden de servicio medicos a nombre del paciente que esta consultando y dirigida a ENDOGASTRO DEL CESAR'
                    ],
                    [
                        'type' => 'image_url',
                        'url' => 'data:image/jpeg;base64,' . $base64Image,
                        'detail' => 'low',
                    ]
                ]
            ];
        } else {
            errlog('Error: El archivo ' . $filePath . ' no existe.');
        }
    } else {
        if ($role == 'tool') {
            $context[] = ['role' => 'tool', 'content' => [['type' => 'text', 'text' => $pregunta]], 'tool_call_id' => $function_call_id];
        } else {
            $context[] = ['role' => $role, 'content' => $pregunta];
        }
    }


$data = [
        'model' => 'gpt-4o-mini-2024-07-18',
        'messages' => array_merge([['role' => 'system', 'content' => $role_system]], $context),
        'max_tokens' => 1848,
        'temperature' => 1,
        'top_p' => 1,
        'frequency_penalty' => 0,
        'presence_penalty' => 0,
        'functions' => [
            [
                'name' => 'consulta_cita',
                'description' => 'Consulta la próxima cita médica del paciente.',
                'parameters' => [
                    'type' => 'object',
                    'properties' => [
                        'numeroidentificacion' => [
                            'type' => 'string',
                            'description' => 'El nĂşmero de documento del paciente.'
                        ]
                    ],
                    'required' => ['numeroidentificacion']
                ]
            ]
        ]
    ];

    $url = 'https://api.openai.com/v1/chat/completions';

    $headers = [
        'Content-Type: application/json',
        'Authorization: ' . 'Bearer ' . $apiKey
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);
    $err = curl_errno($ch);
    $errmsg = curl_error($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($err) {
        errlog('cURL Error: ' . $errmsg);
    }

    $decoded_json = json_decode($response, true);

    if ($http_code !== 200) {
        errlog('Error ' . $http_code . ': ' . ($decoded_json['error']['message'] ?? 'Respuesta no válida de la API de openai'));
    }
    errlog("=>" . $response);
    $role = trim($decoded_json['choices'][0]['message']['role']);
    $ropenai = trim($decoded_json['choices'][0]['message']['content']);
    errlog("role=>" . $role);
    if (isset($decoded_json['choices'][0]['message']['function_call'])) {
        $function_call = $decoded_json['choices'][0]['message']['function_call'];
        $function_call_name = trim($decoded_json['choices'][0]['message']['function_call']['name']);
        errlog($function_call_name);
        $function_call = $decoded_json['choices'][0]['message']['function_call'];
        $arguments = json_decode($function_call['arguments'], true);
        $numeroidentificacion = trim($arguments['numeroidentificacion']);
        $function_call_id = trim($decoded_json['choices'][0]['message']['function_call']['id']);
        switch ($function_call_name) {
            case 'consulta_cita':
                consultaCita($numeroidentificacion, $function_call_id, $messages_from);
                break;
            default:
                errlog('Error: FunciĂłn desconocida.');
        }
        sendmsgtexto($messages_from, $ropenai);
    } elseif (isset($decoded_json['choices'][0]['message']['content'])) {
        $ropenai = trim($decoded_json['choices'][0]['message']['content']);
        sendmsgtexto($messages_from, $ropenai);
    }
    inscontexto($messages_from, $role, $ropenai);

todos los mensajes que envio son correctamente contestados no creo que sea algo en el envio de la imagen ya que la esta recibiendo correctamente, si puedes probar en python un ejemplo como este y verificar que funciona estaria muy agradecido.

can you try to update the message a bit like this:

$context[] = [
                'role' => 'user',
                'content' => [
                    [
                        'type' => 'text',
                        'text' => 'Interpreta la imagen verifica que sea una orden de servicio medicos a nombre del paciente que esta consultando y dirigida a ENDOGASTRO DEL CESAR'
                    ],
                    [
                        'type' => 'image_url',
                        'image_url'=> [ // <-- do it this way
                               'url' => 'data:image/jpeg;base64,' . $base64Image,
                               'detail' => 'low',
                       ]
                    ]
                ]
            ];
2 Likes

Solucionado, muchas gracias :rofl: :joy: :index_pointing_at_the_viewer: esres el mejor :pray:

1 Like

ya identifica si es una orden de servicios pero cuando le subo una me da este mensaje: No puedo interpretar imágenes ni verificar su contenido.

Your image may have triggered some moderation. Sometimes it does that. It might be related to the kind of data you are trying to extract. Try to send some innocuous image just to test the API works. If it works, then it is the problem with the image. Perhaps you can also try using the playground to test your image if it will trigger the same moderation.

2 Likes

Ya lo solucione gracias solo era de darle indicaciones en el pormpt para que hiciera el proceso de la imagen

1 Like