ABJ Informática
Home IA Generativa
00:00:00
335 acessos

API OpenAI — exemplo prático

Ferramentas e APIs

Chamada HTTP mínima à API de chat completions em PHP, com variável de ambiente para a chave e tratamento básico de erros.

Pré-requisitos

Exemplo PHP (chat completion)

<?php
declare(strict_types=1);

$apiKey = getenv('OPENAI_API_KEY');
if ($apiKey === false || $apiKey === '') {
    fwrite(STDERR, "Defina OPENAI_API_KEY\n");
    exit(1);
}

$payload = [
    'model'       => 'gpt-4o-mini',
    'temperature' => 0.2,
    'messages'    => [
        [
            'role'    => 'system',
            'content' => 'Responda em português, de forma concisa.',
        ],
        [
            'role'    => 'user',
            'content' => 'Explique o que é embedding em uma frase.',
        ],
    ],
];

$ch = curl_init('https://api.openai.com/v1/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_POST           => true,
    CURLOPT_HTTPHEADER     => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
    ],
    CURLOPT_POSTFIELDS     => json_encode($payload, JSON_THROW_ON_ERROR),
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT        => 60,
]);

$response = curl_exec($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false || $httpCode >= 400) {
    fwrite(STDERR, "Erro HTTP {$httpCode}: {$response}\n");
    exit(1);
}

$data = json_decode($response, true, 512, JSON_THROW_ON_ERROR);
echo $data['choices'][0]['message']['content'] . PHP_EOL;

Boas práticas na integração

Alternativas compatíveis

Vídeo — ChatGPT no Python

Integração com a API OpenAI em Python: ambiente, chave, cliente e geração de código.

Abrir no YouTube
← Voltar aos tópicos